예제 #1
0
        //
        // The overlapped function called (either by the thread pool or the socket)
        // when IO completes. (only called on Win9x)
        //
        private void OverlappedCallback(object stateObject, bool Signaled)
        {
#if DEBUG
            // GlobalLog.SetThreadSource(ThreadKinds.Worker);  Because of change 1077887, need logic to determine thread type here.
            using (GlobalLog.SetThreadKind(ThreadKinds.System)) {
#endif
            BaseOverlappedAsyncResult asyncResult = (BaseOverlappedAsyncResult)stateObject;

            GlobalLog.Assert(!asyncResult.InternalPeekCompleted, "AcceptOverlappedAsyncResult#{0}::OverlappedCallback()|asyncResult.IsCompleted", ValidationHelper.HashString(asyncResult));
            //
            // the IO completed asynchronously, see if there was a failure the Internal
            // field in the Overlapped structure will be non zero. to optimize the non
            // error case, we look at it without calling WSAGetOverlappedResult().
            //
            uint errorCode = (uint)Marshal.ReadInt32(IntPtrHelper.Add(asyncResult.m_UnmanagedBlob.DangerousGetHandle(),
                                                                      Win32.OverlappedInternalOffset));
            uint numBytes = errorCode != 0 ? unchecked ((uint)-1) : (uint)Marshal.ReadInt32(IntPtrHelper.Add(asyncResult.m_UnmanagedBlob.DangerousGetHandle(),
                                                                                                             Win32.OverlappedInternalHighOffset));
            //
            // this will release the unmanaged pin handles and unmanaged overlapped ptr
            //
            asyncResult.ErrorCode = (int)errorCode;
            object returnObject = asyncResult.PostCompletion((int)numBytes);
            asyncResult.ReleaseUnmanagedStructures();
            asyncResult.InvokeCallback(returnObject);
#if DEBUG
        }
#endif
        }
예제 #2
0
        /*++
         *  Write - provide core Write functionality.
         *
         *  Provide core write functionality. All we do is call through to the
         *  socket Send method..
         *
         *  Input:
         *
         *      Buffer  - Buffer to write from.
         *      Offset  - Offset into the buffer from where we'll start writing.
         *      Count   - Number of bytes to write.
         *
         *  Returns:
         *
         *      Number of bytes written. We'll throw an exception if we
         *      can't write everything. It's brutal, but there's no other
         *      way to indicate an error.
         * --*/

        /// <devdoc>
        ///    <para>
        ///       Writes data to the stream..
        ///    </para>
        /// </devdoc>
        public override void Write(byte[] buffer, int offset, int size)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            bool canWrite = CanWrite; // Prevent race with Dispose.
            if (m_CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (!canWrite)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
            }
            //
            // parameter validation
            //
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }


            Socket chkStreamSocket = m_StreamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
            }

            try {
                //
                // since the socket is in blocking mode this will always complete
                // after ALL the requested number of bytes was transferred
                //
                chkStreamSocket.Send(buffer, offset, size, SocketFlags.None);
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                {
                    throw;
                }

                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_writefailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
예제 #3
0
        //
        //
        protected override void Dispose(bool disposing)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            try
            {
                if (disposing)
                {
                    if (_LeaveStreamOpen)
                    {
                        _InnerStream.Flush();
                    }
                    else
                    {
                        _InnerStream.Close();
                    }
                }
            }
            finally
            {
                base.Dispose(disposing);
            }
#if DEBUG
        }
#endif
        }
예제 #4
0
        internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
            if (m_CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (!CanWrite)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_readonlystream));
            }

            Socket chkStreamSocket = m_StreamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
            }

            try {
                //
                // call BeginSend on the Socket.
                //
                IAsyncResult asyncResult =
                    chkStreamSocket.UnsafeBeginSend(
                        buffer,
                        offset,
                        size,
                        SocketFlags.None,
                        callback,
                        state);

                return(asyncResult);
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                {
                    throw;
                }

                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_writefailure, exception.Message), exception);
            }
            catch {
                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_writefailure, string.Empty), new Exception(SR.GetString(SR.net_nonClsCompliantException)));
            }
#if DEBUG
        }
#endif
        }
예제 #5
0
        /*++
         *  Read - provide core Read functionality.
         *
         *  Provide core read functionality. All we do is call through to the
         *  socket Receive functionality.
         *
         *  Input:
         *
         *      Buffer  - Buffer to read into.
         *      Offset  - Offset into the buffer where we're to read.
         *      Count   - Number of bytes to read.
         *
         *  Returns:
         *
         *      Number of bytes we read, or 0 if the socket is closed.
         *
         * --*/

        /// <devdoc>
        ///    <para>
        ///       Reads data from the stream.
        ///    </para>
        /// </devdoc>
        //UEUE
        public override int Read([In, Out] byte[] buffer, int offset, int size)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            bool canRead = CanRead;  // Prevent race with Dispose.
            if (m_CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (!canRead)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_writeonlystream));
            }
            //
            // parameter validation
            //
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }


            Socket chkStreamSocket = m_StreamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
            }

            try {
                int bytesTransferred = chkStreamSocket.Receive(buffer, offset, size, 0);
                return(bytesTransferred);
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                {
                    throw;
                }

                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_readfailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
예제 #6
0
        // Should this not block?
        public override void Flush()
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            InnerStream.Flush();
#if DEBUG
        }
#endif
        }
예제 #7
0
        //
        public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            _NegoState.EndProcessAuthentication(asyncResult);
#if DEBUG
        }
#endif
        }
예제 #8
0
        private void EndAuthenticateAsClient(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User))
            {
#endif
            _negoState.EndProcessAuthentication(asyncResult);
#if DEBUG
        }
#endif
        }
예제 #9
0
        internal virtual IAsyncResult UnsafeBeginMultipleWrite(
            BufferOffsetSize[] buffers,
            AsyncCallback callback,
            Object state)
        {
#if DEBUG
            GlobalLog.ThreadContract(ThreadKinds.Unknown, "NetworkStream#" + ValidationHelper.HashString(this) + "::BeginMultipleWrite");
            using (GlobalLog.SetThreadKind(ThreadKinds.Async)) {
#endif

            //
            // parameter validation
            //
            if (buffers == null)
            {
                throw new ArgumentNullException("buffers");
            }

            Socket chkStreamSocket = m_StreamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
            }

            try {
                //
                // call BeginMultipleSend on the Socket.
                //
                IAsyncResult asyncResult =
                    chkStreamSocket.UnsafeBeginMultipleSend(
                        buffers,
                        SocketFlags.None,
                        callback,
                        state);

                return(asyncResult);
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                {
                    throw;
                }

                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_writefailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
예제 #10
0
        public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            _NegoState = new NegoState(innerStream, leaveInnerStreamOpen);
            _Package   = NegoState.DefaultPackage;
            InitializeStreamPart();
#if DEBUG
        }
#endif
        }
예제 #11
0
        public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
            {
#endif
            _negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);
            _negoState.ProcessAuthentication(null);
#if DEBUG
        }
#endif
        }
예제 #12
0
        internal virtual IAsyncResult UnsafeBeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
            {
#endif
            bool canWrite = CanWrite;     // Prevent race with Dispose.
            if (_cleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            if (!canWrite)
            {
                throw new InvalidOperationException(SR.net_readonlystream);
            }

            Socket chkStreamSocket = _streamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed));
            }

            try
            {
                // Call BeginSend on the Socket.
                IAsyncResult asyncResult =
                    chkStreamSocket.UnsafeBeginSend(
                        buffer,
                        offset,
                        size,
                        SocketFlags.None,
                        callback,
                        state);

                return(asyncResult);
            }
            catch (Exception exception)
            {
                if (exception is OutOfMemoryException)
                {
                    throw;
                }

                // Some sort of error occurred on the socket call,
                // set the SocketException as InnerException and throw.
                throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
예제 #13
0
        public virtual void AuthenticateAsClient(
            NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
            {
#endif
            _negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);
            _negoState.ProcessAuthentication(null);
#if DEBUG
        }
#endif
        }
예제 #14
0
        /*++
         *  EndRead - handle the end of an async read.
         *
         *  This method is called when an async read is completed. All we
         *  do is call through to the core socket EndReceive functionality.
         *  Input:
         *
         *      buffer  - Buffer to read into.
         *      offset  - Offset into the buffer where we're to read.
         *      size   - Number of bytes to read.
         *
         *  Returns:
         *
         *      The number of bytes read. May throw an exception.
         *
         * --*/

        /// <devdoc>
        ///    <para>
        ///       Handle the end of an asynchronous read.
        ///    </para>
        /// </devdoc>
        public override int EndRead(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            if (m_CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            //
            // parameter validation
            //
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            Socket chkStreamSocket = m_StreamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.GetString(SR.net_io_readfailure, SR.GetString(SR.net_io_connectionclosed)));
            }

            try {
                int bytesTransferred = chkStreamSocket.EndReceive(asyncResult);
                return(bytesTransferred);
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                {
                    throw;
                }

                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_readfailure, exception.Message), exception);
            }
            catch {
                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_readfailure, string.Empty), new Exception(SR.GetString(SR.net_nonClsCompliantException)));
            }
#if DEBUG
        }
#endif
        }
예제 #15
0
        // Can be constructed directly out of a socket
        /// <devdoc>
        /// <para>Creates a new instance of the <see cref='System.Net.Sockets.NetworkStream'/> class for the specified <see cref='System.Net.Sockets.Socket'/>.</para>
        /// </devdoc>
        public NetworkStream(Socket socket)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }
            InitNetworkStream(socket, FileAccess.ReadWrite);
#if DEBUG
        }
#endif
        }
예제 #16
0
        // Starts off an async Write of an array of buffers.
        internal virtual IAsyncResult BeginMultipleWrite(
            BufferOffsetSize[] buffers,
            AsyncCallback callback,
            Object state)
        {
#if DEBUG
            GlobalLog.ThreadContract(ThreadKinds.Unknown, "NetworkStream#" + Logging.HashString(this) + "::BeginMultipleWrite");
            using (GlobalLog.SetThreadKind(ThreadKinds.Async))
            {
#endif
            // Validate input parameters.
            if (buffers == null)
            {
                throw new ArgumentNullException("buffers");
            }

            Socket chkStreamSocket = _streamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.Format(SR.net_io_writefailure, SR.net_io_connectionclosed));
            }

            try
            {
                // Call BeginMultipleSend on the Socket.
                IAsyncResult asyncResult =
                    chkStreamSocket.BeginMultipleSend(
                        buffers,
                        SocketFlags.None,
                        callback,
                        state);

                return(asyncResult);
            }
            catch (Exception exception)
            {
                if (exception is OutOfMemoryException)
                {
                    throw;
                }

                // Some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw.
                throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
예제 #17
0
        private int EndRead(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User))
            {
#endif
            _negoState.CheckThrow(true);

            if (!_negoState.CanGetSecureStream)
            {
                return(InnerStreamAPM.EndRead(asyncResult));
            }


            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
            if (bufferResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            bufferResult.InternalWaitForCompletion();

            if (bufferResult.Result is Exception)
            {
                if (bufferResult.Result is IOException)
                {
                    throw (Exception)bufferResult.Result;
                }

                throw new IOException(SR.net_io_read, (Exception)bufferResult.Result);
            }

            return((int)bufferResult.Result);

#if DEBUG
        }
#endif
        }
예제 #18
0
        // Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket.
        public NetworkStream(Socket socket)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User))
            {
#endif
            if (socket == null)
            {
                throw new ArgumentNullException(nameof(socket));
            }
            InitNetworkStream(socket);
#if DEBUG
        }
#endif
        }
예제 #19
0
        //
        //
        protected override void Dispose(bool disposing)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            try {
                _NegoState.Close();
            }
            finally {
                base.Dispose(disposing);
            }
#if DEBUG
        }
#endif
        }
예제 #20
0
        private int m_CloseTimeout = Socket.DefaultCloseTimeout; // 1 ms; -1 = respect linger options

        public void Close(int timeout)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            if (timeout < -1)
            {
                throw new ArgumentOutOfRangeException("timeout");
            }
            m_CloseTimeout = timeout;
            Close();
#if DEBUG
        }
#endif
        }
예제 #21
0
        public NetworkStream(Socket socket, FileAccess access, bool ownsSocket)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User))
            {
#endif
            if (socket == null)
            {
                throw new ArgumentNullException(nameof(socket));
            }
            if (!socket.Blocking)
            {
                throw new IOException(SR.net_sockets_blocking);
            }
            if (!socket.Connected)
            {
                throw new IOException(SR.net_notconnected);
            }
            if (socket.SocketType != SocketType.Stream)
            {
                throw new IOException(SR.net_notstream);
            }

            _streamSocket = socket;
            _ownsSocket   = ownsSocket;

            switch (access)
            {
            case FileAccess.Read:
                _readable = true;
                break;

            case FileAccess.Write:
                _writeable = true;
                break;

            case FileAccess.ReadWrite:
            default:         // assume FileAccess.ReadWrite
                _readable  = true;
                _writeable = true;
                break;
            }
#if DEBUG
        }
#endif
        }
예제 #22
0
        //
        //
        public override void Write(byte[] buffer, int offset, int count)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            _NegoState.CheckThrow(true);

            if (!_NegoState.CanGetSecureStream)
            {
                InnerStream.Write(buffer, offset, count);
                return;
            }

            ProcessWrite(buffer, offset, count, null);
#if DEBUG
        }
#endif
        }
예제 #23
0
        //
        //
        public override int Read(byte[] buffer, int offset, int count)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            _NegoState.CheckThrow(true);

            if (!_NegoState.CanGetSecureStream)
            {
                return(InnerStream.Read(buffer, offset, count));
            }

            return(ProcessRead(buffer, offset, count, null));

#if DEBUG
        }
#endif
        }
예제 #24
0
        //
        //
        public override void EndWrite(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            _NegoState.CheckThrow(true);

            if (!_NegoState.CanGetSecureStream)
            {
                InnerStream.EndWrite(asyncResult);
                return;
            }

            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
            if (bufferResult == null)
            {
                throw new ArgumentException(SR.GetString(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _NestedWrite, 0) == 0)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndWrite"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            bufferResult.InternalWaitForCompletion();

            if (bufferResult.Result is Exception)
            {
                if (bufferResult.Result is IOException)
                {
                    throw (Exception)bufferResult.Result;
                }
                throw new IOException(SR.GetString(SR.net_io_write), (Exception)bufferResult.Result);
            }
#if DEBUG
        }
#endif
        }
예제 #25
0
        /// <devdoc>
        ///    <para>
        ///       Handle the end of an asynchronous write.
        ///       This method is called when an async write is completed. All we
        ///       do is call through to the core socket EndSend functionality.
        ///       Returns:  The number of bytes read. May throw an exception.
        ///    </para>
        /// </devdoc>
        public override void EndWrite(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            if (m_CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            //
            // parameter validation
            //
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            Socket chkStreamSocket = m_StreamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.GetString(SR.net_io_writefailure, SR.GetString(SR.net_io_connectionclosed)));
            }

            try {
                chkStreamSocket.EndSend(asyncResult);
            }
            catch (Exception exception) {
                if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException)
                {
                    throw;
                }

                //
                // some sort of error occured on the socket call,
                // set the SocketException as InnerException and throw
                //
                throw new IOException(SR.GetString(SR.net_io_writefailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
예제 #26
0
        // EndRead - handle the end of an async read.
        //
        // This method is called when an async read is completed. All we
        // do is call through to the core socket EndReceive functionality.
        //
        // Returns:
        //
        //     The number of bytes read. May throw an exception.
        public int EndRead(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User))
            {
#endif
            if (_cleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }

            // Validate input parameters.
            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            Socket chkStreamSocket = _streamSocket;
            if (chkStreamSocket == null)
            {
                throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed));
            }

            try
            {
                int bytesTransferred = chkStreamSocket.EndReceive(asyncResult);
                return(bytesTransferred);
            }
            catch (Exception exception)
            {
                if (exception is OutOfMemoryException)
                {
                    throw;
                }

                // Some sort of error occurred on the socket call,
                // set the SocketException as InnerException and throw.
                throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
            }
#if DEBUG
        }
#endif
        }
예제 #27
0
        protected override void Dispose(bool disposing)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            // Mark this as disposed before changing anything else.
            bool cleanedUp = m_CleanedUp;
            m_CleanedUp = true;
            if (!cleanedUp && disposing)
            {
                //
                // only resource we need to free is the network stream, since this
                // is based on the client socket, closing the stream will cause us
                // to flush the data to the network, close the stream and (in the
                // NetoworkStream code) close the socket as well.
                //
                if (m_StreamSocket != null)
                {
                    m_Readable  = false;
                    m_Writeable = false;
                    if (m_OwnsSocket)
                    {
                        //
                        // if we own the Socket (false by default), close it
                        // ignoring possible exceptions (eg: the user told us
                        // that we own the Socket but it closed at some point of time,
                        // here we would get an ObjectDisposedException)
                        //
                        Socket chkStreamSocket = m_StreamSocket;
                        if (chkStreamSocket != null)
                        {
                            chkStreamSocket.InternalShutdown(SocketShutdown.Both);
                            chkStreamSocket.Close(m_CloseTimeout);
                        }
                    }
                }
            }
#if DEBUG
        }
#endif
            base.Dispose(disposing);
        }
예제 #28
0
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
            _NegoState.CheckThrow(true);

            if (!_NegoState.CanGetSecureStream)
            {
                return(InnerStream.BeginRead(buffer, offset, count, asyncCallback, asyncState));
            }

            BufferAsyncResult bufferResult    = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback);
            AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult);
            ProcessRead(buffer, offset, count, asyncRequest);
            return(bufferResult);

#if DEBUG
        }
#endif
        }
예제 #29
0
        public virtual IAsyncResult BeginAuthenticateAsServer(NetworkCredential credential,
                                                              ExtendedProtectionPolicy policy,
                                                              ProtectionLevel requiredProtectionLevel,                    //throw if the result is below than this
                                                              TokenImpersonationLevel requiredImpersonationLevel,         //throw if the result is below than this
                                                              AsyncCallback asyncCallback,
                                                              object asyncState)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
            _NegoState.ValidateCreateContext(_Package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel);

            LazyAsyncResult result = new LazyAsyncResult(_NegoState, asyncState, asyncCallback);
            _NegoState.ProcessAuthentication(result);

            return(result);

#if DEBUG
        }
#endif
        }
예제 #30
0
        public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential,
                                                              ChannelBinding binding,
                                                              string targetName,
                                                              ProtectionLevel requiredProtectionLevel,
                                                              TokenImpersonationLevel allowedImpersonationLevel,
                                                              AsyncCallback asyncCallback,
                                                              object asyncState)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
            _NegoState.ValidateCreateContext(_Package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel);

            LazyAsyncResult result = new LazyAsyncResult(_NegoState, asyncState, asyncCallback);
            _NegoState.ProcessAuthentication(result);

            return(result);

#if DEBUG
        }
#endif
        }