Inheritance: System.Security.AccessControl.AccessRule
示例#1
0
        public void ResetAccessRule(PipeAccessRule rule)
        {
            if (rule == null)
                throw new ArgumentNullException(nameof(rule));

            base.ResetAccessRule(rule);
        }
 public static NamedPipeServerStream Create(string name, int maxInstances = NamedPipeServerStream.MaxAllowedServerInstances) {
     PipeSecurity ps = new PipeSecurity();
     SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
     PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
     ps.AddAccessRule(par);
     return new NamedPipeServerStream(name, PipeDirection.InOut, maxInstances, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 1024, 1024, ps);
 }
        public void RemoveAccessRuleSpecific(PipeAccessRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException("rule");
            }
            AuthorizationRuleCollection rules = base.GetAccessRules(true, true, rule.IdentityReference.GetType());

            for (int i = 0; i < rules.Count; i++)
            {
                PipeAccessRule rule2 = rules[i] as PipeAccessRule;
                if (((rule2 != null) && (rule2.PipeAccessRights == rule.PipeAccessRights)) && ((rule2.IdentityReference == rule.IdentityReference) && (rule2.AccessControlType == rule.AccessControlType)))
                {
                    base.RemoveAccessRuleSpecific(rule);
                    return;
                }
            }
            if (rule.PipeAccessRights != PipeAccessRights.FullControl)
            {
                base.RemoveAccessRuleSpecific(new PipeAccessRule(rule.IdentityReference, PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny), false, rule.AccessControlType));
            }
            else
            {
                base.RemoveAccessRuleSpecific(rule);
            }
        }
示例#4
0
        public void SetAccessRule(PipeAccessRule rule)
        {
            if (rule == null)
                throw new ArgumentNullException("rule");

            base.SetAccessRule(rule);
        }
 public void AddAccessRule(PipeAccessRule rule)
 {
     if (rule == null)
     {
         throw new ArgumentNullException("rule");
     }
     base.AddAccessRule(rule);
 }
 public void AddAccessRule(PipeAccessRule rule)
 {
     if (rule == null)
     {
         throw new ArgumentNullException("rule");
     }
     base.AddAccessRule(rule);
 }
示例#7
0
        private void PipeThreadStart()
        {
            PipeSecurity pSec = new PipeSecurity();
            PipeAccessRule pAccRule = new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null)
            , PipeAccessRights.ReadWrite | PipeAccessRights.Synchronize, System.Security.AccessControl.AccessControlType.Allow);
            pSec.AddAccessRule(pAccRule);

            using (_pipeServer = new NamedPipeServerStream("NKT_SQLINTERCEPT_PIPE",
                PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances,
                PipeTransmissionMode.Byte,
                PipeOptions.None,
                MAX_STRING_CCH * 2,
                MAX_STRING_CCH * 2,
                pSec,
                HandleInheritability.Inheritable))
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("(pipe thread) Waiting for connection...");
                Console.ForegroundColor = ConsoleColor.Gray;

                try
                {
                    _pipeServer.WaitForConnection();

                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.WriteLine("(pipe thread) Client connected.");
                    Console.ForegroundColor = ConsoleColor.Gray;

                    while (true)
                    {
                        byte[] readBuf = new byte[MAX_STRING_CCH * 2];

                        int cbRead = _pipeServer.Read(readBuf, 0, MAX_STRING_CCH * 2);

                        string str = Encoding.Unicode.GetString(readBuf, 0, cbRead);

                        Console.WriteLine(str);
                        Console.ForegroundColor = ConsoleColor.Blue;
                        Console.WriteLine("--------------------------------------------------------");
                        Console.ForegroundColor = ConsoleColor.Gray;

                        if (_blockQuery)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("(pipe thread) QUERY ABORTED");
                            Console.ForegroundColor = ConsoleColor.Gray;
                        }

                    }
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine("(pipethread) Pipe or data marshaling operation exception! ({0})", ex.Message);
                }
            }
        }
示例#8
0
        public void ResetAccessRule(PipeAccessRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException(nameof(rule));
            }

            base.ResetAccessRule(rule);
        }
示例#9
0
        /*
        *METHOD		    :	QuestionWindow
        *
        *DESCRIPTION	:	Constructor for the QuestionWindow class. takes in users name, the computers name to connect to and name of the pipe to use.
         *                  Opens connestion to the service and starts the first qestion
        *
        *PARAMETERS		:	string userName     The name of the user
         *                  string serverName   The name of the computer running the server
         *                  string pipeName     The name of the por to connect to
        *
        *RETURNS		:
        *
        */
        public QuestionWindow(string userName, string serverName, string pipeName)
        {
            InitializeComponent();
            this.userName = userName;
            this.serverName = serverName;
            this.pipeName = pipeName;

            answers = new string[4];

            PipeSecurity ps = new PipeSecurity();
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            questionNumber = 1;
            answers[0] = "";
            answers[1] = "";
            answers[2] = "";
            answers[3] = "";

            //start timer for counting down users score (1 per second)
            timer = new System.Timers.Timer();
            timer.Elapsed += on_Timer_Event;
            timer.Interval = 1000;

            //connect to service
            client = new NamedPipeClientStream(serverName, pipeName + "service");//naming convention for pipe is given name(pipeName) and who has the server (service or user)
            client.Connect(30);
            output = new StreamWriter(client);

            //tell service the name of the computer to connect back to
            output.WriteLine(Environment.MachineName);
            output.Flush();

            server = new NamedPipeServerStream(pipeName + "User", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);//naming convention for pipe is given name(pipeName) and who has the server (service or user)
            server.WaitForConnection();
            input = new StreamReader(server);

            Thread.Sleep(100);//allow server time complete actions
            //tell service name of new user
            newUser();
            Thread.Sleep(200);//allow server time complete actions
            //get the first question
            getGameQuestion();
            //start score counter
            timer.Start();
        }
示例#10
0
 public void Init()
 {
     lock (pipeServerLock)
     {
         if (pipeServer != null)
         {
             return;
         }
         var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
         var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,
         System.Security.AccessControl.AccessControlType.Allow);
         var sec = new PipeSecurity();
         sec.AddAccessRule(rule);
         pipeServer = new NamedPipeServerStream(HealthCheckSettings.HEALTH_CHECK_PIPE, PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 0, 0, sec);
         pipeServer.BeginWaitForConnection(new AsyncCallback(WaitForConnectionCallBack), pipeServer);
     }
 }
示例#11
0
 public void StartServer(SelectCounter selectCountersDelegate, ReceivedValues receivedValuesDelegate)
 {
     selectCounters = selectCountersDelegate;
     receivedValues = receivedValuesDelegate;
     System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
     PipeAccessRule pac = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
     PipeSecurity ps = new PipeSecurity();
     ps.AddAccessRule(pac);
     sid = null;
     pipeServer = new NamedPipeServerStream(serverPipeName,
             PipeDirection.InOut,
             serverInstances,
             PipeTransmissionMode.Message,
             PipeOptions.Asynchronous,
             1024,
             1024,
             ps);
     AsyncCallback myCallback = new AsyncCallback(AsyncPipeCallback);
     pipeServer.BeginWaitForConnection(myCallback, null);
 }
示例#12
0
		void NamedPipePermissionsActuallyWorkSync (string name, bool addDenyEveryone)
		{
			if (PlatformID.Win32NT != Environment.OSVersion.Platform) {
				Assert.Ignore (); return;
			}

			PipeSecurity security = new PipeSecurity ();
			SecurityIdentifier worldSid = new SecurityIdentifier ("WD");
			PipeAccessRule rule = new PipeAccessRule (worldSid,
			                                          PipeAccessRights.FullControl,
			                                          AccessControlType.Allow);
			security.AddAccessRule (rule);

			using (NamedPipeServerStream server = CreateNamedServer (false, name, security,
										 PipeAccessRights.ChangePermissions)) {
				security = server.GetAccessControl ();

				AuthorizationRuleCollection rules;
				rules = security.GetAccessRules (true, true, typeof (SecurityIdentifier));
				Assert.AreEqual (1, rules.Count);

				rule = (PipeAccessRule)rules [0];
				Assert.AreEqual (AccessControlType.Allow, rule.AccessControlType);
				Assert.AreEqual (worldSid, rule.IdentityReference);
				Assert.AreEqual (PipeAccessRights.FullControl, rule.PipeAccessRights);

				if (addDenyEveryone)
					AddDenyEveryone (server);

				bool unauthorized = false;
				using (NamedPipeClientStream client = CreateNamedClient (false, name)) {
					try {
						client.Connect (1000);
					} catch (UnauthorizedAccessException) {
						unauthorized = true;
					}
				}

				Assert.AreEqual (addDenyEveryone, unauthorized);
			}
		}
示例#13
0
        public void RemoveAccessRuleSpecific(PipeAccessRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException(nameof(rule));
            }

            // If the rule to be removed matches what is there currently then
            // remove it unaltered. That is, don't mask off the Synchronize bit
            AuthorizationRuleCollection rules = GetAccessRules(true, true,
                                                               rule.IdentityReference.GetType());

            for (int i = 0; i < rules.Count; i++)
            {
                PipeAccessRule fsrule = rules[i] as PipeAccessRule;

                if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) &&
                    (fsrule.IdentityReference == rule.IdentityReference) &&
                    (fsrule.AccessControlType == rule.AccessControlType))
                {
                    base.RemoveAccessRuleSpecific(rule);
                    return;
                }
            }

            // It wasn't an exact match so try masking the sychronize bit (that is
            // automatically added for Allow) before removing the ACL. The logic
            // here should be same as Deny and hence fake a call to
            // AccessMaskFromRights as though the ACL is for Deny
            if (rule.PipeAccessRights != PipeAccessRights.FullControl)
            {
                base.RemoveAccessRuleSpecific(new PipeAccessRule(rule.IdentityReference,
                                                                 PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny),
                                                                 false,
                                                                 rule.AccessControlType));
            }
            else
            {
                base.RemoveAccessRuleSpecific(rule);
            }
        }
示例#14
0
        public bool RemoveAccessRule(PipeAccessRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException("rule");
            }

            // If the rule to be removed matches what is there currently then
            // remove it unaltered. That is, don't mask off the Synchronize bit.
            AuthorizationRuleCollection rules = GetAccessRules(true, true,
                                                               rule.IdentityReference.GetType());

            for (int i = 0; i < rules.Count; i++)
            {
                PipeAccessRule fsrule = rules[i] as PipeAccessRule;

                if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights) &&
                    (fsrule.IdentityReference == rule.IdentityReference) &&
                    (fsrule.AccessControlType == rule.AccessControlType))
                {
                    return(base.RemoveAccessRule(rule));
                }
            }

            // It didn't exactly match any of the current rules so remove this way:
            // mask off the synchronize bit (that is automatically added for Allow)
            // before removing the ACL. The logic here should be same as Deny and hence
            // fake a call to AccessMaskFromRights as though the ACL is for Deny
            if (rule.PipeAccessRights != PipeAccessRights.FullControl)
            {
                return(base.RemoveAccessRule(new PipeAccessRule(
                                                 rule.IdentityReference,
                                                 PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny),
                                                 false,
                                                 rule.AccessControlType)));
            }
            else
            {
                return(base.RemoveAccessRule(rule));
            }
        }
示例#15
0
        public bool RemoveAccessRule(PipeAccessRule rule)
        {
            if (rule == null)
            {
                throw new ArgumentNullException(nameof(rule));
            }

            // If the rule to be removed matches what is there currently then 
            // remove it unaltered. That is, don't mask off the Synchronize bit.
            AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType());

            for (int i = 0; i < rules.Count; i++)
            {
                PipeAccessRule fsrule = rules[i] as PipeAccessRule;

                if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights)
                        && (fsrule.IdentityReference == rule.IdentityReference)
                        && (fsrule.AccessControlType == rule.AccessControlType))
                {
                    return base.RemoveAccessRule(rule);
                }
            }

            // It didn't exactly match any of the current rules so remove this way:
            // mask off the synchronize bit (that is automatically added for Allow)
            // before removing the ACL. The logic here should be same as Deny and hence
            // fake a call to AccessMaskFromRights as though the ACL is for Deny
            if (rule.PipeAccessRights != PipeAccessRights.FullControl)
            {
                return base.RemoveAccessRule(new PipeAccessRule(
                            rule.IdentityReference,
                            PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny),
                            false,
                            rule.AccessControlType));
            }
            else
            {
                return base.RemoveAccessRule(rule);
            }
        }
示例#16
0
 void NewServerThread(string cachedir)
 {
     var t = new Thread(new ParameterizedThreadStart(ConnectionThreadFn));
     t.IsBackground = true;
     serverThreads.Add(t);
     var nss = new NamedPipeServerStream(MakePipeName(cachedir), PipeDirection.InOut, MaxServerThreads, PipeTransmissionMode.Message, PipeOptions.WriteThrough | PipeOptions.Asynchronous);
     if (Settings.PipeSecurityEveryone) {
         var npa = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
         var nps = new PipeSecurity();
         nps.AddAccessRule(npa);
         nss.SetAccessControl(nps);
     }
     t.Start(nss);
     Logging.Emit("server thread started");
 }
示例#17
0
 public bool RemoveAccessRule(PipeAccessRule rule)
 {
     throw new NotImplementedException();
 }
示例#18
0
 public void SetAccessRule(PipeAccessRule rule)
 {
     SetAccessRule((AccessRule)rule);
 }
示例#19
0
 public void RemoveAccessRuleSpecific(PipeAccessRule rule)
 {
     RemoveAccessRuleSpecific((AccessRule)rule);
 }
        public void RemoveAccessRuleSpecific(PipeAccessRule rule) {
            if (rule == null) {
                throw new ArgumentNullException("rule");
            }

            // If the rule to be removed matches what is there currently then 
            // remove it unaltered. That is, don't mask off the Synchronize bit
            AuthorizationRuleCollection rules = GetAccessRules(true, true,
                    rule.IdentityReference.GetType());

            for (int i = 0; i < rules.Count; i++) {
                PipeAccessRule fsrule = rules[i] as PipeAccessRule;

                if ((fsrule != null) && (fsrule.PipeAccessRights == rule.PipeAccessRights)
                    && (fsrule.IdentityReference == rule.IdentityReference)
                    && (fsrule.AccessControlType == rule.AccessControlType)) {
                    base.RemoveAccessRuleSpecific(rule);
                    return;
                }
            }

            // It wasn't an exact match so try masking the sychronize bit (that is 
            // automatically added for Allow) before removing the ACL. The logic 
            // here should be same as Deny and hence fake a call to 
            // AccessMaskFromRights as though the ACL is for Deny
            if (rule.PipeAccessRights != PipeAccessRights.FullControl) {
                base.RemoveAccessRuleSpecific(new PipeAccessRule(rule.IdentityReference,
                    PipeAccessRule.AccessMaskFromRights(rule.PipeAccessRights, AccessControlType.Deny),
                    false,
                    rule.AccessControlType));
            }
            else {
                base.RemoveAccessRuleSpecific(rule);
            }
        }
示例#21
0
		public void AddAccessRule (PipeAccessRule rule)
		{
			AddAccessRule ((AccessRule)rule);
		}
        /// <summary>
        /// Instantiates an endpoint to act as a client
        /// </summary>
        /// <param name="pipeName">The name of the pipe to which we should connect.</param>
        internal void InternalConstruct(string pipeName)
        {
            ErrorUtilities.VerifyThrowArgumentLength(pipeName, "pipeName");

            _debugCommunications = (Environment.GetEnvironmentVariable("MSBUILDDEBUGCOMM") == "1");

            _status = LinkStatus.Inactive;
            _asyncDataMonitor = new object();
            _sharedReadBuffer = InterningBinaryReader.CreateSharedBuffer();

            SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
            PipeSecurity security = new PipeSecurity();

            // Restrict access to just this account.  We set the owner specifically here, and on the
            // pipe client side they will check the owner against this one - they must have identical
            // SIDs or the client will reject this server.  This is used to avoid attacks where a
            // hacked server creates a less restricted pipe in an attempt to lure us into using it and 
            // then sending build requests to the real pipe client (which is the MSBuild Build Manager.)
            PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite, AccessControlType.Allow);
            security.AddAccessRule(rule);
            security.SetOwner(identifier);

            _pipeServer = new NamedPipeServerStream
                (
                pipeName,
                PipeDirection.InOut,
                1, // Only allow one connection at a time.
                PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                PipeBufferSize, // Default input buffer
                PipeBufferSize, // Default output buffer
                security,
                HandleInheritability.None
                );
        }
示例#23
0
 public void AddAccessRule(PipeAccessRule rule)
 {
 }
示例#24
0
 public void SetAccessRule(PipeAccessRule rule)
 {
 }
        private void ReadData()
        {
            var pipeSecurity = new PipeSecurity();
            var everyoneSecurityIdentifier = new SecurityIdentifier(
                WellKnownSidType.WorldSid, null);
            var everyoneAccessRule = new PipeAccessRule(everyoneSecurityIdentifier,
                PipeAccessRights.FullControl, AccessControlType.Allow);
            pipeSecurity.AddAccessRule(everyoneAccessRule);

            try
            {
                using (var namedPipeServer = new NamedPipeServerStream(
                    _serverPipeConfiguration.Name, PipeDirection.InOut, 1,
                    PipeTransmissionMode.Byte, PipeOptions.Asynchronous,
                    0, 0, pipeSecurity))
                {
                    _log.DebugFormat("Start reading pipe: {0}", _serverPipeConfiguration.Name);

                    while (true)
                    {
                        if (_stopReading)
                        {
                            _log.DebugFormat("Stop reading pipe {0} (stop request)", _serverPipeConfiguration.Name);
                            return;
                        }

                        ReadMessage(namedPipeServer);
                    }
                }
            }
            catch (Exception ex)
            {
                _log.ErrorFormat("Stop reading pipe {0} (exception: {1})",
                    _serverPipeConfiguration.Name, ex);
            }
            finally
            {
                _log.DebugFormat("Stop reading pipe {0}", _serverPipeConfiguration.Name);
            }
        }
示例#26
0
		public void RemoveAccessRuleSpecific (PipeAccessRule rule)
		{
			RemoveAccessRuleSpecific ((AccessRule)rule);
		}
示例#27
0
		public void ResetAccessRule (PipeAccessRule rule)
		{
			ResetAccessRule ((AccessRule)rule);
		}
示例#28
0
 public void RemoveAccessRuleSpecific(PipeAccessRule rule)
 {
     throw new NotImplementedException("ACL is not supported in Mono");
 }
示例#29
0
 public bool RemoveAccessRule(PipeAccessRule rule)
 {
     throw new NotImplementedException("ACL is not supported in Mono");
 }
示例#30
0
        public bool RemoveAccessRule(PipeAccessRule rule)
        {
            Contract.Requires(rule.IdentityReference != null);

            return(default(bool));
        }
示例#31
0
 public void AddAccessRule(PipeAccessRule rule !!)
 {
     base.AddAccessRule(rule);
示例#32
0
 public void RemoveAccessRuleSpecific(PipeAccessRule rule)
 {
     Contract.Requires(rule.IdentityReference != null);
 }
        /// <summary>
        /// Create an instance of the pipe. This might be the first instance, or a subsequent instance.
        /// There always needs to be an instance of the pipe created to listen for a new client connection.
        /// </summary>
        /// <returns>The pipe instance or throws an exception.</returns>
        private NamedPipeServerStream ConstructPipe(string pipeName)
        {
            CompilerServerLogger.Log("Constructing pipe '{0}'.", pipeName);

            SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
            PipeSecurity security = new PipeSecurity();

            // Restrict access to just this account.  
            PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow);
            security.AddAccessRule(rule);
            security.SetOwner(identifier);

            NamedPipeServerStream pipeStream = new NamedPipeServerStream(
                pipeName,
                PipeDirection.InOut,
                NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections.
                PipeTransmissionMode.Byte,
                PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                PipeBufferSize, // Default input buffer
                PipeBufferSize, // Default output buffer
                security,
                HandleInheritability.None);

            CompilerServerLogger.Log("Successfully constructed pipe '{0}'.", pipeName);

            return pipeStream;
        }
示例#34
0
 public void ResetAccessRule(PipeAccessRule rule)
 {
 }
示例#35
0
 public bool RemoveAccessRule(PipeAccessRule rule)
 {
     return(RemoveAccessRule((AccessRule)rule));
 }
示例#36
0
		public bool RemoveAccessRule (PipeAccessRule rule)
		{
			return RemoveAccessRule ((AccessRule)rule);
		}
示例#37
0
 public void ResetAccessRule(PipeAccessRule rule)
 {
     ResetAccessRule((AccessRule)rule);
 }
示例#38
0
        // This overload is used in Mono to implement public constructors.
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            PipeSecurity?pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
        {
            Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
            Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);

            // Make sure the pipe name isn't one of our reserved names for anonymous pipes.
            if (string.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
            }

            if (IsCurrentUserOnly)
            {
                Debug.Assert(pipeSecurity == null);

                using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent())
                {
                    SecurityIdentifier identifier = currentIdentity.Owner !;

                    // Grant full control to the owner so multiple servers can be opened.
                    // Full control is the default per MSDN docs for CreateNamedPipe.
                    PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.FullControl, AccessControlType.Allow);
                    pipeSecurity = new PipeSecurity();

                    pipeSecurity.AddAccessRule(rule);
                    pipeSecurity.SetOwner(identifier);
                }

                // PipeOptions.CurrentUserOnly is special since it doesn't match directly to a corresponding Win32 valid flag.
                // Remove it, while keeping others untouched since historically this has been used as a way to pass flags to CreateNamedPipe
                // that were not defined in the enumeration.
                options &= ~PipeOptions.CurrentUserOnly;
            }

            int openMode = ((int)direction) |
                           (maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
                           (int)options |
                           (int)additionalAccessRights;

            // We automatically set the ReadMode to match the TransmissionMode.
            int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;

            // Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
            if (maxNumberOfServerInstances == MaxAllowedServerInstances)
            {
                maxNumberOfServerInstances = 255;
            }

            GCHandle pinningHandle = default;

            try
            {
                Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);
                SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                                                                         maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);

                if (handle.IsInvalid)
                {
                    throw Win32Marshal.GetExceptionForLastWin32Error();
                }

                InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
            }
            finally
            {
                if (pinningHandle.IsAllocated)
                {
                    pinningHandle.Free();
                }
            }
        }
示例#39
0
 public void AddAccessRule(PipeAccessRule rule)
 {
     AddAccessRule((AccessRule)rule);
 }
示例#40
0
 public void RemoveAccessRuleSpecific(PipeAccessRule rule)
 {
     throw new NotImplementedException();
 }
示例#41
0
 public void ResetAccessRule(PipeAccessRule rule)
 {
     throw new NotImplementedException();
 }
 public void SetAccessRule(PipeAccessRule rule)
 {
 }
示例#43
0
        /// <summary>
        /// Checks to see if memory is available, and if it is creates a new
        /// Connection object, awaits the completion of the connection, then
        /// runs <see cref="ConnectionCompleted"/> for cleanup.
        /// </summary>
        private async Task DispatchConnection(NamedPipeServerStream pipeStream)
        {
            try
            {
                // There is always a race between timeout and connections because
                // there is no way to cancel listening on the pipe without
                // closing the pipe. We immediately increment the connection
                // semaphore while processing connections in order to narrow
                // the race window as much as possible.
                Interlocked.Increment(ref this.activeConnectionCount);

                if (Environment.Is64BitProcess || MemoryHelper.IsMemoryAvailable())
                {
                    CompilerServerLogger.Log("Memory available - accepting connection");

                    Connection connection = new Connection(pipeStream, handler);

                    await connection.ServeConnection().ConfigureAwait(false);

                    // The connection should be finished
                    ConnectionCompleted(connection);
                }
                else
                {
                    CompilerServerLogger.Log("Memory tight - rejecting connection.");
                    // As long as we haven't written a response, the client has not 
                    // committed to this server instance and can look elsewhere.
                    pipeStream.Close();

                    // We didn't create a connection -- decrement the semaphore
                    Interlocked.Decrement(ref this.activeConnectionCount);

                    // Start a terminate server timer if there are no active
                    // connections
                    StartTimeoutTimerIfNecessary();
                }
            }
            catch (Exception e) if (CompilerFatalError.Report(e))
            {
                throw ExceptionUtilities.Unreachable;
            }
        }

        /// <summary>
        /// Create an instance of the pipe. This might be the first instance, or a subsequent instance.
        /// There always needs to be an instance of the pipe created to listen for a new client connection.
        /// </summary>
        /// <returns>The pipe instance, or NULL if the pipe couldn't be created..</returns>
        private NamedPipeServerStream ConstructPipe()
        {
            // Add the process ID onto the pipe name so each process gets a unique pipe name.
            // The client must user this algorithm too to connect.
            string pipeName = basePipeName + Process.GetCurrentProcess().Id.ToString();

            try
            {
                CompilerServerLogger.Log("Constructing pipe '{0}'.", pipeName);

                SecurityIdentifier identifier = WindowsIdentity.GetCurrent().Owner;
                PipeSecurity security = new PipeSecurity();

                // Restrict access to just this account.  
                PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow);
                security.AddAccessRule(rule);
                security.SetOwner(identifier);

                NamedPipeServerStream pipeStream = new NamedPipeServerStream(
                    pipeName,
                    PipeDirection.InOut,
                    NamedPipeServerStream.MaxAllowedServerInstances, // Maximum connections.
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous | PipeOptions.WriteThrough,
                    PipeBufferSize, // Default input buffer
                    PipeBufferSize, // Default output buffer
                    security,
                    HandleInheritability.None);

                CompilerServerLogger.Log("Successfully constructed pipe '{0}'.", pipeName);

                return pipeStream;
            }
            catch (Exception e)
            {
                // Windows may not create the pipe for a number of reasons.
                CompilerServerLogger.LogException(e, string.Format("Construction of pipe '{0}' failed", pipeName));
                return null;
            }
        }
 public void AddAccessRule(PipeAccessRule rule)
 {
 }
示例#45
0
 public void ResetAccessRule(PipeAccessRule rule)
 {
     throw new NotImplementedException("ACL is not supported in Mono");
 }
    public bool RemoveAccessRule(PipeAccessRule rule)
    {
      Contract.Requires(rule.IdentityReference != null);

      return default(bool);
    }
示例#47
0
        /*
        *METHOD		    :	btn_submit_Click
        *
        *DESCRIPTION	:	used to send the new question to the service when submit clicked
        *
        *PARAMETERS		:	object sender:  Object relaying information on where the event call came from
        *                   EventArgs e:    Object that contains data about the event
        *
        *RETURNS		:	void
        *
        */
        private void btn_submit_Click(object sender, EventArgs e)
        {
            if (txtbx_server.Text.Length > 0 && txtbx_name.Text.Length > 0)
            {
                try
                {
                    userName = txtbx_name.Text;
                    serverName = txtbx_server.Text;
                    //set up the named pipe security
                    PipeSecurity ps = new PipeSecurity();
                    System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
                    PipeAccessRule par = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
                    ps.AddAccessRule(par);

                    //connect to service
                    client = new NamedPipeClientStream(serverName, "ServiceOutgoing");//add server name
                    client.Connect(30);
                    output = new StreamWriter(client);

                    //tell ther service this computers name
                    output.WriteLine(Environment.MachineName);
                    output.Flush();

                    server = new NamedPipeServerStream("UserOutgoing", PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
                    server.WaitForConnection();
                    input = new StreamReader(server);

                    //get namedPipe Name
                    pipeName = input.ReadLine();

                    server.Disconnect();
                    server.Dispose();
                    Close();
                }
                catch (Exception)
                {
                    MessageBox.Show("Failed to connect to Server", "Error");
                }
            }
        }
 public void RemoveAccessRuleSpecific(PipeAccessRule rule)
 {
   Contract.Requires(rule.IdentityReference != null);
 }
示例#49
0
        private void ServerThreadRoutine(object data)
        {
            string defaultTimeOutValuestring = TimeOutValuestring;
            TvBusinessLayer layer = new TvBusinessLayer();
            Setting setting = null;

            while (PipeServerActive)
            {
                try
                {
                    var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,System.Security.AccessControl.AccessControlType.Allow);
                    var sec = new PipeSecurity();
                    sec.AddAccessRule(rule);

#if (MPTV2)
                    string pipeName = "MP2TvWishListPipe";
#else
                    string pipeName = "TvWishListPipe";
#endif

                    pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, sec);  //only 1 thread for pipe

                    int threadId = Thread.CurrentThread.ManagedThreadId;

                    // Wait for a client to connect
                    Logdebug("TvServer: Waiting for client to connect");
                    PipeServerBusy = false;

                    pipeServer.WaitForConnection();
                    ServerMessage = string.Empty;
                    Logdebug("Client connected on pipe server thread.");
                    PipeServerBusy = true; ;
                    // Read the request from the client. Once the client has
                    // written to the pipe its security token will be available.

                    //pipeServer.ReadTimeout = 5000; //timeout not supported for async streams

                    StreamString ss = new StreamString(pipeServer);

                    // Verify our identity to the connected client using a
                    // string that the client anticipates.


                    MessageFromClient = ss.ReadString();            //receive message from client first
                    //labelreceivedTextServer.Text = messagefromclient;
                    Logdebug("***** CLIENTMESSAGE=" + MessageFromClient);

                    //*******************************
                    //commandinterpretation 
                    //*******************************
                    if (MessageFromClient == PipeCommands.RequestTvVersion.ToString())
                    {
                        string response = PipeCommands.RequestTvVersion.ToString() + "=" + this.Version;
                        Logdebug("sending response " + response);
                        ss.WriteString(response);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.StartEpg.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;
                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }
                        Logdebug("Starting EPG Search from pipe command");
                        Thread StartEPGsearchThread = new Thread(StartEPGsearchCommand);
                        StartEPGsearchThread.Start();
                        

                        while ((ServerMessage.StartsWith(PipeCommands.Ready.ToString())==false) && (ServerMessage.StartsWith(PipeCommands.Error.ToString()) == false))
                        {
                            ServerTimeOutCounter = new Thread(ServerTimeOutError);
                            ServerTimeOutCounter.Start();
                            while ((NewServerMessage == false) || (ServerMessage==string.Empty))
                            {
                                Thread.Sleep(500);
                                Logdebug("waiting for new servermessage (ServerMessage="+ServerMessage);
                            }
                            Logdebug("Sending Servermessage=" + ServerMessage);
                            ss.WriteString(ServerMessage);                   //send response messages until done
                            ServerTimeOutCounter.Abort();
                            NewServerMessage = false;
                        }
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.Error_TimeOut.ToString()) == true)
                    {
                        TimeOutValuestring = MessageFromClient.Replace(PipeCommands.Error_TimeOut.ToString(), string.Empty);
                        Logdebug("new TimeOutValuestring="+TimeOutValuestring);
                        ss.WriteString(TimeOutValuestring);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ExportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Log.Debug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ExportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ExportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ImportTvWishes.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        if (MessageFromClient.Contains("VIEWONLY=TRUE") == true)
                        {
                            ServerMessage = ImportTvWishes(true);
                        }
                        else //Email & Record Mode
                        {
                            ServerMessage = ImportTvWishes(false);
                        }

                        ss.WriteString(ServerMessage);

                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string tag = tokens[0].Replace(PipeCommands.RemoveSetting.ToString(), string.Empty);

                        
                        setting = layer.GetSetting(tag, string.Empty);
                        if (setting != null)
                        {
                            setting.Remove();
                            ServerMessage = "Setting " + tag + " removed";
                            Logdebug("Setting " + tag + " removed");
                        }
                        else
                        {
                            ServerMessage = "Setting " + tag + " could not be removed";
                            Logdebug("Eror: Setting " + tag + " could not be removed");
                 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveRecording.ToString()) == true)
                    {//string command = Main_GUI.PipeCommands.RemoveRecording.ToString() + this.IdRecording.ToString() + ":10";
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        string idRecordingString = tokens[0].Replace(PipeCommands.RemoveRecording.ToString(), string.Empty);
                        try
                        {
                            int idRecording = -1;
                            int.TryParse(idRecordingString, out idRecording);
                            Logdebug("idRecording=" + idRecording.ToString());
                            Recording myrecording = Recording.Retrieve(idRecording);
                            Logdebug("idRecording=" + myrecording.Title.ToString());
                            myrecording.Delete();
                            Logdebug("Recording deleted");
                            ServerMessage = "Recording deleted"; 
                        }
                        catch (Exception exc)
                        {
                            Logdebug("no recording found for idRecordingString = " + idRecordingString);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Recording could not be deleted check the tvserver log file"; 
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.RemoveLongSetting.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        //processing
                        string mysetting = string.Empty;
                        try
                        {
                            //cleanup work
                            mysetting = tokens[0].Replace(PipeCommands.RemoveLongSetting.ToString(), string.Empty);
                            Log.Debug("mysetting=" + mysetting);
                            for (int i = 1; i < 1000; i++)
                            {
                                setting = layer.GetSetting(mysetting + "_" + i.ToString("D3"), "_DOES_NOT_EXIST_");
                                Log.Debug("save_longsetting setting=" + setting.Value);
                                if (setting.Value == "_DOES_NOT_EXIST_")
                                {
                                    setting.Remove();
                                    break;
                                }
                                else
                                {
                                    string value = setting.Value;
                                    setting.Remove();

                                }
                            }
                            ServerMessage = "Long setting could be removed";
                        }
                        catch (Exception exc)
                        {
                            Logdebug("Longsetting could not be removed for mysetting= " + mysetting);
                            Logdebug("exception is " + exc.Message);
                            ServerMessage = "Error: Long setting could not be removed - check the tvserver log file";
                        }

                        ss.WriteString(ServerMessage);
                        TimeOutValuestring = defaultTimeOutValuestring;
                    }
#if (MPTV2)
                    else if (MessageFromClient.StartsWith(PipeCommands.WriteSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.WriteSetting.ToString(), string.Empty);
                        string[] tags = tag.Split('\n');
                        ServiceAgents.Instance.SettingServiceAgent.SaveValue(tags[0], tags[1]);

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadSetting.ToString()) == true)
                    {
                        string tag = MessageFromClient.Replace(PipeCommands.ReadSetting.ToString(), string.Empty);
                        Log.Debug("tag="+tag);
                        string value = ServiceAgents.Instance.SettingServiceAgent.GetValue(tag, string.Empty);
                        Log.Debug("value=" + value);
                        ServerMessage = value;
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllCards.ToString()) == true)
                    {
                        defaultTimeOutValuestring = TimeOutValuestring;

                        string[] tokens = MessageFromClient.Split(':');
                        if (tokens.Length > 1)
                        {
                            TimeOutValuestring = tokens[1];
                            Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring);
                        }

                        ServerMessage = string.Empty;
                        foreach (Card mycard in Card.ListAll())
                        {
                            ServerMessage += mycard.IdCard.ToString() + "\n" + mycard.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }                  
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("groupIdString="+groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("groupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAllByGroup(groupId))
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        Log.Debug("Groupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannels.ToString()) == true)//must be after ReadAllChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (Channel mychannel in Channel.ListAll())
                        {
                            ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelsByGroup.ToString()) == true)
                    {
                        string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllRadioChannelsByGroup.ToString(), string.Empty);
                        Log.Debug("radiogroupIdString=" + groupIdString);
                        int groupId = -1;
                        int.TryParse(groupIdString, out groupId);
                        Log.Debug("radiogroupId=" + groupId.ToString());

                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAllByGroup(groupId))
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        Log.Debug("radioGroupchannels=" + ServerMessage);
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannels.ToString()) == true)//must be after ReadAllRadioChannelsByGroup
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannel myradiochannel in RadioChannel.ListAll())
                        {
                            ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (ChannelGroup mygroup in ChannelGroup.ListAll())
                        {
                            ServerMessage += mygroup.Id.ToString() + "\n" + mygroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelGroups.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (RadioChannelGroup myradiogroup in RadioChannelGroup.ListAll())
                        {
                            ServerMessage += myradiogroup.Id.ToString() + "\n" + myradiogroup.GroupName + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRecordings.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Recording myrecording in Recording.ListAll())
                        {
                            ServerMessage += myrecording.IdRecording.ToString() + "\n" + myrecording.Title + "\n"+myrecording.FileName + "\n" +
                                             myrecording.IdChannel.ToString() + "\n" + myrecording.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myrecording.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ReadAllSchedules.ToString()) == true)
                    {
                        ServerMessage = string.Empty;
                        foreach (Schedule myschedule in Schedule.ListAll())
                        {
                            ServerMessage += myschedule.IdSchedule.ToString() + "\n" + myschedule.ProgramName + "\n" + 
                                             myschedule.IdChannel.ToString() + "\n" + myschedule.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) +
                                             "\n" + myschedule.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.ScheduleType.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" +
                                             myschedule.PostRecordInterval.ToString() + "\n" + myschedule.MaxAirings.ToString() + "\n" +
                                             myschedule.KeepDate.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" +
                                             myschedule.KeepMethod.ToString() + "\n" + myschedule.Priority.ToString() + "\n" +
                                             myschedule.PreRecordInterval.ToString() + "\n" + myschedule.Series.ToString() + "\n";
                        }
                        //65000 max chars                        
                        ss.WriteString(ServerMessage);
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleDelete.ToString()) == true)
                    {
                        string scheduleIdString = MessageFromClient.Replace(PipeCommands.ScheduleDelete.ToString(), string.Empty);
                        Log.Debug("scheduleIdString=" + scheduleIdString);
                        int scheduleId = -1;
                        int.TryParse(scheduleIdString, out scheduleId);
                        Log.Debug("scheduleId=" + scheduleId.ToString());
                        Schedule.Delete(scheduleId);
                        
                        //65000 max chars                        
                        ss.WriteString("Deleted");
                    }
                    else if (MessageFromClient.StartsWith(PipeCommands.ScheduleNew.ToString()) == true)
                    {
                        string schedule = MessageFromClient.Replace(PipeCommands.ScheduleNew.ToString(), string.Empty);
                        string[] scheduletags = schedule.Split('\n');

                        int idChannel = -1;
                        int.TryParse(scheduletags[1], out idChannel);
                        DateTime start = DateTime.ParseExact(scheduletags[2], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);
                        DateTime end = DateTime.ParseExact(scheduletags[3], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture);

                        Schedule myschedule = new Schedule(idChannel, scheduletags[0], start, end);
                        myschedule.Persist();
                        

                        ServerMessage = "SUCCESS";
                        ss.WriteString(ServerMessage);
                    }

#endif

                    else //Unknown command
                    {
                        Logdebug("sending response " + PipeCommands.UnknownCommand.ToString());
                        ss.WriteString(PipeCommands.UnknownCommand.ToString());
                    }
                    
                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }
                catch (Exception e)
                {
                    Log.Error("ServerThread ERROR: " + e.Message);
                }

                if (pipeServer != null)
                {
                    if (pipeServer.IsConnected)
                        pipeServer.Disconnect();

                    pipeServer.Close();
                    pipeServer.Dispose();
                    pipeServer = null;
                }
                Logdebug("Connection closed");

            }

            Logdebug("Pipe Server Thread Completed");
        }
 public void ResetAccessRule(PipeAccessRule rule)
 {
 }
示例#51
0
        static void HandleQueueThread(Object stateInfo)
        {
            // the pipe here will be handled synchronously
            NewQueueToken token = (NewQueueToken)stateInfo;
            string pipename = token.queueName;
            System.Security.Principal.SecurityIdentifier sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null);
            PipeAccessRule pac = new PipeAccessRule(sid, PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            PipeSecurity ps = new PipeSecurity();
            ps.AddAccessRule(pac);
            sid = null;

            using (NamedPipeServerStream queuePipe = new NamedPipeServerStream(pipename,
                    PipeDirection.InOut,
                    serverInstances,
                    PipeTransmissionMode.Message,
                    PipeOptions.None,
                    1024,
                    1024,
                    ps))
            {                Console.WriteLine("pipe {0} created, waiting..", token.queueName);
                // inform the main thread that the queue is on
                token.semaphore.Set();
                if (token.abort)
                    return;
                queuePipe.WaitForConnection();
                Console.WriteLine("pipe {0} connected", token.queueName);
                StreamReader reader = new StreamReader(queuePipe);
                StreamWriter writer = new StreamWriter(queuePipe);
                try
                {
                    MonitorMessage messageIn;
                    // step 1: enable counters
                    char[] data = new char[1024];
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());

                    if (messageIn.OpCode != OpCodes.ENABLE_COUNTERS_MESSAGE)
                        throw new InvalidOperationException("I was expeting an Enumerate Counters message and received " + messageIn.OpCode.ToString());
                    // counters
                    List<string> countersList = new List<string>(messageIn.Body);
                    // list of counters to enable
                    // TODO: how to get selectedCounters?
                    if (token.selectCounter != null)
                    {
                        string[] selectedCounters = token.selectCounter(token.DeviceId, countersList.ToArray());
                        writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0, selectedCounters.Select(x => countersList.IndexOf(x)).ToArray()).ToString());
                        writer.Flush();
                    }
                    else
                    {
                        // delegate not set!
                        writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0, new int[] { }).ToString());
                        writer.Flush();
                    }
                    // step 2:perf init
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GPU_PERF_INIT_MESSAGE)
                        throw new InvalidOperationException("I was expeting an Perf init message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 3: release
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    if (messageIn.OpCode != OpCodes.RELEASE_QUEUE_MESSAGE)
                        throw new InvalidOperationException("I was expeting a release message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 5: end
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GPU_PERF_RELEASE_MESSAGE)
                        throw new InvalidOperationException("I was expeting an End message and received " + messageIn.OpCode.ToString());
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                    // step 4: get counters
                    for (int i = 0; i < data.Length; i++)
                        data[i] = (char)0;
                    reader.ReadBlock(data, 0, data.Length);
                    messageIn = MonitorMessage.ParseFromString(new String(data));
                    Console.WriteLine("pipe {0} received {1}", token.queueName, messageIn.ToString());
                    if (messageIn.OpCode != OpCodes.GET_COUNTERS_MESSAGE)
                        throw new InvalidOperationException("I was expeting a Get Counters message and received " + messageIn.OpCode.ToString());
                    float[] values = messageIn.BodyAsFloatArray;
                    // TODO: send values
                    if (token.receivedValues != null)
                    {
                        token.receivedValues(token.DeviceId, values);
                    }

                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 0, 0).ToString());
                    writer.Flush();

                }
                // Catch the IOException that is raised if the pipe is broken
                // or disconnected.
                catch (IOException e)
                {
                    Console.WriteLine("ERROR: {0}", e.Message);
                }
                catch (InvalidOperationException e)
                {
                    // TODO: what is the code for invalid operation?
                    writer.Write(new MonitorMessage(OpCodes.OK_MESSAGE, 1, 1).ToString());
                    writer.Flush();
                }
                finally
                {
                    queuePipe.Close();
                }
            }
        }
示例#52
0
		public void SetAccessRule (PipeAccessRule rule)
		{
			SetAccessRule ((AccessRule)rule);
		}
示例#53
0
        public void ResetAccessRule(PipeAccessRule rule)
        {
            ArgumentNullException.ThrowIfNull(rule);

            base.ResetAccessRule(rule);
        }
示例#54
-1
        public static void Start()
        {
            if (pipeServer != null)
                throw new InvalidOperationException("Server already started. First call Close.");

            PipeSecurity ps = new PipeSecurity();
            PipeAccessRule par = new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow);
            ps.AddAccessRule(par);

            pipeServer = new NamedPipeServerStream(SERVERNAME,
                PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 4096, 4096, ps);

            Log.Write("NamedPipeServerStream object created, waiting for client connection...");
            pipeServer.BeginWaitForConnection(onReceive, new object());
        }