Inheritance: System.Security.AccessControl.NativeObjectSecurity
Exemplo n.º 1
2
        static NamedPipeServerStream CreateServerStream()
        {
            var user = WindowsIdentity.GetCurrent().User;
            var security = new PipeSecurity();
            security.AddAccessRule( new PipeAccessRule( user, PipeAccessRights.FullControl, AccessControlType.Allow ) );
            security.SetOwner( user );
            security.SetGroup( user );

            IncrementServers();
            try
            {
                return new NamedPipeServerStream(
                    ProtocolConstants.PipeName,
                    PipeDirection.InOut,
                    20,
                    PipeTransmissionMode.Byte,
                    PipeOptions.Asynchronous,
                    CommandLineLength,
                    CommandLineLength,
                    security );
            }
            catch ( Exception )
            {
                DecrementServers();
                throw;
            }
        }
Exemplo n.º 2
0
        public void Run()
        {
            while (true)
            {
                var security = new PipeSecurity();
                security.SetAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.FullControl, AccessControlType.Allow));

                using (pipeServer = new NamedPipeServerStream(
                    Config.PipeName,
                    PipeDirection.InOut,
                    NamedPipeServerStream.MaxAllowedServerInstances,
                    PipeTransmissionMode.Message,
                    PipeOptions.None,
                    Config.BufferSize, Config.BufferSize,
                    security,
                    HandleInheritability.None
                    ))
                {
                    try
                    {
                        Console.Write("Waiting...");
                        pipeServer.WaitForConnection();
                        Console.WriteLine("...Connected!");

                        if (THROTTLE_TIMER)
                        {
                            timer = new Timer
                            {
                                Interval = THROTTLE_DELAY,
                            };
                            timer.Elapsed += (sender, args) => SendMessage();
                            timer.Start();

                            while(pipeServer.IsConnected)Thread.Sleep(1);
                            timer.Stop();
                        }
                        else
                        {
                            while (true) SendMessage();
                        }
                    }
                    catch(Exception ex)
                    {
                        Console.WriteLine("Error: " + ex.Message);
                    }
                    finally
                    {
                        if (pipeServer != null)
                        {
                            Console.WriteLine("Cleaning up pipe server...");
                            pipeServer.Disconnect();
                            pipeServer.Close();
                            pipeServer = null;
                        }
                    }

                }

            }
        }
 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);
 }
Exemplo n.º 4
0
 public NamedPipesReadQueue()
 {
     var ps = new PipeSecurity();
     ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
     _serverStream = new NamedPipeServerStream(Whitebox.Connector.Constants.PipeName, PipeDirection.In, MaxInstances,
                                               PipeTransmissionMode.Message, PipeOptions.None, MaxMessage * MaxMessagesInBuffer,
                                               MaxMessage, ps);
 }
Exemplo n.º 5
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);
                }
            }
        }
Exemplo n.º 6
0
        private static NamedPipeServerStream CreateNamedPipeServerStream(string pipeName) {
            var pipeSecurity = new PipeSecurity();
            pipeSecurity.AddAccessRule(
                new PipeAccessRule(
                    new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
                    PipeAccessRights.ReadWrite, AccessControlType.Allow));

            return new NamedPipeServerStream(pipeName,
                PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.None,
                4096, 4096, pipeSecurity);
        }
 public ServerWorker()
 {
     connected = false;
     disconnected = false;
     PipeSecurity ps = new PipeSecurity();
     ps.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
     ps.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow));
     pipeServer = new NamedPipeServerStream("testpipe", PipeDirection.InOut, MAXCLIENTS, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 5000, 5000, ps);
     thread = new Thread(ThreadRun);
     thread.Start();
 }
Exemplo n.º 8
0
        public MyServiceTasks()
        {
            SetupEventLog();

            PipeSecurity ps = new PipeSecurity();
            ps.AddAccessRule(new PipeAccessRule("Users", PipeAccessRights.ReadWrite | PipeAccessRights.CreateNewInstance, AccessControlType.Allow));
            ps.AddAccessRule(new PipeAccessRule("CREATOR OWNER", PipeAccessRights.FullControl, AccessControlType.Allow));
            ps.AddAccessRule(new PipeAccessRule("SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));

            pipe = new NamedPipeServerStream("MyServicePipe", PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous, 1024, 1024, ps);
            InterProcessSecurity.SetLowIntegrityLevel(pipe.SafePipeHandle);
        }
Exemplo n.º 9
0
 public NpListener(string pipeName, int maxConnections = 254, ILog log = null, IStats stats = null)
 {
     _log = log ?? _log;
     _stats = stats ?? _stats;
     if (maxConnections > 254) maxConnections = 254;
     _maxConnections = maxConnections;
     this.PipeName = pipeName;
     _pipeSecurity = new PipeSecurity();
     _pipeSecurity.AddAccessRule(new PipeAccessRule(@"Everyone", PipeAccessRights.ReadWrite, AccessControlType.Allow));
     _pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow));
     _pipeSecurity.AddAccessRule(new PipeAccessRule(@"SYSTEM", PipeAccessRights.FullControl, AccessControlType.Allow));
 }
Exemplo n.º 10
0
        public void Start(string pipeName)
        {
            _pipeName = pipeName;

            var security = new PipeSecurity();
            var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
            security.AddAccessRule(new PipeAccessRule(sid, PipeAccessRights.FullControl, AccessControlType.Allow));
            _pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.In, 254,
                PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, security);
            _pipeServer.BeginWaitForConnection(WaitForConnectionCallBack, _pipeServer);
            _logger.Info("Opened named pipe '{0}'", _pipeName);
            _closed = false;
        }
Exemplo n.º 11
0
 PipeSecurity createPipeSecurity()
 {
     var pipeSecurity = new PipeSecurity();
     pipeSecurity.AddAccessRule(new PipeAccessRule(
         new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null),
         PipeAccessRights.ReadWrite,
         AccessControlType.Allow));
     pipeSecurity.AddAccessRule(new PipeAccessRule(
         WindowsIdentity.GetCurrent().Owner,
         PipeAccessRights.FullControl,
         AccessControlType.Allow));
     return pipeSecurity;
 }
Exemplo n.º 12
0
		public AnonymousPipeServerStream (PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
			: base (direction, bufferSize)
		{
			if (direction == PipeDirection.InOut)
				throw new NotSupportedException ("Anonymous pipe direction can only be either in or out.");

			if (IsWindows)
				impl = new Win32AnonymousPipeServer (this, direction, inheritability, bufferSize, pipeSecurity);
			else
				impl = new UnixAnonymousPipeServer (this, direction, inheritability, bufferSize);

			InitializeHandle (impl.Handle, false, false);
			IsConnected = true;
		}
Exemplo n.º 13
0
		public NamedPipeServerStream (string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
			: base (direction, transmissionMode, outBufferSize)
		{
			if (pipeSecurity != null)
				throw ThrowACLException ();
			var rights = ToAccessRights (direction) | additionalAccessRights;
			// FIXME: reject some rights declarations (for ACL).

			if (IsWindows)
				impl = new Win32NamedPipeServer (this, pipeName, maxNumberOfServerInstances, transmissionMode, rights, options, inBufferSize, outBufferSize, inheritability);
			else
				impl = new UnixNamedPipeServer (this, pipeName, maxNumberOfServerInstances, transmissionMode, rights, options, inBufferSize, outBufferSize, inheritability);

			InitializeHandle (impl.Handle, false, (options & PipeOptions.Asynchronous) != PipeOptions.None);
		}
Exemplo n.º 14
0
        public Server()
        {
            var security = new PipeSecurity();
            security.SetAccessRule(new PipeAccessRule("Administrators", PipeAccessRights.FullControl, AccessControlType.Allow)); // TODO: other options?

            pipeServer = new NamedPipeServerStream(
                Config.PipeName,
                PipeDirection.InOut, // TODO: single direction, benefits?
                NamedPipeServerStream.MaxAllowedServerInstances,
                PipeTransmissionMode.Message, // TODO: investigate other options
                PipeOptions.None, // TODO: Async and writethrough, benefits?
                Config.BufferSize, Config.BufferSize,
                security,
                HandleInheritability.None
            );
        }
Exemplo n.º 15
0
        public static void SetAccessControl(this PipeStream stream, PipeSecurity pipeSecurity)
        {
            ArgumentNullException.ThrowIfNull(pipeSecurity);

            // Checks that State != WaitingToConnect and State != Closed
            var handle = stream.SafePipeHandle;

            // Checks that State != Broken
            if (stream is NamedPipeClientStream && !stream.IsConnected)
            {
                throw new IOException(SR.IO_IO_PipeBroken);
            }

            // PipeState must be either Disconnected or Connected
            pipeSecurity.Persist(handle);
        }
Exemplo n.º 16
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();
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            argCallbacks = new Dictionary<string, ArgCallback>();
            argCallbacks.Add("--list-mods", Command.ListMods);
            argCallbacks.Add("-l", Command.ListMods);
            argCallbacks.Add("--mod-info", Command.ListModInfo);
            argCallbacks.Add("-i", Command.ListModInfo);
            argCallbacks.Add("--download-url", Command.DownloadUrl);
            argCallbacks.Add("--extract-zip", Command.ExtractZip);
            argCallbacks.Add("--install-ra-packages", Command.InstallRAPackages);
            argCallbacks.Add("--install-cnc-packages", Command.InstallCncPackages);
            argCallbacks.Add("--settings-value", Command.Settings);

            if (args.Length == 0) { PrintUsage(); return; }
            var arg = SplitArgs(args[0]);

            bool piping = false;
            if (args.Length > 1 && SplitArgs(args[1]).Key == "--pipe")
            {
                piping = true;
                string pipename = SplitArgs(args[1]).Value;
                NamedPipeServerStream pipe;
                var id = WindowsIdentity.GetCurrent();
                var principal = new WindowsPrincipal(id);
                if (principal.IsInRole(WindowsBuiltInRole.Administrator))
                {
                    var ps = new PipeSecurity();
                    ps.AddAccessRule(new PipeAccessRule("EVERYONE", (PipeAccessRights)2032031, AccessControlType.Allow));
                    pipe = new NamedPipeServerStream(pipename, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 1024*1024, 1024*1024, ps);
                }
                else
                    pipe = new NamedPipeServerStream(pipename, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 1024*1024,1024*1024,null);

                pipe.WaitForConnection();
                Console.SetOut(new StreamWriter(pipe) { AutoFlush = true });
            }

            ArgCallback callback;
            if (argCallbacks.TryGetValue(arg.Key, out callback))
                callback(arg.Value);
            else
                PrintUsage();

            if (piping)
                Console.Out.Close();
        }
Exemplo n.º 18
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);
     }
 }
Exemplo n.º 19
0
        public RpcPipeServerChannel(string pipeName, int instanceCount)
        {
            _pipeName = pipeName;
            _pipeServers = new NamedPipeServerStream[instanceCount];
            for (int i = 0; i < instanceCount; i++) {
                //
                // TODO: Add PipeSecurity
                PipeSecurity security = new PipeSecurity();
                // new PipeAccessRule(.

                security.AddAccessRule(new PipeAccessRule(new NTAccount("Everyone"), PipeAccessRights.FullControl, AccessControlType.Allow));

                _pipeServers[i] = new NamedPipeServerStream(pipeName, PipeDirection.InOut,
                    instanceCount, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 0, 0,
                    security);

            }
        }
Exemplo n.º 20
0
        public static void SetAccessControl(this PipeStream stream, PipeSecurity pipeSecurity)
        {
            // PipeState can not be Closed and the Handle can not be null or closed
            if (pipeSecurity == null)
            {
                throw new ArgumentNullException(nameof(pipeSecurity));
            }

            var handle = stream.SafePipeHandle; // A non-null, open handle implies a non-closed PipeState.

            // NamedPipeClientStream: PipeState can not be WaitingToConnect or Broken. WaitingToConnect is covered by the SafePipeHandle check.
            if (stream is NamedPipeClientStream && !stream.IsConnected) // Pipe could also be WaitingToConnect, Broken, Disconnected, or Closed.
            {
                throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
            }

            pipeSecurity.Persist(handle);
        }
Exemplo n.º 21
0
        public static void SetAccessControl(this PipeStream stream, PipeSecurity pipeSecurity)
        {
            // PipeState can not be Closed and the Handle can not be null or closed
            if (pipeSecurity == null)
            {
                throw new ArgumentNullException("pipeSecurity");
            }

            var handle = stream.SafePipeHandle; // A non-null, open handle implies a non-closed PipeState.

            // NamedPipeClientStream: PipeState can not be WaitingToConnect or Broken. WaitingToConnect is covered by the SafePipeHandle check.
            if (stream is NamedPipeClientStream && !stream.IsConnected) // Pipe could also be WaitingToConnect, Broken, Disconnected, or Closed.
            {
                throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
            }

            pipeSecurity.Persist(handle);
        }
Exemplo n.º 22
0
        internal void Start()
        {
            // setting up pipeServer
            PipeSecurity pipeSec = new PipeSecurity();
            pipeSec.SetAccessRule(new PipeAccessRule("Everyone", PipeAccessRights.ReadWrite, System.Security.AccessControl.AccessControlType.Allow));
            pipeServer = new NamedPipeServerStream(
                "HKHRATP2\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + System.Diagnostics.Process.GetCurrentProcess().Id,
                PipeDirection.InOut,
                1,
                PipeTransmissionMode.Message,
                PipeOptions.Asynchronous,
                4096,
                4096,
                pipeSec,
                System.IO.HandleInheritability.None
            );

            StartListening();
        }
Exemplo n.º 23
0
        // .ctor without handle - create new
        public unsafe Win32NamedPipeServer(NamedPipeServerStream owner, string pipeName, int maxNumberOfServerInstances,
                                           PipeTransmissionMode transmissionMode, PipeAccessRights rights,
                                           PipeOptions options, int inBufferSize, int outBufferSize,
                                           PipeSecurity pipeSecurity, HandleInheritability inheritability)
        {
            string name = String.Format("\\\\.\\pipe\\{0}", pipeName);

            uint openMode;

            openMode = (uint)rights | (uint)options;             // Enum values match Win32 flags exactly.

            int pipeMode = 0;

            if ((owner.TransmissionMode & PipeTransmissionMode.Message) != 0)
            {
                pipeMode |= 4;
            }
            //if ((readTransmissionMode & PipeTransmissionMode.Message) != 0)
            //	pipeMode |= 2;
            if ((options & PipeOptions.Asynchronous) != 0)
            {
                pipeMode |= 1;
            }

            byte[] securityDescriptor = null;
            if (pipeSecurity != null)
                securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm();

            fixed(byte *securityDescriptorPtr = securityDescriptor)
            {
                // FIXME: is nDefaultTimeout = 0 ok?
                var att = new SecurityAttributes(inheritability, (IntPtr)securityDescriptorPtr);
                var ret = Win32Marshal.CreateNamedPipe(name, openMode, pipeMode, maxNumberOfServerInstances,
                                                       outBufferSize, inBufferSize, 0, ref att, IntPtr.Zero);

                if (ret == new IntPtr(-1L))
                {
                    throw Win32PipeError.GetException();
                }
                handle = new SafePipeHandle(ret, true);
            }
        }
        private void ValidateRemotePipeUser()
        {
            if (!IsCurrentUserOnly)
            {
                return;
            }

            PipeSecurity      accessControl  = this.GetAccessControl();
            IdentityReference?remoteOwnerSid = accessControl.GetOwner(typeof(SecurityIdentifier));

            using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent())
            {
                SecurityIdentifier?currentUserSid = currentIdentity.Owner;
                if (remoteOwnerSid != currentUserSid)
                {
                    State = PipeState.Closed;
                    throw new UnauthorizedAccessException(SR.UnauthorizedAccess_NotOwnedByCurrentUser);
                }
            }
        }
Exemplo n.º 25
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);
 }
Exemplo n.º 26
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);
			}
		}
Exemplo n.º 27
0
        public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
            : base(direction, bufferSize) {
            if (direction == PipeDirection.InOut) {
                throw new NotSupportedException(SR.GetString(SR.NotSupported_AnonymousPipeUnidirectional));
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
                throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
            }

            Object pinningHandle;
            UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out pinningHandle);

            try {
                Create(direction, secAttrs, bufferSize);
            }
            finally {
                if (pinningHandle != null) {
                    GCHandle pinHandle = (GCHandle)pinningHandle;
                    pinHandle.Free();
                }
            }
        }
        internal NamedPipeServerStream(
            string pipeName,
            PipeDirection direction,
            int maxNumberOfServerInstances,
            PipeTransmissionMode transmissionMode,
            PipeOptions options,
            int inBufferSize,
            int outBufferSize,
            PipeSecurity pipeSecurity,
            HandleInheritability inheritability     = HandleInheritability.None,
            PipeAccessRights additionalAccessRights = default)
            : base(direction, transmissionMode, outBufferSize)
        {
            ValidateParameters(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability);

            if (pipeSecurity != null && IsCurrentUserOnly)
            {
                throw new ArgumentException(SR.NotSupported_PipeSecurityIsCurrentUserOnly, nameof(pipeSecurity));
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, pipeSecurity, inheritability, additionalAccessRights);
        }
 public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity) : base(direction, bufferSize)
 {
     object obj2;
     if (direction == PipeDirection.InOut)
     {
         throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeUnidirectional"));
     }
     if ((inheritability < HandleInheritability.None) || (inheritability > HandleInheritability.Inheritable))
     {
         throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
     }
     Microsoft.Win32.UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out obj2);
     try
     {
         this.Create(direction, secAttrs, bufferSize);
     }
     finally
     {
         if (obj2 != null)
         {
             ((GCHandle) obj2).Free();
         }
     }
 }
Exemplo n.º 30
0
 public void SetAccessControl(PipeSecurity pipeSecurity)
 {
     throw new NotImplementedException();
 }
        // Creates the anonymous pipe. This overload is used in Mono to implement public constructors.
        private void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
        {
            Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut");
            Debug.Assert(bufferSize >= 0, "bufferSize is negative");

            bool           bSuccess;
            SafePipeHandle serverHandle;
            SafePipeHandle newServerHandle;

            // Create the two pipe handles that make up the anonymous pipe.
            GCHandle pinningHandle = default;

            try
            {
                Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);

                if (direction == PipeDirection.In)
                {
                    bSuccess = Interop.Kernel32.CreatePipe(out serverHandle, out _clientHandle, ref secAttrs, bufferSize);
                }
                else
                {
                    bSuccess = Interop.Kernel32.CreatePipe(out _clientHandle, out serverHandle, ref secAttrs, bufferSize);
                }
            }
            finally
            {
                if (pinningHandle.IsAllocated)
                {
                    pinningHandle.Free();
                }
            }

            if (!bSuccess)
            {
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            // Duplicate the server handle to make it not inheritable.  Note: We need to do this so that the child
            // process doesn't end up getting another copy of the server handle.  If it were to get a copy, the
            // OS wouldn't be able to inform the child that the server has closed its handle because it will see
            // that there is still one server handle that is open.
            bSuccess = Interop.Kernel32.DuplicateHandle(Interop.Kernel32.GetCurrentProcess(), serverHandle, Interop.Kernel32.GetCurrentProcess(),
                                                        out newServerHandle, 0, false, Interop.Kernel32.HandleOptions.DUPLICATE_SAME_ACCESS);

            if (!bSuccess)
            {
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            // Close the inheritable server handle.
            serverHandle.Dispose();

            InitializeHandle(newServerHandle, false, false);

            State = PipeState.Connected;
        }
Exemplo n.º 32
0
 /// <summary>
 /// Constructs a new <c>NamedPipeServer</c> object that listens for client connections on the given <paramref name="pipeName"/>.
 /// </summary>
 /// <param name="pipeName">Name of the pipe to listen on</param>
 /// <param name="bufferSize">Size of input and output buffer</param>
 /// <param name="security">And object that determine the access control and audit security for the pipe</param>
 public NamedPipeServer(string pipeName, int bufferSize, PipeSecurity security)
     : base(pipeName, bufferSize, security)
 {
 }
Exemplo n.º 33
0
 public static void SetAccessControl(PipeStream stream, PipeSecurity pipeSecurity)
 {
     stream.SetAccessControl(pipeSecurity);
 }
Exemplo n.º 34
0
        public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights) : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(System.SR.GetString("Argument_NeedNonemptyPipeName"));
            }
            if ((options & ~(PipeOptions.Asynchronous | PipeOptions.WriteThrough)) != PipeOptions.None)
            {
                throw new ArgumentOutOfRangeException("options", System.SR.GetString("ArgumentOutOfRange_OptionsInvalid"));
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("inBufferSize", System.SR.GetString("ArgumentOutOfRange_NeedNonNegNum"));
            }
            if (((maxNumberOfServerInstances < 1) || (maxNumberOfServerInstances > 0xfe)) && (maxNumberOfServerInstances != -1))
            {
                throw new ArgumentOutOfRangeException("maxNumberOfServerInstances", System.SR.GetString("ArgumentOutOfRange_MaxNumServerInstances"));
            }
            if ((inheritability < HandleInheritability.None) || (inheritability > HandleInheritability.Inheritable))
            {
                throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
            }
            if ((additionalAccessRights & ~(PipeAccessRights.AccessSystemSecurity | PipeAccessRights.TakeOwnership | PipeAccessRights.ChangePermissions)) != 0)
            {
                throw new ArgumentOutOfRangeException("additionalAccessRights", System.SR.GetString("ArgumentOutOfRange_AdditionalAccessLimited"));
            }
            if (Environment.OSVersion.Platform == PlatformID.Win32Windows)
            {
                throw new PlatformNotSupportedException(System.SR.GetString("PlatformNotSupported_NamedPipeServers"));
            }
            string fullPath = Path.GetFullPath(@"\\.\pipe\" + pipeName);

            if (string.Compare(fullPath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase) == 0)
            {
                throw new ArgumentOutOfRangeException("pipeName", System.SR.GetString("ArgumentOutOfRange_AnonymousReserved"));
            }
            object pinningHandle = null;

            Microsoft.Win32.UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out pinningHandle);
            try
            {
                this.Create(fullPath, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, additionalAccessRights, secAttrs);
            }
            finally
            {
                if (pinningHandle != null)
                {
                    ((GCHandle)pinningHandle).Free();
                }
            }
        }
Exemplo n.º 35
0
 /// <summary>
 /// Constructs a new <c>NamedPipeServer</c> object that listens for client connections on the given <paramref name="pipeName"/>.
 /// </summary>
 /// <param name="pipeName">Name of the pipe to listen on</param>
 /// <param name="bufferSize">Size of input and output buffer</param>
 /// <param name="security">And object that determine the access control and audit security for the pipe</param>
 public Server(string pipeName, int bufferSize, PipeSecurity security)
 {
     _pipeName   = pipeName;
     _bufferSize = bufferSize;
     _security   = security;
 }
Exemplo n.º 36
0
 public static void SetAccessControl(this PipeStream stream, PipeSecurity pipeSecurity !!)
 {
        public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity) : base(direction, bufferSize)
        {
            object obj2;

            if (direction == PipeDirection.InOut)
            {
                throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeUnidirectional"));
            }
            if ((inheritability < HandleInheritability.None) || (inheritability > HandleInheritability.Inheritable))
            {
                throw new ArgumentOutOfRangeException("inheritability", System.SR.GetString("ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable"));
            }
            Microsoft.Win32.UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out obj2);
            try
            {
                this.Create(direction, secAttrs, bufferSize);
            }
            finally
            {
                if (obj2 != null)
                {
                    ((GCHandle)obj2).Free();
                }
            }
        }
Exemplo n.º 38
0
		public void SetAccessControl (PipeSecurity pipeSecurity)
		{
			throw ThrowACLException ();
		}
Exemplo n.º 39
0
 public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
     : base(PipeDirection.In, 0)
 {
     throw new PlatformNotSupportedException();
 }
Exemplo n.º 40
0
        public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeSecurity != null)
            {
                throw ThrowACLException();
            }
            var rights = ToAccessRights(direction) | additionalAccessRights;

            // FIXME: reject some rights declarations (for ACL).

            if (IsWindows)
            {
                impl = new Win32NamedPipeServer(this, pipeName, maxNumberOfServerInstances, transmissionMode, rights, options, inBufferSize, outBufferSize, inheritability);
            }
            else
            {
                impl = new UnixNamedPipeServer(this, pipeName, maxNumberOfServerInstances, transmissionMode, rights, options, inBufferSize, outBufferSize, inheritability);
            }

            InitializeHandle(impl.Handle, false, (options & PipeOptions.Asynchronous) != PipeOptions.None);
        }
Exemplo n.º 41
0
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
     : this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability)
 {
     if (additionalAccessRights != 0 || pipeSecurity != null)
     {
         throw new PlatformNotSupportedException();
     }
 }
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights) : base(default(PipeDirection), default(int))
 {
     Contract.Ensures(1 <= pipeName.Length);
 }
Exemplo n.º 43
0
        public AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
            : base(direction, bufferSize)
        {
            if (direction == PipeDirection.InOut)
            {
                throw new NotSupportedException("Anonymous pipe direction can only be either in or out.");
            }

            if (IsWindows)
            {
                impl = new Win32AnonymousPipeServer(this, direction, inheritability, bufferSize, pipeSecurity);
            }
            else
            {
                impl = new UnixAnonymousPipeServer(this, direction, inheritability, bufferSize);
            }

            InitializeHandle(impl.Handle, false, false);
            IsConnected = true;
        }
Exemplo n.º 44
0
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity)
     : base(PipeDirection.InOut, -1)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 45
0
 public static void SetAccessControl(System.IO.Pipes.PipeStream stream, System.IO.Pipes.PipeSecurity pipeSecurity)
 {
 }
Exemplo n.º 46
0
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
     : base(PipeDirection.InOut, -1)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 47
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");
        }
Exemplo n.º 48
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();
                }
            }
        }
Exemplo n.º 49
0
 public void SetAccessControl(PipeSecurity pipeSecurity)
 {
     throw ThrowACLException();
 }
Exemplo n.º 50
0
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability)
     : base(PipeDirection.In, 0)
 {
     throw new PlatformNotSupportedException();
 }
Exemplo n.º 51
0
        /// <summary>
        ///   Mains this instance.
        /// </summary>
        /// <remarks>
        /// </remarks>
        private Task Main()
        {
            if (IsRunning) {
                return _engineTask;
            }
            Signals.EngineStartupStatus = 0;

            if (!IsInteractive) {
                EngineServiceManager.EnsureServiceAclsCorrect();
            }

            var npmi = PackageManagerImpl.Instance;

            _cancellationTokenSource = new CancellationTokenSource();
            _isRunning = true;

            Signals.StartingUp = true;
            // make sure coapp is properly set up.
            Task.Factory.StartNew(() => {
                try {
                    Logger.Warning("CoApp Startup Beginning------------------------------------------");

                    // this ensures that composition rules are run for toolkit.
                    Signals.EngineStartupStatus = 5;
                    EnsureCanonicalFoldersArePresent();
                    Signals.EngineStartupStatus = 10;
                    var v = Package.GetCurrentPackageVersion(CanonicalName.CoAppItself);
                    if( v > 0 ) {
                        var p = InstalledPackageFeed.Instance.FindPackages(CanonicalName.CoAppItself).HighestPackages().FirstOrDefault();
                        if( p != null ) {
                            p.DoPackageComposition();
                        }
                    }
                    Signals.EngineStartupStatus = 95;
                    Logger.Warning("CoApp Version : " + v);

                    /*
                     * what can we do if the right version isn't here?
                     *
                    FourPartVersion thisVersion = Assembly.GetExecutingAssembly().Version();
                    if( thisVersion > v ) {

                    }
                     * */

                    // Completes startup.

                    Signals.EngineStartupStatus = 100;
                    Signals.Available = true;
                    Logger.Warning("CoApp Startup Finished------------------------------------------");
                } catch (Exception e) {
                    Logger.Error(e);
                    RequestStop();
                }
            });

            _engineTask = Task.Factory.StartNew(() => {
                _pipeSecurity = new PipeSecurity();
                _pipeSecurity.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
                _pipeSecurity.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().Owner, PipeAccessRights.FullControl, AccessControlType.Allow));

                // start a few listeners by default--each listener will also spawn a new empty one.
                StartListener();
                StartListener();
            }, _cancellationTokenSource.Token).AutoManage();

            _engineTask = _engineTask.ContinueWith(antecedent => {
                RequestStop();
                // ensure the sessions are all getting closed.
                Session.CancelAll();
                _engineTask = null;
            }, TaskContinuationOptions.AttachedToParent).AutoManage();
            return _engineTask;
        }
Exemplo n.º 52
0
        public static NamedPipeServerStream CreateAndConnectPipe(string pipeName, int bufferSize, PipeSecurity security)
        {
            var pipe = CreatePipe(pipeName, bufferSize, security);

            pipe.WaitForConnection();

            return(pipe);
        }
Exemplo n.º 53
0
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity, HandleInheritability inheritability) : this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, pipeSecurity, inheritability, 0)
 {
 }
Exemplo n.º 54
0
 public static NamedPipeServerStream CreatePipe(string pipeName, int bufferSize, PipeSecurity security)
 {
     return(new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous | PipeOptions.WriteThrough, bufferSize, bufferSize, security));
 }
Exemplo n.º 55
0
        internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability, PipeSecurity pipeSecurity, ref GCHandle pinningHandle)
        {
            Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES);
            secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES);

            if ((inheritability & HandleInheritability.Inheritable) != 0)
            {
                secAttrs.bInheritHandle = Interop.BOOL.TRUE;
            }

            if (pipeSecurity != null)
            {
                byte[] securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm();
                pinningHandle = GCHandle.Alloc(securityDescriptor, GCHandleType.Pinned);
                fixed(byte *pSecurityDescriptor = securityDescriptor)
                {
                    secAttrs.lpSecurityDescriptor = (IntPtr)pSecurityDescriptor;
                }
            }

            return(secAttrs);
        }
        internal AnonymousPipeServerStream(PipeDirection direction, HandleInheritability inheritability, int bufferSize, PipeSecurity pipeSecurity)
            : base(direction, bufferSize)
        {
            if (direction == PipeDirection.InOut)
            {
                throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional);
            }

            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(direction, inheritability, bufferSize, pipeSecurity);
        }
Exemplo n.º 57
0
        public void Start(Boolean isClient)
        {
            if (isClient) {
                NamedPipeClientStream client = new NamedPipeClientStream(".", _pipeName, PipeDirection.InOut, PipeOptions.Asynchronous);
                client.Connect(10000); // 10 second timeout.

                pipe = client;
                isReady = true;
            } else {
                // Grant read/write access to everyone, so the pipe can be written to from impersonated processes
                PipeSecurity pipeSecurity = new PipeSecurity();
                pipeSecurity.SetAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), PipeAccessRights.ReadWrite, AccessControlType.Allow));
                NamedPipeServerStream server = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous, 4096, 4096, pipeSecurity);
                server.BeginWaitForConnection(new AsyncCallback(WaitForConnection), server);
            }
        }
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize, PipeSecurity pipeSecurity) : base(default(PipeDirection), default(int))
 {
     Contract.Ensures(1 <= pipeName.Length);
 }
Exemplo n.º 59
0
 private void ServerMain()
 {
     while (pipeServer.ThreadState != System.Threading.ThreadState.AbortRequested)
        {
     PipeSecurity security = new PipeSecurity();
     security.AddAccessRule(new PipeAccessRule(
      WindowsIdentity.GetCurrent().User,
      PipeAccessRights.FullControl, AccessControlType.Allow));
     using (NamedPipeServerStream server = new NamedPipeServerStream(instanceID,
      PipeDirection.In, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous,
      128, 128, security))
     {
      ServerAsyncInfo async = new ServerAsyncInfo();
      async.Server = server;
      async.WaitHandle = new AutoResetEvent(false);
      IAsyncResult result = server.BeginWaitForConnection(WaitForConnection, async);
      if (result.AsyncWaitHandle.WaitOne())
       async.WaitHandle.WaitOne();
     }
        }
 }
Exemplo n.º 60
-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());
        }