internal unsafe IAsyncResult BeginRead(byte[] data, int offset, int size, AsyncCallback callback, object state)
        {
            bool              flag;
            PipeAsyncResult   ar           = new PipeAsyncResult(callback);
            NativeOverlapped *lpOverlapped = new Overlapped(0, 0, IntPtr.Zero, ar).UnsafePack(IOCallback, data);

            ar._overlapped = lpOverlapped;
            fixed(byte *numRef = data)
            {
                flag = NativePipe.ReadFile(this._handle, numRef + offset, size, IntPtr.Zero, lpOverlapped);
            }

            if (!flag)
            {
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode == 0x6dL)
                {
                    ar.CallUserCallback();
                    return(ar);
                }
                if (errorCode != 0x3e5L)
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ReadFailure"), new object[] { GetMessage(errorCode) }));
                }
            }
            return(ar);
        }
        internal static IpcPort Create(string portName, CommonSecurityDescriptor securityDescriptor, bool exclusive)
        {
            SECURITY_ATTRIBUTES security_attributes;

            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new NotSupportedException(CoreChannel.GetResourceString("Remoting_Ipc_Win9x"));
            }
            PipeHandle handle = null;
            string     lpName = @"\\.\pipe\" + portName;

            security_attributes = new SECURITY_ATTRIBUTES {
                nLength = Marshal.SizeOf(security_attributes)
            };
            byte[] binaryForm = null;
            if (securityDescriptor == null)
            {
                securityDescriptor = s_securityDescriptor;
            }
            binaryForm = new byte[securityDescriptor.BinaryLength];
            securityDescriptor.GetBinaryForm(binaryForm, 0);
            GCHandle handle2 = GCHandle.Alloc(binaryForm, GCHandleType.Pinned);

            security_attributes.lpSecurityDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(binaryForm, 0);
            handle = NativePipe.CreateNamedPipe(lpName, (uint)(0x40000003 | (exclusive ? 0x80000 : 0)), 0, 0xff, 0x2000, 0x2000, uint.MaxValue, security_attributes);
            handle2.Free();
            if (handle.Handle.ToInt32() == -1)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_CreateIpcFailed"), new object[] { GetMessage(errorCode) }));
            }
            return(new IpcPort(portName, handle));
        }
Exemplo n.º 3
0
        public bool WaitForConnect()
        {
            // Wait for clients to connect
            bool status = NativePipe.ConnectNamedPipe(_handle, null);

            return(status ? true : (Marshal.GetLastWin32Error() == NativePipe.ERROR_PIPE_CONNECTED));
        }
Exemplo n.º 4
0
        internal static IpcPort Connect(String portName, bool secure, TokenImpersonationLevel impersonationLevel, int timeout)
        {
            string pipeName      = prefix + portName;
            uint   impersonation = NativePipe.SECURITY_SQOS_PRESENT;

            // convert the impersonation Level to the correct flag
            if (secure)
            {
                switch (impersonationLevel)
                {
                case TokenImpersonationLevel.None:
                    impersonation = NativePipe.SECURITY_SQOS_PRESENT;
                    break;

                case TokenImpersonationLevel.Identification:
                    impersonation = NativePipe.SECURITY_SQOS_PRESENT | NativePipe.SECURITY_IDENTIFICATION;
                    break;

                case TokenImpersonationLevel.Impersonation:
                    impersonation = NativePipe.SECURITY_SQOS_PRESENT | NativePipe.SECURITY_IMPERSONATION;
                    break;

                case TokenImpersonationLevel.Delegation:
                    impersonation = NativePipe.SECURITY_SQOS_PRESENT | NativePipe.SECURITY_DELEGATION;
                    break;
                }
            }

            while (true)
            {
                // Invoke CreateFile with the pipeName to open a client side connection
                PipeHandle handle = NativePipe.CreateFile(pipeName,
                                                          NativePipe.GENERIC_READ | NativePipe.GENERIC_WRITE,
                                                          NativePipe.FILE_SHARE_READ |
                                                          NativePipe.FILE_SHARE_WRITE,
                                                          IntPtr.Zero,
                                                          NativePipe.OPEN_EXISTING,
                                                          NativePipe.FILE_ATTRIBUTE_NORMAL |
                                                          NativePipe.FILE_FLAG_OVERLAPPED |
                                                          impersonation,
                                                          IntPtr.Zero);

                if (handle.Handle.ToInt32() != NativePipe.INVALID_HANDLE_VALUE)
                {
                    return(new IpcPort(portName, handle));
                }

                int error = Marshal.GetLastWin32Error();
                if (error != NativePipe.ERROR_PIPE_BUSY)
                {
                    throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ConnectIpcFailed"), GetMessage(error)));
                }

                if (!NativePipe.WaitNamedPipe(pipeName, timeout))
                {
                    throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_Busy"), GetMessage(error)));
                }
            }
        }
 internal void ImpersonateClient()
 {
     if (!NativePipe.ImpersonateNamedPipeClient(this._handle))
     {
         int errorCode = Marshal.GetLastWin32Error();
         throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ImpersonationFailed"), new object[] { GetMessage(errorCode) }));
     }
 }
 public bool WaitForConnect()
 {
     if (!NativePipe.ConnectNamedPipe(this._handle, null))
     {
         return(Marshal.GetLastWin32Error() == 0x217L);
     }
     return(true);
 }
Exemplo n.º 7
0
        internal void ImpersonateClient()
        {
            bool status = NativePipe.ImpersonateNamedPipeClient(_handle);

            if (!status)
            {
                int error = Marshal.GetLastWin32Error();
                throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ImpersonationFailed"), GetMessage(error)));
            }
        }
        internal static string GetMessage(int errorCode)
        {
            StringBuilder lpBuffer = new StringBuilder(0x200);

            if (NativePipe.FormatMessage(0x3200, NativePipe.NULL, errorCode, 0, lpBuffer, lpBuffer.Capacity, NativePipe.NULL) != 0)
            {
                return(lpBuffer.ToString());
            }
            return(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_UnknownError_Num"), new object[] { errorCode.ToString(CultureInfo.InvariantCulture) }));
        }
Exemplo n.º 9
0
        internal static IpcPort Create(String portName, CommonSecurityDescriptor securityDescriptor, bool exclusive)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                throw new NotSupportedException(CoreChannel.GetResourceString("Remoting_Ipc_Win9x"));
            }
            PipeHandle handle = null;
            // Add the prefix to the portName
            string pipeName          = prefix + portName;
            SECURITY_ATTRIBUTES attr = new SECURITY_ATTRIBUTES();

            attr.nLength = (int)Marshal.SizeOf(attr);
            byte[] sd = null;
            // If no securityDescriptor was set by the user use the default
            if (securityDescriptor == null)
            {
                securityDescriptor = s_securityDescriptor;
            }

            sd = new byte[securityDescriptor.BinaryLength];
            // Get the binary form of the descriptor
            securityDescriptor.GetBinaryForm(sd, 0);

            GCHandle pinningHandle = GCHandle.Alloc(sd, GCHandleType.Pinned);

            // get the address of the security descriptor
            attr.lpSecurityDescriptor = Marshal.UnsafeAddrOfPinnedArrayElement(sd, 0);

            // Create the named pipe with the appropriate name
            handle = NativePipe.CreateNamedPipe(pipeName,
                                                NativePipe.PIPE_ACCESS_DUPLEX | NativePipe.FILE_FLAG_OVERLAPPED
                                                | (exclusive ? NativePipe.FILE_FLAG_FIRST_PIPE_INSTANCE : 0x0), // Or exclusive flag
                                                NativePipe.PIPE_TYPE_BYTE | NativePipe.PIPE_READMODE_BYTE | NativePipe.PIPE_WAIT,
                                                NativePipe.PIPE_UNLIMITED_INSTANCES,
                                                8192,
                                                8192,
                                                NativePipe.NMPWAIT_WAIT_FOREVER,
                                                attr);

            pinningHandle.Free();
            if (handle.Handle.ToInt32() == NativePipe.INVALID_HANDLE_VALUE)
            {
                int error = Marshal.GetLastWin32Error();
                throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_CreateIpcFailed"), GetMessage(error)));
            }

            return(new IpcPort(portName, handle));
        }
Exemplo n.º 10
0
        internal unsafe void Write(byte[] data, int offset, int size)
        {
            int  lpNumberOfBytesWritten = 0;
            bool flag = false;

            fixed(byte *numRef = data)
            {
                flag = NativePipe.WriteFile(this._handle, numRef + offset, size, ref lpNumberOfBytesWritten, IntPtr.Zero);
            }

            if (!flag)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_WriteFailure"), new object[] { GetMessage(errorCode) }));
            }
        }
Exemplo n.º 11
0
        internal unsafe int Read(byte[] data, int offset, int length)
        {
            bool flag = false;
            int  lpNumberOfBytesRead = 0;

            fixed(byte *numRef = data)
            {
                flag = NativePipe.ReadFile(this._handle, numRef + offset, length, ref lpNumberOfBytesRead, IntPtr.Zero);
            }

            if (!flag)
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ReadFailure"), new object[] { GetMessage(errorCode) }));
            }
            return(lpNumberOfBytesRead);
        }
Exemplo n.º 12
0
        internal unsafe void Write(byte[] data, int offset, int size)
        {
            int  numBytesWritten = 0;
            bool status          = false;

            // pin the buffer and write data
            fixed(byte *p = data)
            {
                status = NativePipe.WriteFile(_handle, p + offset, size, ref numBytesWritten, IntPtr.Zero);
            }

            if (!status)
            {
                int error = Marshal.GetLastWin32Error();
                throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_WriteFailure"), GetMessage(error)));
            }
        }
Exemplo n.º 13
0
        internal static IpcPort Connect(string portName, bool secure, TokenImpersonationLevel impersonationLevel, int timeout)
        {
            string lpFileName = @"\\.\pipe\" + portName;
            uint   num        = 0x100000;

            if (secure)
            {
                switch (impersonationLevel)
                {
                case TokenImpersonationLevel.None:
                    num = 0x100000;
                    break;

                case TokenImpersonationLevel.Identification:
                    num = 0x110000;
                    break;

                case TokenImpersonationLevel.Impersonation:
                    num = 0x120000;
                    break;

                case TokenImpersonationLevel.Delegation:
                    num = 0x130000;
                    break;
                }
            }
            while (true)
            {
                PipeHandle handle = NativePipe.CreateFile(lpFileName, 0xc0000000, 3, IntPtr.Zero, 3, 0x40000080 | num, IntPtr.Zero);
                if (handle.Handle.ToInt32() != -1)
                {
                    return(new IpcPort(portName, handle));
                }
                int errorCode = Marshal.GetLastWin32Error();
                if (errorCode != 0xe7L)
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ConnectIpcFailed"), new object[] { GetMessage(errorCode) }));
                }
                if (!NativePipe.WaitNamedPipe(lpFileName, timeout))
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_Busy"), new object[] { GetMessage(errorCode) }));
                }
            }
        }
Exemplo n.º 14
0
        // Gets an error message for a Win32 error code.
        internal static String GetMessage(int errorCode)
        {
            StringBuilder sb     = new StringBuilder(512);
            int           result = NativePipe.FormatMessage(NativePipe.FORMAT_MESSAGE_IGNORE_INSERTS |
                                                            NativePipe.FORMAT_MESSAGE_FROM_SYSTEM | NativePipe.FORMAT_MESSAGE_ARGUMENT_ARRAY,
                                                            NativePipe.NULL, errorCode, 0, sb, sb.Capacity, NativePipe.NULL);

            if (result != 0)
            {
                // result is the # of characters copied to the StringBuilder on NT,
                // but on Win9x, it appears to be the number of MBCS bytes.
                // Just give up and return the String as-is...
                String s = sb.ToString();
                return(s);
            }
            else
            {
                return(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_UnknownError_Num"), errorCode.ToString(CultureInfo.InvariantCulture)));
            }
        }
Exemplo n.º 15
0
        internal unsafe int Read(byte[] data, int offset, int length)
        {
            bool status       = false;
            int  numBytesRead = 0;

            fixed(byte *p = data)
            {
                status = NativePipe.ReadFile(_handle, p + offset, length, ref numBytesRead, IntPtr.Zero);
            }

            if (!status)
            {
                int error = Marshal.GetLastWin32Error();
                throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ReadFailure"), GetMessage(error)));
            }
            else
            {
                return(numBytesRead);
            }
        }
Exemplo n.º 16
0
        internal unsafe IAsyncResult BeginRead(byte[] data, int offset, int size, AsyncCallback callback, object state)
        {
            PipeAsyncResult asyncResult = new PipeAsyncResult(callback);
            // Create a managed overlapped class
            // We will set the file offsets later
            Overlapped overlapped = new Overlapped(0, 0, IntPtr.Zero, asyncResult);

            // Pack the Overlapped class, and store it in the async result
            NativeOverlapped *intOverlapped;

            intOverlapped           = overlapped.UnsafePack(IOCallback, data);
            asyncResult._overlapped = intOverlapped;
            bool status;

            // pin the buffer and read data with overlapped
            fixed(byte *p = data)
            {
                status = NativePipe.ReadFile(_handle, p + offset, size, IntPtr.Zero, intOverlapped);
            }

            if (!status)
            {
                int error = Marshal.GetLastWin32Error();
                // For pipes, when they hit EOF, they will come here.
                if (error == NativePipe.ERROR_BROKEN_PIPE)
                {
                    // Not an error, but EOF.  AsyncFSCallback will NOT be
                    // called.  Call the user callback here.
                    asyncResult.CallUserCallback();
                    // EndRead will free the Overlapped struct correctly.
                }
                else if (error != NativePipe.ERROR_IO_PENDING)
                {
                    throw new RemotingException(String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Ipc_ReadFailure"), GetMessage(error)));
                }
            }
            return(asyncResult);
        }
        internal void ServiceRequest(object state)
        {
            IpcServerHandler  handler        = (IpcServerHandler)state;
            ITransportHeaders requestHeaders = handler.ReadHeaders();
            Stream            requestStream  = handler.GetRequestStream();

            requestHeaders["__CustomErrorsEnabled"] = false;
            ServerChannelSinkStack sinkStack = new ServerChannelSinkStack();

            sinkStack.Push(this, handler);
            IMessage          responseMsg      = null;
            ITransportHeaders responseHeaders  = null;
            Stream            responseStream   = null;
            WindowsIdentity   current          = null;
            IPrincipal        currentPrincipal = null;
            bool             flag     = false;
            bool             flag2    = false;
            ServerProcessing complete = ServerProcessing.Complete;

            try
            {
                if (this._secure)
                {
                    handler.Port.ImpersonateClient();
                    currentPrincipal = Thread.CurrentPrincipal;
                    flag2            = true;
                    flag             = true;
                    current          = WindowsIdentity.GetCurrent();
                    if (!this._impersonate)
                    {
                        NativePipe.RevertToSelf();
                        Thread.CurrentPrincipal = new GenericPrincipal(current, null);
                        flag = false;
                    }
                    else
                    {
                        if ((current.ImpersonationLevel != TokenImpersonationLevel.Impersonation) && (current.ImpersonationLevel != TokenImpersonationLevel.Delegation))
                        {
                            throw new RemotingException(CoreChannel.GetResourceString("Remoting_Ipc_TokenImpersonationFailure"));
                        }
                        Thread.CurrentPrincipal = new WindowsPrincipal(current);
                    }
                }
                complete = this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream);
            }
            catch (Exception exception)
            {
                handler.CloseOnFatalError(exception);
            }
            finally
            {
                if (flag2)
                {
                    Thread.CurrentPrincipal = currentPrincipal;
                }
                if (flag)
                {
                    NativePipe.RevertToSelf();
                    flag = false;
                }
            }
            switch (complete)
            {
            case ServerProcessing.Complete:
                sinkStack.Pop(this);
                handler.SendResponse(responseHeaders, responseStream);
                break;

            case ServerProcessing.OneWay:
                handler.SendResponse(responseHeaders, responseStream);
                break;

            case ServerProcessing.Async:
                sinkStack.StoreAndDispatch(this, handler);
                break;
            }
            if (complete != ServerProcessing.Async)
            {
                handler.BeginReadMessage();
            }
        }
Exemplo n.º 18
0
        internal void ServiceRequest(Object state)
        {
            IpcServerHandler ipcServerHandler = (IpcServerHandler)state;

            // Read the headers from the stream, using the header size in the message
            ITransportHeaders headers = ipcServerHandler.ReadHeaders();

            // Get the request Stream
            Stream requestStream = ipcServerHandler.GetRequestStream();

            // customErrors should be disabled, since we are on the same machine
            headers["__CustomErrorsEnabled"] = false;

            // process request
            ServerChannelSinkStack sinkStack = new ServerChannelSinkStack();

            sinkStack.Push(this, ipcServerHandler);

            IMessage          responseMessage = null;
            ITransportHeaders responseHeaders = null;
            Stream            responseStream  = null;
            WindowsIdentity   identity        = null;
            IPrincipal        oldPrincipal    = null;
            bool             impersonated     = false;
            bool             principalChanged = false;
            ServerProcessing processing       = ServerProcessing.Complete;

            try{
                if (_secure)
                {
                    IpcPort port = ipcServerHandler.Port;
                    port.ImpersonateClient();
                    oldPrincipal     = Thread.CurrentPrincipal;
                    principalChanged = true;
                    impersonated     = true;
                    identity         = WindowsIdentity.GetCurrent();
                    // If the authentication mode is to identify callers only revert the impersonation immediately
                    if (!_impersonate)
                    {
                        NativePipe.RevertToSelf();
                        Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
                        impersonated            = false;
                    }
                    else
                    {
                        if (identity.ImpersonationLevel == TokenImpersonationLevel.Impersonation ||
                            identity.ImpersonationLevel == TokenImpersonationLevel.Delegation)
                        {
                            // Set the current principal
                            Thread.CurrentPrincipal = new WindowsPrincipal(identity);
                        }
                        else
                        {
                            throw new RemotingException(CoreChannel.GetResourceString(
                                                            "Remoting_Ipc_TokenImpersonationFailure"));
                        }
                    }
                }

                processing =
                    _nextSink.ProcessMessage(sinkStack, null, headers, requestStream,
                                             out responseMessage,
                                             out responseHeaders, out responseStream);
            }
            catch (Exception e) {
                ipcServerHandler.CloseOnFatalError(e);
            }
            finally{
                // Revert the principal if we had changed the principal
                if (principalChanged)
                {
                    Thread.CurrentPrincipal = oldPrincipal;
                }
                // Revert the impersonation if we had impersonated
                if (impersonated)
                {
                    NativePipe.RevertToSelf();
                    impersonated = false;
                }
            }

            // handle response
            switch (processing)
            {
            case ServerProcessing.Complete:
            {
                // Send the response. Call completed synchronously.
                sinkStack.Pop(this);
                // Send the response back to the client
                ipcServerHandler.SendResponse(responseHeaders, responseStream);
                break;
            } // case ServerProcessing.Complete

            case ServerProcessing.OneWay:
            {
                // No response needed, but the following method will make sure that
                //   we send at least a skeleton reply if the incoming request was
                //   not marked OneWayRequest (client/server metadata could be out of
                //   [....]).
                ipcServerHandler.SendResponse(responseHeaders, responseStream);
                break;
            } // case ServerProcessing.OneWay

            case ServerProcessing.Async:
            {
                sinkStack.StoreAndDispatch(this, ipcServerHandler);
                break;
            } // case ServerProcessing.Async
            } // switch (processing)

            // Start waiting for the next request
            if (processing != ServerProcessing.Async)
            {
                ipcServerHandler.BeginReadMessage();
            }
        } // ServiceRequest
 protected override bool ReleaseHandle()
 {
     return(NativePipe.CloseHandle(base.handle) != 0);
 }