Inheritance: IAsyncResult
Esempio n. 1
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
            {
            }
        }
Esempio n. 3
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");
        }
        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;
                        }
                    }
                }
            }
        }
Esempio n. 6
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }

            string suri;

            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
            {
                suri = this.RequestUri.ToString();
            }
            else
            {
                suri = this.RequestUri.OriginalString;
            }
            FrameworkEventSource.Log.BeginGetRequestStream(this, suri);

            return(m_ReadAResult);
        }
Esempio n. 7
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");
#if !MONO
            bool success = true;
#endif
            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
            } catch (Exception exception) {
#if !MONO
                success = false;
#endif
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
#if !MONO
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogBeginGetRequestStream(success, synchronous: false);
                }
#endif
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }

            return(m_ReadAResult);
        }
Esempio n. 8
0
 public AsyncProtocolRequest(LazyAsyncResult userAsyncResult)
 {
     if (userAsyncResult == null)
     {
         NetEventSource.Fail(this, "userAsyncResult == null");
     }
     if (userAsyncResult.InternalPeekCompleted)
     {
         NetEventSource.Fail(this, "userAsyncResult is already completed.");
     }
     UserAsyncResult = userAsyncResult;
 }
Esempio n. 9
0
 public AsyncProtocolRequest(LazyAsyncResult userAsyncResult)
 {
     if (userAsyncResult == null)
     {
         NetEventSource.Fail(this, "userAsyncResult == null");
     }
     if (userAsyncResult.InternalPeekCompleted)
     {
         NetEventSource.Fail(this, "userAsyncResult is already completed.");
     }
     UserAsyncResult = userAsyncResult;
 }
Esempio n. 10
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");
            }
        }
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
        {
            CheckError();
            LazyAsyncResult userResult = new LazyAsyncResult(this, state, callback);

            try {
                m_NetworkStream.BeginRead(buffer, offset, size, new AsyncCallback(AsyncReadCallback), userResult);
            } catch {
                CheckError();
                throw;
            }
            return(userResult);
        }
Esempio n. 12
0
 public AsyncProtocolRequest(LazyAsyncResult userAsyncResult, CancellationToken cancellationToken = default)
 {
     if (userAsyncResult == null)
     {
         NetEventSource.Fail(this, "userAsyncResult == null");
     }
     if (userAsyncResult !.InternalPeekCompleted)
     {
         NetEventSource.Fail(this, "userAsyncResult is already completed.");
     }
     UserAsyncResult   = userAsyncResult;
     CancellationToken = cancellationToken;
 }
Esempio n. 13
0
        private static void WorkerThreadComplete(object state)
        {
            Debug.Assert(state is LazyAsyncResult);
            LazyAsyncResult thisPtr = (LazyAsyncResult)state;

            try
            {
                thisPtr._asyncCallback !(thisPtr);
            }
            finally
            {
                thisPtr.Cleanup();
            }
        }
Esempio n. 14
0
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            GlobalLog.Enter("FileWebRequest::EndGetResponse");

            WebResponse response;

#if !MONO
            bool success = false;
#endif
            try {
                LazyAsyncResult ar = asyncResult as LazyAsyncResult;
                if (asyncResult == null || ar == null)
                {
                    Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
                    GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
                    throw e;
                }


                object result = ar.InternalWaitForCompletion();
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                response      = (WebResponse)result;
                m_readPending = false;
#if !MONO
                success = true;
#endif
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::EndGetResponse");

#if !MONO
                // there is no statusCode in FileWebRequest object, defaulting it to zero.
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogEndGetResponse(success, synchronous: false, statusCode: 0);
                }
#endif
            }

            return(response);
        }
Esempio n. 15
0
 public AsyncProtocolRequest(LazyAsyncResult userAsyncResult)
 {
     if (GlobalLog.IsEnabled)
     {
         if (userAsyncResult == null)
         {
             GlobalLog.Assert("AsyncProtocolRequest()|userAsyncResult == null");
         }
         if (userAsyncResult.InternalPeekCompleted)
         {
             GlobalLog.Assert("AsyncProtocolRequest()|userAsyncResult is already completed.");
         }
     }
     UserAsyncResult = userAsyncResult;
 }
Esempio n. 16
0
 public AsyncProtocolRequest(LazyAsyncResult userAsyncResult)
 {
     if (GlobalLog.IsEnabled)
     {
         if (userAsyncResult == null)
         {
             GlobalLog.Assert("AsyncProtocolRequest()|userAsyncResult == null");
         }
         if (userAsyncResult.InternalPeekCompleted)
         {
             GlobalLog.Assert("AsyncProtocolRequest()|userAsyncResult is already completed.");
         }
     }
     UserAsyncResult = userAsyncResult;
 }
Esempio n. 17
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetResponse");

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                lock (this) {
                    if (m_readPending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetResponse", e);
                        throw e;
                    }
                    m_readPending = true;
                }

                m_WriteAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetResponseCallback, m_WriteAResult);
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetResponse");
            }

            string suri;

            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
            {
                suri = this.RequestUri.ToString();
            }
            else
            {
                suri = this.RequestUri.OriginalString;
            }
            if (FrameworkEventSource.Log.IsEnabled())
            {
                LogBeginGetResponse(suri);
            }

            return(m_WriteAResult);
        }
 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;
     }
 }
 internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, AsyncCallback callback, object state)
 {
     this.PrepareHeaders(sendEnvelope);
     writer.WriteHeaders(this.Headers);
     if (this.Content != null)
     {
         return this.Content.BeginSend(writer, callback, state);
     }
     LazyAsyncResult result = new LazyAsyncResult(this, state, callback);
     IAsyncResult result2 = writer.BeginGetContentStream(new AsyncCallback(this.EmptySendCallback), new EmptySendContext(writer, result));
     if (result2.CompletedSynchronously)
     {
         writer.EndGetContentStream(result2).Close();
     }
     return result;
 }
        private static void ConnectCallback(IAsyncResult asyncResult)
        {
            FtpControlStream asyncState = (FtpControlStream)asyncResult.AsyncState;

            try
            {
                LazyAsyncResult result = asyncResult as LazyAsyncResult;
                ((Socket)result.AsyncObject).EndConnect(asyncResult);
                asyncState.ContinueCommandPipeline();
            }
            catch (Exception exception)
            {
                asyncState.CloseSocket();
                asyncState.InvokeRequestCallback(exception);
            }
        }
Esempio n. 21
0
        public override Stream EndGetRequestStream(IAsyncResult asyncResult)
        {
            GlobalLog.Enter("FileWebRequest::EndGetRequestStream");

            Stream stream;

#if !MONO
            bool success = false;
#endif
            try {
                LazyAsyncResult ar = asyncResult as LazyAsyncResult;
                if (asyncResult == null || ar == null)
                {
                    Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
                    GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
                    throw e;
                }

                object result = ar.InternalWaitForCompletion();
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                stream         = (Stream)result;
                m_writePending = false;
#if !MONO
                success = true;
#endif
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetRequestStream", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::EndGetRequestStream");
#if !MONO
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogEndGetRequestStream(success, synchronous: false);
                }
#endif
            }

            return(stream);
        }
Esempio n. 22
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetResponse");
#if !MONO
            bool success = true;
#endif

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                lock (this) {
                    if (m_readPending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetResponse", e);
                        throw e;
                    }
                    m_readPending = true;
                }

                m_WriteAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetResponseCallback, m_WriteAResult);
            } catch (Exception exception) {
#if !MONO
                success = false;
#endif
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetResponse", exception);
                }
                throw;
            } finally {
#if !MONO
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogBeginGetResponse(success, synchronous: false);
                }
#endif
                GlobalLog.Leave("FileWebRequest::BeginGetResponse");
            }

            return(m_WriteAResult);
        }
Esempio n. 23
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");
        }
Esempio n. 24
0
        public IAsyncResult ReadAsync(object caller, byte[] userBuffer, int userBufferOffset,
                                      int userBufferCount, AsyncCallback callback, object state)
        {
            SetReadParameters(userBuffer, userBufferOffset, userBufferCount);

            userAsyncResult = new LazyAsyncResult(caller, state, callback);

            // Store to local var to handle inline completions that would reset 'userAsyncResult'.
            IAsyncResult localResult = userAsyncResult;

            try
            {
                ProcessResponse();
            }
            catch (Exception e)
            {
                CompleteUserRead(e);
            }

            return(localResult);
        }
 public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
 {
     try
     {
         if (this.Aborted)
         {
             throw ExceptionHelper.RequestAbortedException;
         }
         if (!this.CanGetRequestStream())
         {
             Exception exception = new ProtocolViolationException(SR.GetString("net_nouploadonget"));
             throw exception;
         }
         if (this.m_response != null)
         {
             Exception exception2 = new InvalidOperationException(SR.GetString("net_reqsubmitted"));
             throw exception2;
         }
         lock (this)
         {
             if (this.m_writePending)
             {
                 Exception exception3 = new InvalidOperationException(SR.GetString("net_repcall"));
                 throw exception3;
             }
             this.m_writePending = true;
         }
         this.m_ReadAResult = new LazyAsyncResult(this, state, callback);
         ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, this.m_ReadAResult);
     }
     catch (Exception exception4)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception4);
         }
         throw;
     }
     return(this.m_ReadAResult);
 }
Esempio n. 26
0
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            GlobalLog.Enter("FileWebRequest::EndGetResponse");

            WebResponse response;

            try {
                LazyAsyncResult ar = asyncResult as LazyAsyncResult;
                if (asyncResult == null || ar == null)
                {
                    Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
                    GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
                    throw e;
                }


                object result = ar.InternalWaitForCompletion();
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                response      = (WebResponse)result;
                m_readPending = false;
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::EndGetResponse");
            }

            if (FrameworkEventSource.Log.IsEnabled())
            {
                LogEndGetResponse();
            }

            return(response);
        }
        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);
        }
Esempio n. 28
0
        public void Reset(LazyAsyncResult userAsyncResult)
        {
            if (userAsyncResult == null)
            {
                NetEventSource.Fail(this, "userAsyncResult == null");
            }
            if (userAsyncResult.InternalPeekCompleted)
            {
                NetEventSource.Fail(this, "userAsyncResult is already completed.");
            }
            UserAsyncResult = userAsyncResult;

            _callback = null;
            _completionStatus = 0;
            Result = 0;
            AsyncState = null;
            Buffer = null;
            Offset = 0;
            Count = 0;
#if DEBUG
            _DebugAsyncChain = 0;
#endif
        }
Esempio n. 29
0
        public void Reset(LazyAsyncResult userAsyncResult)
        {
            if (userAsyncResult == null)
            {
                NetEventSource.Fail(this, "userAsyncResult == null");
            }
            if (userAsyncResult.InternalPeekCompleted)
            {
                NetEventSource.Fail(this, "userAsyncResult is already completed.");
            }
            UserAsyncResult = userAsyncResult;

            _callback         = null;
            _completionStatus = 0;
            Result            = 0;
            AsyncState        = null;
            Buffer            = null;
            Offset            = 0;
            Count             = 0;
#if DEBUG
            _debugAsyncChain = 0;
#endif
        }
        internal bool ProcessAuthentication(LazyAsyncResult result)
        {
            bool flag  = false;
            bool flag2 = result == null;

            lock (this.m_PendingIO)
            {
                if (this.m_Worker.IsAuthenticated)
                {
                    return(false);
                }
                if (this.m_PendingIO.Count == 0)
                {
                    flag = true;
                }
                if (flag2)
                {
                    result = new LazyAsyncResult(this, null, null);
                }
                this.m_PendingIO.Add(result);
            }
            try
            {
                if (flag)
                {
                    bool            flag3 = true;
                    LazyAsyncResult state = null;
                    try
                    {
                        try
                        {
                            this.m_Worker.ValidateCreateContext(false, this.m_DestinationHost, (SslProtocols)ServicePointManager.SecurityProtocol, null, this.m_ClientCertificates, true, ServicePointManager.CheckCertificateRevocationList, ServicePointManager.CheckCertificateName);
                            if (!flag2)
                            {
                                state = new LazyAsyncResult(this.m_Worker, null, new AsyncCallback(this.WakeupPendingIO));
                            }
                            if (this._ExecutionContext != null)
                            {
                                ExecutionContext.Run(this._ExecutionContext.CreateCopy(), new ContextCallback(this.CallProcessAuthentication), state);
                            }
                            else
                            {
                                this.m_Worker.ProcessAuthentication(state);
                            }
                        }
                        catch
                        {
                            flag3 = false;
                            throw;
                        }
                        goto Label_0198;
                    }
                    finally
                    {
                        if (flag2 || !flag3)
                        {
                            lock (this.m_PendingIO)
                            {
                                if (this.m_PendingIO.Count > 1)
                                {
                                    ThreadPool.QueueUserWorkItem(new WaitCallback(this.StartWakeupPendingIO), null);
                                }
                                else
                                {
                                    this.m_PendingIO.Clear();
                                }
                            }
                        }
                    }
                }
                if (flag2)
                {
                    Exception exception = result.InternalWaitForCompletion() as Exception;
                    if (exception != null)
                    {
                        throw exception;
                    }
                }
            }
            catch
            {
                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;
                }
                throw;
            }
Label_0198:
            return(true);
        }
Esempio n. 31
0
        /*
            InvokeGetRequestStreamCallback - Notify our GetRequestStream caller

            This is needed to tell our caller that we're finished,
            and he can go ahead and write to the stream.
        */
        private void InvokeGetRequestStreamCallback(bool signalled) {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::InvokeGetRequestStreamCallback", signalled.ToString());

            LazyAsyncResult asyncResult = _WriteAResult;

            GlobalLog.Assert( // check that this is the correct request
                asyncResult == null || this == (HttpWebRequest)asyncResult.AsyncObject,
                "InvokeGetRequestStreamCallback: this != asyncResult.AsyncObject", "");

            GlobalLog.Assert( // check that the event didn't already complete
                asyncResult == null || !asyncResult.IsCompleted,
                "InvokeGetRequestStreamCallback: asyncResult already completed!", "");

            if (asyncResult != null) {
                _WriteAResult = null;

                // It's done now, mark it as completed.
                // Otherwise it worked, so return the stream.

                try {
                    asyncResult.InvokeCallback(!signalled, _SubmitWriteStream);
                }
                catch (Exception exception) {
                    Abort();
                    GlobalLog.LeaveException("HttpWebRequest#" + ValidationHelper.HashString(this) + "::InvokeGetRequestStreamCallback", exception);
                    throw;
                }
            }

            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::InvokeGetRequestStreamCallback", "success");
        }
Esempio n. 32
0
        /// <summary>
        /// <para>Used to query for the Response of an FTP request [async version]</para>
        /// </summary>
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
                NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
            }

            ContextAwareResult asyncResult;

            try
            {
                if (_ftpWebResponse != null)
                {
                    asyncResult = new ContextAwareResult(this, state, callback);
                    asyncResult.InvokeCallback(_ftpWebResponse);
                    return asyncResult;
                }

                if (_getResponseStarted)
                {
                    throw new InvalidOperationException(SR.net_repcall);
                }

                _getResponseStarted = true;
                CheckError();

                RequestStage prev = FinishRequestStage(RequestStage.RequestStarted);
                asyncResult = new ContextAwareResult(true, true, this, state, callback);
                _readAsyncResult = asyncResult;

                if (prev >= RequestStage.RequestStarted)
                {
                    // To make sure the context is flowed
                    asyncResult.StartPostingAsyncOp();
                    asyncResult.FinishPostingAsyncOp();

                    if (prev >= RequestStage.ReadReady)
                        asyncResult = null;
                    else
                    {
                        lock (_syncObject)
                        {
                            if (_requestStage >= RequestStage.ReadReady)
                                asyncResult = null; ;
                        }
                    }

                    if (asyncResult == null)
                    {
                        // need to complete it now
                        asyncResult = (ContextAwareResult)_readAsyncResult;
                        if (!asyncResult.InternalPeekCompleted)
                            asyncResult.InvokeCallback();
                    }
                }
                else
                {
                    // Do internal processing in this handler to optimize context flowing.
                    lock (asyncResult.StartPostingAsyncOp())
                    {
                        SubmitRequest(true);
                        asyncResult.FinishPostingAsyncOp();
                    }
                    FinishRequestStage(RequestStage.CheckForError);
                }
            }
            catch (Exception exception)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
                throw;
            }
            finally
            {
                if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
            }

            return asyncResult;
        }
Esempio n. 33
0
        private Stream TimedSubmitRequestHelper(bool isAsync)
        {
            if (isAsync)
            {
                // non-null in the case of re-submit (recovery)
                if (_requestCompleteAsyncResult == null)
                    _requestCompleteAsyncResult = new LazyAsyncResult(null, null, null);
                return _connection.SubmitRequest(this, true, true);
            }

            Stream stream = null;
            bool timedOut = false;
            TimerThread.Timer timer = TimerQueue.CreateTimer(_timerCallback, null);
            try
            {
                stream = _connection.SubmitRequest(this, false, true);
            }
            catch (Exception exception)
            {
                if (!(exception is SocketException || exception is ObjectDisposedException) || !timer.HasExpired)
                {
                    timer.Cancel();
                    throw;
                }

                timedOut = true;
            }

            if (timedOut || !timer.Cancel())
            {
                _timedOut = true;
                throw ExceptionHelper.TimeoutException;
            }

            if (stream != null)
            {
                lock (_syncObject)
                {
                    if (_aborted)
                    {
                        ((ICloseEx)stream).CloseEx(CloseExState.Abort | CloseExState.Silent);
                        CheckError(); //must throw
                        throw new InternalException(); //consider replacing this on Assert
                    }
                    _stream = stream;
                }
            }

            return stream;
        }
Esempio n. 34
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));
        }
Esempio n. 35
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");

            try {
                if (Aborted)
                    throw ExceptionHelper.RequestAbortedException;
                if (!CanGetRequestStream()) {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null) {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock(this) {
                    if (m_writePending) {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }
                                                    
                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
            } catch (Exception exception) {
                if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }

            string suri;
            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
                suri = this.RequestUri.ToString();
            else
                suri = this.RequestUri.OriginalString;
            FrameworkEventSource.Log.BeginGetRequestStream(this, suri);

            return m_ReadAResult;
        }
Esempio n. 36
0
        internal bool ProcessAuthentication(LazyAsyncResult result)
        {
            bool doHandshake = false;
            bool isSyncCall  = result == null;

            lock (m_PendingIO)
            {
                // do we have handshake as already done before we grabbed a lock?
                if (m_Worker.IsAuthenticated)
                {
                    return(false);
                }

                if (m_PendingIO.Count == 0)
                {
                    doHandshake = true;
                }

                if (isSyncCall)
                {
                    // we will wait on this guy in this method for the handshake to complete
                    result = new LazyAsyncResult(this, null, null);
                }

                m_PendingIO.Add(result);
            }

            try {
                if (doHandshake)
                {
                    bool            success         = true;
                    LazyAsyncResult handshakeResult = null;
                    try
                    {
                        m_Worker.ValidateCreateContext(false,
                                                       m_DestinationHost,
                                                       m_SslProtocols,
                                                       null,
                                                       m_ClientCertificates,
                                                       true,
                                                       m_CheckCertificateRevocationList,
                                                       ServicePointManager.CheckCertificateName);


                        if (!isSyncCall)
                        {
                            // wrap a user async IO/Handshake request into auth request
                            handshakeResult = new LazyAsyncResult(m_Worker, null, new AsyncCallback(WakeupPendingIO));
#if DEBUG
                            result._DebugAsyncChain = handshakeResult;
#endif
                        }

                        //
                        // TlsStream is used by classes that manually control ExecutionContext, so set it here if we need to.
                        //
                        if (_ExecutionContext != null)
                        {
                            ExecutionContext.Run(_ExecutionContext.CreateCopy(), new ContextCallback(CallProcessAuthentication), handshakeResult);
                        }
                        else
                        {
                            m_Worker.ProcessAuthentication(handshakeResult);
                        }
                    }
                    catch
                    {
                        success = false;
                        throw;
                    }
                    finally
                    {
                        if (isSyncCall || !success)
                        {
                            lock (m_PendingIO)
                            {
                                if (m_PendingIO.Count > 1)
                                {
                                    // It was a real sync handshake (now completed) and another IO came in.
                                    // It's now waiting on us so resume.
                                    ThreadPool.QueueUserWorkItem(new WaitCallback(StartWakeupPendingIO), null);
                                }
                                else
                                {
                                    m_PendingIO.Clear();
                                }
                            }
                        }
                    }
                }
                else if (isSyncCall)
                {
                    GlobalLog.Assert(result != null, "TlsStream::ProcessAuthentication() this is a Sync call and it did not started the handshake hence null result must be wrapped into LazyAsyncResult");
                    Exception e = result.InternalWaitForCompletion() as Exception;
                    if (e != null)
                    {
                        throw e;
                    }
                }
            }
            catch {
                if (m_Worker.IsCertValidationFailed)
                {
                    m_ExceptionStatus = WebExceptionStatus.TrustFailure;
                }
                else if (m_Worker.LastSecurityStatus != SecurityStatus.OK)
                {
                    m_ExceptionStatus = WebExceptionStatus.SecureChannelFailure;
                }
                else
                {
                    m_ExceptionStatus = WebExceptionStatus.ReceiveFailure;
                }
                throw;
            }

            // Here in the async case a user IO has been queued (and may be already completed)
            // For sync case it does not matter since the caller will resume IO upon return
            return(true);
        }
        //
        // Used to query for the Response of an FTP request
        //
        public override WebResponse GetResponse()
        {
            if(Logging.On)Logging.Enter(Logging.Web, this, "GetResponse", "");
            if(Logging.On)Logging.PrintInfo(Logging.Web, this, "GetResponse", SR.GetString(SR.net_log_method_equal, m_MethodInfo.Method));
            GlobalLog.Enter("FtpWebRequest#" + ValidationHelper.HashString(this) + "::GetResponse");

            try {
                CheckError();

                if (m_FtpWebResponse != null)
                    return m_FtpWebResponse;

                if (m_GetResponseStarted) {
                    throw new InvalidOperationException(SR.GetString(SR.net_repcall));
                }

                m_GetResponseStarted = true;

                m_StartTime = DateTime.UtcNow;
                m_RemainingTimeout = Timeout;

                // We don't really need this variable, but we just need 
                // to call the property to measure its execution time
                ServicePoint servicePoint = ServicePoint;

                if (Timeout != System.Threading.Timeout.Infinite)
                {
                    m_RemainingTimeout = Timeout - (int)((DateTime.UtcNow - m_StartTime).TotalMilliseconds);

                    if(m_RemainingTimeout <= 0){
                        throw new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
                    }
                }

                if (ServicePoint.InternalProxyServicePoint)
                {
                    if (EnableSsl) {
                        m_GetResponseStarted = false;
                        throw new WebException(SR.GetString(SR.net_ftp_proxy_does_not_support_ssl));
                    }

                    try {
                        HttpWebRequest httpWebRequest = GetHttpWebRequest();
                        if (Logging.On) Logging.Associate(Logging.Web, this, httpWebRequest);

                        m_FtpWebResponse = new FtpWebResponse((HttpWebResponse)httpWebRequest.GetResponse());
                    } catch (WebException webException) {
                        if (webException.Response != null &&
                            webException.Response is HttpWebResponse)
                        {
                            webException = new WebException(webException.Message,
                                null,
                                webException.Status,
                                new FtpWebResponse((HttpWebResponse)webException.Response),
                                webException.InternalStatus);
                        }
                        SetException(webException);
                        throw webException;
                    }
                    // Catch added to address Bug # 545645
                    catch (InvalidOperationException invalidOpException)
                    {
                        SetException(invalidOpException);
                        FinishRequestStage(RequestStage.CheckForError);
                        throw;
                    }
                }
                else
                {
                    RequestStage prev = FinishRequestStage(RequestStage.RequestStarted);
                    if (prev >= RequestStage.RequestStarted)
                    {
                        if (prev < RequestStage.ReadReady)
                        {
                            lock (m_SyncObject)
                            {
                                if (m_RequestStage < RequestStage.ReadReady)
                                    m_ReadAsyncResult = new LazyAsyncResult(null, null, null);
                            }

                            // GetRequeststream or BeginGetRequestStream has not finished yet?
                            if (m_ReadAsyncResult != null)
                                m_ReadAsyncResult.InternalWaitForCompletion();

                            CheckError();
                        }
                    }
                    else
                    {
                        do
                        {
                            SubmitRequest(false);
                            if (m_MethodInfo.IsUpload)
                                FinishRequestStage(RequestStage.WriteReady);
                            else
                                FinishRequestStage(RequestStage.ReadReady);
                            CheckError();
                        } while (!CheckCacheRetrieveOnResponse());

                        EnsureFtpWebResponse(null);
                        // This may update the Stream memeber on m_FtpWebResponse based on the CacheProtocol feedback.
                        CheckCacheUpdateOnResponse();

                        if (m_FtpWebResponse.IsFromCache)
                            FinishRequestStage(RequestStage.ReleaseConnection);
                    }
                }
            } catch (Exception exception) {
                if(Logging.On)Logging.Exception(Logging.Web, this, "GetResponse", exception);

                // if m_Exception == null, we are about to throw an exception to the user
                // and we haven't saved the exception, which also means we haven't dealt
                // with it. So just release the connection and log this for investigation
                if (m_Exception == null) {
                    if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_unexpected_exception, "GetResponse()"));

                    if (!NclUtilities.IsFatal(exception)){
                        GlobalLog.Assert("Find out why we are getting an unexpected exception.");
                    }
                    SetException(exception);
                    FinishRequestStage(RequestStage.CheckForError);
                }
                throw;
            } finally {

                GlobalLog.Leave("FtpWebRequest#" + ValidationHelper.HashString(this) + "::GetResponse", "returns #"+ValidationHelper.HashString(m_FtpWebResponse));
                if(Logging.On)Logging.Exit(Logging.Web, this, "GetResponse", "");
            }
            return m_FtpWebResponse;
        }
Esempio n. 38
0
        /*++

        Routine Description:

            Wakes up blocked threads, so they can throw exceptions.

        Arguments:

            None.

        Return Value:

            HttpWebResponse

        --*/
        internal void SetResponse(Exception E) {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", E.ToString() + "/*** SETRESPONSE IN ERROR ***");

            //
            // Since we are no longer attached to this Connection,
            // we null out our abort delegate.
            //
            _AbortDelegate = null;

            if ( _WriteEvent != null ) {
                GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse(Exception) calling _WriteEvent.Set()");
                _WriteEvent.Set();
            }

            if ((E as WebException) == null) {
                if (_HttpResponse==null) {
                    E = new WebException(E.Message, E);
                }
                else {
                    E = new WebException(
                        SR.GetString(
                            SR.net_servererror,
                            NetRes.GetWebStatusCodeString(
                                ResponseStatusCode,
                                _HttpResponse.StatusDescription)),
                        E,
                        WebExceptionStatus.ProtocolError,
                        _HttpResponse );
                }
            }

            _ResponseException = E;

            // grab crit sec to protect BeginGetResponse/EndGetResponse code path
            Monitor.Enter(this);

            _HaveResponse = true;

            LazyAsyncResult writeAsyncResult = _WriteAResult;
            LazyAsyncResult readAsyncResult = _ReadAResult;

            _WriteAResult = null;
            _ReadAResult = null;

            Monitor.Exit(this);

            if (writeAsyncResult != null) {
                writeAsyncResult.InvokeCallback(false);
            }
            if (readAsyncResult != null) {
                readAsyncResult.InvokeCallback(false);
            }

            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse");
        }
 public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state) {
     CheckError();
     LazyAsyncResult userResult = new LazyAsyncResult(this, state, callback);
     try {
         m_NetworkStream.BeginRead(buffer, offset, size, new AsyncCallback(AsyncReadCallback), userResult);
     } catch {
         CheckError();
         throw;
     }
     return userResult;
 }
 public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
 {
     try
     {
         if (this.Aborted)
         {
             throw ExceptionHelper.RequestAbortedException;
         }
         lock (this)
         {
             if (this.m_readPending)
             {
                 Exception exception = new InvalidOperationException(SR.GetString("net_repcall"));
                 throw exception;
             }
             this.m_readPending = true;
         }
         this.m_WriteAResult = new LazyAsyncResult(this, state, callback);
         ThreadPool.QueueUserWorkItem(s_GetResponseCallback, this.m_WriteAResult);
     }
     catch (Exception exception2)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "BeginGetResponse", exception2);
         }
         throw;
     }
     return this.m_WriteAResult;
 }
 public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
 {
     try
     {
         if (this.Aborted)
         {
             throw ExceptionHelper.RequestAbortedException;
         }
         if (!this.CanGetRequestStream())
         {
             Exception exception = new ProtocolViolationException(SR.GetString("net_nouploadonget"));
             throw exception;
         }
         if (this.m_response != null)
         {
             Exception exception2 = new InvalidOperationException(SR.GetString("net_reqsubmitted"));
             throw exception2;
         }
         lock (this)
         {
             if (this.m_writePending)
             {
                 Exception exception3 = new InvalidOperationException(SR.GetString("net_repcall"));
                 throw exception3;
             }
             this.m_writePending = true;
         }
         this.m_ReadAResult = new LazyAsyncResult(this, state, callback);
         ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, this.m_ReadAResult);
     }
     catch (Exception exception4)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception4);
         }
         throw;
     }
     return this.m_ReadAResult;
 }
Esempio n. 42
0
 public AsyncProtocolRequest(LazyAsyncResult userAsyncResult) : this(userAsyncResult, CancellationToken.None)
 {
 }
        //
        // Handles either async or sync Writing for *public* stream API
        //
        private IAsyncResult InternalWrite(bool async, byte[] buffer, int offset, int size, AsyncCallback callback, object state ) {
            //
            // if we have a stream error, or we've already shut down this socket
            //  then we must prevent new BeginRead/BeginWrite's from getting
            //  submited to the socket, since we've already closed the stream.
            //
            if (ErrorInStream) {
                GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing:" + m_ErrorException.ToString());
                throw m_ErrorException;
            }

            if (IsClosed && !IgnoreSocketErrors) {
                GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
                throw new WebException(
                            NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.ConnectionClosed),
                            WebExceptionStatus.ConnectionClosed);
            }
            
            if (m_Request.Aborted && !IgnoreSocketErrors) {
                GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
                throw new WebException(
                    NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled),
                    WebExceptionStatus.RequestCanceled);
            }             

            int nesting = Interlocked.CompareExchange(ref m_CallNesting, Nesting.IoInProgress, Nesting.Idle);
            GlobalLog.Print((async?"Async ":"") + "InternalWrite() In: callNesting : " + nesting.ToString());
            if (nesting != Nesting.Idle && nesting != Nesting.Closed)
            {
                throw new NotSupportedException(SR.GetString(SR.net_no_concurrent_io_allowed));
            }

            //
            // buffer data to the ScatterGatherBuffers
            // regardles of chunking, we buffer the data as if we were not chunking
            // and on resubmit, we don't bother chunking.
            //
            if (BufferedData!=null && size != 0 && (m_Request.ContentLength != 0 || !IsPostStream || !m_Request.NtlmKeepAlive)) {
                //
                // if we don't need to, we shouldn't send data on the wire as well
                // but in this case we gave a stream to the user so we have transport
                //
                BufferedData.Write(buffer, offset, size);
            }

            LazyAsyncResult asyncResult = null;
            bool completeSync = false;
            try
            {
                if (size == 0 || BufferOnly || m_SuppressWrite || IgnoreSocketErrors)
                {
                    //
                    // We're not putting this data on the wire, then we're done
                    //
                    if(m_SuppressWrite && m_BytesLeftToWrite > 0 && size > 0)
                    {
                        m_BytesLeftToWrite -= size;
                    }

                    GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() swallowing: size==0 || BufferOnly || IgnoreSocketErrors= " + (size==0) + BufferOnly + IgnoreSocketErrors);
                    if (async) {
                        asyncResult = new LazyAsyncResult(this, state, callback);
                        completeSync = true;
                    }
                    return asyncResult;
                }
                else if (WriteChunked) {
                    //
                    // We're chunking. Write the chunk header out first,
                    // then the data, then a CRLF.
                    // for this we'll use BeginMultipleSend();
                    //
                    int chunkHeaderOffset = 0;
                    byte[] chunkHeaderBuffer = GetChunkHeader(size, out chunkHeaderOffset);

                    BufferOffsetSize[] buffers;
                    GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() m_ErrorResponseStatus:" + m_ErrorResponseStatus);

                    if (m_ErrorResponseStatus) {
                        //if we already got a (>200) response, then just terminate chunking and
                        //switch to simple buffering (if any)
                        GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() setting m_IgnoreSocketErrors to True (was:" + m_IgnoreSocketErrors + ") sending chunk terminator");
                        m_IgnoreSocketErrors = true;
                        buffers = new BufferOffsetSize[1];
                        buffers[0] = new BufferOffsetSize(NclConstants.ChunkTerminator, 0, NclConstants.ChunkTerminator.Length, false);
                    }
                    else {
                        buffers = new BufferOffsetSize[3];
                        buffers[0] = new BufferOffsetSize(chunkHeaderBuffer, chunkHeaderOffset, chunkHeaderBuffer.Length - chunkHeaderOffset, false);
                        buffers[1] = new BufferOffsetSize(buffer, offset, size, false);
                        buffers[2] = new BufferOffsetSize(NclConstants.CRLF, 0, NclConstants.CRLF.Length, false);
                    }

                    asyncResult = (async) ? new NestedMultipleAsyncResult(this, state, callback, buffers) : null;

                    //
                    // after setting up the buffers and error checking do the async Write Call
                    //

                    try {
                        if (async) {
                            m_Connection.BeginMultipleWrite(buffers, m_WriteCallbackDelegate, asyncResult);
                        }
                        else {
                            SafeSetSocketTimeout(SocketShutdown.Send);
                            m_Connection.MultipleWrite(buffers);
                        }
                    }

                    catch (Exception exception) {
                        // IgnoreSocketErrors can be set at any time - need to check it again.
                        if (IgnoreSocketErrors && !NclUtilities.IsFatal(exception))
                        {
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() swallowing: IgnoreSocketErrors set after throw.");
                            if (async)
                            {
                                completeSync = true;
                            }
                            return asyncResult;
                        }

                        if (m_Request.Aborted && (exception is IOException || exception is ObjectDisposedException)) {
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
                            throw new WebException(
                                NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled),
                                WebExceptionStatus.RequestCanceled);
                        }

                        nesting = Nesting.InError;

                        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;
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() IGNORE write fault");
                            if (async)
                            {
                                completeSync = true;
                            }
                        }
                        else {
                            // Note we could swallow this since receive callback is already posted and
                            // should give us similar failure
                            IOError(exception);
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing:" + exception.ToString());
                            throw;
                        }
                    }
                    GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite chunked");
                    return asyncResult;
                }
                else {
                    //
                    // We're not chunking. See if we're sending too much; if not,
                    // go ahead and write it.
                    //
                    asyncResult = (async) ? new NestedSingleAsyncResult(this, state, callback, buffer, offset, size) : null;

                    if (BytesLeftToWrite != -1) {
                        //
                        // but only check if we aren't writing to an unknown content-length size,
                        // as we can be buffering.
                        //
                        if (BytesLeftToWrite < (long)size) {
                            //
                            // writing too much data.
                            //
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite()");
                            throw new ProtocolViolationException(SR.GetString(SR.net_entitytoobig));
                        }

                        if (!async) {
                            //
                            // Otherwise update our bytes left to send and send it.
                            //
                            m_BytesLeftToWrite -= (long)size;
                        }
                    }

                    //
                    // After doing, the m_WriteByte size calculations, and error checking
                    //  here doing the async Write Call
                    //

                    try {
                        if (async) {
                            if(m_Request.ContentLength == 0 && IsPostStream) {
                                m_BytesLeftToWrite -=size;
                                completeSync = true;
                            }
                           else{
                                m_BytesAlreadyTransferred = size;
                                m_Connection.BeginWrite(buffer, offset, size, m_WriteCallbackDelegate, asyncResult);
                           }
                        }
                        else {
                            SafeSetSocketTimeout(SocketShutdown.Send);
                            //If we are doing the ntlm handshake,  contentlength
                            //could be 0 for the first part, even if there is data
                            //to write.
                            if (m_Request.ContentLength != 0 || !IsPostStream || !m_Request.NtlmKeepAlive) {
                                m_Connection.Write(buffer, offset, size);
                            }
                        }
                    }
                    catch (Exception exception) {
                        // IgnoreSocketErrors can be set at any time - need to check it again.
                        if (IgnoreSocketErrors && !NclUtilities.IsFatal(exception))
                        {
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() swallowing: IgnoreSocketErrors set after throw.");
                            if (async)
                            {
                                completeSync = true;
                            }
                            return asyncResult;
                        }

                        if (m_Request.Aborted && (exception is IOException || exception is ObjectDisposedException)) {
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing");
                            throw new WebException(
                                NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled),
                                WebExceptionStatus.RequestCanceled);
                        }

                        nesting = Nesting.InError;

                        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;
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternWrite() IGNORE write fault");
                            if (async)
                            {
                                completeSync = true;
                            }
                        }
                        else {
                            // Note we could swallow this since receive callback is already posted and
                            // should give us similar failure
                            IOError(exception);
                            GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite() throwing:" + exception.ToString());
                            throw;
                        }
                    }
                    GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::InternalWrite");
                    return asyncResult;
                }
            }
            finally {
                if (!async || nesting == Nesting.InError || completeSync)
                {
                    nesting = Interlocked.CompareExchange(ref m_CallNesting, (nesting == Nesting.InError? Nesting.InError: Nesting.Idle), Nesting.IoInProgress);
                    GlobalLog.Print("InternalWrite() Out callNesting: " + nesting.ToString());
                    if (nesting == Nesting.Closed)
                    {
                        //send closing bytes
                        ResumeInternalClose(asyncResult);
                    }
                    else if (completeSync && asyncResult != null)
                    {
                        asyncResult.InvokeCallback();
                    }
                }
            }
        }
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            if(Logging.On)Logging.Enter(Logging.Web, this, "BeginGetResponse", "");
            if(Logging.On)Logging.PrintInfo(Logging.Web, this, "BeginGetResponse", SR.GetString(SR.net_log_method_equal, m_MethodInfo.Method));
            GlobalLog.Enter("FtpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse");

            ContextAwareResult asyncResult;

            try {
                if (m_FtpWebResponse != null)
                {
                    asyncResult = new ContextAwareResult(this, state, callback);
                    asyncResult.InvokeCallback(m_FtpWebResponse);
                    return asyncResult;
                }

                if (m_GetResponseStarted) {
                    throw new InvalidOperationException(SR.GetString(SR.net_repcall));
                }

                m_GetResponseStarted = true;
                CheckError();

                if (ServicePoint.InternalProxyServicePoint)
                {
                    HttpWebRequest httpWebRequest = GetHttpWebRequest();
                    if (Logging.On) Logging.Associate(Logging.Web, this, httpWebRequest);
                    asyncResult = (ContextAwareResult)httpWebRequest.BeginGetResponse(callback, state);
                }
                else
                {
                    RequestStage prev = FinishRequestStage(RequestStage.RequestStarted);
                    asyncResult = new ContextAwareResult(true, true, this, state, callback);
                    m_ReadAsyncResult = asyncResult;

                    if (prev >= RequestStage.RequestStarted)
                    {
                        // To make sure the context is flowed
                        asyncResult.StartPostingAsyncOp();
                        asyncResult.FinishPostingAsyncOp();

                        if (prev >= RequestStage.ReadReady)
                            asyncResult = null;
                        else
                        {
                            lock (m_SyncObject)
                            {
                                if (m_RequestStage >= RequestStage.ReadReady)
                                    asyncResult = null;;
                            }
                        }

                        if(asyncResult == null)
                        {
                            // need to complete it now
                            asyncResult = (ContextAwareResult)m_ReadAsyncResult;
                            if (!asyncResult.InternalPeekCompleted)
                                asyncResult.InvokeCallback();
                        }
                    }
                    else
                    {
                        // Do internal processing in this handler to optimize context flowing.
                        lock (asyncResult.StartPostingAsyncOp())
                        {
                            SubmitRequest(true);
                            asyncResult.FinishPostingAsyncOp();
                        }
                        FinishRequestStage(RequestStage.CheckForError);
                    }
                }
            } catch (Exception exception) {
                if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetResponse", exception);
                throw;
            } finally {
                GlobalLog.Leave("FtpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse");
                if(Logging.On)Logging.Exit(Logging.Web, this, "BeginGetResponse", "");
            }

            string suri;
            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
                suri = this.RequestUri.ToString();
            else
                suri = this.RequestUri.OriginalString;
            FrameworkEventSource.Log.BeginGetResponse(this, suri);

            return asyncResult;
        }
Esempio n. 45
0
        //
        // Used to query for the Response of an FTP request
        //
        public override WebResponse GetResponse()
        {
            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "GetResponse", "");
                NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "GetResponse", string.Format("Method: {0}", _methodInfo.Method));
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::GetResponse");
            }

            try
            {
                CheckError();

                if (_ftpWebResponse != null)
                {
                    return _ftpWebResponse;
                }

                if (_getResponseStarted)
                {
                    throw new InvalidOperationException(SR.net_repcall);
                }

                _getResponseStarted = true;

                _startTime = DateTime.UtcNow;
                _remainingTimeout = Timeout;

                if (Timeout != System.Threading.Timeout.Infinite)
                {
                    _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds);

                    if (_remainingTimeout <= 0)
                    {
                        throw ExceptionHelper.TimeoutException;
                    }
                }

                RequestStage prev = FinishRequestStage(RequestStage.RequestStarted);
                if (prev >= RequestStage.RequestStarted)
                {
                    if (prev < RequestStage.ReadReady)
                    {
                        lock (_syncObject)
                        {
                            if (_requestStage < RequestStage.ReadReady)
                                _readAsyncResult = new LazyAsyncResult(null, null, null);
                        }

                        // GetRequeststream or BeginGetRequestStream has not finished yet
                        if (_readAsyncResult != null)
                            _readAsyncResult.InternalWaitForCompletion();

                        CheckError();
                    }
                }
                else
                {
                    SubmitRequest(false);
                    if (_methodInfo.IsUpload)
                        FinishRequestStage(RequestStage.WriteReady);
                    else
                        FinishRequestStage(RequestStage.ReadReady);
                    CheckError();

                    EnsureFtpWebResponse(null);
                }
            }
            catch (Exception exception)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "GetResponse", exception);
                }

                // if _exception == null, we are about to throw an exception to the user
                // and we haven't saved the exception, which also means we haven't dealt
                // with it. So just release the connection and log this for investigation.
                if (_exception == null)
                {
                    if (NetEventSource.Log.IsEnabled())
                        NetEventSource.PrintWarning(NetEventSource.ComponentType.Web, "Unexpected exception in GetResponse()");

                    if (!ExceptionCheck.IsFatal(exception))
                    {
                        if (GlobalLog.IsEnabled)
                        {
                            GlobalLog.Assert("Find out why we are getting an unexpected exception.");
                        }

                        Debug.Fail("Find out why we are getting an unexpected exception.");
                    }
                    SetException(exception);
                    FinishRequestStage(RequestStage.CheckForError);
                }
                throw;
            }
            finally
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::GetResponse", "returns #" + LoggingHash.HashString(_ftpWebResponse));
                }
                if (NetEventSource.Log.IsEnabled())
                    NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "GetResponse", "");
            }
            return _ftpWebResponse;
        }
Esempio n. 46
0
        public int    Count;                      // ditto

        //
        //
        public AsyncProtocolRequest(LazyAsyncResult userAsyncResult)
        {
            GlobalLog.Assert(userAsyncResult != null, "AsyncProtocolRequest()|userAsyncResult == null");
            GlobalLog.Assert(!userAsyncResult.InternalPeekCompleted, "AsyncProtocolRequest()|userAsyncResult is already completed.");
            UserAsyncResult = userAsyncResult;
        }
Esempio n. 47
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
                        }
                    }
                }
            }
        }
Esempio n. 48
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;
        }
Esempio n. 49
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetResponse");

            try {
                if (Aborted)
                    throw ExceptionHelper.RequestAbortedException;
                lock(this) {
                    if (m_readPending) {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetResponse", e);
                        throw e;
                    }
                    m_readPending = true;
                }

                m_WriteAResult = new LazyAsyncResult(this,state,callback);
                ThreadPool.QueueUserWorkItem(s_GetResponseCallback,m_WriteAResult);
            } catch (Exception exception) {
                if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetResponse", exception);
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetResponse");
            }

            string suri;
            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
                suri = this.RequestUri.ToString();
            else
                suri = this.RequestUri.OriginalString;
            FrameworkEventSource.Log.BeginGetResponse(this, suri);

            return m_WriteAResult;
        }
 internal MimePartContext(BaseWriter writer, LazyAsyncResult result)
 {
     this.writer = writer;
     this.result = result;
     this.buffer = new byte[0x4400];
 }
Esempio n. 51
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));
        }
Esempio n. 52
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;
       }
 }
Esempio n. 53
0
        //
        // Used to query for the Response of an FTP request
        //
        public override WebResponse GetResponse()
        {
            if (NetEventSource.IsEnabled)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
                if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Method: {_methodInfo.Method}");
            }

            try
            {
                CheckError();

                if (_ftpWebResponse != null)
                {
                    return _ftpWebResponse;
                }

                if (_getResponseStarted)
                {
                    throw new InvalidOperationException(SR.net_repcall);
                }

                _getResponseStarted = true;

                _startTime = DateTime.UtcNow;
                _remainingTimeout = Timeout;

                if (Timeout != System.Threading.Timeout.Infinite)
                {
                    _remainingTimeout = Timeout - (int)((DateTime.UtcNow - _startTime).TotalMilliseconds);

                    if (_remainingTimeout <= 0)
                    {
                        throw ExceptionHelper.TimeoutException;
                    }
                }

                RequestStage prev = FinishRequestStage(RequestStage.RequestStarted);
                if (prev >= RequestStage.RequestStarted)
                {
                    if (prev < RequestStage.ReadReady)
                    {
                        lock (_syncObject)
                        {
                            if (_requestStage < RequestStage.ReadReady)
                                _readAsyncResult = new LazyAsyncResult(null, null, null);
                        }

                        // GetRequeststream or BeginGetRequestStream has not finished yet
                        if (_readAsyncResult != null)
                            _readAsyncResult.InternalWaitForCompletion();

                        CheckError();
                    }
                }
                else
                {
                    SubmitRequest(false);
                    if (_methodInfo.IsUpload)
                        FinishRequestStage(RequestStage.WriteReady);
                    else
                        FinishRequestStage(RequestStage.ReadReady);
                    CheckError();

                    EnsureFtpWebResponse(null);
                }
            }
            catch (Exception exception)
            {
                if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);

                // if _exception == null, we are about to throw an exception to the user
                // and we haven't saved the exception, which also means we haven't dealt
                // with it. So just release the connection and log this for investigation.
                if (_exception == null)
                {
                    if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception);
                    SetException(exception);
                    FinishRequestStage(RequestStage.CheckForError);
                }
                throw;
            }
            finally
            {
                if (NetEventSource.IsEnabled) NetEventSource.Exit(this, _ftpWebResponse);
            }
            return _ftpWebResponse;
        }
 //
 // Optionally sends chunk terminator and proceeds with close that was collided with pending user write IO
 //
 void ResumeInternalClose(LazyAsyncResult userResult)
 {
     GlobalLog.Print("ConnectStream##" + ValidationHelper.HashString(this) + "::ResumeInternalClose(), userResult:" + userResult);
     //
     // write stream. terminate our chunking if needed.
     //
     if (WriteChunked && !ErrorInStream && !m_IgnoreSocketErrors)
     {
         m_IgnoreSocketErrors = true;
         try {
             if (userResult == null)
             {
                 SafeSetSocketTimeout(SocketShutdown.Send);
                 m_Connection.Write(NclConstants.ChunkTerminator, 0, NclConstants.ChunkTerminator.Length);
             }
             else
             {
                 m_Connection.BeginWrite(NclConstants.ChunkTerminator, 0, NclConstants.ChunkTerminator.Length, new AsyncCallback(ResumeClose_Part2_Wrapper), userResult);
                 return;
             }
         }
         catch (Exception exception) {
             GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::CloseInternal() exceptionOnWrite:" + exception.Message);
         }
     }
     ResumeClose_Part2(userResult); //never throws
 }
 internal EmptySendContext(BaseWriter writer, LazyAsyncResult result)
 {
     this.writer = writer;
     this.result = result;
 }
 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();
         }
     }
 }
Esempio n. 57
0
        /*++

        Routine Description:

            Wakes up blocked threads, so they can read response object,
              from the result

            We also handle the continuation/termination of a BeginGetResponse,
            by saving out the result and calling its callback if needed.

        Arguments:

            coreData - Contains the data used to create the Response object
            exception - true if we're allowed to throw an exception on error

        Return Value:

            none

        --*/
        internal void SetResponse(CoreResponseData coreResponseData) {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", "*** SETRESP ***");

            //
            // Since we are no longer attached to this Connection,
            // we null out our abort delegate.
            //

            _AbortDelegate = null;

            try {
                if (coreResponseData != null) {
                    _HttpResponse = new HttpWebResponse(_Uri, _Verb, coreResponseData, _MediaType, UsesProxySemantics);
                    coreResponseData = null;
                }
                else {

                    //
                    // not sure how this would happen, but we should not throw an exception,
                    //  which we were earlier doing.
                    //

                    GlobalLog.Assert(false,
                                 "coreResponseData == null",
                                 "");


                    GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", "ASSERT");
                    return;
                }

                //
                // give apps the chance to examine the headers of the new response
                //

                if (_CookieContainer != null) {
                    CookieModule.OnReceivedHeaders(this);
                }

                // New Response

                HttpProcessingResult httpResult = HttpProcessingResult.Continue;

                // handle redirects, authentication, and such
                httpResult = DoSubmitRequestProcessing();

                if (httpResult == HttpProcessingResult.Continue) {
                    //
                    // Now grab crit sec here, before returning,
                    //  this is to prevent some one from reading
                    //  ReadAResult it as null before we finish
                    //  processing our response
                    //

                    LazyAsyncResult asyncResult = null;
                    lock(this)
                    {
                        asyncResult = _ReadAResult;

                        GlobalLog.Assert(asyncResult == null || this == (HttpWebRequest)asyncResult.AsyncObject,
                                     "SetResponse: this != asyncResult.AsyncObject",
                                     "");

                        GlobalLog.Assert(asyncResult == null || !asyncResult.IsCompleted, "SetResponse: asyncResult already completed!", "");

                        _HaveResponse = true;

                        if (asyncResult != null) {
                            _ReadAResult = null;
                        }
                    }

                    if (asyncResult != null) {
                        asyncResult.InvokeCallback(false, _HttpResponse);
                    }

                    if ( _WriteEvent != null ) {
                        GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse(CoreResponseData) calling _WriteEvent.Set()");
                        _WriteEvent.Set();
                    }
                }
            } catch (Exception exception) {
                Abort();
                GlobalLog.LeaveException("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", exception);
                throw;
            }

            if (_Abort) {
                try {
                    if ( _HttpResponse != null ) {
                        _HttpResponse.Close();
                    }
                }
                catch {
                }

                GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", "ABORT");
                return;
            }

            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse");
        }
Esempio n. 58
0
 public AsyncProtocolRequest(LazyAsyncResult userAsyncResult)
 {
     GlobalLog.Assert(userAsyncResult != null, "AsyncProtocolRequest()|userAsyncResult == null");
     GlobalLog.Assert(!userAsyncResult.InternalPeekCompleted, "AsyncProtocolRequest()|userAsyncResult is already completed.");
     UserAsyncResult = userAsyncResult;
 }
        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;
                        }

                        if (Logging.On) Logging.Dump(Logging.Web, this, "WriteCallback", castedSingleAsyncResult.Buffer, castedSingleAsyncResult.Offset, castedSingleAsyncResult.Size);
                    }
                    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);
                        if(Logging.On) {
                            foreach (BufferOffsetSize bufferOffsetSize in castedMultipleAsyncResult.Buffers) {
                                Logging.Dump(Logging.Web, castedMultipleAsyncResult, "WriteCallback", bufferOffsetSize.Buffer, bufferOffsetSize.Offset, bufferOffsetSize.Size);
                            }
                        }
                    }
                    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);
                }
            }
        }
Esempio n. 60
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;
     }
       }
 }