Exemple #1
0
        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter("SmtpTransport#" + LoggingHash.HashString(this) + "::BeginConnect");
            }
            IAsyncResult result = null;

            try
            {
                _connection         = new SmtpConnection(this, _client, _credentials, _authenticationModules);
                _connection.Timeout = _timeout;
                if (MailEventSource.Log.IsEnabled())
                {
                    MailEventSource.Log.Associate(this, _connection);
                }
                if (EnableSsl)
                {
                    _connection.EnableSsl          = true;
                    _connection.ClientCertificates = ClientCertificates;
                }

                result = _connection.BeginGetConnection(outerResult, callback, state, host, port);
            }
            catch (Exception innerException)
            {
                throw new SmtpException(SR.MailHostNotFound, innerException);
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Leave("SmtpTransport#" + LoggingHash.HashString(this) + "::BeginConnect Sync Completion");
            }
            return(result);
        }
Exemple #2
0
        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback?callback, object?state, string host, int port)
        {
            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }
            IAsyncResult?result = null;

            try
            {
                _connection = new SmtpConnection(this, _client, _credentials, _authenticationModules);
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Associate(this, _connection);
                }
                if (EnableSsl)
                {
                    _connection.EnableSsl          = true;
                    _connection.ClientCertificates = ClientCertificates;
                }

                result = _connection.BeginGetConnection(outerResult, callback, state, host, port);
            }
            catch (Exception innerException)
            {
                throw new SmtpException(SR.MailHostNotFound, innerException);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, "Sync completion");
                NetEventSource.Exit(this);
            }
            return(result);
        }
        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);
        }
Exemple #4
0
        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);
        }
Exemple #5
0
        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);
        }
        private void Complete(Exception exception, IAsyncResult result)
        {
            ContextAwareResult asyncState = (ContextAwareResult)result.AsyncState;

            try
            {
                if (this.cancelled)
                {
                    exception = null;
                    this.Abort();
                }
                else if ((exception != null) && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
                {
                    this.Abort();
                    if (!(exception is SmtpException))
                    {
                        exception = new SmtpException(SR.GetString("SmtpSendMailFailure"), exception);
                    }
                }
                else
                {
                    if (this.writer != null)
                    {
                        this.writer.Close();
                    }
                    this.transport.ReleaseConnection();
                }
            }
            finally
            {
                asyncState.InvokeCallback(exception);
            }
        }
 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;
 }
Exemple #8
0
        private void Complete(Exception exception, IAsyncResult result)
        {
            ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this);
            }
            try
            {
                if (_cancelled)
                {
                    //any exceptions were probably caused by cancellation, clear it.
                    exception = null;
                    Abort();
                }
                // An individual failed recipient exception is benign, only abort here if ALL the recipients failed.
                else if (exception != null && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
                {
                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Error(this, exception);
                    }
                    Abort();

                    if (!(exception is SmtpException))
                    {
                        exception = new SmtpException(SR.SmtpSendMailFailure, exception);
                    }
                }
                else
                {
                    if (_writer != null)
                    {
                        try
                        {
                            _writer.Close();
                        }
                        // Close may result in a DataStopCommand and the server may return error codes at this time.
                        catch (SmtpException se)
                        {
                            exception = se;
                        }
                    }
                    _transport.ReleaseConnection();
                }
            }
            finally
            {
                operationCompletedResult.InvokeCallback(exception);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, "Complete");
            }
        }
Exemple #9
0
            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 static void ContextSafeCompleteCallback(IAsyncResult ar)
        {
            ContextAwareResult      result     = (ContextAwareResult)ar;
            SmtpClient              asyncState = (SmtpClient)ar.AsyncState;
            Exception               error      = result.Result as Exception;
            AsyncOperation          asyncOp    = asyncState.asyncOp;
            AsyncCompletedEventArgs arg        = new AsyncCompletedEventArgs(error, asyncState.cancelled, asyncOp.UserSuppliedState);

            asyncState.InCall = false;
            asyncOp.PostOperationCompleted(asyncState.onSendCompletedDelegate, arg);
        }
Exemple #11
0
        private static void ContextSafeCompleteCallback(IAsyncResult ar)
        {
            ContextAwareResult      result    = (ContextAwareResult)ar;
            SmtpClient              client    = (SmtpClient)ar.AsyncState !;
            Exception?              exception = result.Result as Exception;
            AsyncOperation          asyncOp   = client._asyncOp !;
            AsyncCompletedEventArgs eventArgs = new AsyncCompletedEventArgs(exception, client._cancelled, asyncOp.UserSuppliedState);

            client.InCall = false;
            client._failedRecipientException = null; // Reset before the next send.
            asyncOp.PostOperationCompleted(client._onSendCompletedDelegate, eventArgs);
        }
        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);
        }
        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);
        }
Exemple #14
0
        void Complete(Exception exception, IAsyncResult result)
        {
            ContextAwareResult operationCompletedResult = (ContextAwareResult)result.AsyncState;

            GlobalLog.Enter("SmtpClient#" + ValidationHelper.HashString(this) + "::Complete");
            try {
                if (cancelled)
                {
                    //any exceptions were probably caused by cancellation, clear it.
                    exception = null;
                    Abort();
                }
                // An individual failed recipient exception is benign, only abort here if ALL the recipients failed.
                else if (exception != null && (!(exception is SmtpFailedRecipientException) || ((SmtpFailedRecipientException)exception).fatal))
                {
                    GlobalLog.Print("SmtpClient#" + ValidationHelper.HashString(this) + "::Complete Exception: " + exception.ToString());
                    Abort();

                    if (!(exception is SmtpException))
                    {
                        exception = new SmtpException(SR.GetString(SR.SmtpSendMailFailure), exception);
                    }
                }
                else
                {
                    if (writer != null)
                    {
                        try {
                            writer.Close();
                        }
                        // Close may result in a DataStopCommand and the server may return error codes at this time.
                        catch (SmtpException se) {
                            exception = se;
                        }
                    }
                    transport.ReleaseConnection();
                }
            }
            finally {
                operationCompletedResult.InvokeCallback(exception);
            }
            GlobalLog.Leave("SmtpClient#" + ValidationHelper.HashString(this) + "::Complete");
        }
        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 UnicastIPAddressInformationCollection EndGetUnicastAddresses(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            ContextAwareResult result = asyncResult as ContextAwareResult;

            if (((result == null) || (result.AsyncObject == null)) || (result.AsyncObject.GetType() != typeof(SystemIPGlobalProperties)))
            {
                throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"));
            }
            if (result.EndCalled)
            {
                throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndGetStableUnicastAddresses" }));
            }
            result.InternalWaitForCompletion();
            result.EndCalled = true;
            return(GetUnicastAddressTable());
        }
        private UnicastIPAddressInformationCollection EndGetUnicastAddresses(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            ContextAwareResult result = asyncResult as ContextAwareResult;

            if (result == null || result.AsyncObject == null || result.AsyncObject.GetType() != typeof(SystemIPGlobalProperties))
            {
                throw new ArgumentException(SR.net_io_invalidasyncresult);
            }

            if (result.EndCalled)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndGetStableUnicastAddresses"));
            }

            result.InternalWaitForCompletion();

            result.EndCalled = true;
            return(GetUnicastAddressTable());
        }
Exemple #18
0
        public void SendAsync(MailMessage message, object userToken)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Enter(NetEventSource.ComponentType.Web, this, "SendAsync", "DeliveryMethod=" + DeliveryMethod.ToString());
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsync Transport#" + LoggingHash.HashString(_transport));
            }

            try
            {
                if (InCall)
                {
                    throw new InvalidOperationException(SR.net_inasync);
                }

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

                if (DeliveryMethod == SmtpDeliveryMethod.Network)
                    CheckHostAndPort();

                _recipients = new MailAddressCollection();

                if (message.From == null)
                {
                    throw new InvalidOperationException(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.SmtpRecipientRequired);
                }

                try
                {
                    InCall = true;
                    _cancelled = false;
                    _message = message;
                    string pickupDirectory = PickupDirectoryLocation;

                    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 && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null);

                    _asyncOp = AsyncOperationManager.CreateOperation(userToken);
                    switch (DeliveryMethod)
                    {
                        case SmtpDeliveryMethod.PickupDirectoryFromIis:
                            throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);

                        case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                            {
                                if (EnableSsl)
                                {
                                    throw new SmtpException(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, s_contextSafeCompleteCallback);
                            lock (_operationCompletedResult.StartPostingAsyncOp())
                            {
                                if (GlobalLog.IsEnabled)
                                {
                                    GlobalLog.Print("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsync calling BeginConnect.  Transport#" + LoggingHash.HashString(_transport));
                                }

                                _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
                                _operationCompletedResult.FinishPostingAsyncOp();
                            }
                            break;
                    }
                }
                catch (Exception e)
                {
                    InCall = false;

                    if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Web, this, "Send", e);

                    if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                    {
                        throw;
                    }

                    Abort();
                    if (_timedOut)
                    {
                        throw new SmtpException(SR.net_timeout);
                    }

                    if (e is SecurityException ||
                        e is AuthenticationException ||
                        e is SmtpException)
                    {
                        throw;
                    }

                    throw new SmtpException(SR.SmtpSendMailFailure, e);
                }
            }
            finally
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Exit(NetEventSource.ComponentType.Web, this, "SendAsync", null);
                }

                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Leave("SmtpClient#" + LoggingHash.HashString(this) + "::SendAsync");
                }
            }
        }
Exemple #19
0
        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter("SmtpTransport#" + LoggingHash.HashString(this) + "::BeginConnect");
            }
            IAsyncResult result = null;
            try
            {
                _connection = new SmtpConnection(this, _client, _credentials, _authenticationModules);
                _connection.Timeout = _timeout;
                if (MailEventSource.Log.IsEnabled())
                {
                    MailEventSource.Log.Associate(this, _connection);
                }
                if (EnableSsl)
                {
                    _connection.EnableSsl = true;
                    _connection.ClientCertificates = ClientCertificates;
                }

                result = _connection.BeginGetConnection(outerResult, callback, state, host, port);
            }
            catch (Exception innerException)
            {
                throw new SmtpException(SR.MailHostNotFound, innerException);
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Leave("SmtpTransport#" + LoggingHash.HashString(this) + "::BeginConnect Sync Completion");
            }
            return result;
        }
        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);
                }
            }
        }
Exemple #21
0
        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");
            }
        }
Exemple #22
0
        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)
                {
                    NetEventSource.Fail(this, "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));
        }
Exemple #23
0
        private Authorization SetContextAndTryAuthenticate(ISmtpAuthenticationModule module, NetworkCredential credential, ContextAwareResult context)
        {
            // We may need to restore user thread token here
            if (ReferenceEquals(credential, CredentialCache.DefaultNetworkCredentials))
            {
                // CONSIDER: Change to a real runtime check that throws InvalidOperationException to help catch customer race conditions.
#if DEBUG
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.AssertFormat(context == null || context.IdentityRequested, "SmtpConnection#{0}::SetContextAndTryAuthenticate|Authentication required when it wasn't expected.  (Maybe Credentials was changed on another thread?)", LoggingHash.HashString(this));
                }
#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));
        }
Exemple #24
0
        internal IAsyncResult BeginGetConnection(ContextAwareResult outerResult, AsyncCallback callback, object state, string host, int port)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
            IAsyncResult result = null;
            try
            {
                _connection = new SmtpConnection(this, _client, _credentials, _authenticationModules);
                _connection.Timeout = _timeout;
                if (NetEventSource.IsEnabled) NetEventSource.Associate(this, _connection);
                if (EnableSsl)
                {
                    _connection.EnableSsl = true;
                    _connection.ClientCertificates = ClientCertificates;
                }

                result = _connection.BeginGetConnection(outerResult, callback, state, host, port);
            }
            catch (Exception innerException)
            {
                throw new SmtpException(SR.MailHostNotFound, innerException);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Info(this, "Sync completion");
                NetEventSource.Exit(this);
            }
            return result;
        }
Exemple #25
0
        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));
        }
Exemple #26
0
        public void SendAsync(MailMessage message, object userToken)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (NetEventSource.IsEnabled)
            {
                NetEventSource.Enter(this, message, userToken, _transport);
            }

            try
            {
                if (InCall)
                {
                    throw new InvalidOperationException(SR.net_inasync);
                }

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

                if (DeliveryMethod == SmtpDeliveryMethod.Network)
                {
                    CheckHostAndPort();
                }

                _recipients = new MailAddressCollection();

                if (message.From == null)
                {
                    throw new InvalidOperationException(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.SmtpRecipientRequired);
                }

                try
                {
                    InCall     = true;
                    _cancelled = false;
                    _message   = message;
                    string pickupDirectory = PickupDirectoryLocation;

                    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 && (ReferenceEquals(Credentials, CredentialCache.DefaultNetworkCredentials) || (cache = Credentials as CredentialCache) == null || IsSystemNetworkCredentialInCache(cache));

                    _asyncOp = AsyncOperationManager.CreateOperation(userToken);
                    switch (DeliveryMethod)
                    {
                    case SmtpDeliveryMethod.PickupDirectoryFromIis:
                        throw new NotSupportedException(SR.SmtpGetIisPickupDirectoryNotSupported);

                    case SmtpDeliveryMethod.SpecifiedPickupDirectory:
                    {
                        if (EnableSsl)
                        {
                            throw new SmtpException(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, s_contextSafeCompleteCallback);
                        lock (_operationCompletedResult.StartPostingAsyncOp())
                        {
                            if (NetEventSource.IsEnabled)
                            {
                                NetEventSource.Info(this, $"Calling BeginConnect. Transport: {_transport}");
                            }
                            _transport.BeginGetConnection(_operationCompletedResult, ConnectCallback, _operationCompletedResult, Host, Port);
                            _operationCompletedResult.FinishPostingAsyncOp();
                        }
                        break;
                    }
                }
                catch (Exception e)
                {
                    InCall = false;

                    if (NetEventSource.IsEnabled)
                    {
                        NetEventSource.Error(this, e);
                    }

                    if (e is SmtpFailedRecipientException && !((SmtpFailedRecipientException)e).fatal)
                    {
                        throw;
                    }

                    Abort();
                    if (_timedOut)
                    {
                        throw new SmtpException(SR.net_timeout);
                    }

                    if (e is SecurityException ||
                        e is AuthenticationException ||
                        e is SmtpException)
                    {
                        throw;
                    }

                    throw new SmtpException(SR.SmtpSendMailFailure, e);
                }
            }
            finally
            {
                if (NetEventSource.IsEnabled)
                {
                    NetEventSource.Exit(this);
                }
            }
        }
        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;
        }
 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));
 }