InvokeCallback() private method

private InvokeCallback ( ) : void
return void
Exemplo n.º 1
0
        private static void GetRequestStreamCallback(object state)
        {
            GlobalLog.Enter("FileWebRequest::GetRequestStreamCallback");
            LazyAsyncResult asyncResult = (LazyAsyncResult)state;
            FileWebRequest  request     = (FileWebRequest)asyncResult.AsyncObject;

            try
            {
                if (request.m_stream == null)
                {
                    request.m_stream     = new FileWebStream(request, request.m_uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read);
                    request.m_fileAccess = FileAccess.Write;
                    request.m_writing    = true;
                }
            }
            catch (Exception e)
            {
                // any exceptions previously thrown must be passed to the callback
                Exception ex = new WebException(e.Message, e);
                GlobalLog.LeaveException("FileWebRequest::GetRequestStreamCallback", ex);

                // if the callback throws, correct behavior is to crash the process
                asyncResult.InvokeCallback(ex);
                return;
            }

            // if the callback throws, correct behavior is to crash the process
            asyncResult.InvokeCallback(request.m_stream);
            GlobalLog.Leave("FileWebRequest::GetRequestStreamCallback");
        }
Exemplo n.º 2
0
        private void AsyncReadCallback(IAsyncResult ar)
        {
            LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState;

            try
            {
                try
                {
                    int readBytes = _networkStream.EndRead(ar);
                    if (readBytes == 0)
                    {
                        _isFullyRead = true;
                        Close(); // This should block for pipeline completion
                    }
                    userResult.InvokeCallback(readBytes);
                }
                catch (Exception exception)
                {
                    // Complete with error. If already completed rethrow on the worker thread
                    if (!userResult.IsCompleted)
                    {
                        userResult.InvokeCallback(exception);
                    }
                }
            }
            catch { }
        }
        private void AsyncReadCallback(IAsyncResult ar)
        {
            LazyAsyncResult asyncState = (LazyAsyncResult)ar.AsyncState;

            try
            {
                try
                {
                    int result = this.m_NetworkStream.EndRead(ar);
                    if (result == 0)
                    {
                        this.m_IsFullyRead = true;
                        this.Close();
                    }
                    asyncState.InvokeCallback(result);
                }
                catch (Exception exception)
                {
                    if (!asyncState.IsCompleted)
                    {
                        asyncState.InvokeCallback(exception);
                    }
                }
            }
            catch
            {
            }
        }
        private static void GetResponseCallback(object state)
        {
            LazyAsyncResult result      = (LazyAsyncResult)state;
            FileWebRequest  asyncObject = (FileWebRequest)result.AsyncObject;

            if (asyncObject.m_writePending || asyncObject.m_writing)
            {
                lock (asyncObject)
                {
                    if (asyncObject.m_writePending || asyncObject.m_writing)
                    {
                        asyncObject.m_readerEvent = new ManualResetEvent(false);
                    }
                }
            }
            if (asyncObject.m_readerEvent != null)
            {
                asyncObject.m_readerEvent.WaitOne();
            }
            try
            {
                if (asyncObject.m_response == null)
                {
                    asyncObject.m_response = new FileWebResponse(asyncObject, asyncObject.m_uri, asyncObject.m_fileAccess, !asyncObject.m_syncHint);
                }
            }
            catch (Exception exception)
            {
                Exception exception2 = new WebException(exception.Message, exception);
                result.InvokeCallback(exception2);
                return;
            }
            result.InvokeCallback(asyncObject.m_response);
        }
Exemplo n.º 5
0
        private void CompleteUserRead(object result)
        {
            bool error = result is Exception;

            // Reset user buffer information.
            this.userBuffer       = null;
            this.userBufferCount  = 0;
            this.userBufferOffset = 0;

            if (error)
            {
                TransitionToErrorState();
            }

            if (IsAsync)
            {
                LazyAsyncResult localResult = userAsyncResult;
                userAsyncResult = null;

                localResult.InvokeCallback(result);
            }
            else
            {
                if (error)
                {
                    throw result as Exception;
                }

                Contract.Assert(result is int);
                syncResult = (int)result;
            }
        }
        private void WakeupPendingIO(IAsyncResult ar)
        {
            Exception exception = null;

            try
            {
                if (ar != null)
                {
                    this.m_Worker.EndProcessAuthentication(ar);
                }
            }
            catch (Exception exception2)
            {
                exception = exception2;
                if (this.m_Worker.IsCertValidationFailed)
                {
                    this.m_ExceptionStatus = WebExceptionStatus.TrustFailure;
                }
                else if (this.m_Worker.LastSecurityStatus != SecurityStatus.OK)
                {
                    this.m_ExceptionStatus = WebExceptionStatus.SecureChannelFailure;
                }
                else
                {
                    this.m_ExceptionStatus = WebExceptionStatus.ReceiveFailure;
                }
            }
            lock (this.m_PendingIO)
            {
                while (this.m_PendingIO.Count != 0)
                {
                    LazyAsyncResult result = (LazyAsyncResult)this.m_PendingIO[this.m_PendingIO.Count - 1];
                    this.m_PendingIO.RemoveAt(this.m_PendingIO.Count - 1);
                    if (result is BufferAsyncResult)
                    {
                        if (this.m_PendingIO.Count == 0)
                        {
                            this.ResumeIOWorker(result);
                        }
                        else
                        {
                            ThreadPool.QueueUserWorkItem(new WaitCallback(this.ResumeIOWorker), result);
                        }
                    }
                    else
                    {
                        try
                        {
                            result.InvokeCallback(exception);
                            continue;
                        }
                        catch
                        {
                            continue;
                        }
                    }
                }
            }
        }
Exemplo n.º 7
0
        private static void GetResponseCallback(object state)
        {
            GlobalLog.Enter("FileWebRequest::GetResponseCallback");
            LazyAsyncResult asyncResult = (LazyAsyncResult)state;
            FileWebRequest  request     = (FileWebRequest)asyncResult.AsyncObject;

            if (request.m_writePending || request.m_writing)
            {
                lock (request) {
                    if (request.m_writePending || request.m_writing)
                    {
                        request.m_readerEvent = new ManualResetEvent(false);
                    }
                }
            }
            if (request.m_readerEvent != null)
            {
                request.m_readerEvent.WaitOne();
            }

            try
            {
                if (request.m_response == null)
                {
                    request.m_response = new FileWebResponse(request, request.m_uri, request.m_fileAccess, !request.m_syncHint);
                }
            }
            catch (Exception e)
            {
                // any exceptions previously thrown must be passed to the callback
                Exception ex = new WebException(e.Message, e);
                GlobalLog.LeaveException("FileWebRequest::GetResponseCallback", ex);

                // if the callback throws, correct behavior is to crash the process
                asyncResult.InvokeCallback(ex);
                return;
            }

            // if the callback throws, the correct behavior is to crash the process
            asyncResult.InvokeCallback(request.m_response);
            GlobalLog.Leave("FileWebRequest::GetResponseCallback");
        }
Exemplo n.º 8
0
        public override void Abort()
        {
            GlobalLog.Enter("FileWebRequest::Abort");
            if (Logging.On)
            {
                Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled));
            }
            try {
                if (Interlocked.Increment(ref m_Aborted) == 1)
                {
                    LazyAsyncResult readAResult  = m_ReadAResult;
                    LazyAsyncResult writeAResult = m_WriteAResult;

                    WebException webException = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);

                    Stream requestStream = m_stream;

                    if (readAResult != null && !readAResult.IsCompleted)
                    {
                        readAResult.InvokeCallback(webException);
                    }
                    if (writeAResult != null && !writeAResult.IsCompleted)
                    {
                        writeAResult.InvokeCallback(webException);
                    }

                    if (requestStream != null)
                    {
                        if (requestStream is ICloseEx)
                        {
                            ((ICloseEx)requestStream).CloseEx(CloseExState.Abort);
                        }
                        else
                        {
                            requestStream.Close();
                        }
                    }

                    if (m_response != null)
                    {
                        ((ICloseEx)m_response).CloseEx(CloseExState.Abort);
                    }
                }
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "Abort", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::Abort");
            }
        }
        private static void GetRequestStreamCallback(object state)
        {
            LazyAsyncResult result      = (LazyAsyncResult)state;
            FileWebRequest  asyncObject = (FileWebRequest)result.AsyncObject;

            try
            {
                if (asyncObject.m_stream == null)
                {
                    asyncObject.m_stream     = new FileWebStream(asyncObject, asyncObject.m_uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read);
                    asyncObject.m_fileAccess = FileAccess.Write;
                    asyncObject.m_writing    = true;
                }
            }
            catch (Exception exception)
            {
                Exception exception2 = new WebException(exception.Message, exception);
                result.InvokeCallback(exception2);
                return;
            }
            result.InvokeCallback(asyncObject.m_stream);
        }
 private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
 {
     if (this.HandshakeComplete && this._RemoteOk)
     {
         if (lazyResult != null)
         {
             lazyResult.InvokeCallback();
         }
     }
     else
     {
         this.StartReceiveBlob(lazyResult);
     }
 }
 public override void Abort()
 {
     if (Logging.On)
     {
         Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled));
     }
     try
     {
         if (Interlocked.Increment(ref this.m_Aborted) == 1)
         {
             LazyAsyncResult readAResult  = this.m_ReadAResult;
             LazyAsyncResult writeAResult = this.m_WriteAResult;
             WebException    result       = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
             Stream          stream       = this.m_stream;
             if ((readAResult != null) && !readAResult.IsCompleted)
             {
                 readAResult.InvokeCallback(result);
             }
             if ((writeAResult != null) && !writeAResult.IsCompleted)
             {
                 writeAResult.InvokeCallback(result);
             }
             if (stream != null)
             {
                 if (stream is ICloseEx)
                 {
                     ((ICloseEx)stream).CloseEx(CloseExState.Abort);
                 }
                 else
                 {
                     stream.Close();
                 }
             }
             if (this.m_response != null)
             {
                 ((ICloseEx)this.m_response).CloseEx(CloseExState.Abort);
             }
         }
     }
     catch (Exception exception2)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "Abort", exception2);
         }
         throw;
     }
 }
 private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult)
 {
     if (this.HandshakeComplete)
     {
         if (!this._RemoteOk)
         {
             throw new AuthenticationException(SR.GetString("net_io_header_id", new object[] { "MessageId", this._Framer.ReadHeader.MessageId, 20 }), null);
         }
         if (lazyResult != null)
         {
             lazyResult.InvokeCallback();
         }
     }
     else
     {
         this.StartSendBlob(message, lazyResult);
     }
 }
Exemplo n.º 13
0
        /*
            Accessor:   BeginGetRequestStream

            Retreives the Request Stream from an HTTP Request uses an Async
              operation to do this, and the result is retrived async.

            Async operations include work in progess, this call is used to retrieve
             results by pushing the async operations to async worker thread on the callback.
            There are many open issues involved here including the handling of possible blocking
            within the bounds of the async worker thread or the case of Write and Read stream
            operations still blocking.


            Input:

            Returns: The Async Result


        */
        /// <include file='doc\HttpWebRequest.uex' path='docs/doc[@for="HttpWebRequest.BeginGetRequestStream"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetRequestStream");

            if (!CanGetRequestStream) {
                throw new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
            }

            // prevent someone from trying to send data without setting
            // a ContentLength or SendChunked when buffering is disabled and on a KeepAlive connection
            if (MissingEntityBodyDelimiter) {
                throw new ProtocolViolationException(SR.GetString(SR.net_contentlengthmissing));
            }

            // prevent someone from setting a Transfer Encoding without having SendChunked=true
            if (TransferEncodingWithoutChunked) {
                throw new InvalidOperationException(SR.GetString(SR.net_needchunked));
            }

            // used to make sure the user issues a GetRequestStream before GetResponse
            _WriteStreamRetrieved = true;

            Monitor.Enter(this);

            if (_WriteAResult != null) {

                Monitor.Exit(this);

                throw new InvalidOperationException(SR.GetString(SR.net_repcall));
            }

            // get async going
            LazyAsyncResult asyncResult =
                new LazyAsyncResult(
                    this,
                    state,
                    callback );

            _WriteAResult = asyncResult;
            Monitor.Exit(this);

            //
            // See if we're already submitted a request.
            //
            if (_RequestSubmitted) {
                // We already have. Make sure we have a write stream.
                if (_SubmitWriteStream != null) {
                    // It was, just return the stream.
                    try {
                        asyncResult.InvokeCallback(true, _SubmitWriteStream);
                    }
                    catch {
                        Abort();
                        throw;
                    }

                    goto done;
                }
                else {
                    //
                    // No write stream, this is an application error.
                    //
                    if (_ResponseException!=null) {
                        //
                        // somebody already aborted for some reason
                        // rethrow for the same reason
                        //
                        throw _ResponseException;
                    }
                    else {
                        throw new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    }
                }
            }

            // OK, we haven't submitted the request yet, so do so
            // now.
            //

            // prevent new requests when low on resources
            if (System.Net.Connection.IsThreadPoolLow()) {
                throw new InvalidOperationException(SR.GetString(SR.net_needmorethreads));
            }

            if (_HttpWriteMode == HttpWriteMode.None) {
                _HttpWriteMode = HttpWriteMode.Write;
            }

            // save off verb from origin Verb
            GlobalLog.Print("HttpWebRequest#"+ValidationHelper.HashString(this)+": setting _Verb to _OriginVerb ["+_OriginVerb+"]");
            _Verb = _OriginVerb;
            BeginSubmitRequest(false);

done:
            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetRequestStream", ValidationHelper.HashString(asyncResult));
            return asyncResult;
        }
Exemplo n.º 14
0
 //
 // This will check and logically complete the auth handshake
 //
 private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
 {
     if (HandshakeComplete && _RemoteOk)
     {
         //we are done with success
         if (lazyResult != null)
         {
             lazyResult.InvokeCallback();
         }
         return;
     }
     StartReceiveBlob(lazyResult);
 }
 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
 {
     Write(buffer, offset, count);
     LazyAsyncResult ar = new LazyAsyncResult(null, state, callback);
     ar.InvokeCallback(null);
     return ar;
 }
Exemplo n.º 16
0
        //
        // This will check and logically complete the auth handshake
        //
        private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult)
        {
            //If we are done don't go into send
            if (HandshakeComplete)
            {
                if (!_RemoteOk)
                {
                    throw new AuthenticationException(SR.GetString(SR.net_io_header_id, "MessageId", _Framer.ReadHeader.MessageId, FrameHeader.HandshakeDoneId), null);
                }
                if (lazyResult != null)
                {
                    lazyResult.InvokeCallback();
                }
                return;
            }

            // Not yet done, get a new blob and send it if any
            StartSendBlob(message, lazyResult);
        }
 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
 {
     this.Write(buffer, offset, count);
     LazyAsyncResult result = new LazyAsyncResult(null, state, callback);
     result.InvokeCallback(null);
     return result;
 }
Exemplo n.º 18
0
        /*
            Accessor:   BeginGetResponse

            Used to query for the Response of an HTTP Request using Async


            Input:

            Returns: The Async Result


        */

        /// <include file='doc\HttpWebRequest.uex' path='docs/doc[@for="HttpWebRequest.BeginGetResponse"]/*' />
        /// <devdoc>
        /// </devdoc>
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse");

            // prevent someone from setting ContentLength/Chunked, and the doing a Get
            if (_HttpWriteMode!=HttpWriteMode.None && !CanGetRequestStream) {
                throw new ProtocolViolationException(SR.GetString(SR.net_nocontentlengthonget));
            }

            // prevent someone from trying to send data without setting
            // a ContentLength or SendChunked when buffering is disabled and on a KeepAlive connection
            if (MissingEntityBodyDelimiter) {
                throw new ProtocolViolationException(SR.GetString(SR.net_contentlengthmissing));
            }

            // prevent someone from setting a Transfer Encoding without having SendChunked=true
            if (TransferEncodingWithoutChunked) {
                throw new InvalidOperationException(SR.GetString(SR.net_needchunked));
            }


            Monitor.Enter(this);

            if (_ReadAResult != null) {
                Monitor.Exit(this);
                throw new InvalidOperationException(SR.GetString(SR.net_repcall));
            }

            // Set the async object, so we can save it for the callback
            //
            // We do this in an interlocked fashion. The checking and setting of
            // _ReadAResult must be interlocked with the check of _HaveResponse
            // to avoid a race condition with our async receive thread.

            //
            // get async going
            //

            // prevent new requests when low on resources

            if (System.Net.Connection.IsThreadPoolLow()) {
                Monitor.Exit(this);
                throw new InvalidOperationException(SR.GetString(SR.net_needmorethreads));
            }

            LazyAsyncResult asyncResult =
                new LazyAsyncResult(
                    this,
                    state,
                    callback );

            _ReadAResult = asyncResult;

            // See if we already have a response. If we have, we can
            // just return it.

            if (_HaveResponse) {
                Monitor.Exit(this);

                // Already have a response, so return it if it's valid.

                if (_HttpResponse != null) {
                    try {
                        asyncResult.InvokeCallback(true, _HttpResponse);
                    }
                    catch {
                        Abort();
                        throw;
                    }
                    goto done;
                }
                else {
                    throw _ResponseException;
                }
            }
            else {
                Monitor.Exit(this);
            }

            // If we're here it's because we don't have the response yet. We may have
            // already submitted the request, but if not do so now.

            if (!_RequestSubmitted) {
                // Save Off verb, and use it to make the request
                GlobalLog.Print("HttpWebRequest#"+ValidationHelper.HashString(this)+": setting _Verb to _OriginVerb ["+_OriginVerb+"]");
                _Verb = _OriginVerb;

                // Start request, but don't block
                BeginSubmitRequest(false);

            }

done:
            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse", ValidationHelper.HashString(asyncResult));
            return asyncResult;
        }
Exemplo n.º 19
0
        //
        // This is proven to be called without any user stack or it was just ONE IO queued.
        //
        private void WakeupPendingIO(IAsyncResult ar)
        {
            Exception exception = null;

            try {
                if (ar != null)
                {
                    m_Worker.EndProcessAuthentication(ar);
                }
            }
            catch (Exception e) {
                // This method does not throw because it job is to notify everyon waiting on the result
                // NOTE: SSL engine remembers the exception and will rethrow it on any access for SecureStream
                // property means on  any IO attempt.
                exception = e;

                if (m_Worker.IsCertValidationFailed)
                {
                    m_ExceptionStatus = WebExceptionStatus.TrustFailure;
                }
                else if (m_Worker.LastSecurityStatus != SecurityStatus.OK)
                {
                    m_ExceptionStatus = WebExceptionStatus.SecureChannelFailure;
                }
                else
                {
                    m_ExceptionStatus = WebExceptionStatus.ReceiveFailure;
                }
            }

            lock (m_PendingIO)
            {
                while (m_PendingIO.Count != 0)
                {
                    LazyAsyncResult lazyResult = (LazyAsyncResult )m_PendingIO[m_PendingIO.Count - 1];

                    m_PendingIO.RemoveAt(m_PendingIO.Count - 1);

                    if (lazyResult is BufferAsyncResult)
                    {
                        if (m_PendingIO.Count == 0)
                        {
                            // Resume the LAST IO on that thread and offload other IOs on worker threads
                            ResumeIOWorker(lazyResult);
                        }
                        else
                        {
                            ThreadPool.QueueUserWorkItem(new WaitCallback(ResumeIOWorker), lazyResult);
                        }
                    }
                    else
                    {
                        //resume sync IO waiting on other thread or signal waiting async handshake result.
                        try {
                            lazyResult.InvokeCallback(exception);
                        }
                        catch {
                            // this method never throws unles the failure is catastrophic
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
 private void ResumeClose_Part2(LazyAsyncResult userResult)
 {
     try
     {
         try
         {
             if (ErrorInStream)
             {
                 GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::ResumeClose_Part2() Aborting the connection");
                 m_Connection.AbortSocket(true);
             }
         }
         finally
         {
             CallDone();
             GlobalLog.Leave("ConnectStream#" + ValidationHelper.HashString(this) + "::ResumeClose_Part2", "Done");
         }
     }
     catch { }
     finally
     {
         if (userResult != null)
         {
             userResult.InvokeCallback();
         }
     }
 }
Exemplo n.º 21
0
        private void DoBeginAccept(LazyAsyncResult asyncResult)
        {
            if (m_RightEndPoint==null) {
                throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustbind));
            }

            if(!isListening){
                throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustlisten));
            }

            //
            // We keep a queue, which lists the set of requests that want to
            //  be called when an accept queue completes.  We call accept
            //  once, and then as it completes asyncrounsly we pull the
            //  requests out of the queue and call their callback.
            //
            // We start by grabbing Critical Section, then attempt to
            //  determine if we haven an empty Queue of Accept Sockets
            //  or if its in a Callback on the Callback thread.
            //
            // If its in the callback thread proocessing of the callback, then we
            //  just need to notify the callback by adding an additional request
            //   to the queue.
            //
            // If its an empty queue, and its not in the callback, then
            //   we just need to get the Accept going, make it go async
            //   and leave.
            //
            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginAccept()");

            bool needFinishedCall = false;
            SocketError errorCode = 0;

            Queue acceptQueue = GetAcceptQueue();
            lock(this)
            {
                if (acceptQueue.Count == 0)
                {
                    SocketAddress socketAddress = m_RightEndPoint.Serialize();

                    GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginAccept() queue is empty calling UnsafeNclNativeMethods.OSSOCK.accept");

                    // Check if a socket is already available.  We need to be non-blocking to do this.
                    InternalSetBlocking(false);

                    SafeCloseSocket acceptedSocketHandle = null;
                    try
                    {
                        acceptedSocketHandle = SafeCloseSocket.Accept(
                            m_Handle,
                            socketAddress.m_Buffer,
                            ref socketAddress.m_Size);
                        errorCode = acceptedSocketHandle.IsInvalid ? (SocketError) Marshal.GetLastWin32Error() : SocketError.Success;
                    }
                    catch (ObjectDisposedException)
                    {
                        errorCode = SocketError.NotSocket;
                    }

                    GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginAccept() UnsafeNclNativeMethods.OSSOCK.accept returns:" + errorCode.ToString());

                    if (errorCode != SocketError.WouldBlock)
                    {
                        if (errorCode == SocketError.Success)
                        {
                            asyncResult.Result = CreateAcceptSocket(acceptedSocketHandle, m_RightEndPoint.Create(socketAddress), false);
                        }
                        else
                        {
                            asyncResult.ErrorCode = (int) errorCode;
                        }

                        // Reset the blocking.
                        InternalSetBlocking(true);

                        // Continue outside the lock.
                        needFinishedCall = true;
                    }
                    else
                    {
                        // It would block.  Start listening for accepts, and add ourselves to the queue.
                        acceptQueue.Enqueue(asyncResult);
                        if (!SetAsyncEventSelect(AsyncEventBits.FdAccept))
                        {
                            acceptQueue.Dequeue();
                            throw new ObjectDisposedException(this.GetType().FullName);
                        }
                    }
                }
                else {
                    acceptQueue.Enqueue(asyncResult);

                    GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginAccept() queue is not empty Count:" + acceptQueue.Count.ToString());
                }
            }

            if (needFinishedCall) {
                if (errorCode == SocketError.Success)
                {
                    // Completed synchronously, invoke the callback.
                    asyncResult.InvokeCallback();
                }
                else
                {
                    //
                    // update our internal state after this socket error and throw
                    //
                    SocketException socketException = new SocketException(errorCode);
                    UpdateStatusAfterSocketError(socketException);
                    if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "BeginAccept", socketException);
                    throw socketException;
                }
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginAccept() returning AsyncResult:" + ValidationHelper.HashString(asyncResult));
        }
Exemplo n.º 22
0
        // Leaving the public logging as "BeginConnect" since that makes sense to the people looking at the output.
        // Private logging can remain "DoBeginConnect".
        private void DoBeginConnect(EndPoint endPointSnapshot, SocketAddress socketAddress, LazyAsyncResult asyncResult)
        {
            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginConnect() endPointSnapshot:" + endPointSnapshot.ToString());

            EndPoint oldEndPoint = m_RightEndPoint;
            
            // get async going
            if (m_AcceptQueueOrConnectResult != null)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_sockets_no_duplicate_async));
            }

            m_AcceptQueueOrConnectResult = asyncResult;

            if (!SetAsyncEventSelect(AsyncEventBits.FdConnect)){
                m_AcceptQueueOrConnectResult = null;
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            
            // This can throw ObjectDisposedException.
            IntPtr handle = m_Handle.DangerousGetHandle();

            //we should fix this in Whidbey.
            if (m_RightEndPoint == null) {
                  m_RightEndPoint = endPointSnapshot;
            }

            SocketError errorCode = UnsafeNclNativeMethods.OSSOCK.WSAConnect(
                handle,
                socketAddress.m_Buffer,
                socketAddress.m_Size,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero,
                IntPtr.Zero);

            if (errorCode!=SocketError.Success) {
                errorCode = (SocketError)Marshal.GetLastWin32Error();
            }
            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginConnect() UnsafeNclNativeMethods.OSSOCK.WSAConnect returns errorCode:" + errorCode);

            if (errorCode != SocketError.WouldBlock)
            {
                bool completeSynchronously = true;
                if (errorCode == SocketError.Success)
                {
                    SetToConnected();
                }
                else
                {
                    asyncResult.ErrorCode = (int) errorCode;
                }

                // Using interlocked to avoid a race condition with RegisteredWaitCallback
                // Although UnsetAsyncEventSelect() below should cancel the callback, but 
                // it may already be in progress and therefore resulting in simultaneous
                // registeredWaitCallback calling ConnectCallback() and the synchronous
                // completion here.
                if (Interlocked.Exchange(ref m_RegisteredWait, null) == null)
                    completeSynchronously = false;
                //
                // Cancel async event and go back to blocking mode.
                //
                UnsetAsyncEventSelect();

                if (errorCode == SocketError.Success)
                {
                    //
                    // synchronously complete the IO and call the user's callback.
                    //
                    if (completeSynchronously)
                        asyncResult.InvokeCallback();
                }
                else
                {
                    //
                    // if the asynchronous native call fails synchronously
                    // we'll throw a SocketException
                    //
                    m_RightEndPoint = oldEndPoint;
                    SocketException socketException = new SocketException(errorCode);
                    UpdateStatusAfterSocketError(socketException);
                    m_AcceptQueueOrConnectResult = null;
                    if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "BeginConnect", socketException);
                    throw socketException;
                }
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginConnect() to:" + endPointSnapshot.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult));
        }
Exemplo n.º 23
0
 private void DoBeginAccept(LazyAsyncResult asyncResult)
 {
     if (this.m_RightEndPoint == null)
     throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
       if (!this.isListening)
     throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten"));
       bool flag = false;
       SocketError socketError = SocketError.Success;
       System.Collections.Queue acceptQueue = this.GetAcceptQueue();
       lock (this)
       {
     if (acceptQueue.Count == 0)
     {
       SocketAddress local_3 = this.m_RightEndPoint.Serialize();
       this.InternalSetBlocking(false);
       SafeCloseSocket local_4 = (SafeCloseSocket) null;
       try
       {
     local_4 = SafeCloseSocket.Accept(this.m_Handle, local_3.m_Buffer, ref local_3.m_Size);
     socketError = local_4.IsInvalid ? (SocketError) Marshal.GetLastWin32Error() : SocketError.Success;
       }
       catch (ObjectDisposedException exception_0)
       {
     socketError = SocketError.NotSocket;
       }
       if (socketError != SocketError.WouldBlock)
       {
     if (socketError == SocketError.Success)
       asyncResult.Result = (object) this.CreateAcceptSocket(local_4, this.m_RightEndPoint.Create(local_3), false);
     else
       asyncResult.ErrorCode = (int) socketError;
     this.InternalSetBlocking(true);
     flag = true;
       }
       else
       {
     acceptQueue.Enqueue((object) asyncResult);
     if (!this.SetAsyncEventSelect(AsyncEventBits.FdAccept))
     {
       acceptQueue.Dequeue();
       throw new ObjectDisposedException(this.GetType().FullName);
     }
       }
     }
     else
       acceptQueue.Enqueue((object) asyncResult);
       }
       if (!flag)
     return;
       if (socketError == SocketError.Success)
       {
     asyncResult.InvokeCallback();
       }
       else
       {
     SocketException socketException = new SocketException(socketError);
     this.UpdateStatusAfterSocketError(socketException);
     if (Socket.s_LoggingEnabled)
       Logging.Exception(Logging.Sockets, (object) this, "BeginAccept", (Exception) socketException);
     throw socketException;
       }
 }
Exemplo n.º 24
0
        private void ProcessWriteCallback(IAsyncResult asyncResult, LazyAsyncResult userResult)
        {
            Exception userException = null;

            try {
                NestedSingleAsyncResult castedSingleAsyncResult = userResult as NestedSingleAsyncResult;
                if (castedSingleAsyncResult != null)
                {
                    try {
                        m_Connection.EndWrite(asyncResult);
                        if (BytesLeftToWrite != -1) {
                            // Update our bytes left to send.
                            m_BytesLeftToWrite -= m_BytesAlreadyTransferred;
                            m_BytesAlreadyTransferred = 0;
                        }
                    }
                    catch (Exception exception) {

                        userException = exception;

                        if (NclUtilities.IsFatal(exception))
                        {
                            m_ErrorResponseStatus = false;
                            IOError(exception);
                            throw;
                        }
                        if (m_ErrorResponseStatus) {
                            // We already got a error response, hence server could drop the connection,
                            // Here we are recovering for future (optional) resubmit ...
                            m_IgnoreSocketErrors = true;
                            userException = null;
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::EndWrite() IGNORE write fault");
                        }
                    }
                }
                else {
                    NestedMultipleAsyncResult castedMultipleAsyncResult = (NestedMultipleAsyncResult) userResult;
                    try {
                        m_Connection.EndMultipleWrite(asyncResult);
                    }
                    catch (Exception exception) {

                        userException = exception;

                        if (NclUtilities.IsFatal(exception))
                        {
                            m_ErrorResponseStatus = false;
                            IOError(exception);
                            throw;
                        }
                        if (m_ErrorResponseStatus) {
                            // We already got a error response, hence server could drop the connection,
                            // Here we are recovering for future (optional) resubmit ...
                            m_IgnoreSocketErrors = true;
                            userException = null;
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::EndWrite() IGNORE write fault");
                        }
                    }
                }
            }
            finally {

                if (Nesting.Closed == ExchangeCallNesting((userException == null? Nesting.Idle: Nesting.InError), Nesting.IoInProgress))
                {
                    if (userException != null && m_ErrorException == null)
                    {
                        Interlocked.CompareExchange<Exception>(ref m_ErrorException, userException, null);
                    }
                    ResumeInternalClose(userResult);
                }
                else
                {
                    userResult.InvokeCallback(userException);
                }
            }
        }
Exemplo n.º 25
0
 private void DoBeginConnect(EndPoint endPointSnapshot, SocketAddress socketAddress, LazyAsyncResult asyncResult)
 {
     EndPoint endPoint = this.m_RightEndPoint;
       if (this.m_AcceptQueueOrConnectResult != null)
     throw new InvalidOperationException(SR.GetString("net_sockets_no_duplicate_async"));
       this.m_AcceptQueueOrConnectResult = (object) asyncResult;
       if (!this.SetAsyncEventSelect(AsyncEventBits.FdConnect))
       {
     this.m_AcceptQueueOrConnectResult = (object) null;
     throw new ObjectDisposedException(this.GetType().FullName);
       }
       else
       {
     IntPtr handle = this.m_Handle.DangerousGetHandle();
     if (this.m_RightEndPoint == null)
       this.m_RightEndPoint = endPointSnapshot;
     SocketError socketError = UnsafeNclNativeMethods.OSSOCK.WSAConnect(handle, socketAddress.m_Buffer, socketAddress.m_Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
     if (socketError != SocketError.Success)
       socketError = (SocketError) Marshal.GetLastWin32Error();
     if (socketError == SocketError.WouldBlock)
       return;
     bool flag = true;
     if (socketError == SocketError.Success)
       this.SetToConnected();
     else
       asyncResult.ErrorCode = (int) socketError;
     if (Interlocked.Exchange<RegisteredWaitHandle>(ref this.m_RegisteredWait, (RegisteredWaitHandle) null) == null)
       flag = false;
     this.UnsetAsyncEventSelect();
     if (socketError == SocketError.Success)
     {
       if (!flag)
     return;
       asyncResult.InvokeCallback();
     }
     else
     {
       this.m_RightEndPoint = endPoint;
       SocketException socketException = new SocketException(socketError);
       this.UpdateStatusAfterSocketError(socketException);
       this.m_AcceptQueueOrConnectResult = (object) null;
       if (Socket.s_LoggingEnabled)
     Logging.Exception(Logging.Sockets, (object) this, "BeginConnect", (Exception) socketException);
       throw socketException;
     }
       }
 }
Exemplo n.º 26
0
 //
 // Important: This will abandon _Callback and directly notify UserAsyncResult.
 //
 internal void CompleteWithError(Exception e)
 {
     UserAsyncResult.InvokeCallback(e);
 }
        private void DoBeginAccept(LazyAsyncResult asyncResult)
        {
            if (this.m_RightEndPoint == null)
            {
                throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
            }
            if (!this.isListening)
            {
                throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten"));
            }
            bool flag = false;
            SocketError success = SocketError.Success;
            System.Collections.Queue acceptQueue = this.GetAcceptQueue();
            lock (this)
            {
                if (acceptQueue.Count == 0)
                {
                    SocketAddress socketAddress = this.m_RightEndPoint.Serialize();
                    this.InternalSetBlocking(false);
                    SafeCloseSocket fd = null;
                    try
                    {
                        fd = SafeCloseSocket.Accept(this.m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
                        success = fd.IsInvalid ? ((SocketError) Marshal.GetLastWin32Error()) : SocketError.Success;
                    }
                    catch (ObjectDisposedException)
                    {
                        success = SocketError.NotSocket;
                    }
                    switch (success)
                    {
                        case SocketError.WouldBlock:
                            acceptQueue.Enqueue(asyncResult);
                            if (!this.SetAsyncEventSelect(AsyncEventBits.FdAccept))
                            {
                                acceptQueue.Dequeue();
                                throw new ObjectDisposedException(base.GetType().FullName);
                            }
                            goto Label_0117;

                        case SocketError.Success:
                            asyncResult.Result = this.CreateAcceptSocket(fd, this.m_RightEndPoint.Create(socketAddress), false);
                            break;

                        default:
                            asyncResult.ErrorCode = (int) success;
                            break;
                    }
                    this.InternalSetBlocking(true);
                    flag = true;
                }
                else
                {
                    acceptQueue.Enqueue(asyncResult);
                }
            }
        Label_0117:
            if (!flag)
            {
                return;
            }
            if (success == SocketError.Success)
            {
                asyncResult.InvokeCallback();
            }
            else
            {
                SocketException socketException = new SocketException(success);
                this.UpdateStatusAfterSocketError(socketException);
                if (s_LoggingEnabled)
                {
                    Logging.Exception(Logging.Sockets, this, "BeginAccept", socketException);
                }
                throw socketException;
            }
        }