internal IAsyncResult BeginWrite(BufferOffsetSize[] buffers, AsyncCallback asyncCallback, object asyncState)
 {
     LazyAsyncResult userAsyncResult = new LazyAsyncResult(this, asyncState, asyncCallback);
     SplitWriteAsyncProtocolRequest asyncRequest = new SplitWriteAsyncProtocolRequest(userAsyncResult);
     this.ProcessWrite(buffers, asyncRequest);
     return userAsyncResult;
 }
Ejemplo n.º 2
0
        public Socket EndAcceptSocket(IAsyncResult asyncResult)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.Sockets, this, "EndAcceptSocket", null);
            }

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

#if MONO
            var    sar         = asyncResult as SocketAsyncResult;
            Socket asyncSocket = sar == null ? null : sar.socket;
#else
            LazyAsyncResult lazyResult  = asyncResult as LazyAsyncResult;
            Socket          asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;
#endif
            if (asyncSocket == null)
            {
                throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
            }

            // This will throw ObjectDisposedException if Stop() has been called.
            Socket socket = asyncSocket.EndAccept(asyncResult);

            if (Logging.On)
            {
                Logging.Exit(Logging.Sockets, this, "EndAcceptSocket", socket);
            }
            return(socket);
        }
Ejemplo n.º 3
0
        public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.Sockets, this, "EndAcceptTcpClient", null);
            }

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

            LazyAsyncResult lazyResult  = asyncResult as LazyAsyncResult;
            Socket          asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;

            if (asyncSocket == null)
            {
                throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult");
            }

            // This will throw ObjectDisposedException if Stop() has been called.
            Socket socket = asyncSocket.EndAccept(asyncResult);

            if (Logging.On)
            {
                Logging.Exit(Logging.Sockets, this, "EndAcceptTcpClient", socket);
            }

            return(new TcpClient(socket));
        }
Ejemplo n.º 4
0
        public Socket EndAcceptSocket(IAsyncResult asyncResult)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }

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

            LazyAsyncResult lazyResult  = asyncResult as LazyAsyncResult;
            Socket          asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;

            if (asyncSocket == null)
            {
                throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
            }

            // This will throw ObjectDisposedException if Stop() has been called.
            Socket socket = asyncSocket.EndAccept(asyncResult);

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Exit(this, socket);
            }
            return(socket);
        }
        internal void EndSend(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            LazyAsyncResult castedAsyncResult = asyncResult as MimePartAsyncResult;

            if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
            {
                throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
            }

            if (castedAsyncResult.EndCalled)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndSend"));
            }

            castedAsyncResult.InternalWaitForCompletion();
            castedAsyncResult.EndCalled = true;
            if (castedAsyncResult.Result is Exception)
            {
                throw (Exception)castedAsyncResult.Result;
            }
        }
 public virtual IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
 {
     this._SslState.ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true, checkCertificateRevocation);
     LazyAsyncResult lazyResult = new LazyAsyncResult(this._SslState, asyncState, asyncCallback);
     this._SslState.ProcessAuthentication(lazyResult);
     return lazyResult;
 }
Ejemplo n.º 7
0
        public TcpClient EndAcceptTcpClient(IAsyncResult asyncResult)
        {
            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndAcceptTcpClient", null);
            }

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

            LazyAsyncResult lazyResult  = asyncResult as LazyAsyncResult;
            Socket          asyncSocket = lazyResult == null ? null : lazyResult.AsyncObject as Socket;

            if (asyncSocket == null)
            {
                throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult));
            }

            // This will throw ObjectDisposedException if Stop() has been called.
            Socket socket = asyncSocket.EndAccept(asyncResult);

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndAcceptTcpClient", socket);
            }

            return(new TcpClient(socket));
        }
Ejemplo n.º 8
0
        internal virtual void EndSend(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            if (Content != null)
            {
                Content.EndSend(asyncResult);
            }
            else
            {
                LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult;

                if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this)
                {
                    throw new ArgumentException(SR.net_io_invalidasyncresult);
                }

                if (castedAsyncResult.EndCalled)
                {
                    throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndSend)));
                }

                castedAsyncResult.InternalWaitForCompletion();
                castedAsyncResult.EndCalled = true;
                if (castedAsyncResult.Result is Exception)
                {
                    throw (Exception)castedAsyncResult.Result;
                }
            }
        }
Ejemplo n.º 9
0
        IAsyncResult BeginReadOrWrite(ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, BufferOffsetSize userBuffer, AsyncCallback asyncCallback, object asyncState)
        {
            LazyAsyncResult lazyResult = new LazyAsyncResult(this, asyncState, asyncCallback);

            ProcessReadOrWrite(ref nestedRequest, ref internalBuffer, operation, userBuffer, lazyResult);
            return(lazyResult);
        }
        public override void EndExecute(IAsyncResult asyncResult)
        {
            LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;

            if (lazyAsyncResult == null)
            {
                throw new InvalidOperationException("EndExecute: asyncResult or the AsyncState cannot be null here.");
            }
            if (!lazyAsyncResult.IsCompleted)
            {
                lazyAsyncResult.InternalWaitForCompletion();
            }
            this.performanceCounter.Stop(OperationType.EndToEnd, 1);
            this.resourceMonitor.ResetBudget();
            base.LastError = (lazyAsyncResult.Result as Exception);
            base.SaveSyncMetadata();
            if (base.LastError == null)
            {
                ProtocolLog.LogInformation(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.EndExecute: Succeeded");
            }
            else
            {
                ProtocolLog.LogError(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.EndExecute: Failed", base.LastError);
            }
            string[] logLine = this.performanceCounter.GetLogLine();
            foreach (string str in logLine)
            {
                ProtocolLog.LogStatistics(this.loggingComponent, this.loggingContext, "MaintenanceSynchronizer.Statistics: " + str);
            }
            base.Dispose();
        }
 internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
 {
     LazyAsyncResult userAsyncResult = new LazyAsyncResult(this, asyncState, asyncCallback);
     AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(userAsyncResult);
     this.ProcessWrite(buffer, offset, count, asyncRequest);
     return userAsyncResult;
 }
Ejemplo n.º 12
0
            public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
            {
                this.Write(buffer, offset, count);
                LazyAsyncResult result = new LazyAsyncResult(null, state, callback);

                result.InvokeCallback(null);
                return(result);
            }
            public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
            {
                Write(buffer, offset, count);
                LazyAsyncResult ar = new LazyAsyncResult(null, state, callback);

                ar.InvokeCallback(null);
                return(ar);
            }
Ejemplo n.º 14
0
        public IAsyncResult BeginAuthenticateAsClient(string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
        {
            ValidateCreateContext(false, targetHost, enabledSslProtocols, null, clientCertificates, true);
            var result = new LazyAsyncResult(this, asyncState, asyncCallback);

            ProcessAuthentication(result);
            return(result);
        }
Ejemplo n.º 15
0
        public IAsyncResult BeginAuthenticateAsServer(X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
        {
            ValidateCreateContext(true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
            var result = new LazyAsyncResult(this, asyncState, asyncCallback);

            ProcessAuthentication(result);
            return(result);
        }
Ejemplo n.º 16
0
        // Token: 0x0600092B RID: 2347 RVA: 0x00028CCC File Offset: 0x00026ECC
        public IAsyncResult BeginDiagnostic(DiagnosticsCacheRequest cacheRequest, AsyncCallback callback, object asyncState)
        {
            ArgumentValidator.ThrowIfNull("cacheRequest", cacheRequest);
            LazyAsyncResult lazyAsyncResult = new LazyAsyncResult(null, asyncState, callback);

            CacheManager.Instance.ResetAllCaches();
            callback(lazyAsyncResult);
            return(lazyAsyncResult);
        }
Ejemplo n.º 17
0
        // Token: 0x0600092C RID: 2348 RVA: 0x00028D00 File Offset: 0x00026F00
        public void EndDiagnostic(IAsyncResult result)
        {
            ArgumentValidator.ThrowIfNull("result", result);
            ArgumentValidator.ThrowIfTypeInvalid <LazyAsyncResult>("result", result);
            LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)result;

            if (lazyAsyncResult.EndCalled)
            {
                throw new InvalidOperationException("End was already called. Invalid Begin/End");
            }
            lazyAsyncResult.EndCalled = true;
        }
 protected override IAsyncResult BeginGetTokenCore(TimeSpan timeout, AsyncCallback callback, object state)
 {
     if (this.cachedSecurityToken != null)
     {
         LazyAsyncResult lazyAsyncResult = new LazyAsyncResult(null, state, callback);
         ExTraceGlobals.RightsManagementTracer.TraceDebug(0L, "Got cached saml token. Invoking callback.");
         lazyAsyncResult.InvokeCallback();
         return(lazyAsyncResult);
     }
     this.latencyTracker.BeginTrackRmsLatency(RmsOperationType.RequestDelegationToken);
     return(this.securityTokenService.BeginIssueToken(this.CreateDelegationTokenRequest(), callback, state));
 }
 private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult)
 {
     if (this.HandshakeComplete && this._RemoteOk)
     {
         if (lazyResult != null)
         {
             lazyResult.InvokeCallback();
         }
     }
     else
     {
         this.StartReceiveBlob(lazyResult);
     }
 }
Ejemplo n.º 20
0
 private int EndReadFromInternalBuf(LazyAsyncResult result)
 {
     SocketStream.IoReq ioReq = result.AsyncObject as SocketStream.IoReq;
     if (ioReq == null)
     {
         throw new ArgumentException("AsyncObject corrupt");
     }
     result.InternalWaitForCompletion();
     if (ioReq.SocketError != SocketError.Success)
     {
         throw new SocketException((int)ioReq.SocketError);
     }
     return(ioReq.BytesTransferred);
 }
Ejemplo n.º 21
0
            public object EndExecute(IAsyncResult asyncResult)
            {
                LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;

                if (lazyAsyncResult == null)
                {
                    throw new InvalidOperationException("EndExecute: asyncResult cannot be null.");
                }
                if (!lazyAsyncResult.IsCompleted)
                {
                    lazyAsyncResult.InternalWaitForCompletion();
                }
                return(lazyAsyncResult.Result);
            }
Ejemplo n.º 22
0
        private static void StableUnicastAddressTableCallback(object param)
        {
            EventWaitHandle handle = param as EventWaitHandle;

            if (handle != null)
            {
                handle.Set();
            }
            else
            {
                LazyAsyncResult asyncResult = (LazyAsyncResult)param;
                asyncResult.InvokeCallback();
            }
        }
            public override void EndWrite(IAsyncResult asyncResult)
            {
                if (asyncResult == null)
                {
                    throw new ArgumentNullException("asyncResult");
                }
                LazyAsyncResult ar = (LazyAsyncResult)asyncResult;

                if (ar.EndCalled)
                {
                    throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndWrite"));
                }
                ar.EndCalled = true;
                ar.InternalWaitForCompletion();
            }
Ejemplo n.º 24
0
            public override void EndWrite(IAsyncResult asyncResult)
            {
                if (asyncResult == null)
                {
                    throw new ArgumentNullException("asyncResult");
                }
                LazyAsyncResult result = (LazyAsyncResult)asyncResult;

                if (result.EndCalled)
                {
                    throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndWrite" }));
                }
                result.EndCalled = true;
                result.InternalWaitForCompletion();
            }
Ejemplo n.º 25
0
        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);
        }
Ejemplo n.º 26
0
        // Token: 0x0600092A RID: 2346 RVA: 0x00028C5C File Offset: 0x00026E5C
        public CacheResponseContext EndRemoveObject(IAsyncResult result)
        {
            ArgumentValidator.ThrowIfNull("result", result);
            ArgumentValidator.ThrowIfTypeInvalid <LazyAsyncResult>("result", result);
            LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)result;

            if (lazyAsyncResult.EndCalled)
            {
                throw new InvalidOperationException("End was already called. Invalid Begin/End");
            }
            CacheResponseContext cacheResponseContext = (CacheResponseContext)lazyAsyncResult.AsyncObject;

            this.stopwatch.Stop();
            cacheResponseContext.EndOperationLatency = this.stopwatch.ElapsedMilliseconds;
            lazyAsyncResult.EndCalled = true;
            return(cacheResponseContext);
        }
Ejemplo n.º 27
0
 // Token: 0x06000929 RID: 2345 RVA: 0x00028C10 File Offset: 0x00026E10
 public IAsyncResult BeginRemoveObject(RemoveDirectoryCacheRequest cacheRequest, AsyncCallback callback, object asyncState)
 {
     this.stopwatch = Stopwatch.StartNew();
     return(this.Invoke(delegate
     {
         ArgumentValidator.ThrowIfNull("cacheRequest", cacheRequest);
         CacheResponseContext cacheResponseContext = new CacheResponseContext();
         LazyAsyncResult lazyAsyncResult = new LazyAsyncResult(cacheResponseContext, asyncState, callback);
         MSExchangeDirectoryCacheServiceCounters.NumberOfCacheRemovalRequests.Increment();
         this.InternalRemoveObject(cacheRequest.ForestOrPartitionFqdn, cacheRequest.Key);
         this.stopwatch.Stop();
         cacheResponseContext.BeginOperationLatency = this.stopwatch.ElapsedMilliseconds;
         this.stopwatch.Restart();
         callback(lazyAsyncResult);
         return lazyAsyncResult;
     }));
 }
 private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult)
 {
     if (this.HandshakeComplete)
     {
         if (!this._RemoteOk)
         {
             throw new AuthenticationException(SR.GetString("net_io_header_id", new object[] { "MessageId", this._Framer.ReadHeader.MessageId, 20 }), null);
         }
         if (lazyResult != null)
         {
             lazyResult.InvokeCallback();
         }
     }
     else
     {
         this.StartSendBlob(message, lazyResult);
     }
 }
Ejemplo n.º 29
0
        public override int EndRead(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;

            if (lazyAsyncResult != null)
            {
                return(this.EndReadFromInternalBuf(lazyAsyncResult));
            }
            Socket streamSocket = this.m_StreamSocket;

            if (streamSocket == null)
            {
                throw new IOException("EndRead with no socket");
            }
            return(streamSocket.EndReceive(asyncResult));
        }
Ejemplo n.º 30
0
        internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
                                                AsyncCallback callback, object state)
        {
            PrepareHeaders(sendEnvelope, allowUnicode);
            writer.WriteHeaders(Headers, allowUnicode);

            if (Content != null)
            {
                return(Content.BeginSend(writer, callback, allowUnicode, state));
            }
            else
            {
                LazyAsyncResult result    = new LazyAsyncResult(this, state, callback);
                IAsyncResult    newResult = writer.BeginGetContentStream(EmptySendCallback, new EmptySendContext(writer, result));
                if (newResult.CompletedSynchronously)
                {
                    writer.EndGetContentStream(newResult).Close();
                }
                return(result);
            }
        }
Ejemplo n.º 31
0
        internal void EndSend(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            LazyAsyncResult result = asyncResult as MimePartAsyncResult;

            if ((result == null) || (result.AsyncObject != this))
            {
                throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
            }
            if (result.EndCalled)
            {
                throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndSend" }));
            }
            result.InternalWaitForCompletion();
            result.EndCalled = true;
            if (result.Result is Exception)
            {
                throw ((Exception)result.Result);
            }
        }
Ejemplo n.º 32
0
        internal void ProcessAuthentication(LazyAsyncResult lazyResult)
        {
            var asyncRequest = new AsyncProtocolRequest(this, lazyResult);

            if (Interlocked.CompareExchange(ref asyncHandshakeRequest, asyncRequest, null) != null)
            {
                throw new InvalidOperationException("Invalid nested call.");
            }

            try {
                if (lastException != null)
                {
                    throw lastException;
                }
                if (xobileTlsContext == null)
                {
                    throw new InvalidOperationException();
                }

                readBuffer.Reset();
                writeBuffer.Reset();

                try {
                    asyncRequest.StartOperation(ProcessHandshake);
                } catch (Exception ex) {
                    throw SetException(ex);
                }
            } finally {
                if (lazyResult == null || lastException != null)
                {
                    readBuffer.Reset();
                    writeBuffer.Reset();
                    asyncHandshakeRequest = null;
                }
            }
        }
Ejemplo n.º 33
0
 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
 {
     Write(buffer, offset, count);
     LazyAsyncResult ar = new LazyAsyncResult(null, state, callback);
     ar.InvokeCallback(null);
     return ar;
 }
Ejemplo n.º 34
0
        internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode,
            AsyncCallback callback, object state)
        {
            PrepareHeaders(sendEnvelope, allowUnicode);
            writer.WriteHeaders(Headers, allowUnicode);

            if (Content != null)
            {
                return Content.BeginSend(writer, callback, allowUnicode, state);
            }
            else
            {
                LazyAsyncResult result = new LazyAsyncResult(this, state, callback);
                IAsyncResult newResult = writer.BeginGetContentStream(EmptySendCallback, new EmptySendContext(writer, result));
                if (newResult.CompletedSynchronously)
                {
                    writer.EndGetContentStream(newResult).Close();
                }
                return result;
            }
        }
Ejemplo n.º 35
0
 internal EmptySendContext(BaseWriter writer, LazyAsyncResult result)
 {
     _writer = writer;
     _result = result;
 }
Ejemplo n.º 36
0
		internal void ProcessAuthentication (LazyAsyncResult lazyResult)
		{
			var asyncRequest = new AsyncProtocolRequest (this, lazyResult);
			if (Interlocked.CompareExchange (ref asyncHandshakeRequest, asyncRequest, null) != null)
				throw new InvalidOperationException ("Invalid nested call.");

			try {
				if (lastException != null)
					throw lastException;
				if (xobileTlsContext == null)
					throw new InvalidOperationException ();

				readBuffer.Reset ();
				writeBuffer.Reset ();

				try {
					asyncRequest.StartOperation (ProcessHandshake);
				} catch (Exception ex) {
					ExceptionDispatchInfo.Capture (SetException (ex)).Throw ();
				}
			} finally {
				if (lazyResult == null || lastException != null) {
					readBuffer.Reset ();
					writeBuffer.Reset ();
					asyncHandshakeRequest = null;
				}
			}
		}
Ejemplo n.º 37
0
        private void SubmitRequest(ServicePoint servicePoint)
        {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SubmitRequest");
            GlobalLog.ThreadContract(ThreadKinds.Unknown, "HttpWebRequest#" + ValidationHelper.HashString(this) + "::SubmitRequest");
            GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SubmitRequest() HaveResponse:" + HaveResponse + " Saw100Continue:" + Saw100Continue);

            if (!Async)
            {
                _ConnectionAResult = new LazyAsyncResult(this, null, null);
                _ConnectionReaderAResult = new LazyAsyncResult(this, null, null);
                OpenWriteSideResponseWindow();
            }

            if (_Timer == null && !Async){
                _Timer = TimerQueue.CreateTimer(s_TimeoutCallback, this);
            }

            try {

                if (_SubmitWriteStream != null && _SubmitWriteStream.IsPostStream)
                {
                    // _OldSubmitWriteStream is the stream that holds real user data
                    // In no case it can be overwritten.
                    // For multiple resubmits the ContentLength was set already, so no need call it again.
                    // on first resubmission the real user data hasn't been saved, so _OldSubmitWriteStream is null
                    GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SubmitRequest() (resubmit) firstResubmission:" + (_OldSubmitWriteStream == null) + " NtlmKeepAlive:" + NtlmKeepAlive);
                    if (_OldSubmitWriteStream == null && !_SubmitWriteStream.ErrorInStream && AllowWriteStreamBuffering)
                    {
                        // save the real user data.
                        GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SubmitRequest() (resubmit) save the real user data _OldSubmitWriteStream#" + ValidationHelper.HashString(_OldSubmitWriteStream));
                        _OldSubmitWriteStream = _SubmitWriteStream;
                    }
                    // make sure we reformat the headers before resubmitting
                    _WriteBuffer = null;
                }

                m_Retry = false;

                // If pre-authentication is requested call the AuthenticationManager
                // and add authorization header if there is response
                if (PreAuthenticate) {
                    if (UsesProxySemantics && _Proxy != null && _Proxy.Credentials != null)
                        ProxyAuthenticationState.PreAuthIfNeeded(this, _Proxy.Credentials);
                    if (Credentials != null)
                        ServerAuthenticationState.PreAuthIfNeeded(this, Credentials);
                }

                if (WriteBuffer == null) {
                    UpdateHeaders();
                }

                if (CheckCacheRetrieveBeforeSubmit()) {
                    // We are done and internal Response processing is kicked in
                    GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SubmitRequest CACHED RESPONSE");
                    return;
                }

                // At this point we are going to send a live request
                // _AbortDelegate is set on submission process.
                servicePoint.SubmitRequest(this, GetConnectionGroupLine());
            }
            finally {
                if (!Async)
                    CheckWriteSideResponseProcessing();
            }
            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SubmitRequest");
        }
Ejemplo n.º 38
0
        //
        // Process an exception and optionally set request for retrying
        //
        private void SetResponse(Exception E) {
#if DEBUG
            bool callbackInvoked = false;
            try
            {
#endif
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", E.ToString() + "/*** SETRESPONSE IN ERROR ***");
            GlobalLog.ThreadContract(ThreadKinds.Unknown, "HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse");

            HttpProcessingResult httpResult = HttpProcessingResult.Continue;

            //
            // Preserve the very first web exception occured if it was fatal
            //
            WebException webException = HaveResponse ? _ReadAResult.Result as WebException : null;
            WebException newWebException = E as WebException;
            if (webException != null && (webException.InternalStatus == WebExceptionInternalStatus.RequestFatal ||
                webException.InternalStatus == WebExceptionInternalStatus.ServicePointFatal) &&
                (newWebException == null || newWebException.InternalStatus != WebExceptionInternalStatus.RequestFatal))
            {
                E = webException;
            }
            else
            {
                webException = newWebException;
            }

            if (E != null)
            {
                if (Logging.On) Logging.Exception(Logging.Web, this, "", webException);
            }

            try {
                if ( webException != null &&
                     (webException.InternalStatus == WebExceptionInternalStatus.Isolated ||
                     webException.InternalStatus == WebExceptionInternalStatus.ServicePointFatal ||
                     (webException.InternalStatus == WebExceptionInternalStatus.Recoverable && !m_OnceFailed)))
                {

                    if (webException.InternalStatus == WebExceptionInternalStatus.Recoverable)
                        m_OnceFailed = true;

                    Pipelined = false;

                    if (_SubmitWriteStream != null && _OldSubmitWriteStream == null && _SubmitWriteStream.BufferOnly) {
                        _OldSubmitWriteStream = _SubmitWriteStream;
                    }

                    httpResult = DoSubmitRequestProcessing(ref E);
                }
            }
            catch (Exception unexpectedException)
            {
                if (NclUtilities.IsFatal(unexpectedException)) throw;

                // This is highly unexpected but if happens would result into Aborted exception with caught one as an inner exception
                httpResult = HttpProcessingResult.Continue;
                E = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), unexpectedException, WebExceptionStatus.RequestCanceled, _HttpResponse);
            }
            finally
            {
                if (httpResult == HttpProcessingResult.Continue)
                {
                    CancelTimer();

                    if (!(E is WebException) && !(E is SecurityException))
                    {
                        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 );
                        }
                    }

                    LazyAsyncResult writeAResult;
                    LazyAsyncResult readAResult = null;

                    // Async Abort may happen at any time including when the request is being cleared
                    // and resubmitted hence using checked response.
                    HttpWebResponse chkResponse = _HttpResponse;

                    lock (this)
                    {
                        writeAResult = _WriteAResult;

                        if (_ReadAResult == null)
                        {
                            _ReadAResult = new LazyAsyncResult(null, null, null, E); //never throws
                        }
                        else
                        {
                            readAResult = _ReadAResult;
                        }
                    }

                    try
                    {
                        FinishRequest(chkResponse, E); //never throws

                        try
                        {
                            if (writeAResult != null) {
                                writeAResult.InvokeCallback(E);
                            }
                        }
                        finally
                        {
                            if (readAResult != null) {
#if DEBUG
                                callbackInvoked = true;
#endif
                                readAResult.InvokeCallback(E);
                            }
                        }
                    }
                    finally
                    {
                        chkResponse = _ReadAResult.Result as HttpWebResponse;

                        // If the response was already set that exception closes it.
                        if (chkResponse != null)
                        {
                            chkResponse.Abort();    //never throws
                        }

                        if (CacheProtocol != null)
                        {
                            CacheProtocol.Abort();  //never throws
                        }
                    }
                }
#if DEBUG
                else
                {
                    callbackInvoked = true;
                }
#endif
            }
            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::SetResponse", httpResult.ToString());
#if DEBUG
            }
            catch (Exception exception)
            {
                t_LastStressException = exception;

                if (!NclUtilities.IsFatal(exception)){
                    GlobalLog.Assert(callbackInvoked, "HttpWebRequest#{0}::SetResponse|{1}", ValidationHelper.HashString(this), exception.Message);
                }
                throw;
            }
#endif
        }
Ejemplo n.º 39
0
		public IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
		{
			ValidateCreateContext (true, string.Empty, enabledSslProtocols, serverCertificate, null, clientCertificateRequired);
			var result = new LazyAsyncResult (this, asyncState, asyncCallback);
			ProcessAuthentication (result);
			return result;
		}
Ejemplo n.º 40
0
 // Token: 0x06000925 RID: 2341 RVA: 0x000285E4 File Offset: 0x000267E4
 public IAsyncResult BeginGetObject(DirectoryCacheRequest cacheRequest, AsyncCallback callback, object asyncState)
 {
     this.stopwatch = Stopwatch.StartNew();
     return(this.Invoke(delegate
     {
         ArgumentValidator.ThrowIfNull("cacheRequest", cacheRequest);
         if (cacheRequest.ObjectType == ObjectType.ADRawEntry && cacheRequest.Properties == null)
         {
             throw new ArgumentException("properties cannot be null when request object type is ADRawEntry");
         }
         MSExchangeDirectoryCacheServiceCounters.NumberOfCacheReadRequests.Increment();
         GetObjectContext getObjectContext = new GetObjectContext();
         getObjectContext.ResultState = ADCacheResultState.NotFound;
         LazyAsyncResult lazyAsyncResult = new LazyAsyncResult(getObjectContext, asyncState, callback);
         ExTraceGlobals.WCFServiceEndpointTracer.TraceDebug <DirectoryCacheRequest>((long)this.GetHashCode(), "Begin GetObject. Request {0}", cacheRequest);
         MSExchangeDirectoryCacheServiceCounters.CacheHitRatioBase.Increment();
         ObjectTuple objectTuple = null;
         foreach (Tuple <string, KeyType> tuple in cacheRequest.Keys)
         {
             CacheEntry cacheEntry = null;
             foreach (KeyType keyType in DirectoryCacheService.AllSupportedKeyTypes)
             {
                 if ((keyType & tuple.Item2) != KeyType.None)
                 {
                     string composedKey = this.GetComposedKey(cacheRequest.ForestOrPartitionFqdn, tuple.Item1, keyType);
                     string text = (string)CacheManager.Instance.KeyTable.Get(composedKey, null);
                     if (text != null)
                     {
                         cacheEntry = (CacheEntry)CacheManager.Instance.ADObjectCache.Get(text, null);
                         if (cacheEntry != null && cacheEntry[keyType].Contains(composedKey.ToLower()))
                         {
                             break;
                         }
                         if (cacheEntry != null)
                         {
                             if (ExTraceGlobals.WCFServiceEndpointTracer.IsTraceEnabled(TraceType.DebugTrace))
                             {
                                 string keyValues = string.Empty;
                                 cacheEntry[keyType].ForEach(delegate(string keyVal)
                                 {
                                     keyValues += keyVal;
                                     keyValues += ",";
                                 });
                                 ExTraceGlobals.WCFServiceEndpointTracer.TraceDebug <string, string>((long)this.GetHashCode(), "the key {0} does not match the cacheEntry's one {1}", composedKey, keyValues);
                             }
                             cacheEntry = null;
                         }
                     }
                 }
             }
             if (cacheEntry != null)
             {
                 if (cacheEntry.Invalid)
                 {
                     break;
                 }
                 foreach (ObjectTuple objectTuple2 in cacheEntry.SimpleADObjectList)
                 {
                     if (objectTuple2.ObjType == cacheRequest.ObjectType)
                     {
                         objectTuple = objectTuple2;
                         break;
                     }
                 }
                 if (objectTuple == null)
                 {
                     break;
                 }
                 if (cacheRequest.Properties != null)
                 {
                     foreach (string key in cacheRequest.Properties)
                     {
                         if (!objectTuple.ADObject.Properties.ContainsKey(key))
                         {
                             objectTuple = null;
                             getObjectContext.ResultState = ADCacheResultState.PropertiesMissing;
                             ADProviderPerf.UpdateDirectoryADRawCachePropertiesMismatchRate(true);
                             break;
                         }
                     }
                 }
                 if (objectTuple == null)
                 {
                     break;
                 }
                 getObjectContext.Object = objectTuple.ADObject;
                 getObjectContext.ResultState = ADCacheResultState.Succeed;
                 if (cacheRequest.Properties != null)
                 {
                     ADProviderPerf.UpdateDirectoryADRawCachePropertiesMismatchRate(false);
                     break;
                 }
                 break;
             }
         }
         ExTraceGlobals.WCFServiceEndpointTracer.TraceDebug <string, string>((long)this.GetHashCode(), "Begin GetObject. Request {0}. Was Cache {1}", cacheRequest.RequestId, (getObjectContext.Object != null) ? "HIT" : "MISS");
         ADProviderPerf.UpdateDirectoryCacheHitRatio(null != getObjectContext.Object, cacheRequest.ObjectType);
         this.stopwatch.Stop();
         getObjectContext.BeginOperationLatency = this.stopwatch.ElapsedMilliseconds;
         this.stopwatch.Restart();
         callback(lazyAsyncResult);
         return lazyAsyncResult;
     }));
 }
Ejemplo n.º 41
0
 internal MimePartContext(BaseWriter writer, LazyAsyncResult result, IEnumerator<MimeBasePart> partsEnumerator) {
     this.writer = writer;
     this.result = result;
     this.partsEnumerator = partsEnumerator;
 }
Ejemplo n.º 42
0
 internal EmptySendContext(BaseWriter writer, LazyAsyncResult result)
 {
     _writer = writer;
     _result = result;
 }
Ejemplo n.º 43
0
 private void ResumeClose_Part2(LazyAsyncResult userResult)
 {
     try
     {
         try
         {
             if (ErrorInStream)
             {
                 GlobalLog.Print("ConnectStream#" + ValidationHelper.HashString(this) + "::ResumeClose_Part2() Aborting the connection");
                 m_Connection.AbortSocket(true);
             }
         }
         finally
         {
             CallDone();
             GlobalLog.Leave("ConnectStream#" + ValidationHelper.HashString(this) + "::ResumeClose_Part2", "Done");
         }
     }
     catch { }
     finally
     {
         if (userResult != null)
         {
             userResult.InvokeCallback();
         }
     }
 }
Ejemplo n.º 44
0
        private void ProcessWriteCallback(IAsyncResult asyncResult, LazyAsyncResult userResult)
        {
            Exception userException = null;

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

                        userException = exception;

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

                        userException = exception;

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

                if (Nesting.Closed == ExchangeCallNesting((userException == null? Nesting.Idle: Nesting.InError), Nesting.IoInProgress))
                {
                    if (userException != null && m_ErrorException == null)
                    {
                        Interlocked.CompareExchange<Exception>(ref m_ErrorException, userException, null);
                    }
                    ResumeInternalClose(userResult);
                }
                else
                {
                    userResult.InvokeCallback(userException);
                }
            }
        }
Ejemplo n.º 45
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,
                                                       (System.Security.Authentication.SslProtocols)ServicePointManager.SecurityProtocol,
                                                       null, m_ClientCertificates,
                                                       true,
                                                       ServicePointManager.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 [....] 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 [....] 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 [....] case it does not matter since the caller will resume IO upon return
            return true;
        }
Ejemplo n.º 46
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.


        --*/
        private void ProcessResponse() {
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::ProcessResponse", "From Cache = " + _HttpResponse.IsFromCache);
            GlobalLog.ThreadContract(ThreadKinds.Unknown, "HttpWebRequest#" + ValidationHelper.HashString(this) + "::ProcessResponse");

            HttpProcessingResult httpResult = HttpProcessingResult.Continue;
            Exception exception = null;

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

            if (httpResult == HttpProcessingResult.Continue)
            {
                CancelTimer();

                object result = exception != null ? (object) exception : (object) _HttpResponse;

                if (_ReadAResult == null)
                {
                    lock (this)
                    {
                        if (_ReadAResult == null)
                        {
                            _ReadAResult = new LazyAsyncResult(null, null, null);  //never throws
                        }
                    }
                }

                try
                {
                    FinishRequest(_HttpResponse, exception); // never throws

                    _ReadAResult.InvokeCallback(result);

                    try
                    {
                        SetRequestContinue();
                    }
                    catch { }
                }
                catch (Exception e)
                {
                    Abort(e, AbortState.Public);
                    throw;
                }
                finally
                {
                    // If request was already aborted the response will not be set on asyncResult, hence abort it now
                    if (exception == null && _ReadAResult.Result != (object) _HttpResponse)
                    {
                        WebException webException = _ReadAResult.Result as WebException;
                        if (webException != null && webException.Response != null)
                        {
                            GlobalLog.Assert(object.ReferenceEquals(webException.Response, _HttpResponse), "HttpWebRequset#{0}::ProcessResponse|Different HttpWebResponse in exception versus _HttpResponse.", ValidationHelper.HashString(this));
                            _HttpResponse.Abort();  // never throws
                        }
                    }
                }
            }
            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::ProcessResponse");
        }
Ejemplo n.º 47
0
		int ProcessReadOrWrite (ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, BufferOffsetSize userBuffer, LazyAsyncResult lazyResult)
		{
			if (userBuffer == null || userBuffer.Buffer == null)
				throw new ArgumentNullException ("buffer");
			if (userBuffer.Offset < 0)
				throw new ArgumentOutOfRangeException ("offset");
			if (userBuffer.Size < 0 || userBuffer.Offset + userBuffer.Size > userBuffer.Buffer.Length)
				throw new ArgumentOutOfRangeException ("count");

			CheckThrow (true);

			var name = internalBuffer == readBuffer ? "read" : "write";
			Debug ("ProcessReadOrWrite: {0} {1}", name, userBuffer);

			var asyncRequest = new AsyncProtocolRequest (this, lazyResult, userBuffer);
			return StartOperation (ref nestedRequest, ref internalBuffer, operation, asyncRequest, name);
		}
Ejemplo n.º 48
0
 public AsyncProtocolRequest(MobileAuthenticatedStream parent, LazyAsyncResult lazyResult, BufferOffsetSize userBuffer = null)
 {
     Parent = parent;
     UserAsyncResult = lazyResult;
     UserBuffer = userBuffer;
 }
Ejemplo n.º 49
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse");
            if(Logging.On)Logging.Enter(Logging.Web, this, "BeginGetResponse", "");

            // No need to recheck the request parameters if we already did it in BeginGetRequestStream().
            // This prevents problems when redirects change verbs.
            if (!RequestSubmitted)
            {
                CheckProtocol(false);
            }

            ConnectStream stream = _OldSubmitWriteStream != null ? _OldSubmitWriteStream : _SubmitWriteStream;

            // Close the request stream if the user forgot to do so. Throw an exception if user has not written all of
            // the promised data.
            if (stream != null && !stream.IsClosed)
            {
                if (stream.BytesLeftToWrite > 0)
                {
                    throw new ProtocolViolationException(SR.GetString(SR.net_entire_body_not_written));
                }
                else
                {
                    stream.Close();
                }
            }
            else if (stream == null && HasEntityBody)
            {
                throw new ProtocolViolationException(SR.GetString(SR.net_must_provide_request_body));
            }

#if !FEATURE_PAL
            ContextAwareResult asyncResult = new ContextAwareResult(IdentityRequired, true, this, state, callback);
#else // FEATURE_PAL
            ContextAwareResult asyncResult = new ContextAwareResult(false, true, this, state, callback);
#endif

            if (!RequestSubmitted && NclUtilities.IsThreadPoolLow())
            {
                // prevent new requests when low on resources
                Exception exception = new InvalidOperationException(SR.GetString(SR.net_needmorethreads));
                Abort(exception, AbortState.Public);
                throw exception;
            }

            // Need to lock the context until it's created (if necessary) in Returning().
            lock (asyncResult.StartPostingAsyncOp())
            {
                bool gotResponse = false;
                bool requestSubmitted;
                lock (this)
                {
                    requestSubmitted = SetRequestSubmitted();

                    if (HaveResponse)
                    {
                        gotResponse = true;
                    }
                    else
                    {
                        if (_ReadAResult != null)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.net_repcall));
                        }

                        _ReadAResult = asyncResult;
                        Async = true;
                    }
                }

                // Must check this after setting _ReadAResult, which holds the context which may be used for permission checks etc.
                // See if we need to do the call-done processing here.
                CheckDeferredCallDone(stream);

                if (gotResponse)
                {
                    if (Logging.On) Logging.Exit(Logging.Web, this, "BeginGetResponse", _ReadAResult.Result);
                    GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse", "Already Completed, response = " + ValidationHelper.HashString(_ReadAResult.Result));
                    Exception e = _ReadAResult.Result as Exception;
                    if (e != null)
                    {
                        throw e;
                    }

                    try
                    {
                        asyncResult.InvokeCallback(_ReadAResult.Result);
                    }
                    catch (Exception exception)
                    {
                        Abort(exception, AbortState.Public);
                        throw;
                    }
                }
                else
                {
                    // If we're here it's because we don't have the response yet. We may have
                    // already submitted the request, but if not do so now.
                    if (!requestSubmitted)
                    {
                        // Save Off verb, and use it to make the request
                        GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + ": resetting CurrentMethod to " + _OriginVerb);
                        CurrentMethod = _OriginVerb;
                    }

                    // If we're here it's because we don't have the response yet. We may have
                    //  already submitted the request, but if not do so now.
                    if (_RerequestCount > 0 || !requestSubmitted) {
                        while (m_Retry) {
                            // Keep looping in case there are redirects, auth re-requests, etc
                            BeginSubmitRequest();
                        }
                    }
                }
                asyncResult.FinishPostingAsyncOp();
            }

            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse", ValidationHelper.HashString(asyncResult));
            if(Logging.On)Logging.Exit(Logging.Web, this, "BeginGetResponse", asyncResult);

            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;
#if DEBUG
            }
#endif
        }
Ejemplo n.º 50
0
        /// <devdoc>
        ///    <para>
        ///       Returns a response from a request to an Internet resource.
        ///    The response property. This property returns the WebResponse for this
        ///    request. This may require that a request be submitted first.
        ///
        ///     The idea is that we look and see if a request has already been
        ///    submitted. If one has, we'll just return the existing response
        ///    (if it's not null). If we haven't submitted a request yet, we'll
        ///    do so now, possible multiple times while we handle redirects
        ///    etc.
        ///    </para>
        /// </devdoc>
        public override WebResponse GetResponse() {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::GetResponse");
            if(Logging.On)Logging.Enter(Logging.Web, this, "GetResponse", "");

            // No need to recheck the request parameters if we already did it in GetRequestStream().
            // This prevents problems when redirects change verbs.
            if (!RequestSubmitted)
            {
                CheckProtocol(false);
            }

            // Many of these logics require GetResponse() to be called after all write-stream activity is done.  You can't call it
            // simultaneously on another thread and expect it to block until it can run.  Doing that can cause the request to
            // hang.

            ConnectStream stream = _OldSubmitWriteStream != null ? _OldSubmitWriteStream : _SubmitWriteStream;

            // Close the request stream if the user forgot to do so. Throw an exception if user has not written all of
            // the promised data.
            if (stream != null && !stream.IsClosed)
            {
                if (stream.BytesLeftToWrite > 0)
                {
                    throw new ProtocolViolationException(SR.GetString(SR.net_entire_body_not_written));
                }
                else
                {
                    stream.Close();
                }
            }
            else if (stream == null && HasEntityBody)
            {
                throw new ProtocolViolationException(SR.GetString(SR.net_must_provide_request_body));
            }

            // return response, if the response is already set
            bool gotResponse = false;
            HttpWebResponse httpWebResponse = null;
            bool requestSubmitted;
            lock (this)
            {
                requestSubmitted = SetRequestSubmitted();
                if (HaveResponse)
                {
                    gotResponse = true;
                    httpWebResponse = _ReadAResult.Result as HttpWebResponse;
                }
                else
                {
                    if (_ReadAResult != null)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.net_repcall));
                    }

                    Async = false;

                    // Since we don't really allow switching between [....] and async, if the request is already async, this needs to
                    // capture context for use in the ongoing async operations as if it were BeginGetResponse().
                    if (Async)
                    {
#if !FEATURE_PAL
                        ContextAwareResult readResult = new ContextAwareResult(IdentityRequired, true, this, null, null);
#else
                        ContextAwareResult readResult = new ContextAwareResult(false, true, this, null, null);
#endif
                        readResult.StartPostingAsyncOp(false);
                        readResult.FinishPostingAsyncOp();
                        _ReadAResult = readResult;
                    }
                    else
                    {
                        _ReadAResult = new LazyAsyncResult(this, null, null);
                    }
                }
            }

            // See if we need to do the call-done processing here.
            CheckDeferredCallDone(stream);

            if (!gotResponse)
            {
                //The previous call may have been async.  If we are now doing a [....] call, we should
                //use the timeout
                if (_Timer == null){
                    _Timer = TimerQueue.CreateTimer(s_TimeoutCallback, this);
                }


                // Save Off verb, and use it to make the request
                if (!requestSubmitted) {
                    GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + ": resetting CurrentMethod to " + _OriginVerb);
                    CurrentMethod = _OriginVerb;
                }

                // If we're here it's because we don't have the response yet. We may have
                //  already submitted the request, but if not do so now.
                while (m_Retry) {
                    // Keep looping in case there are redirects, auth re-requests, etc
                    BeginSubmitRequest();
                }

                while(!Async && Aborted && !_ReadAResult.InternalPeekCompleted)
                {
                    // spin untill the _CoreResponse is set
                    if (!(_CoreResponse is Exception))
                        Thread.SpinWait(1);
                    else
                        CheckWriteSideResponseProcessing();
                }

                httpWebResponse = _ReadAResult.InternalWaitForCompletion() as HttpWebResponse;
                _ReadAResult.EndCalled = true;
            }

            if (httpWebResponse == null)
            {
                if (Logging.On) Logging.Exception(Logging.Web, this, "GetResponse", _ReadAResult.Result as Exception);
                NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.HttpWebRequestFailed);
                throw (Exception) _ReadAResult.Result;
            }

            GlobalLog.Assert(httpWebResponse.ResponseStream != null, "HttpWebRequest#{0}::GetResponse()|httpWebResponse.ResponseStream == null", ValidationHelper.HashString(this));
            if(Logging.On)Logging.Exit(Logging.Web, this, "GetResponse", httpWebResponse);
            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::GetResponse", ValidationHelper.HashString(httpWebResponse));

            if (!gotResponse)
            {
                InitLifetimeTracking(httpWebResponse);
            }

            return httpWebResponse;
#if DEBUG
            }
#endif
        }
 internal SplitWriteAsyncProtocolRequest(LazyAsyncResult userAsyncResult) : base(userAsyncResult)
 {
 }
Ejemplo n.º 52
0
 internal MimePartContext(BaseWriter writer, LazyAsyncResult result)
 {
     this.writer = writer;
     this.result = result;
     buffer = new byte[maxBufferSize];
 }
Ejemplo n.º 53
0
 internal MimePartContext(BaseWriter writer, LazyAsyncResult result, IEnumerator <MimeBasePart> partsEnumerator)
 {
     _writer          = writer;
     _result          = result;
     _partsEnumerator = partsEnumerator;
 }
Ejemplo n.º 54
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            #if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
            #endif
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse");
            if(Logging.On)Logging.Enter(Logging.Web, this, "BeginGetResponse", "");

            CheckProtocol(false);

            ConnectStream stream = _OldSubmitWriteStream != null ? _OldSubmitWriteStream : _SubmitWriteStream;

            // Close the request stream if the user forgot to do that and all data is written.
            if(stream != null && !stream.IsClosed && stream.BytesLeftToWrite == 0)
            {
                stream.Close();
            }

            ContextAwareResult asyncResult = new ContextAwareResult(false, true, this, state, callback);

            if (!RequestSubmitted && NclUtilities.IsThreadPoolLow())
            {
                // prevent new requests when low on resources
                Exception exception = new InvalidOperationException(SR.GetString(SR.net_needmorethreads));
                Abort(exception, AbortState.Public);
                throw exception;
            }

            // Need to lock the context until it's created (if necessary) in Returning().
            lock (asyncResult.StartPostingAsyncOp())
            {
                bool gotResponse = false;
                bool requestSubmitted;
                lock (this)
                {
                    requestSubmitted = SetRequestSubmitted();

                    if (HaveResponse)
                    {
                        gotResponse = true;
                    }
                    else
                    {
                        if (_ReadAResult != null)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.net_repcall));
                        }

                        _ReadAResult = asyncResult;
                        Async = true;
                    }
                }

                // Must check this after setting _ReadAResult, which holds the context which may be used for permission checks etc.
                // See if we need to do the call-done processing here.
                CheckDeferredCallDone(stream);

                if (gotResponse)
                {
                    if (Logging.On) Logging.Exit(Logging.Web, this, "BeginGetResponse", _ReadAResult.Result);
                    GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse", "Already Completed, response = " + ValidationHelper.HashString(_ReadAResult.Result));
                    Exception e = _ReadAResult.Result as Exception;
                    if (e != null)
                    {
                        throw e;
                    }

                    try
                    {
                        asyncResult.InvokeCallback(_ReadAResult.Result);
                    }
                    catch (Exception exception)
                    {
                        Abort(exception, AbortState.Public);
                        throw;
                    }
                }
                else
                {
                    // If we're here it's because we don't have the response yet. We may have
                    // already submitted the request, but if not do so now.
                    if (!requestSubmitted)
                    {
                        // Save Off verb, and use it to make the request
                        GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + ": resetting CurrentMethod to " + _OriginVerb);
                        CurrentMethod = _OriginVerb;
                    }

                    // If we're here it's because we don't have the response yet. We may have
                    //  already submitted the request, but if not do so now.
                    if (_RerequestCount > 0 || !requestSubmitted) {
                        while (m_Retry) {
                            // Keep looping in case there are redirects, auth re-requests, etc
                            BeginSubmitRequest();
                        }
                    }
                }
                asyncResult.FinishPostingAsyncOp();
            }

            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse", ValidationHelper.HashString(asyncResult));
            if(Logging.On)Logging.Exit(Logging.Web, this, "BeginGetResponse", asyncResult);
            return asyncResult;
            #if DEBUG
            }
            #endif
        }
Ejemplo n.º 55
0
 //
 // 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
 }
Ejemplo n.º 56
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) {
#endif
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetRequestStream");
            if(Logging.On)Logging.Enter(Logging.Web, this, "BeginGetRequestStream", "");
            CheckProtocol(true);

#if !FEATURE_PAL
            ContextAwareResult asyncResult = new ContextAwareResult(IdentityRequired, true, this, state, callback);
#else // !FEATURE_PAL
            ContextAwareResult asyncResult = new ContextAwareResult(false, true, this, state, callback);
#endif // !FEATURE_PAL


            lock (asyncResult.StartPostingAsyncOp())
            {
                // and have a result (weird but was supported in V1.X as repeated calls for the submit stream.
                if (_WriteAResult != null && _WriteAResult.InternalPeekCompleted)
                {
                    if (_WriteAResult.Result is Exception)
                    {
                        throw (Exception)_WriteAResult.Result;
                    }

                    try
                    {
                        asyncResult.InvokeCallback(_WriteAResult.Result);
                    }
                    catch (Exception e)
                    {
                        Abort(e, AbortState.Public);
                        throw;
                    }
                }
                else
                {
                    // prevent new requests when low on resources
                    if (!RequestSubmitted && NclUtilities.IsThreadPoolLow())
                    {
                        Exception exception = new InvalidOperationException(SR.GetString(SR.net_needmorethreads));
                        Abort(exception, AbortState.Public);
                        throw exception;
                    }

                    lock(this)
                    {
                        if (_WriteAResult != null)
                        {
                            throw new InvalidOperationException(SR.GetString(SR.net_repcall));
                        }

                        // See if we're already submitted a request (e.g. via GetResponse).
                        if (SetRequestSubmitted())
                        {
                            // Not completed write stream, this is an application error.
                            throw new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                        }

                        // If there's already been a _ReadAResult completed, it better have been with an exception, like an abort.
                        // We need to check within this lock.  Before the lock, _WriteAResult didn't exist so won't have been notified.
                        // BeginSubmitRequest() will fail silently if we go ahead and call it after an abort.  Since we know this is the
                        // first call to any of the [Begin]GetRe... methods by the above checks, we know ProcessResponse can't have been
                        // called or any other valid _ReadAResult created yet.
                        if (_ReadAResult != null)
                        {
                            GlobalLog.Assert(_ReadAResult.InternalPeekCompleted, "HttpWebRequest#{0}::BeginGetRequestStream()|Incomplete _ReadAResult present on request.", ValidationHelper.HashString(this));
                            GlobalLog.Assert(_ReadAResult.Result is Exception, "HttpWebRequest#{0}::BeginGetRequestStream()|_ReadAResult with successful completion already present on request.", ValidationHelper.HashString(this));
                            throw (Exception) _ReadAResult.Result;
                        }

                        // get async going
                        _WriteAResult = asyncResult;
                        Async = true;
                    }

                    // OK, we haven't submitted the request yet, so do so now
                    // save off verb from origin Verb
                    GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetRequestStream() resetting CurrentMethod to " + _OriginVerb);
                    CurrentMethod = _OriginVerb;
                    BeginSubmitRequest();
                }

                asyncResult.FinishPostingAsyncOp();
            }

            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetRequestStream", ValidationHelper.HashString(asyncResult));
            if(Logging.On)Logging.Exit(Logging.Web, this, "BeginGetRequestStream", asyncResult);

            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 asyncResult;
#if DEBUG
            }
#endif
        }
Ejemplo n.º 57
0
        //
        // 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() ----ing: 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() ----ing: 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 ---- 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() ----ing: 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 ---- 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();
                    }
                }
            }
        }
Ejemplo n.º 58
0
        /// <devdoc>
        /// <para>Gets a <see cref='System.IO.Stream'/> that the application can use to write request data.
        ///    This property returns a stream that the calling application can write on.
        ///    This property is not settable.  Getting this property may cause the
        ///    request to be sent, if it wasn't already. Getting this property after
        ///    a request has been sent that doesn't have an entity body causes an
        ///    exception to be thrown.
        ///</para>
        /// </devdoc>
        public Stream GetRequestStream(out TransportContext context) {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) {
#endif
            GlobalLog.Enter("HttpWebRequest#" + ValidationHelper.HashString(this) + "::GetRequestStream");
            if(Logging.On)Logging.Enter(Logging.Web, this, "GetRequestStream", "");

            context = null;

            CheckProtocol(true);

            // See if we're already submitted a request and have a result cached.
            if (_WriteAResult == null || !_WriteAResult.InternalPeekCompleted)
            {
                lock(this)
                {
                    if (_WriteAResult != null)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.net_repcall));
                    }

                    // See if we're already submitted a request (e.g. via GetResponse).
                    if (SetRequestSubmitted())
                    {
                        // Not completed write stream, this is an application error.
                        throw new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    }

                    // If there's already been a _ReadAResult completed, it better have been with an exception, like an abort.
                    // We need to check within this lock.  Before the lock, _WriteAResult didn't exist so won't have been notified.
                    // BeginSubmitRequest() will fail silently if we go ahead and call it after an abort.  Since we know this is the
                    // first call to any of the [Begin]GetRe... methods by the above checks, we know ProcessResponse can't have been
                    // called or any other valid _ReadAResult created yet.
                    if (_ReadAResult != null)
                    {
                        GlobalLog.Assert(_ReadAResult.InternalPeekCompleted, "HttpWebRequest#{0}::GetRequestStream()|Incomplete _ReadAResult present on request.", ValidationHelper.HashString(this));
                        GlobalLog.Assert(_ReadAResult.Result is Exception, "HttpWebRequest#{0}::GetRequestStream()|_ReadAResult with successful completion already present on request.", ValidationHelper.HashString(this));
                        throw (Exception) _ReadAResult.Result;
                    }

                    // use the AsyncResult to return our Stream
                    _WriteAResult = new LazyAsyncResult(this, null, null);

                    Async = false;
                }

                // OK, we haven't submitted the request yet, so do so now
                // save off verb from origin Verb
                GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "GetRequestStream() resetting CurrentMethod to " + _OriginVerb);
                CurrentMethod = _OriginVerb;

                // Submit the Request, causes us to queue ourselves to a Connection and may block
                // It has happened that [....] path uses this loop the Retry memeber for handling resubmissions.
                while (m_Retry && !_WriteAResult.InternalPeekCompleted) {
                    _OldSubmitWriteStream = null;
                    _SubmitWriteStream = null;
                    BeginSubmitRequest();
                }

                while(Aborted && !_WriteAResult.InternalPeekCompleted)
                {
                    // spin untill the _CoreResponse is set
                    if (!(_CoreResponse is Exception))
                        Thread.SpinWait(1);
                    else
                        CheckWriteSideResponseProcessing();
                }
            }

            ConnectStream connectStream = _WriteAResult.InternalWaitForCompletion() as ConnectStream;
            _WriteAResult.EndCalled = true;
            if (connectStream == null)
            {
                if (Logging.On) Logging.Exception(Logging.Web, this, "EndGetRequestStream", _WriteAResult.Result as Exception);
                throw (Exception) _WriteAResult.Result;
            }

            context = new ConnectStreamContext(connectStream);

            if(Logging.On)Logging.Exit(Logging.Web, this, "GetRequestStream", connectStream);
            GlobalLog.Leave("HttpWebRequest#" + ValidationHelper.HashString(this) + "::GetRequestStream", ValidationHelper.HashString(connectStream));
            return connectStream;
#if DEBUG
            }
#endif
        }
Ejemplo n.º 59
0
 internal MimePartContext(BaseWriter writer, LazyAsyncResult result)
 {
     this.writer = writer;
     this.result = result;
     this.buffer = new byte[0x4400];
 }
Ejemplo n.º 60
0
		IAsyncResult BeginReadOrWrite (ref AsyncProtocolRequest nestedRequest, ref BufferOffsetSize2 internalBuffer, AsyncOperation operation, BufferOffsetSize userBuffer, AsyncCallback asyncCallback, object asyncState)
		{
			LazyAsyncResult lazyResult = new LazyAsyncResult (this, asyncState, asyncCallback);
			ProcessReadOrWrite (ref nestedRequest, ref internalBuffer, operation, userBuffer, lazyResult);
			return lazyResult;
		}