// // this method runs in the context of the user Begin call . // private static void WrappedGetRequestStreamCallback(object state) { GlobalLog.Enter("FileWebRequest::GetRequestStreamCallback"); ContextAwareResult asyncResult = (ContextAwareResult)state; FileWebRequest request = (FileWebRequest)asyncResult.AsyncObject; try { if (request.m_stream == null) { request.m_stream = new FileWebStream(request, request.m_uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read); request.m_fileAccess = FileAccess.Write; request.m_writing = true; asyncResult.InvokeCallback(request.m_stream); GlobalLog.Leave("FileWebRequest::GetRequestStreamCallback"); } } catch (Exception e) { if (asyncResult.IsCompleted || NclUtilities.IsFatal(e)) { throw; } Exception ex = new WebException(e.Message, e); GlobalLog.LeaveException("FileWebRequest::GetRequestStreamCallback", ex); asyncResult.InvokeCallback(ex); } }
public override WebResponse EndGetResponse(IAsyncResult asyncResult) { GlobalLog.Enter("FileWebRequest::EndGetResponse"); WebResponse response; try { ContextAwareResult ar = asyncResult as ContextAwareResult; if (asyncResult == null || ar == null) { Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult"); GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e); throw e; } object result = ar.InternalWaitForCompletion(); if (result is Exception) { throw (Exception)result; } response = (WebResponse)result; m_readPending = false; } catch (Exception exception) { if (Logging.On) { Logging.Exception(Logging.Web, this, "EndGetResponse", exception); } throw; } finally { GlobalLog.Leave("FileWebRequest::EndGetResponse"); } return(response); }
internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ContextAwareResult context, System.Security.Authentication.ExtendedProtection.ChannelBinding channelBinding) { if ((credential is SystemNetworkCredential) && ComNetOS.IsWinNt) { WindowsIdentity identity = (context == null) ? null : context.Identity; try { IDisposable disposable = (identity == null) ? null : identity.Impersonate(); if (disposable != null) { using (disposable) { this.Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); return; } } ExecutionContext executionContext = (context == null) ? null : context.ContextCopy; if (executionContext == null) { this.Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } else { ExecutionContext.Run(executionContext, s_InitializeCallback, new InitializeCallbackContext(this, isServer, package, credential, spn, requestedContextFlags, channelBinding)); } return; } catch { throw; } } this.Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); }
private static void GetResponseCallback(object state) { ContextAwareResult asyncResult = (ContextAwareResult)state; try { ExecutionContext context = asyncResult.ContextCopy; if (context == null) { WrappedGetResponseCallback(state); } else { ExecutionContext.Run(context, s_WrappedResponseCallback, state); } } catch (InvalidOperationException) { // ContextCopy must have returned InvalidOperation because the // operation is already completed (e.g. due to Abort) // Verify it is completed and return. if (asyncResult.InternalPeekCompleted) { return; } else { throw; } } }
public override void Abort() { GlobalLog.Enter("FileWebRequest::Abort"); if (Logging.On) { Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled)); } try { if (Interlocked.Increment(ref m_Aborted) == 1) { ContextAwareResult readAResult = m_ReadAResult; ContextAwareResult writeAResult = m_WriteAResult; WebException webException = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled); Stream requestStream = m_stream; if (readAResult != null && !readAResult.IsCompleted) { readAResult.InvokeCallback(webException); } if (writeAResult != null && !writeAResult.IsCompleted) { writeAResult.InvokeCallback(webException); } if (requestStream != null) { if (requestStream is ICloseEx) { ((ICloseEx)requestStream).CloseEx(CloseExState.Abort); } else { requestStream.Close(); } } if (m_response != null) { ((ICloseEx)m_response).CloseEx(CloseExState.Abort); } } } catch (Exception exception) { if (Logging.On) { Logging.Exception(Logging.Web, this, "Abort", exception); } throw; } finally { GlobalLog.Leave("FileWebRequest::Abort"); } }
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { GlobalLog.Enter("FileWebRequest::BeginGetRequestStream"); try { if (Aborted) { throw ExceptionHelper.RequestAbortedException; } if (!CanGetRequestStream()) { Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget)); GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e); throw e; } if (m_response != null) { Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted)); GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e); throw e; } lock (this) { if (m_writePending) { Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall)); GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e); throw e; } m_writePending = true; } //we need to force the capture of the identity and context to make sure the //posted callback doesn't inavertently gain access to something it shouldn't. m_ReadAResult = new ContextAwareResult(true, true, true, this, state, callback); lock (m_ReadAResult.StartPostingAsyncOp()) { ThreadPool.UnsafeQueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult); m_ReadAResult.FinishPostingAsyncOp(); } } catch (Exception exception) { if (Logging.On) { Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception); } throw; } finally { GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam"); } return(m_ReadAResult); }
public override IAsyncResult BeginGetUnicastAddresses(AsyncCallback callback, object state) { if (!ComNetOS.IsVista) { throw new PlatformNotSupportedException(SR.GetString("VistaRequired")); } ContextAwareResult result = new ContextAwareResult(false, false, this, state, callback); result.StartPostingAsyncOp(false); if (TeredoHelper.UnsafeNotifyStableUnicastIpAddressTable(new Action<object>(SystemIPGlobalProperties.StableUnicastAddressTableCallback), result)) { result.InvokeCallback(); } result.FinishPostingAsyncOp(); return result; }
// // this method runs in the context of the user Begin call . // private static void WrappedGetResponseCallback(object state) { GlobalLog.Enter("FileWebRequest::GetResponseCallback"); ContextAwareResult asyncResult = (ContextAwareResult)state; FileWebRequest request = (FileWebRequest)asyncResult.AsyncObject; if (request.m_writePending || request.m_writing) { lock (request) { if (request.m_writePending || request.m_writing) { request.m_readerEvent = new ManualResetEvent(false); } } } if (request.m_readerEvent != null) { request.m_readerEvent.WaitOne(); } try { if (request.m_response == null) { request.m_response = new FileWebResponse(request, request.m_uri, request.m_fileAccess, !request.m_syncHint); } GlobalLog.Leave("FileWebRequest::GetResponseCallback"); asyncResult.InvokeCallback(request.m_response); } catch (Exception e) { if (asyncResult.IsCompleted || NclUtilities.IsFatal(e)) { throw; } Exception ex = new WebException(e.Message, e); GlobalLog.LeaveException("FileWebRequest::GetResponseCallback", ex); asyncResult.InvokeCallback(ex); } }
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 }
/// <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 ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) : base(null, state, callback) { this.currentModule = -1; this.connection = connection; this.host = host; this.port = port; this.m_OuterResult = outerResult; }
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 }
internal IAsyncResult BeginGetConnection(ServicePoint servicePoint, ContextAwareResult outerResult, AsyncCallback callback, object state) { if (Logging.On) { Logging.Associate(Logging.Web, this, servicePoint); } if ((this.EnableSsl && (this.ClientCertificates != null)) && (this.ClientCertificates.Count > 0)) { this.connectionPool = ConnectionPoolManager.GetConnectionPool(servicePoint, this.ClientCertificates.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), m_CreateConnectionCallback); } else { this.connectionPool = ConnectionPoolManager.GetConnectionPool(servicePoint, "", m_CreateConnectionCallback); } ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, servicePoint.Host, servicePoint.Port, outerResult, callback, state); result.GetConnection(false); return result; }
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { if (Logging.On) { Logging.Enter(Logging.Web, this, "BeginGetRequestStream", ""); } if (Logging.On) { Logging.PrintInfo(Logging.Web, this, "BeginGetRequestStream", SR.GetString("net_log_method_equal", new object[] { this.m_MethodInfo.Method })); } ContextAwareResult result = null; try { if (this.m_GetRequestStreamStarted) { throw new InvalidOperationException(SR.GetString("net_repcall")); } this.m_GetRequestStreamStarted = true; if (!this.m_MethodInfo.IsUpload) { throw new ProtocolViolationException(SR.GetString("net_nouploadonget")); } this.CheckError(); if (this.ServicePoint.InternalProxyServicePoint) { HttpWebRequest httpWebRequest = this.GetHttpWebRequest(); if (Logging.On) { Logging.Associate(Logging.Web, this, httpWebRequest); } return (ContextAwareResult) httpWebRequest.BeginGetRequestStream(callback, state); } this.FinishRequestStage(RequestStage.RequestStarted); result = new ContextAwareResult(true, true, this, state, callback); lock (result.StartPostingAsyncOp()) { this.m_WriteAsyncResult = result; this.SubmitRequest(true); result.FinishPostingAsyncOp(); this.FinishRequestStage(RequestStage.CheckForError); } return result; } catch (Exception exception) { if (Logging.On) { Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception); } throw; } finally { if (Logging.On) { Logging.Exit(Logging.Web, this, "BeginGetRequestStream", ""); } } return result; }
private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context) { // We may need to restore user thread token here if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials)) { #if DEBUG if (context != null && !context.IdentityRequested) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("SmtpConnection#{0}::SetContextAndTryAuthenticate|Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)", LoggingHash.HashString(this)); } Debug.Fail("SmtpConnection#" + LoggingHash.HashString(this) + "::SetContextAndTryAuthenticate|Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)"); } #endif try { ExecutionContext x = context == null ? null : context.ContextCopy; if (x != null) { AuthenticateCallbackContext authenticationContext = new AuthenticateCallbackContext(this, module, credential, _client.TargetName, _channelBindingToken); ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext); return authenticationContext._result; } else { return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken); } } catch { // Prevent the impersonation from leaking to upstack exception filters. throw; } } return module.Authenticate(null, credential, this, _client.TargetName, _channelBindingToken); }
internal IAsyncResult BeginGetConnection(ServicePoint servicePoint, ContextAwareResult outerResult, AsyncCallback callback, object state) { if (Logging.On) Logging.Associate(Logging.Web, this, servicePoint); Debug.Assert(servicePoint != null, "servicePoint was null from SmtpTransport"); if (EnableSsl && ClientCertificates != null && ClientCertificates.Count > 0) connectionPool = ConnectionPoolManager.GetConnectionPool(servicePoint, ClientCertificates.GetHashCode().ToString(NumberFormatInfo.InvariantInfo), m_CreateConnectionCallback); else connectionPool = ConnectionPoolManager.GetConnectionPool(servicePoint, "", m_CreateConnectionCallback); ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, servicePoint.Host, servicePoint.Port, outerResult, callback, state); result.GetConnection(false); return result; }
internal NTAuthentication(bool isServer, string package, NetworkCredential credential, string spn, ContextFlags requestedContextFlags, ContextAwareResult context, ChannelBinding channelBinding) { // // check if we're using DefaultCredentials // if (credential is SystemNetworkCredential) { // #if DEBUG GlobalLog.Assert(context == null || context.IdentityRequested, "NTAuthentication#{0}::.ctor|Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)", ValidationHelper.HashString(this)); #endif WindowsIdentity w = context == null ? null : context.Identity; try { IDisposable ctx = w == null ? null : w.Impersonate(); if (ctx != null) { using (ctx) { Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } } else { ExecutionContext x = context == null ? null : context.ContextCopy; if (x == null) { Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } else { ExecutionContext.Run(x, s_InitializeCallback, new InitializeCallbackContext(this, isServer, package, credential, spn, requestedContextFlags, channelBinding)); } } } catch { // Prevent the impersonation from leaking to upstack exception filters. throw; } } else { Initialize(isServer, package, credential, spn, requestedContextFlags, channelBinding); } }
/// <summary> /// <para>Used to query for the Request stream of an FTP Request [async version]</para> /// </summary> public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } ContextAwareResult asyncResult = null; try { if (_getRequestStreamStarted) { throw new InvalidOperationException(SR.net_repcall); } _getRequestStreamStarted = true; if (!_methodInfo.IsUpload) { throw new ProtocolViolationException(SR.net_nouploadonget); } CheckError(); FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); lock (asyncResult.StartPostingAsyncOp()) { _writeAsyncResult = asyncResult; SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); FinishRequestStage(RequestStage.CheckForError); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return asyncResult; }
/// <summary> /// <para>Used to query for the Request stream of an FTP Request [async version]</para> /// </summary> public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", ""); NetEventSource.PrintInfo(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", string.Format("Method: {0}", _methodInfo.Method)); } if (GlobalLog.IsEnabled) { GlobalLog.Enter("FtpWebRequest#" + LoggingHash.HashString(this) + "::BeginGetRequestStream"); } ContextAwareResult asyncResult = null; try { if (_getRequestStreamStarted) { throw new InvalidOperationException(SR.net_repcall); } _getRequestStreamStarted = true; if (!_methodInfo.IsUpload) { throw new ProtocolViolationException(SR.net_nouploadonget); } CheckError(); FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); lock (asyncResult.StartPostingAsyncOp()) { _writeAsyncResult = asyncResult; SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); FinishRequestStage(RequestStage.CheckForError); } } catch (Exception exception) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", exception); throw; } finally { if (GlobalLog.IsEnabled) { GlobalLog.Leave("FtpWebRequest#" + LoggingHash.HashString(this) + "::BeginGetRequestStream"); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "BeginGetRequestStream", ""); } return asyncResult; }
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { ContextAwareResult readAsyncResult; if (Logging.On) { Logging.Enter(Logging.Web, this, "BeginGetResponse", ""); } if (Logging.On) { Logging.PrintInfo(Logging.Web, this, "BeginGetResponse", SR.GetString("net_log_method_equal", new object[] { this.m_MethodInfo.Method })); } try { if (this.m_FtpWebResponse != null) { readAsyncResult = new ContextAwareResult(this, state, callback); readAsyncResult.InvokeCallback(this.m_FtpWebResponse); return readAsyncResult; } if (this.m_GetResponseStarted) { throw new InvalidOperationException(SR.GetString("net_repcall")); } this.m_GetResponseStarted = true; this.CheckError(); if (this.ServicePoint.InternalProxyServicePoint) { HttpWebRequest httpWebRequest = this.GetHttpWebRequest(); if (Logging.On) { Logging.Associate(Logging.Web, this, httpWebRequest); } return (ContextAwareResult) httpWebRequest.BeginGetResponse(callback, state); } RequestStage stage = this.FinishRequestStage(RequestStage.RequestStarted); readAsyncResult = new ContextAwareResult(true, true, this, state, callback); this.m_ReadAsyncResult = readAsyncResult; if (stage >= RequestStage.RequestStarted) { readAsyncResult.StartPostingAsyncOp(); readAsyncResult.FinishPostingAsyncOp(); if (stage >= RequestStage.ReadReady) { readAsyncResult = null; } else { lock (this.m_SyncObject) { if (this.m_RequestStage >= RequestStage.ReadReady) { readAsyncResult = null; } } } if (readAsyncResult == null) { readAsyncResult = (ContextAwareResult) this.m_ReadAsyncResult; if (!readAsyncResult.InternalPeekCompleted) { readAsyncResult.InvokeCallback(); } } return readAsyncResult; } lock (readAsyncResult.StartPostingAsyncOp()) { this.SubmitRequest(true); readAsyncResult.FinishPostingAsyncOp(); } this.FinishRequestStage(RequestStage.CheckForError); return readAsyncResult; } catch (Exception exception) { if (Logging.On) { Logging.Exception(Logging.Web, this, "BeginGetResponse", exception); } throw; } finally { if (Logging.On) { Logging.Exit(Logging.Web, this, "BeginGetResponse", ""); } } return readAsyncResult; }
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { if(Logging.On)Logging.Enter(Logging.Web, this, "BeginGetResponse", ""); if(Logging.On)Logging.PrintInfo(Logging.Web, this, "BeginGetResponse", SR.GetString(SR.net_log_method_equal, m_MethodInfo.Method)); GlobalLog.Enter("FtpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse"); ContextAwareResult asyncResult; try { if (m_FtpWebResponse != null) { asyncResult = new ContextAwareResult(this, state, callback); asyncResult.InvokeCallback(m_FtpWebResponse); return asyncResult; } if (m_GetResponseStarted) { throw new InvalidOperationException(SR.GetString(SR.net_repcall)); } m_GetResponseStarted = true; CheckError(); if (ServicePoint.InternalProxyServicePoint) { HttpWebRequest httpWebRequest = GetHttpWebRequest(); if (Logging.On) Logging.Associate(Logging.Web, this, httpWebRequest); asyncResult = (ContextAwareResult)httpWebRequest.BeginGetResponse(callback, state); } else { RequestStage prev = FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); m_ReadAsyncResult = asyncResult; if (prev >= RequestStage.RequestStarted) { // To make sure the context is flowed asyncResult.StartPostingAsyncOp(); asyncResult.FinishPostingAsyncOp(); if (prev >= RequestStage.ReadReady) asyncResult = null; else { lock (m_SyncObject) { if (m_RequestStage >= RequestStage.ReadReady) asyncResult = null;; } } if(asyncResult == null) { // need to complete it now asyncResult = (ContextAwareResult)m_ReadAsyncResult; if (!asyncResult.InternalPeekCompleted) asyncResult.InvokeCallback(); } } else { // Do internal processing in this handler to optimize context flowing. lock (asyncResult.StartPostingAsyncOp()) { SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); } FinishRequestStage(RequestStage.CheckForError); } } } catch (Exception exception) { if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetResponse", exception); throw; } finally { GlobalLog.Leave("FtpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetResponse"); if(Logging.On)Logging.Exit(Logging.Web, this, "BeginGetResponse", ""); } string suri; if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient)) suri = this.RequestUri.ToString(); else suri = this.RequestUri.OriginalString; FrameworkEventSource.Log.BeginGetResponse(this, suri); return asyncResult; }
internal IAsyncResult BeginGetConnection(ServicePoint servicePoint, ContextAwareResult outerResult, AsyncCallback callback, object state) { GlobalLog.Enter("SmtpTransport#" + ValidationHelper.HashString(this) + "::BeginConnect"); IAsyncResult result = null; try{ UpdateServicePoint(servicePoint); connection = new SmtpConnection(this, client, credentials, authenticationModules); connection.Timeout = timeout; if(Logging.On)Logging.Associate(Logging.Web, this, connection); if (EnableSsl) { connection.EnableSsl = true; connection.ClientCertificates = ClientCertificates; } result = connection.BeginGetConnection(servicePoint, outerResult, callback, state); } catch(Exception innerException){ throw new SmtpException(SR.GetString(SR.MailHostNotFound), innerException); } GlobalLog.Leave("SmtpTransport#" + ValidationHelper.HashString(this) + "::BeginConnect [....] Completion"); return result; }
public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { if(Logging.On)Logging.Enter(Logging.Web, this, "BeginGetRequestStream", ""); if(Logging.On)Logging.PrintInfo(Logging.Web, this, "BeginGetRequestStream", SR.GetString(SR.net_log_method_equal, m_MethodInfo.Method)); GlobalLog.Enter("FtpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetRequestStream"); ContextAwareResult asyncResult = null; try { if (m_GetRequestStreamStarted) { throw new InvalidOperationException(SR.GetString(SR.net_repcall)); } m_GetRequestStreamStarted = true; if (!m_MethodInfo.IsUpload) { throw new ProtocolViolationException(SR.GetString(SR.net_nouploadonget)); } CheckError(); if (ServicePoint.InternalProxyServicePoint) { HttpWebRequest httpWebRequest = GetHttpWebRequest(); if (Logging.On) Logging.Associate(Logging.Web, this, httpWebRequest); asyncResult = (ContextAwareResult)httpWebRequest.BeginGetRequestStream(callback, state); } else { FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); lock (asyncResult.StartPostingAsyncOp()) { m_WriteAsyncResult = asyncResult; SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); FinishRequestStage(RequestStage.CheckForError); } } } catch (Exception exception) { if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception); throw; } finally { GlobalLog.Leave("FtpWebRequest#" + ValidationHelper.HashString(this) + "::BeginGetRequestStream"); if(Logging.On)Logging.Exit(Logging.Web, this, "BeginGetRequestStream", ""); } 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; }
private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context) { #if !FEATURE_PAL // We may need to restore user thread token here if (credential is SystemNetworkCredential) { // #if DEBUG GlobalLog.Assert(context == null || context.IdentityRequested, "SmtpConnection#{0}::SetContextAndTryAuthenticate|Authentication required when it wasn't expected. (Maybe Credentials was changed on another thread?)", ValidationHelper.HashString(this)); #endif WindowsIdentity w = context == null ? null : context.Identity; try { IDisposable ctx = w == null ? null : w.Impersonate(); if (ctx != null) { using (ctx) { return module.Authenticate(null, credential, this, this.client.TargetName, this.channelBindingToken); } } else { ExecutionContext x = context == null ? null : context.ContextCopy; if (x != null) { AuthenticateCallbackContext authenticationContext = new AuthenticateCallbackContext(this, module, credential, this.client.TargetName, this.channelBindingToken); ExecutionContext.Run(x, s_AuthenticateCallback, authenticationContext); return authenticationContext.result; } else { return module.Authenticate(null, credential, this, this.client.TargetName, this.channelBindingToken); } } } catch { // Prevent the impersonation from leaking to upstack exception filters. throw; } } #endif // !FEATURE_PAL return module.Authenticate(null, credential, this, this.client.TargetName, this.channelBindingToken); }
public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { GlobalLog.Enter("FileWebRequest::BeginGetResponse"); try { if (Aborted) throw ExceptionHelper.RequestAbortedException; lock(this) { if (m_readPending) { Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall)); GlobalLog.LeaveException("FileWebRequest::BeginGetResponse", e); throw e; } m_readPending = true; } //we need to force the capture of the identity and context to make sure the //posted callback doesn't inavertently gain access to something it shouldn't. m_WriteAResult = new ContextAwareResult(true, true, true, this, state, callback); lock (m_WriteAResult.StartPostingAsyncOp()) { ThreadPool.UnsafeQueueUserWorkItem(s_GetResponseCallback, m_WriteAResult); m_WriteAResult.FinishPostingAsyncOp(); } } catch (Exception exception) { if(Logging.On)Logging.Exception(Logging.Web, this, "BeginGetResponse", exception); throw; } finally { GlobalLog.Leave("FileWebRequest::BeginGetResponse"); } return m_WriteAResult; }
public override IAsyncResult BeginGetUnicastAddresses(AsyncCallback callback, object state){ ContextAwareResult asyncResult = new ContextAwareResult(false, false, this, state, callback); asyncResult.StartPostingAsyncOp(false); if (TeredoHelper.UnsafeNotifyStableUnicastIpAddressTable(StableUnicastAddressTableCallback, asyncResult)) { asyncResult.InvokeCallback(); } asyncResult.FinishPostingAsyncOp(); return asyncResult; }
/// <summary> /// <para>Used to query for the Response of an FTP request [async version]</para> /// </summary> public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this); NetEventSource.Info(this, $"Method: {_methodInfo.Method}"); } ContextAwareResult asyncResult; try { if (_ftpWebResponse != null) { asyncResult = new ContextAwareResult(this, state, callback); asyncResult.InvokeCallback(_ftpWebResponse); return asyncResult; } if (_getResponseStarted) { throw new InvalidOperationException(SR.net_repcall); } _getResponseStarted = true; CheckError(); RequestStage prev = FinishRequestStage(RequestStage.RequestStarted); asyncResult = new ContextAwareResult(true, true, this, state, callback); _readAsyncResult = asyncResult; if (prev >= RequestStage.RequestStarted) { // To make sure the context is flowed asyncResult.StartPostingAsyncOp(); asyncResult.FinishPostingAsyncOp(); if (prev >= RequestStage.ReadReady) asyncResult = null; else { lock (_syncObject) { if (_requestStage >= RequestStage.ReadReady) asyncResult = null; ; } } if (asyncResult == null) { // need to complete it now asyncResult = (ContextAwareResult)_readAsyncResult; if (!asyncResult.InternalPeekCompleted) asyncResult.InvokeCallback(); } } else { // Do internal processing in this handler to optimize context flowing. lock (asyncResult.StartPostingAsyncOp()) { SubmitRequest(true); asyncResult.FinishPostingAsyncOp(); } FinishRequestStage(RequestStage.CheckForError); } } catch (Exception exception) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, exception); throw; } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return asyncResult; }
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 }
internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port) { ConnectAndHandshakeAsyncResult result = new ConnectAndHandshakeAsyncResult(this, host, port, outerResult, callback, state); result.GetConnection(); return result; }
public void SendAsync(MailMessage message, object userToken) { if (disposed) { throw new ObjectDisposedException(this.GetType().FullName); } if (Logging.On) Logging.Enter(Logging.Web, this, "SendAsync", "DeliveryMethod=" + DeliveryMethod.ToString()); GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync Transport#" + ValidationHelper.HashString(transport)); try { if (InCall) { throw new InvalidOperationException(SR.GetString(SR.net_inasync)); } if (message == null) { throw new ArgumentNullException("message"); } if (DeliveryMethod == SmtpDeliveryMethod.Network) CheckHostAndPort(); recipients = new MailAddressCollection(); if (message.From == null) { throw new InvalidOperationException(SR.GetString(SR.SmtpFromRequired)); } if (message.To != null) { foreach (MailAddress address in message.To) { recipients.Add(address); } } if (message.Bcc != null) { foreach (MailAddress address in message.Bcc) { recipients.Add(address); } } if (message.CC != null) { foreach (MailAddress address in message.CC) { recipients.Add(address); } } if (recipients.Count == 0) { throw new InvalidOperationException(SR.GetString(SR.SmtpRecipientRequired)); } try { InCall = true; cancelled = false; this.message = message; string pickupDirectory = PickupDirectoryLocation; #if !FEATURE_PAL CredentialCache cache; // Skip token capturing if no credentials are used or they don't include a default one. // Also do capture the token if ICredential is not of CredentialCache type so we don't know what the exact credential response will be. transport.IdentityRequired = Credentials != null && (Credentials is SystemNetworkCredential || (cache = Credentials as CredentialCache) == null || cache.IsDefaultInCache); #endif // !FEATURE_PAL asyncOp = AsyncOperationManager.CreateOperation(userToken); switch (DeliveryMethod) { #if !FEATURE_PAL case SmtpDeliveryMethod.PickupDirectoryFromIis: pickupDirectory = IisPickupDirectory.GetPickupDirectory(); goto case SmtpDeliveryMethod.SpecifiedPickupDirectory; #endif // !FEATURE_PAL case SmtpDeliveryMethod.SpecifiedPickupDirectory: { if (EnableSsl) throw new SmtpException(SR.GetString(SR.SmtpPickupDirectoryDoesnotSupportSsl)); writer = GetFileMailWriter(pickupDirectory); bool allowUnicode = IsUnicodeSupported(); ValidateUnicodeRequirement(message, recipients, allowUnicode); message.Send(writer, true, allowUnicode); if (writer != null) writer.Close(); transport.ReleaseConnection(); AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(null, false, asyncOp.UserSuppliedState); InCall = false; asyncOp.PostOperationCompleted(onSendCompletedDelegate, eventArgs); break; } case SmtpDeliveryMethod.Network: default: operationCompletedResult = new ContextAwareResult(transport.IdentityRequired, true, null, this, _ContextSafeCompleteCallback); lock (operationCompletedResult.StartPostingAsyncOp()) { GlobalLog.Print("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync calling BeginConnect. Transport#" + ValidationHelper.HashString(transport)); transport.BeginGetConnection(ServicePoint, operationCompletedResult, ConnectCallback, operationCompletedResult); operationCompletedResult.FinishPostingAsyncOp(); } break; } } catch (Exception e) { InCall = false; if (Logging.On) Logging.Exception(Logging.Web, this, "Send", e); if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal) { throw; } Abort(); if (timedOut) { throw new SmtpException(SR.GetString(SR.net_timeout)); } if (e is SecurityException || e is AuthenticationException || e is SmtpException) { throw; } throw new SmtpException(SR.GetString(SR.SmtpSendMailFailure), e); } } finally { if (Logging.On) Logging.Exit(Logging.Web, this, "SendAsync", null); GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::SendAsync"); } }
internal ConnectAndHandshakeAsyncResult(SmtpConnection connection, string host, int port, ContextAwareResult outerResult, AsyncCallback callback, object state) : base(null, state, callback) { _connection = connection; _host = host; _port = port; _outerResult = outerResult; }
private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context) { if ((credential is SystemNetworkCredential) && ComNetOS.IsWinNt) { WindowsIdentity identity = (context == null) ? null : context.Identity; try { IDisposable disposable = (identity == null) ? null : identity.Impersonate(); if (disposable != null) { using (disposable) { return module.Authenticate(null, credential, this, this.client.TargetName, this.channelBindingToken); } } ExecutionContext executionContext = (context == null) ? null : context.ContextCopy; if (executionContext != null) { AuthenticateCallbackContext state = new AuthenticateCallbackContext(this, module, credential, this.client.TargetName, this.channelBindingToken); ExecutionContext.Run(executionContext, s_AuthenticateCallback, state); return state.result; } return module.Authenticate(null, credential, this, this.client.TargetName, this.channelBindingToken); } catch { throw; } } return module.Authenticate(null, credential, this, this.client.TargetName, this.channelBindingToken); }
public void SendAsync(MailMessage message, object userToken) { if (this.disposed) { throw new ObjectDisposedException(base.GetType().FullName); } if (Logging.On) { Logging.Enter(Logging.Web, this, "SendAsync", "DeliveryMethod=" + this.DeliveryMethod.ToString()); } try { if (this.InCall) { throw new InvalidOperationException(SR.GetString("net_inasync")); } if (message == null) { throw new ArgumentNullException("message"); } if (this.DeliveryMethod == SmtpDeliveryMethod.Network) { this.CheckHostAndPort(); } this.recipients = new MailAddressCollection(); if (message.From == null) { throw new InvalidOperationException(SR.GetString("SmtpFromRequired")); } if (message.To != null) { foreach (MailAddress address in message.To) { this.recipients.Add(address); } } if (message.Bcc != null) { foreach (MailAddress address2 in message.Bcc) { this.recipients.Add(address2); } } if (message.CC != null) { foreach (MailAddress address3 in message.CC) { this.recipients.Add(address3); } } if (this.recipients.Count == 0) { throw new InvalidOperationException(SR.GetString("SmtpRecipientRequired")); } try { CredentialCache cache; this.InCall = true; this.cancelled = false; this.message = message; this.transport.IdentityRequired = ((this.Credentials != null) && ComNetOS.IsWinNt) && (((this.Credentials is SystemNetworkCredential) || ((cache = this.Credentials as CredentialCache) == null)) || cache.IsDefaultInCache); this.asyncOp = AsyncOperationManager.CreateOperation(userToken); switch (this.DeliveryMethod) { case SmtpDeliveryMethod.SpecifiedPickupDirectory: if (this.EnableSsl) { throw new SmtpException(SR.GetString("SmtpPickupDirectoryDoesnotSupportSsl")); } break; case SmtpDeliveryMethod.PickupDirectoryFromIis: if (this.EnableSsl) { throw new SmtpException(SR.GetString("SmtpPickupDirectoryDoesnotSupportSsl")); } goto Label_02B2; default: goto Label_0329; } this.writer = this.GetFileMailWriter(this.PickupDirectoryLocation); message.Send(this.writer, this.DeliveryMethod != SmtpDeliveryMethod.Network); if (this.writer != null) { this.writer.Close(); } this.transport.ReleaseConnection(); AsyncCompletedEventArgs arg = new AsyncCompletedEventArgs(null, false, this.asyncOp.UserSuppliedState); this.InCall = false; this.asyncOp.PostOperationCompleted(this.onSendCompletedDelegate, arg); return; Label_02B2: this.writer = this.GetFileMailWriter(IisPickupDirectory.GetPickupDirectory()); message.Send(this.writer, this.DeliveryMethod != SmtpDeliveryMethod.Network); if (this.writer != null) { this.writer.Close(); } this.transport.ReleaseConnection(); AsyncCompletedEventArgs args2 = new AsyncCompletedEventArgs(null, false, this.asyncOp.UserSuppliedState); this.InCall = false; this.asyncOp.PostOperationCompleted(this.onSendCompletedDelegate, args2); return; Label_0329: this.operationCompletedResult = new ContextAwareResult(this.transport.IdentityRequired, true, null, this, _ContextSafeCompleteCallback); lock (this.operationCompletedResult.StartPostingAsyncOp()) { this.transport.BeginGetConnection(this.ServicePoint, this.operationCompletedResult, new AsyncCallback(this.ConnectCallback), this.operationCompletedResult); this.operationCompletedResult.FinishPostingAsyncOp(); } } catch (Exception exception) { this.InCall = false; if (Logging.On) { Logging.Exception(Logging.Web, this, "Send", exception); } if ((exception is SmtpFailedRecipientException) && !((SmtpFailedRecipientException) exception).fatal) { throw; } this.Abort(); if (this.timedOut) { throw new SmtpException(SR.GetString("net_timeout")); } if (((exception is SecurityException) || (exception is AuthenticationException)) || (exception is SmtpException)) { throw; } throw new SmtpException(SR.GetString("SmtpSendMailFailure"), exception); } } finally { if (Logging.On) { Logging.Exit(Logging.Web, this, "SendAsync", (string) null); } } }
public void SendAsync(MailMessage message, object userToken) { if (this.disposed) throw new ObjectDisposedException(this.GetType().FullName); if (Logging.On) Logging.Enter(Logging.Web, (object) this, "SendAsync", "DeliveryMethod=" + ((object) this.DeliveryMethod).ToString()); try { if (this.InCall) throw new InvalidOperationException(SR.GetString("net_inasync")); if (message == null) throw new ArgumentNullException("message"); if (this.DeliveryMethod == SmtpDeliveryMethod.Network) this.CheckHostAndPort(); this.recipients = new MailAddressCollection(); if (message.From == null) throw new InvalidOperationException(SR.GetString("SmtpFromRequired")); if (message.To != null) { foreach (MailAddress mailAddress in (Collection<MailAddress>) message.To) ((Collection<MailAddress>) this.recipients).Add(mailAddress); } if (message.Bcc != null) { foreach (MailAddress mailAddress in (Collection<MailAddress>) message.Bcc) ((Collection<MailAddress>) this.recipients).Add(mailAddress); } if (message.CC != null) { foreach (MailAddress mailAddress in (Collection<MailAddress>) message.CC) ((Collection<MailAddress>) this.recipients).Add(mailAddress); } if (this.recipients.Count == 0) throw new InvalidOperationException(SR.GetString("SmtpRecipientRequired")); try { this.InCall = true; this.cancelled = false; this.message = message; string pickupDirectory = this.PickupDirectoryLocation; CredentialCache credentialCache; this.transport.IdentityRequired = this.Credentials != null && (this.Credentials is SystemNetworkCredential || (credentialCache = this.Credentials as CredentialCache) == null || credentialCache.IsDefaultInCache); this.asyncOp = AsyncOperationManager.CreateOperation(userToken); switch (this.DeliveryMethod) { case SmtpDeliveryMethod.SpecifiedPickupDirectory: if (this.EnableSsl) throw new SmtpException(SR.GetString("SmtpPickupDirectoryDoesnotSupportSsl")); this.writer = this.GetFileMailWriter(pickupDirectory); bool allowUnicode = this.IsUnicodeSupported(); this.ValidateUnicodeRequirement(message, this.recipients, allowUnicode); message.Send((BaseWriter) this.writer, true, allowUnicode); if (this.writer != null) this.writer.Close(); this.transport.ReleaseConnection(); AsyncCompletedEventArgs completedEventArgs = new AsyncCompletedEventArgs((Exception) null, false, this.asyncOp.UserSuppliedState); this.InCall = false; this.asyncOp.PostOperationCompleted(this.onSendCompletedDelegate, (object) completedEventArgs); break; case SmtpDeliveryMethod.PickupDirectoryFromIis: pickupDirectory = IisPickupDirectory.GetPickupDirectory(); goto case 1; default: this.operationCompletedResult = new ContextAwareResult(this.transport.IdentityRequired, true, (object) null, (object) this, SmtpClient._ContextSafeCompleteCallback); lock (this.operationCompletedResult.StartPostingAsyncOp()) { this.transport.BeginGetConnection(this.ServicePoint, this.operationCompletedResult, new AsyncCallback(this.ConnectCallback), (object) this.operationCompletedResult); this.operationCompletedResult.FinishPostingAsyncOp(); break; } } } catch (Exception ex) { this.InCall = false; if (Logging.On) Logging.Exception(Logging.Web, (object) this, "Send", ex); if (ex is SmtpFailedRecipientException && !((SmtpFailedRecipientException) ex).fatal) { throw; } else { this.Abort(); if (this.timedOut) throw new SmtpException(SR.GetString("net_timeout")); if (!(ex is SecurityException) && !(ex is AuthenticationException) && !(ex is SmtpException)) throw new SmtpException(SR.GetString("SmtpSendMailFailure"), ex); throw; } } } finally { if (Logging.On) Logging.Exit(Logging.Web, (object) this, "SendAsync", (string) null); } }
internal IAsyncResult BeginGetConnection(ServicePoint servicePoint, ContextAwareResult outerResult, AsyncCallback callback, object state) { IAsyncResult result = null; try { this.UpdateServicePoint(servicePoint); this.connection = new SmtpConnection(this, this.client, this.credentials, this.authenticationModules); this.connection.Timeout = this.timeout; if (Logging.On) { Logging.Associate(Logging.Web, this, this.connection); } if (this.EnableSsl) { this.connection.EnableSsl = true; this.connection.ClientCertificates = this.ClientCertificates; } result = this.connection.BeginGetConnection(servicePoint, outerResult, callback, state); } catch (Exception exception) { throw new SmtpException(SR.GetString("MailHostNotFound"), exception); } return result; }