Example #1
0
        private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                                      PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                                      HandleInheritability inheritability)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            // win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited)
            // through the MaxAllowedServerInstances constant. This is consistent e.g. with -1 as infinite timeout, etc
            if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances))
            {
                throw new ArgumentOutOfRangeException("maxNumberOfServerInstances", SR.ArgumentOutOfRange_MaxNumServerInstances);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
                   options, inBufferSize, outBufferSize, inheritability);
        }
        public static void ServerNotConnectedThrows()
        {
            using (NamedPipeServerStream server = new NamedPipeServerStream("tempnotconnected", PipeDirection.InOut, 1))
            {
                // doesn't throw exceptions
                PipeTransmissionMode transmitMode = server.TransmissionMode;
                Assert.Throws <ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ||
                    RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    Assert.Equal(0, server.InBufferSize);
                    Assert.Equal(0, server.OutBufferSize);
                }
                else
                {
                    Assert.Throws <PlatformNotSupportedException>(() => server.InBufferSize);
                    Assert.Throws <PlatformNotSupportedException>(() => server.OutBufferSize);
                }
                PipeTransmissionMode readMode = server.ReadMode;
                server.ReadMode = PipeTransmissionMode.Byte;

                Assert.Throws <InvalidOperationException>(() => server.WriteByte(5));
                Assert.Throws <InvalidOperationException>(() => server.ReadByte());
                Assert.Throws <InvalidOperationException>(() => server.Disconnect());    // disconnect when not connected
                Assert.Throws <InvalidOperationException>(() => server.IsMessageComplete);
            }
        }
Example #3
0
        private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                                      PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                                      HandleInheritability inheritability)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            ValidateMaxNumberOfServerInstances(maxNumberOfServerInstances);
            // inheritability will always be None since this private constructor is only called from other constructors from which
            // inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core
            // doesnt.
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
                   options, inBufferSize, outBufferSize, inheritability);
        }
        public void OperationsOnUnconnectedServer()
        {
            (NamedPipeServerStream server, NamedPipeClientStream client) = CreateServerAndClientStreams();
            using StreamPair streams = (server, client);

            // doesn't throw exceptions
            PipeTransmissionMode transmitMode = server.TransmissionMode;

            Assert.Throws <ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);

            var buffer = new byte[4];

            foreach ((Stream writeable, Stream readable) in GetReadWritePairs(streams))
            {
                if (ReferenceEquals(writeable, server))
                {
                    Assert.Equal(0, server.OutBufferSize);
                    Assert.Throws <InvalidOperationException>(() => server.Write(buffer, 0, buffer.Length));
                    Assert.Throws <InvalidOperationException>(() => server.WriteByte(5));
                    Assert.Throws <InvalidOperationException>(() => { server.WriteAsync(buffer, 0, buffer.Length); });
                }
                else
                {
                    Assert.Equal(0, server.InBufferSize);
                    PipeTransmissionMode readMode = server.ReadMode;
                    Assert.Throws <InvalidOperationException>(() => server.Read(buffer, 0, buffer.Length));
                    Assert.Throws <InvalidOperationException>(() => server.ReadByte());
                    Assert.Throws <InvalidOperationException>(() => { server.ReadAsync(buffer, 0, buffer.Length); });
                }
            }

            Assert.Throws <InvalidOperationException>(() => server.Disconnect());    // disconnect when not connected
            Assert.Throws <InvalidOperationException>(() => server.IsMessageComplete);
        }
Example #5
0
        private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
        {
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");

            // always defaults to this until overridden
            _readMode         = transmissionMode;
            _transmissionMode = transmissionMode;

            _pipeDirection = direction;

            if ((_pipeDirection & PipeDirection.In) != 0)
            {
                _canRead = true;
            }
            if ((_pipeDirection & PipeDirection.Out) != 0)
            {
                _canWrite = true;
            }

            _outBufferSize = outBufferSize;

            // This should always default to true
            _isMessageComplete = true;

            _state = PipeState.WaitingToConnect;
        }
Example #6
0
        private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
        {
            Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
            Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");

            // always defaults to this until overridden
            _readMode = transmissionMode;
            _transmissionMode = transmissionMode;

            _pipeDirection = direction;

            if ((_pipeDirection & PipeDirection.In) != 0)
            {
                _canRead = true;
            }
            if ((_pipeDirection & PipeDirection.Out) != 0)
            {
                _canWrite = true;
            }

            _outBufferSize = outBufferSize;

            // This should always default to true
            _isMessageComplete = true;

            _state = PipeState.WaitingToConnect;
            _streamAsyncHelper = new StreamAsyncHelper(this);
        }
 public void Create_InvalidTransmissionMode(PipeTransmissionMode transmissionMode)
 {
     Assert.Throws <ArgumentOutOfRangeException>("transmissionMode", () =>
     {
         CreateAndVerifyNamedPipe(GetRandomName(), GetBasicPipeSecurity(), transmissionMode: transmissionMode).Dispose();
     });
 }
Example #8
0
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            HandleInheritability inheritability)
        {
            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 == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            if (transmissionMode == PipeTransmissionMode.Message)
            {
                throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
            }

            // NOTE: We don't have a good way to enforce maxNumberOfServerInstances, and don't currently try.
            // It's a Windows-specific concept.

            _path           = GetPipePath(".", pipeName);
            _direction      = direction;
            _options        = options;
            _inBufferSize   = inBufferSize;
            _outBufferSize  = outBufferSize;
            _inheritability = inheritability;
        }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            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 == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            if (transmissionMode == PipeTransmissionMode.Message)
            {
                throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
            }

            // NOTE: We don't have a good way to enforce maxNumberOfServerInstances, and don't currently try.
            // It's a Windows-specific concept.

            _path = GetPipePath(".", pipeName);
            _direction = direction;
            _options = options;
            _inBufferSize = inBufferSize;
            _outBufferSize = outBufferSize;
            _inheritability = inheritability;
        }
        private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            // win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited)
            // through the MaxAllowedServerInstances constant. This is consistent e.g. with -1 as infinite timeout, etc
            if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances))
            {
                throw new ArgumentOutOfRangeException("maxNumberOfServerInstances", SR.ArgumentOutOfRange_MaxNumServerInstances);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
                options, inBufferSize, outBufferSize, inheritability);
        }
Example #11
0
 private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                     PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                     HandleInheritability inheritability)
 {
     Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize,
            outBufferSize, null, inheritability, 0);
 }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            HandleInheritability inheritability)
        {
            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 == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            if (transmissionMode == PipeTransmissionMode.Message)
            {
                throw new PlatformNotSupportedException(SR.PlatformNotSupported_MessageTransmissionMode);
            }

            // We don't have a good way to enforce maxNumberOfServerInstances across processes; we only factor it in
            // for streams created in this process.  Between processes, we behave similarly to maxNumberOfServerInstances == 1,
            // in that the second process to come along and create a stream will find the pipe already in existence and will fail.
            _instance = SharedServer.Get(
                GetPipePath(".", pipeName),
                (maxNumberOfServerInstances == MaxAllowedServerInstances) ? int.MaxValue : maxNumberOfServerInstances);

            _direction      = direction;
            _options        = options;
            _inBufferSize   = inBufferSize;
            _outBufferSize  = outBufferSize;
            _inheritability = inheritability;
        }
        private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException("pipeName");
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("inBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            ValidateMaxNumberOfServerInstances(maxNumberOfServerInstances);
            // inheritability will always be None since this private constructor is only called from other constructors from which
            // inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core
            // doesnt.
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException("inheritability", SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
                options, inBufferSize, outBufferSize, inheritability);
        }
Example #14
0
        public void OperationsOnUnconnectedServer()
        {
            using (NamedPipePair pair = CreateNamedPipePair())
            {
                NamedPipeServerStream server = pair.serverStream;

                // doesn't throw exceptions
                PipeTransmissionMode transmitMode = server.TransmissionMode;
                Assert.Throws <ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999);

                byte[] buffer = new byte[] { 0, 0, 0, 0 };

                if (pair.writeToServer)
                {
                    Assert.Equal(0, server.OutBufferSize);
                    Assert.Throws <InvalidOperationException>(() => server.Write(buffer, 0, buffer.Length));
                    Assert.Throws <InvalidOperationException>(() => server.WriteByte(5));
                    Assert.Throws <InvalidOperationException>(() => { server.WriteAsync(buffer, 0, buffer.Length); });
                }
                else
                {
                    Assert.Equal(0, server.InBufferSize);
                    PipeTransmissionMode readMode = server.ReadMode;
                    Assert.Throws <InvalidOperationException>(() => server.Read(buffer, 0, buffer.Length));
                    Assert.Throws <InvalidOperationException>(() => server.ReadByte());
                    Assert.Throws <InvalidOperationException>(() => { server.ReadAsync(buffer, 0, buffer.Length); });
                }

                Assert.Throws <InvalidOperationException>(() => server.Disconnect());    // disconnect when not connected
                Assert.Throws <InvalidOperationException>(() => server.IsMessageComplete);
            }
        }
        private void ValidateParameters(
            string pipeName,
            PipeDirection direction,
            int maxNumberOfServerInstances,
            PipeTransmissionMode transmissionMode,
            PipeOptions options,
            int inBufferSize,
            int outBufferSize,
            HandleInheritability inheritability)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException(nameof(pipeName));
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if (direction < PipeDirection.In || direction > PipeDirection.InOut)
            {
                throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
            }
            if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
            {
                throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly)) != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(inBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if (outBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances))
            {
                // win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited)
                // through the MaxAllowedServerInstances constant. This is consistent e.g. with -1 as infinite timeout, etc.
                // We do this check for consistency on Unix, even though maxNumberOfServerInstances is otherwise ignored.
                throw new ArgumentOutOfRangeException(nameof(maxNumberOfServerInstances), SR.ArgumentOutOfRange_MaxNumServerInstances);
            }

            // inheritability will always be None since this private constructor is only called from other constructors from which
            // inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core
            // doesn't.
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            if ((options & PipeOptions.CurrentUserOnly) != 0)
            {
                IsCurrentUserOnly = true;
            }
        }
Example #16
0
 public NamedPipeListener(string pipeName, PipeOptions pipeOptions, PipeTransmissionMode pipeTransmissionMode, int maxAllowedServerInstances, ILoggerHttpOverStream logger)
 {
     _pipeName                  = pipeName;
     _pipeOptions               = pipeOptions;
     _pipeTransmissionMode      = pipeTransmissionMode;
     _maxAllowedServerInstances = maxAllowedServerInstances;
     _logger = logger ?? new NoopLogger();
 }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            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 == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            if (transmissionMode == PipeTransmissionMode.Message)
            {
                throw new PlatformNotSupportedException();
            }

            // NOTE: We don't have a good way to enforce maxNumberOfServerInstances, and don't currently try.
            // It's a Windows-specific concept.

            // Make sure the FIFO exists, but don't open it until WaitForConnection is called.
            _path = GetPipePath(".", pipeName);
            while (true)
            {
                int result = Interop.libc.mkfifo(_path, (int)Interop.libc.Permissions.S_IRWXU);
                if (result == 0)
                {
                    // The FIFO was successfully created - note that although we create the FIFO here, we don't
                    // ever delete it. If we remove the FIFO we could invalidate other servers that also use it. 
                    // See #2764 for further discussion.
                    break;
                }

                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                if (errorInfo.Error == Interop.Error.EINTR)
                {
                    // interrupted; try again
                    continue;
                }
                else if (errorInfo.Error == Interop.Error.EEXIST)
                {
                    // FIFO already exists; nothing more to do
                    break;
                }
                else
                {
                    // something else; fail
                    throw Interop.GetExceptionForIoErrno(errorInfo, _path);
                }
            }

            // Store the rest of the creation arguments.  They'll be used when we open the connection
            // in WaitForConnection.
            _direction = direction;
            _options = options;
            _inBufferSize = inBufferSize;
            _outBufferSize = outBufferSize;
            _inheritability = inheritability;
        }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            HandleInheritability inheritability)
        {
            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 == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
            Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");

            if (transmissionMode == PipeTransmissionMode.Message)
            {
                throw new PlatformNotSupportedException();
            }

            // NOTE: We don't have a good way to enforce maxNumberOfServerInstances, and don't currently try.
            // It's a Windows-specific concept.

            // Make sure the FIFO exists, but don't open it until WaitForConnection is called.
            _path = GetPipePath(".", pipeName);
            while (true)
            {
                int result = Interop.libc.mkfifo(_path, (int)Interop.libc.Permissions.S_IRWXU);
                if (result == 0)
                {
                    // The FIFO was successfully created - note that although we create the FIFO here, we don't
                    // ever delete it. If we remove the FIFO we could invalidate other servers that also use it.
                    // See #2764 for further discussion.
                    break;
                }

                Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
                if (errorInfo.Error == Interop.Error.EINTR)
                {
                    // interrupted; try again
                    continue;
                }
                else if (errorInfo.Error == Interop.Error.EEXIST)
                {
                    // FIFO already exists; nothing more to do
                    break;
                }
                else
                {
                    // something else; fail
                    throw Interop.GetExceptionForIoErrno(errorInfo, _path);
                }
            }

            // Store the rest of the creation arguments.  They'll be used when we open the connection
            // in WaitForConnection.
            _direction      = direction;
            _options        = options;
            _inBufferSize   = inBufferSize;
            _outBufferSize  = outBufferSize;
            _inheritability = inheritability;
        }
Example #19
0
        private void OpenPipeServer()
        {
            PipeDirection        pipeDirection        = PipeDirection.InOut;
            PipeTransmissionMode pipeTransmissionMode = PipeTransmissionMode.Message;
            int maxNumberOfServerInstances            = 1;

            _pipe = new NamedPipeServerStream(_pipeToken.Token, pipeDirection, maxNumberOfServerInstances, pipeTransmissionMode);
            _pipe.WaitForConnection();
        }
Example #20
0
        private void OpenPipeServer()
        {
            PipeDirection        pipeDirection        = PipeDirection.InOut;
            PipeTransmissionMode pipeTransmissionMode = PipeTransmissionMode.Byte;
            PipeOptions          pipeOptions          = PipeOptions.Asynchronous;
            int maxNumberOfServerInstances            = 1;

            _pipe = new NamedPipeServerStream(_pipeToken.Token, pipeDirection, maxNumberOfServerInstances, pipeTransmissionMode, pipeOptions);
            _pipe.WaitForConnection();
        }
Example #21
0
 protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
 {
     this.direction         = direction;
     this.transmission_mode = transmissionMode;
     read_trans_mode        = transmissionMode;
     if (outBufferSize <= 0)
     {
         throw new ArgumentOutOfRangeException("bufferSize must be greater than 0");
     }
     buffer_size = outBufferSize;
 }
        private void EnsurePipeInstance()
        {
            if (_stream == null)
            {
                const PipeDirection direction = PipeDirection.InOut;
                const int           maxconn   =
#if WINDOWS_UWP || NETSTANDARD1_3
                    -1
#else
                    NamedPipeServerStream.MaxAllowedServerInstances
#endif
                ;
                const PipeTransmissionMode mode = PipeTransmissionMode.Byte;
                const int inbuf   = 4096;
                const int outbuf  = 4096;
                var       options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None;


                // TODO: "CreatePipeNative" ist only a workaround, and there are have basically two possible outcomes:
                // - once NamedPipeServerStream() gets a CTOR that supports pipesec, remove CreatePipeNative()
                // - if 31190 gets resolved before, use _stream.SetAccessControl(pipesec) instead of CreatePipeNative()
                // EITHER WAY,
                // - if CreatePipeNative() finally gets removed, also remove "allow unsafe code" from the project settings

                try
                {
                    var handle = CreatePipeNative(_pipeAddress, inbuf, outbuf);
                    if ((handle != null) && (!handle.IsInvalid))
                    {
                        _stream = new NamedPipeServerStream(PipeDirection.InOut, _asyncMode, false, handle);
                        handle  = null; // we don't own it any longer
                    }
                    else
                    {
                        handle?.Dispose();
                        _stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf /*, pipesec*/);
                    }
                }
                catch (NotImplementedException) // Mono still does not support async, fallback to sync
                {
                    if (_asyncMode)
                    {
                        options   &= (~PipeOptions.Asynchronous);
                        _stream    = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf);
                        _asyncMode = false;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
        /// <summary>
        /// Create a named pipe server stream with pipe security options.
        /// </summary>
        public static NamedPipeServerStream Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                                                   PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                                                   PipeSecurity pipeSecurity, HandleInheritability inheritability)
        {
            SafePipeHandle handle = CreatePipeHandle(pipeName, direction, maxNumberOfServerInstances,
                                                     transmissionMode, options, inBufferSize, outBufferSize,
                                                     pipeSecurity, inheritability, (PipeAccessRights)0);

            bool isAsync     = (options & PipeOptions.Asynchronous) != 0;
            bool isConnected = false;

            return(new NamedPipeServerStream(direction, isAsync, isConnected, handle));
        }
 /// <summary>
 /// Full named pipe server constructor
 /// </summary>
 /// <param name="pipeName">Pipe name</param>
 /// <param name="direction">Pipe direction: In, Out or InOut (duplex).
 /// Win32 note: this gets OR'd into dwOpenMode to CreateNamedPipe
 /// </param>
 /// <param name="maxNumberOfServerInstances">Maximum number of server instances. Specify a fixed value between
 /// 1 and 254 (Windows)/greater than 1 (Unix), or use NamedPipeServerStream.MaxAllowedServerInstances to use the
 /// maximum amount allowed by system resources.</param>
 /// <param name="transmissionMode">Byte mode or message mode.
 /// Win32 note: this gets used for dwPipeMode. CreateNamedPipe allows you to specify PIPE_TYPE_BYTE/MESSAGE
 /// and PIPE_READMODE_BYTE/MESSAGE independently, but this sets type and readmode to match.
 /// </param>
 /// <param name="options">PipeOption enum: None, Asynchronous, or Write-through
 /// Win32 note: this gets passed in with dwOpenMode to CreateNamedPipe. Asynchronous corresponds to
 /// FILE_FLAG_OVERLAPPED option. PipeOptions enum doesn't expose FIRST_PIPE_INSTANCE option because
 /// this sets that automatically based on the number of instances specified.
 /// </param>
 /// <param name="inBufferSize">Incoming buffer size, 0 or higher.
 /// Note: this size is always advisory; OS uses a suggestion.
 /// </param>
 /// <param name="outBufferSize">Outgoing buffer size, 0 or higher (see above)</param>
 /// <param name="inheritability">Whether handle is inheritable</param>
 private NamedPipeServerStream(string pipeName,
                               PipeDirection direction,
                               int maxNumberOfServerInstances,
                               PipeTransmissionMode transmissionMode,
                               PipeOptions options,
                               int inBufferSize,
                               int outBufferSize,
                               HandleInheritability inheritability)
     : base(direction, transmissionMode, outBufferSize)
 {
     ValidateParameters(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability);
     Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability);
 }
Example #25
0
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                            PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                            HandleInheritability inheritability)
        {
            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");

            throw NotImplemented.ByDesign; // TODO: Implement this
        }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            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");

            throw NotImplemented.ByDesign; // TODO: Implement this
        }
 /// <summary>
 /// Creates a new instance of the <see cref="NamedPipeServerStream" /> class with the specified pipe name, pipe direction, maximum number of server instances, transmission mode, pipe options, recommended in and out buffer sizes, pipe security, inheritability mode, and pipe access rights.
 /// </summary>
 /// <param name="pipeName">The name of the pipe.</param>
 /// <param name="direction">One of the enumeration values that determines the direction of the pipe.</param>
 /// <param name="maxNumberOfServerInstances">The maximum number of server instances that share the same name. You can pass <see cref="NamedPipeServerStream.MaxAllowedServerInstances" /> for this value.</param>
 /// <param name="transmissionMode">One of the enumeration values that determines the transmission mode of the pipe.</param>
 /// <param name="options">One of the enumeration values that determines how to open or create the pipe.</param>
 /// <param name="inBufferSize">The input buffer size.</param>
 /// <param name="outBufferSize">The output buffer size.</param>
 /// <param name="pipeSecurity">An object that determines the access control and audit security for the pipe.</param>
 /// <param name="inheritability">One of the enumeration values that determines whether the underlying handle can be inherited by child processes.</param>
 /// <param name="additionalAccessRights">One of the enumeration values that specifies the access rights of the pipe.</param>
 /// <returns>A new named pipe server stream instance.</returns>
 /// <exception cref="ArgumentNullException"><paramref name="pipeName" /> is <see langword="null" />.</exception>
 /// <exception cref="ArgumentException"><paramref name="pipeName" /> is empty.</exception>
 /// <exception cref="IOException"><paramref name="options" /> is <see cref="PipeOptions.None" />.</exception>
 /// <exception cref="ArgumentOutOfRangeException"><paramref name="options" /> contains an invalid flag.
 /// -or-
 /// <paramref name="inBufferSize" /> is a negative number.
 /// -or
 /// <paramref name="maxNumberOfServerInstances" /> is not a valid number: it should be greater or equal than 1 and less or equal than 254, or should be set to the value of <see cref="NamedPipeServerStream.MaxAllowedServerInstances" />.
 /// -or-
 /// <paramref name="inheritability" /> contains an invalid enum value.
 /// -or
 /// <paramref name="pipeName" /> is 'anonymous', which is reserved.</exception>
 /// <remarks>If `options` contains &lt;xref:System.IO.Pipes.PipeOptions.CurrentUserOnly&gt;, the passed `pipeSecurity` is ignored and the returned &lt;xref:System.IO.Pipes.NamedPipeServerStream&gt; object is created using a custom &lt;xref:System.IO.Pipes.PipeSecurity&gt; instance assigned to the current Windows user as its only owner with full control of the pipe.</remarks>
 public static NamedPipeServerStream Create(
     string pipeName,
     PipeDirection direction,
     int maxNumberOfServerInstances,
     PipeTransmissionMode transmissionMode,
     PipeOptions options,
     int inBufferSize,
     int outBufferSize,
     PipeSecurity?pipeSecurity,
     HandleInheritability inheritability     = HandleInheritability.None,
     PipeAccessRights additionalAccessRights = default)
 {
     return(new NamedPipeServerStream(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, pipeSecurity, inheritability, additionalAccessRights));
 }
Example #28
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);
		}
 public NamedPipeServerStreams(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                               PipeTransmissionMode transmissionMode, PipeOptions options)
     : base(pipeName, true)
 {
     if (maxNumberOfServerInstances != NamedPipeServerStream.MaxAllowedServerInstances && (maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254))
     {
         throw new ArgumentOutOfRangeException(nameof(maxNumberOfServerInstances), maxNumberOfServerInstances,
                                               $"maxNumberOfServerInstances must be either a value between 1 and 254 or NamedPipeServerStream.MaxAllowedServerInstances (to determine the maximum number allowed for the system resources).");
     }
     _direction = PipeDirection.InOut;
     _maxNumberOfServerInstances = maxNumberOfServerInstances;
     _transmissionMode           = transmissionMode;
     _options = options | PipeOptions.Asynchronous;                                // Asynchronous is always required
     CreatePipes();
 }
Example #30
0
 protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
 {
     if ((direction < PipeDirection.In) || (direction > PipeDirection.InOut))
     {
         throw new ArgumentOutOfRangeException("direction", System.SR.GetString("ArgumentOutOfRange_DirectionModeInOutOrInOut"));
     }
     if ((transmissionMode < PipeTransmissionMode.Byte) || (transmissionMode > PipeTransmissionMode.Message))
     {
         throw new ArgumentOutOfRangeException("transmissionMode", System.SR.GetString("ArgumentOutOfRange_TransmissionModeByteOrMsg"));
     }
     if (outBufferSize < 0)
     {
         throw new ArgumentOutOfRangeException("outBufferSize", System.SR.GetString("ArgumentOutOfRange_NeedNonNegNum"));
     }
     this.Init(direction, transmissionMode, outBufferSize);
 }
 protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
 {
     if ((direction < PipeDirection.In) || (direction > PipeDirection.InOut))
     {
         throw new ArgumentOutOfRangeException("direction", System.SR.GetString("ArgumentOutOfRange_DirectionModeInOutOrInOut"));
     }
     if ((transmissionMode < PipeTransmissionMode.Byte) || (transmissionMode > PipeTransmissionMode.Message))
     {
         throw new ArgumentOutOfRangeException("transmissionMode", System.SR.GetString("ArgumentOutOfRange_TransmissionModeByteOrMsg"));
     }
     if (outBufferSize < 0)
     {
         throw new ArgumentOutOfRangeException("outBufferSize", System.SR.GetString("ArgumentOutOfRange_NeedNonNegNum"));
     }
     this.Init(direction, transmissionMode, outBufferSize);
 }
Example #32
0
 private static NamedPipeServerStream CreateServer(
     string pipeName,
     PipeDirection direction,
     int maxNumberOfServerInstances,
     PipeTransmissionMode transmissionMode,
     PipeOptions options,
     int inBufferSize,
     int outBufferSize) =>
 new NamedPipeServerStream(
     GetPipeNameOrPath(pipeName),
     direction,
     maxNumberOfServerInstances,
     transmissionMode,
     options | CurrentUserOption,
     inBufferSize,
     outBufferSize);
Example #33
0
        protected void ValidateOptions(PipeOptions options, PipeTransmissionMode mode)
        {
            if ((options & PipeOptions.WriteThrough) != 0)
            {
                throw new NotImplementedException("WriteThrough is not supported");
            }

            if ((mode & PipeTransmissionMode.Message) != 0)
            {
                throw new NotImplementedException("Message transmission mode is not supported");
            }
            if ((options & PipeOptions.Asynchronous) != 0)             // FIXME: use O_NONBLOCK?
            {
                throw new NotImplementedException("Asynchronous pipe mode is not supported");
            }
        }
Example #34
0
        private void WaitForConnection(string pipeName, PipeSecurity pipeSecurity, PipeTransmissionMode pipeTransmissionMode)
        {
            NamedPipeServerStream handshakePipe            = null;
            NamedPipeServerStream dataPipe                 = null;
            NamedPipeConnection <TRead, TWrite> connection = null;

            var connectionPipeName = GetNextConnectionPipeName(pipeName);

            try
            {
                // Send the client the name of the data pipe to use
                handshakePipe = PipeServerFactory.CreateAndConnectPipe(pipeName, pipeSecurity, pipeTransmissionMode);
                var handshakeWrapper = new PipeStreamWrapper <string, string>(handshakePipe);
                handshakeWrapper.WriteObject(connectionPipeName);
                handshakeWrapper.WaitForPipeDrain();
                handshakeWrapper.Close();

                // Wait for the client to connect to the data pipe
                dataPipe = PipeServerFactory.CreatePipe(connectionPipeName, pipeSecurity, pipeTransmissionMode);
                dataPipe.WaitForConnection();

                // Add the client's connection to the list of connections
                connection = ConnectionFactory.CreateConnection <TRead, TWrite>(dataPipe);
                connection.ReceiveMessage += ClientOnReceiveMessage;
                connection.Disconnected   += ClientOnDisconnected;
                connection.Error          += ConnectionOnError;
                connection.Open();

                lock (_connections)
                {
                    _connections.Add(connection);
                }

                ClientOnConnected(connection);
            }
            // Catch the IOException that is raised if the pipe is broken or disconnected.
            catch (Exception e)
            {
                Console.Error.WriteLine("Named pipe is broken or disconnected: {0}", e);

                Cleanup(handshakePipe);
                Cleanup(dataPipe);

                ClientOnDisconnected(connection);
            }
        }
Example #35
0
        private void UpdateReadMode()
        {
            int num;

            if (!Microsoft.Win32.UnsafeNativeMethods.GetNamedPipeHandleState(this.SafePipeHandle, out num, Microsoft.Win32.UnsafeNativeMethods.NULL, Microsoft.Win32.UnsafeNativeMethods.NULL, Microsoft.Win32.UnsafeNativeMethods.NULL, Microsoft.Win32.UnsafeNativeMethods.NULL, 0))
            {
                this.WinIOError(Marshal.GetLastWin32Error());
            }
            if ((num & 2) != 0)
            {
                this.m_readMode = PipeTransmissionMode.Message;
            }
            else
            {
                this.m_readMode = PipeTransmissionMode.Byte;
            }
        }
Example #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OverlappingPipeClientStream"/> class.
 /// </summary>
 /// <param name="serverName">Name of the server.</param>
 /// <param name="pipeName">Name of the pipe.</param>
 /// <param name="transmissionMode"></param>
 /// <param name="impersonationLevel">The impersonation level.</param>
 /// <param name="inheritability">The inheritability.</param>
 public OverlappingPipeClientStream(
     [NotNull] string serverName,
     [NotNull] string pipeName,
     PipeTransmissionMode transmissionMode,
     TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None,
     HandleInheritability inheritability        = HandleInheritability.None)
     : base(new NamedPipeClientStream(
                serverName,
                pipeName,
                PipeDirection.InOut,
                PipeOptions.Asynchronous,
                impersonationLevel,
                inheritability))
 {
     Debug.Assert(Stream != null);
     ReadMode = transmissionMode;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OverlappingPipeClientStream"/> class.
 /// </summary>
 /// <param name="serverName">Name of the server.</param>
 /// <param name="pipeName">Name of the pipe.</param>
 /// <param name="transmissionMode"></param>
 /// <param name="impersonationLevel">The impersonation level.</param>
 /// <param name="inheritability">The inheritability.</param>
 public OverlappingPipeClientStream(
     [NotNull] string serverName,
     [NotNull] string pipeName,
     PipeTransmissionMode transmissionMode,
     TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None,
     HandleInheritability inheritability = HandleInheritability.None)
     : base(new NamedPipeClientStream(
                serverName,
                pipeName,
                PipeDirection.InOut,
                PipeOptions.Asynchronous,
                impersonationLevel,
                inheritability))
 {
     Debug.Assert(Stream != null);
     ReadMode = transmissionMode;
 }
        private NamedPipeServerStream CreateNamedPipe(
            string pipeName,
            PipeSecurity expectedSecurity,
            PipeDirection direction               = DefaultPipeDirection,
            int maxNumberOfServerInstances        = DefaultNumberOfServerInstances,
            PipeTransmissionMode transmissionMode = DefaultPipeTransmissionMode,
            PipeOptions options = DefaultPipeOptions,
            int inBufferSize    = DefaultBufferSize,
            int outBufferSize   = DefaultBufferSize,
            HandleInheritability inheritability     = DefaultInheritability,
            PipeAccessRights additionalAccessRights = 0)
        {
            NamedPipeServerStream pipe = NamedPipeServerStreamAcl.Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, expectedSecurity, inheritability, additionalAccessRights);

            Assert.NotNull(pipe);
            return(pipe);
        }
Example #39
0
        protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
        {
            if (direction < PipeDirection.In || direction > PipeDirection.InOut)
            {
                throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
            }
            if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
            {
                throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
            }
            if (outBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
            }

            Init(direction, transmissionMode, outBufferSize);
        }
Example #40
0
        protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
        {
            if (direction < PipeDirection.In || direction > PipeDirection.InOut)
            {
                throw new ArgumentOutOfRangeException("direction", SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
            }
            if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
            {
                throw new ArgumentOutOfRangeException("transmissionMode", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
            }
            if (outBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException("outBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
            }

            Init(direction, transmissionMode, outBufferSize);
        }
        private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
        {
            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("pipeName", SR.ArgumentOutOfRange_AnonymousReserved);
            }


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

            // 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;
            }

            Interop.mincore.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability);
            SafePipeHandle handle = Interop.mincore.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);

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

            InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
        }
Example #42
0
        private NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                HandleInheritability inheritability)
            : base(direction, transmissionMode, outBufferSize)
        {
            if (pipeName == null)
            {
                throw new ArgumentNullException(nameof(pipeName));
            }
            if (pipeName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_NeedNonemptyPipeName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (inBufferSize < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(inBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
            }
            if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances))
            {
                // win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited)
                // through the MaxAllowedServerInstances constant. This is consistent e.g. with -1 as infinite timeout, etc.
                // We do this check for consistency on Unix, even though maxNumberOfServerInstances is otherwise ignored.
                throw new ArgumentOutOfRangeException(nameof(maxNumberOfServerInstances), SR.ArgumentOutOfRange_MaxNumServerInstances);
            }

            // inheritability will always be None since this private constructor is only called from other constructors from which
            // inheritability is always set to None. Desktop has a public constructor to allow setting it to something else, but Core
            // doesn't.
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }

            Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode,
                options, inBufferSize, outBufferSize, inheritability);
        }
		public NamedPipeServerStream (string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize)
#if MOBILE		
			: base (direction, inBufferSize)
		{
			throw new NotImplementedException ();
		}
 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);
 }
Example #45
0
 public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances,
         PipeTransmissionMode transmissionMode, PipeOptions options)
     : this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, 0, 0,
         null, HandleInheritability.None, (PipeAccessRights)0) { }
 protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
 {
 }
Example #47
0
		// .ctor without handle - create new
		public Win32NamedPipeServer (NamedPipeServerStream owner, string pipeName, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeAccessRights rights, PipeOptions options, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
		{
			string name = String.Format ("\\\\.\\pipe\\{0}", pipeName);

			uint openMode = 0;
			if ((rights & PipeAccessRights.ReadData) != 0)
				openMode |= 1;
			if ((rights & PipeAccessRights.WriteData) != 0)
				openMode |= 2;
			if ((options & PipeOptions.WriteThrough) != 0)
				openMode |= 0x80000000;
			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;

			// FIXME: is nDefaultTimeout = 0 ok?
			var att = new SecurityAttributesHack (inheritability == HandleInheritability.Inheritable);
			var ret = Win32Marshal.CreateNamedPipe (name, openMode, pipeMode, maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref att, IntPtr.Zero);
			if (ret == new IntPtr (-1L))
				throw new Win32Exception (Marshal.GetLastWin32Error ());
			handle = new SafePipeHandle (ret, true);
		}
Example #48
0
		protected void ValidateOptions (PipeOptions options, PipeTransmissionMode mode)
		{
			if ((options & PipeOptions.WriteThrough) != 0)
				throw new NotImplementedException ("WriteThrough is not supported");

			if ((mode & PipeTransmissionMode.Message) != 0)
				throw new NotImplementedException ("Message transmission mode is not supported");
			if ((options & PipeOptions.Asynchronous) != 0) // FIXME: use O_NONBLOCK?
				throw new NotImplementedException ("Asynchronous pipe mode is not supported");
		}
Example #49
0
		public NamedPipeServerStream (string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode)
			: this (pipeName, direction, maxNumberOfServerInstances, transmissionMode, PipeOptions.None)
		{
		}
 public NamedPipeChannelConfigurator Mode( PipeTransmissionMode mode )
 {
     Definition.Mode = mode;
     return this;
 }
Example #51
0
        private void Create(String fullPipeName, PipeDirection direction, int maxNumberOfServerInstances,
                PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
                PipeAccessRights rights, UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs) {
            Debug.Assert(fullPipeName != null && fullPipeName.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");

            int openMode = ((int)direction) |
                           (maxNumberOfServerInstances == 1 ? UnsafeNativeMethods.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
                           (int)options |
                           (int)rights;

            // 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;
            }

            SafePipeHandle handle = UnsafeNativeMethods.CreateNamedPipe(fullPipeName, openMode, pipeModes,
                    maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, secAttrs);

            if (handle.IsInvalid) {
                __Error.WinIOError(Marshal.GetLastWin32Error(), String.Empty);
            }

            InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
        }
Example #52
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(SR.GetString(SR.Argument_NeedNonemptyPipeName));
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous)) != 0) {
                throw new ArgumentOutOfRangeException("options", SR.GetString(SR.ArgumentOutOfRange_OptionsInvalid));
            }
            if (inBufferSize < 0) {
                throw new ArgumentOutOfRangeException("inBufferSize", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
            }
            // win32 allows fixed values of 1-254 or 255 to mean max allowed by system. We expose 255 as -1 (unlimited)
            // through the MaxAllowedServerInstances constant. This is consistent e.g. with -1 as infinite timeout, etc
            if ((maxNumberOfServerInstances < 1 || maxNumberOfServerInstances > 254) && (maxNumberOfServerInstances != MaxAllowedServerInstances)) {
                throw new ArgumentOutOfRangeException("maxNumberOfServerInstances", SR.GetString(SR.ArgumentOutOfRange_MaxNumServerInstances));
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable) {
                throw new ArgumentOutOfRangeException("inheritability", SR.GetString(SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable));
            }
            // ChangePermissions, TakeOwnership, and AccessSystemSecurity are only legal values user may provide;
            // internally this is set to 0 if not provided. This handles both cases.
            if ((additionalAccessRights & ~(PipeAccessRights.ChangePermissions | PipeAccessRights.TakeOwnership |
                       PipeAccessRights.AccessSystemSecurity)) != 0) {
                throw new ArgumentOutOfRangeException("additionalAccessRights", SR.GetString(SR.ArgumentOutOfRange_AdditionalAccessLimited));
            }

            // Named Pipe Servers require Windows NT
            if (Environment.OSVersion.Platform == PlatformID.Win32Windows) {
                throw new PlatformNotSupportedException(SR.GetString(SR.PlatformNotSupported_NamedPipeServers));
            }

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

            // Make sure the pipe name isn't one of our reserved names for anonymous pipes.
            if (String.Compare(normalizedPipePath, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase) == 0) {
                throw new ArgumentOutOfRangeException("pipeName", SR.GetString(SR.ArgumentOutOfRange_AnonymousReserved));
            }
            
            Object pinningHandle = null;
            UnsafeNativeMethods.SECURITY_ATTRIBUTES secAttrs = PipeStream.GetSecAttrs(inheritability, pipeSecurity, out pinningHandle);

            try {
                Create(normalizedPipePath, direction, maxNumberOfServerInstances, transmissionMode,
                        options, inBufferSize, outBufferSize, additionalAccessRights, secAttrs);
            }
            finally {
                if (pinningHandle != null) {
                    GCHandle pinHandle = (GCHandle)pinningHandle;
                    pinHandle.Free();
                }
            }
        }
Example #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, (PipeAccessRights)0) { }
 public NamedPipeServerStream(String pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize)
     : this(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, HandleInheritability.None)
 { 
 }
Example #55
0
		// .ctor without handle - create new
		public UnixNamedPipeServer (NamedPipeServerStream owner, string pipeName, int maxNumberOfServerInstances,
		                             PipeTransmissionMode transmissionMode, PipeAccessRights rights, PipeOptions options,
		                            int inBufferSize, int outBufferSize, HandleInheritability inheritability)
		{
			string name = Path.Combine ("/var/tmp/", pipeName);
			EnsureTargetFile (name);

			RightsToAccess (rights);

			ValidateOptions (options, owner.TransmissionMode);

			// FIXME: maxNumberOfServerInstances, modes, sizes, handle inheritability
			
			var fs = new FileStream (name, FileMode.Open, RightsToFileAccess (rights), FileShare.ReadWrite);
			handle = new SafePipeHandle (fs.Handle, false);
			owner.Stream = fs;
			should_close_handle = true;
		}
		protected PipeStream (PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
		{
			this.direction = direction;
			this.transmission_mode = transmissionMode;
			read_trans_mode = transmissionMode;
			if (outBufferSize <= 0)
				throw new ArgumentOutOfRangeException ("bufferSize must be greater than 0");
			buffer_size = outBufferSize;
		}
Example #57
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);
			}
		}
Example #58
0
        private void UpdateReadMode() {
            int flags;
            if (!UnsafeNativeMethods.GetNamedPipeHandleState(SafePipeHandle, out flags, UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL,
                    UnsafeNativeMethods.NULL, UnsafeNativeMethods.NULL, 0)) {
                WinIOError(Marshal.GetLastWin32Error());
            }

            if ((flags & UnsafeNativeMethods.PIPE_READMODE_MESSAGE) != 0) {
                m_readMode = PipeTransmissionMode.Message;
            }
            else {
                m_readMode = PipeTransmissionMode.Byte;
            }
        }
 public NamedPipeServerStream(string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options) : base (default(PipeDirection), default(int))
 {
   Contract.Ensures(1 <= pipeName.Length);
 }
Example #60
0
		public NamedPipeServerStream (string pipeName, PipeDirection direction, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize)
			: this (pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, null)
		{
		}