private unsafe int WriteFileNative(Microsoft.Win32.SafeHandles.SafePipeHandle handle, byte[] buffer, int offset, int count, NativeOverlapped *overlapped, out int hr) { if (buffer.Length == 0) { hr = 0; return(0); } int numBytesWritten = 0; int num2 = 0; fixed(byte *numRef = buffer) { if (this.m_isAsync) { num2 = Microsoft.Win32.UnsafeNativeMethods.WriteFile(handle, numRef + offset, count, IntPtr.Zero, overlapped); } else { num2 = Microsoft.Win32.UnsafeNativeMethods.WriteFile(handle, numRef + offset, count, out numBytesWritten, IntPtr.Zero); } } if (num2 == 0) { hr = Marshal.GetLastWin32Error(); return(-1); } hr = 0; return(numBytesWritten); }
protected void InitializeHandle(Microsoft.Win32.SafeHandles.SafePipeHandle handle, bool isExposed, bool isAsync) { isAsync &= _canUseAsync; if (isAsync) { bool flag = false; new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); try { flag = ThreadPool.BindHandle(handle); } finally { CodeAccessPermission.RevertAssert(); } if (!flag) { throw new IOException(System.SR.GetString("IO_IO_BindHandleFailed")); } } this.m_handle = handle; this.m_isAsync = isAsync; this.m_isHandleExposed = isExposed; this.m_isFromExistingHandle = isExposed; }
protected static void StartClient(PipeDirection direction, SafePipeHandle clientPipeHandle) { using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(direction, clientPipeHandle)) { DoStreamOperations(client); } }
internal static extern bool GetNamedPipeInfo( SafePipeHandle hNamedPipe, IntPtr lpFlags, IntPtr lpOutBufferSize, out int lpInBufferSize, IntPtr lpMaxInstances );
public AnonymousPipeServerStream(PipeDirection direction, SafePipeHandle serverSafePipeHandle, SafePipeHandle clientSafePipeHandle) : base(direction, 0) { if (direction == PipeDirection.InOut) { throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeUnidirectional")); } if (serverSafePipeHandle == null) { throw new ArgumentNullException("serverSafePipeHandle"); } if (clientSafePipeHandle == null) { throw new ArgumentNullException("clientSafePipeHandle"); } if (serverSafePipeHandle.IsInvalid) { throw new ArgumentException(System.SR.GetString("Argument_InvalidHandle"), "serverSafePipeHandle"); } if (clientSafePipeHandle.IsInvalid) { throw new ArgumentException(System.SR.GetString("Argument_InvalidHandle"), "clientSafePipeHandle"); } if (Microsoft.Win32.UnsafeNativeMethods.GetFileType(serverSafePipeHandle) != 3) { throw new IOException(System.SR.GetString("IO_IO_InvalidPipeHandle")); } if (Microsoft.Win32.UnsafeNativeMethods.GetFileType(clientSafePipeHandle) != 3) { throw new IOException(System.SR.GetString("IO_IO_InvalidPipeHandle")); } base.InitializeHandle(serverSafePipeHandle, true, false); this.m_clientHandle = clientSafePipeHandle; this.m_clientHandleExposed = true; base.State = PipeState.Connected; }
public AnonymousPipeServerStream(PipeDirection direction, SafePipeHandle serverSafePipeHandle, SafePipeHandle clientSafePipeHandle) : base(direction, 0) { if (direction == PipeDirection.InOut) { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } if (serverSafePipeHandle == null) { throw new ArgumentNullException("serverSafePipeHandle"); } if (clientSafePipeHandle == null) { throw new ArgumentNullException("clientSafePipeHandle"); } if (serverSafePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, "serverSafePipeHandle"); } if (clientSafePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, "clientSafePipeHandle"); } ValidateHandleIsPipe(serverSafePipeHandle); ValidateHandleIsPipe(clientSafePipeHandle); InitializeHandle(serverSafePipeHandle, true, false); _clientHandle = clientSafePipeHandle; _clientHandleExposed = true; State = PipeState.Connected; }
public AnonymousPipeClientStream(PipeDirection direction, String pipeHandleAsString) : base(direction, 0) { if (direction == PipeDirection.InOut) { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } if (pipeHandleAsString == null) { throw new ArgumentNullException("pipeHandleAsString"); } // Initialize SafePipeHandle from String and check if it's valid. First see if it's parseable long result = 0; bool parseable = long.TryParse(pipeHandleAsString, out result); if (!parseable) { throw new ArgumentException(SR.Argument_InvalidHandle, "pipeHandleAsString"); } // next check whether the handle is invalid SafePipeHandle safePipeHandle = new SafePipeHandle((IntPtr)result, true); if (safePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, "pipeHandleAsString"); } Init(direction, safePipeHandle); }
private void Create(PipeDirection direction, HandleInheritability inheritability, int bufferSize) { Debug.Assert(direction != PipeDirection.InOut, "Anonymous pipe direction shouldn't be InOut"); // Ignore bufferSize. It's optional, and the fcntl F_SETPIPE_SZ for changing it is Linux specific. // Use pipe or pipe2 to create our anonymous pipe int[] fds = new int[2]; unsafe { fixed (int* fdsptr = fds) { CreatePipe(inheritability, fdsptr); } } // Create SafePipeHandles for each end of the pipe. Which ends goes with server and which goes with // client depends on the direction of the pipe. SafePipeHandle serverHandle = new SafePipeHandle( (IntPtr)fds[direction == PipeDirection.In ? Interop.libc.ReadEndOfPipe : Interop.libc.WriteEndOfPipe], ownsHandle: true); SafePipeHandle clientHandle = new SafePipeHandle( (IntPtr)fds[direction == PipeDirection.In ? Interop.libc.WriteEndOfPipe : Interop.libc.ReadEndOfPipe], ownsHandle: true); // We're connected. Finish initialization using the newly created handles. InitializeHandle(serverHandle, isExposed: false, isAsync: false); _clientHandle = clientHandle; State = PipeState.Connected; }
internal static extern bool DuplicateHandle( IntPtr hSourceProcessHandle, SafePipeHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafePipeHandle lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
internal void InitializeBufferSize(SafePipeHandle handle, int bufferSize) { if (bufferSize > 0) { SysCall(handle, (fd, _, size) => Interop.libc.fcntl(fd, Interop.libc.FcntlCommands.F_SETPIPE_SZ, size), IntPtr.Zero, bufferSize); } }
public static void InOutPipeDirection_Throws_NotSupportedException() { // Anonymous pipes can't be made with PipeDirection.InOut Assert.Throws<NotSupportedException>(() => new AnonymousPipeClientStream(PipeDirection.InOut, "123")); SafePipeHandle pipeHandle = new SafePipeHandle(new IntPtr(-1), true); Assert.Throws<NotSupportedException>(() => new AnonymousPipeClientStream(PipeDirection.InOut, pipeHandle)); }
internal static extern bool GetNamedPipeHandleState( SafePipeHandle hNamedPipe, IntPtr lpState, out int lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize);
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { // Check that this handle is infact a handle to a pipe. if (Interop.mincore.GetFileType(safePipeHandle) != Interop.mincore.FileTypes.FILE_TYPE_PIPE) { throw new IOException(SR.IO_InvalidPipeHandle); } }
public static void StartClient(PipeDirection direction, SafePipeHandle clientPipeHandle) { using (AnonymousPipeClientStream client = new AnonymousPipeClientStream(direction, clientPipeHandle)) { DoStreamOperations(client); } // If you don't see this message that means that this task crashed. Console.WriteLine("*** Client operations suceedeed. ***"); }
/// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> private void InitializeAsyncHandle(SafePipeHandle handle) { // If the handle is of async type, bind the handle to the ThreadPool so that we can use // the async operations (it's needed so that our native callbacks get called). if (!ThreadPool.BindHandle(handle)) { throw new IOException(SR.IO_BindHandleFailed); } }
private void Init(PipeDirection direction, SafePipeHandle safePipeHandle) { if (Microsoft.Win32.UnsafeNativeMethods.GetFileType(safePipeHandle) != 3) { throw new IOException(System.SR.GetString("IO_IO_InvalidPipeHandle")); } base.InitializeHandle(safePipeHandle, true, false); base.State = PipeState.Connected; }
private void Init(PipeDirection direction, SafePipeHandle safePipeHandle) { Debug.Assert(direction != PipeDirection.InOut, "anonymous pipes are unidirectional, caller should have verified before calling Init"); Debug.Assert(safePipeHandle != null && !safePipeHandle.IsInvalid, "safePipeHandle must be valid"); ValidateHandleIsPipe(safePipeHandle); InitializeHandle(safePipeHandle, true, false); State = PipeState.Connected; }
public NamedPipeClientStream (PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base (direction, DefaultBufferSize) { if (IsWindows) impl = new Win32NamedPipeClient (this, safePipeHandle); else impl = new UnixNamedPipeClient (this, safePipeHandle); IsConnected = isConnected; InitializeHandle (safePipeHandle, true, isAsync); }
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { Interop.Sys.FileStatus status; int result = CheckPipeCall(Interop.Sys.FStat(safePipeHandle, out status)); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO) { throw new IOException(SR.IO_InvalidPipeHandle); } } }
public AnonymousPipeClientStream (PipeDirection direction,SafePipeHandle safePipeHandle) : base (direction, DefaultBufferSize) { /* if (IsWindows) impl = new Win32AnonymousPipeClient (this, safePipeHandle); else impl = new UnixAnonymousPipeClient (this, safePipeHandle); */ InitializeHandle (safePipeHandle, false, false); IsConnected = true; }
internal static bool TryGetNumberOfServerInstances(SafePipeHandle handle, out int numberOfServerInstances) { int serverInstances; if (GetNamedPipeHandleState(handle, IntPtr.Zero, out serverInstances, IntPtr.Zero, IntPtr.Zero, null, 0)) { numberOfServerInstances = serverInstances; return true; } numberOfServerInstances = 0; return false; }
public static void InvalidPipeHandle_Throws() { using (AnonymousPipeServerStream dummyserver = new AnonymousPipeServerStream(PipeDirection.Out)) { Assert.Throws<ArgumentNullException>("serverSafePipeHandle", () => new AnonymousPipeServerStream(PipeDirection.Out, null, dummyserver.ClientSafePipeHandle)); Assert.Throws<ArgumentNullException>("clientSafePipeHandle", () => new AnonymousPipeServerStream(PipeDirection.Out, dummyserver.SafePipeHandle, null)); SafePipeHandle pipeHandle = new SafePipeHandle(new IntPtr(-1), true); Assert.Throws<ArgumentException>("serverSafePipeHandle", () => new AnonymousPipeServerStream(PipeDirection.Out, pipeHandle, dummyserver.ClientSafePipeHandle)); Assert.Throws<ArgumentException>("clientSafePipeHandle", () => new AnonymousPipeServerStream(PipeDirection.Out, dummyserver.SafePipeHandle, pipeHandle)); } }
internal static bool TryGetImpersonationUserName(SafePipeHandle handle, out string userName) { const int CREDUI_MAX_USERNAME_LENGTH = 513; int serverInstances; var builder = new StringBuilder(CREDUI_MAX_USERNAME_LENGTH + 1); if (GetNamedPipeHandleState(handle, IntPtr.Zero, out serverInstances, IntPtr.Zero, IntPtr.Zero, builder, builder.Capacity)) { userName = builder.ToString(); return true; } userName = ""; return false; }
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal static void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { SysCall(safePipeHandle, (fd, _, __) => { Interop.libcoreclr.fileinfo buf; int result = Interop.libcoreclr.GetFileInformationFromFd(fd, out buf); if (result == 0) { if ((buf.mode & Interop.libcoreclr.FileTypes.S_IFMT) != Interop.libcoreclr.FileTypes.S_IFIFO) { throw new IOException(SR.IO_InvalidPipeHandle); } } return result; }); }
public AnonymousPipeClientStream(PipeDirection direction, SafePipeHandle safePipeHandle) : base(direction, 0) { if (direction == PipeDirection.InOut) { throw new NotSupportedException(System.SR.GetString("NotSupported_AnonymousPipeUnidirectional")); } if (safePipeHandle == null) { throw new ArgumentNullException("safePipeHandle"); } if (safePipeHandle.IsInvalid) { throw new ArgumentException(System.SR.GetString("Argument_InvalidHandle"), "safePipeHandle"); } this.Init(direction, safePipeHandle); }
/// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { SysCall(safePipeHandle, (fd, _, __, ___) => { Interop.Sys.FileStatus status; int result = Interop.Sys.FStat(fd, out status); if (result == 0) { if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) != Interop.Sys.FileTypes.S_IFIFO) { throw new IOException(SR.IO_InvalidPipeHandle); } } return result; }); }
public AnonymousPipeClientStream (PipeDirection direction, SafePipeHandle safePipeHandle) : base (direction, DefaultBufferSize) { /* if (IsWindows) impl = new Win32AnonymousPipeClient (this, safePipeHandle); else impl = new UnixAnonymousPipeClient (this, safePipeHandle); */ #if MOBILE throw new NotImplementedException (); #else InitializeHandle (safePipeHandle, false, false); #endif IsConnected = true; }
public AnonymousPipeClientStream(PipeDirection direction, SafePipeHandle safePipeHandle) : base(direction, 0) { if (direction == PipeDirection.InOut) { throw new NotSupportedException(SR.NotSupported_AnonymousPipeUnidirectional); } if (safePipeHandle == null) { throw new ArgumentNullException(nameof(safePipeHandle)); } if (safePipeHandle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, nameof(safePipeHandle)); } Init(direction, safePipeHandle); }
// AnonymousPipeServerStream owner; public Win32AnonymousPipeServer (AnonymousPipeServerStream owner, PipeDirection direction, HandleInheritability inheritability, int bufferSize) { IntPtr r, w; SecurityAttributesHack att = new SecurityAttributesHack (inheritability == HandleInheritability.Inheritable); if (!Win32Marshal.CreatePipe (out r, out w, ref att, bufferSize)) throw new Win32Exception (Marshal.GetLastWin32Error ()); var rh = new SafePipeHandle (r, true); var wh = new SafePipeHandle (w, true); if (direction == PipeDirection.Out) { server_handle = wh; client_handle = rh; } else { server_handle = rh; client_handle = wh; } }
/// <summary>Opens the specified file with the requested flags and mode.</summary> /// <param name="path">The path to the file.</param> /// <param name="flags">The flags with which to open the file.</param> /// <param name="mode">The mode for opening the file.</param> /// <returns>A SafeFileHandle for the opened file.</returns> internal static SafePipeHandle Open(string path, Interop.libc.OpenFlags flags, int mode) { // SafePipeHandle wraps a file descriptor rather than a pointer, and a file descriptor is always 4 bytes // rather than being pointer sized, which means we can't utilize the runtime's ability to marshal safe handles. // Ideally this would be a constrained execution region, but we don't have access to PrepareConstrainedRegions. // We still use a finally block to house the code that opens the file and stores the handle in hopes // of making it as non-interruptable as possible. The SafePipeHandle is also allocated first to avoid // the allocation after getting the file descriptor but before storing it. SafePipeHandle handle = new SafePipeHandle(); try { } finally { int fd; while (Interop.CheckIo(fd = Interop.libc.open(path, flags, mode))) ; Debug.Assert(fd >= 0); handle.SetHandle((IntPtr)fd); } return handle; }
public void WaitForConnection() { CheckConnectOperationsServer(); if (State == PipeState.Connected) { throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected); } // Binding to an existing path fails, so we need to remove anything left over at this location. // There's of course a race condition here, where it could be recreated by someone else between this // deletion and the bind below, in which case we'll simply let the bind fail and throw. Interop.Sys.Unlink(_path); // ignore any failures var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); try { socket.Bind(new UnixDomainSocketEndPoint(_path)); socket.Listen(1); Socket acceptedSocket = socket.Accept(); SafePipeHandle serverHandle = new SafePipeHandle(acceptedSocket); try { ConfigureSocket(acceptedSocket, serverHandle, _direction, _inBufferSize, _outBufferSize, _inheritability); } catch { serverHandle.Dispose(); acceptedSocket.Dispose(); throw; } InitializeHandle(serverHandle, isExposed: false, isAsync: (_options & PipeOptions.Asynchronous) != 0); State = PipeState.Connected; } finally { // Bind will have created a file. Now that the client is connected, it's no longer necessary, so get rid of it. Interop.Sys.Unlink(_path); // ignore any failures; worst case is we leave a tmp file // Clean up the listening socket socket.Dispose(); } }
public NamedPipeClientStream(PipeDirection direction, bool isAsync, bool isConnected, SafePipeHandle safePipeHandle) : base(direction, 0) { if (safePipeHandle == null) { throw new ArgumentNullException("safePipeHandle"); } if (safePipeHandle.IsInvalid) { throw new ArgumentException(System.SR.GetString("Argument_InvalidHandle"), "safePipeHandle"); } if (Microsoft.Win32.UnsafeNativeMethods.GetFileType(safePipeHandle) != 3) { throw new IOException(System.SR.GetString("IO_IO_InvalidPipeHandle")); } base.InitializeHandle(safePipeHandle, true, isAsync); if (isConnected) { base.State = PipeState.Connected; } }