public ClusterController(ClientConfiguration clientConfig)
     : this(clientConfig,
         pool =>
         {
             Log.Debug(m => m("Creating DefaultIOStrategy"));
             return new DefaultIOStrategy(pool);
         },
     (config, endpoint) =>
     {
         IConnectionPool connectionPool;
         if (config.UseSsl)
         {
             connectionPool = new ConnectionPool<SslConnection>(config, endpoint);
         }
         else
         {
             connectionPool = new ConnectionPool<Connection>(config, endpoint);
         }
         connectionPool.Initialize();
         return connectionPool;
     },
     SaslFactory.GetFactory3(),
     clientConfig.Converter(),
     clientConfig.Transcoder())
 {
 }
示例#2
0
 /// <devdoc>
 ///    <para>
 ///     Setups and Creates a NetworkStream connection to the server
 ///     perform any initalization if needed
 ///    </para>
 /// </devdoc>
 internal CommandStream(
     ConnectionPool connectionPool,
     TimeSpan lifetime,
     bool checkLifetime
     ) : base(connectionPool, lifetime, checkLifetime) {
         m_Decoder = m_Encoding.GetDecoder();
 }
 public ClusterManager(ClientConfiguration clientConfig)
     : this(clientConfig,
         pool =>
         {
             Log.Debug(m => m("Creating DefaultIOStrategy"));
             return new DefaultIOStrategy(pool);
         },
     (config, endpoint) =>
     {
         IConnectionPool connectionPool;
         if (config.UseSsl)
         {
             connectionPool = new ConnectionPool<SslConnection>(config, endpoint);
         }
         else
         {
             connectionPool = new ConnectionPool<EapConnection>(config, endpoint);
         }
         return connectionPool;
     },
     SaslFactory.GetFactory3(),
     new AutoByteConverter(), 
     new TypeSerializer(new AutoByteConverter(), clientConfig.DeserializationContractResolver, clientConfig.SerializationContractResolver))
 {
 }
 internal PooledStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base () { // pooled constructor
     m_ConnectionPool = connectionPool;
     m_Lifetime = lifetime;
     m_CheckLifetime = checkLifetime;
     m_Initalizing = true;
     m_NetworkStream = new NetworkStream();
     m_CreateTime = DateTime.UtcNow;
 }
 internal PooledStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime)
 {
     this.m_ConnectionPool = connectionPool;
     this.m_Lifetime = lifetime;
     this.m_CheckLifetime = checkLifetime;
     this.m_Initalizing = true;
     this.m_NetworkStream = new System.Net.Sockets.NetworkStream();
     this.m_CreateTime = DateTime.UtcNow;
 }
 internal static ConnectionPool GetConnectionPool(ServicePoint servicePoint, string groupName, CreateConnectionDelegate createConnectionCallback) {
     string key = GenerateKey(servicePoint.Host, servicePoint.Port, groupName);
     lock(InternalSyncObject) {
         ConnectionPool connectionPool = (ConnectionPool) m_ConnectionPools[key];
         if (connectionPool == null) {                    
             connectionPool = new ConnectionPool(servicePoint, servicePoint.ConnectionLimit, 0, servicePoint.MaxIdleTime, createConnectionCallback);
             m_ConnectionPools[key] = connectionPool;
         }
         return connectionPool;
     }
 }
 public ClusterManager(ClientConfiguration clientConfig, Func<IConnectionPool, IOStrategy> ioStrategyFactory)
     : this(clientConfig,
     ioStrategyFactory,
     (config, endpoint) =>
     {
         IConnectionPool connectionPool;
         if (config.UseSsl)
         {
             connectionPool = new ConnectionPool<SslConnection>(config, endpoint);
         }
         else
         {
             connectionPool = new ConnectionPool<EapConnection>(config, endpoint);
         }
         return connectionPool;
     }, SaslFactory.GetFactory3(),
     new AutoByteConverter(),
     new TypeSerializer(new AutoByteConverter(), clientConfig.DeserializationContractResolver, clientConfig.SerializationContractResolver))
 {
 }
 public ClusterController(ClientConfiguration clientConfig, Func<IConnectionPool, IOStrategy> ioStrategyFactory)
     : this(clientConfig,
     ioStrategyFactory,
     (config, endpoint) =>
     {
         IConnectionPool connectionPool;
         if (config.UseSsl)
         {
             connectionPool = new ConnectionPool<SslConnection>(config, endpoint);
         }
         else
         {
             connectionPool = new ConnectionPool<Connection>(config, endpoint);
         }
         connectionPool.Initialize();
         return connectionPool;
     }, SaslFactory.GetFactory3(),
     clientConfig.Converter(),
     clientConfig.Transcoder())
 {
 }
        //
        // NOTE1: The caller must synchronize access to SubmitRequest(), only one call is even allowed for a particular request!
        // NOTE2: This method eats all exceptions so the caller must rethrow them
        //
        private void SubmitRequest(bool async) {
            try {
                m_Async = async;

                if (CheckCacheRetrieveBeforeSubmit())
                {
                    RequestCallback(null);
                    return;
                }

                //  This is the only place touching m_ConnectionPool
                if (m_ConnectionPool == null)
                    m_ConnectionPool = ConnectionPoolManager.GetConnectionPool(ServicePoint, GetConnectionGroupLine(), m_CreateConnectionCallback);

                //
                // FYI: Will do 2 attempts max as per AttemptedRecovery
                //
                Stream  stream;

                while(true)
                {
                    FtpControlStream connection = m_Connection;

                    if (connection == null)
                    {
                        connection = QueueOrCreateConnection();
                        if (connection == null)
                            return;
                    }

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

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

                    GlobalLog.Print("Request being submitted"+ValidationHelper.HashString(this));
                    connection.SetSocketTimeoutOption(SocketShutdown.Both, RemainingTimeout, false);

                    try {
                        stream = TimedSubmitRequestHelper(async);
                    } catch (Exception e) {
                        if (AttemptedRecovery(e)){
                            if(!async){
                                if (Timeout != System.Threading.Timeout.Infinite)
                                {
                                    m_RemainingTimeout = Timeout - (int)((DateTime.UtcNow - m_StartTime).TotalMilliseconds);
                                    if(m_RemainingTimeout <= 0){
                                        throw;
                                    }
                                }
                            }
                            continue;
                        }
                        throw;
                    }
                    // no retry needed
                    break;
                }
            } catch (WebException webException) {
                //if this was a timeout, throw a timeout exception
                IOException ioEx = webException.InnerException as IOException;
                if(ioEx != null){
                    SocketException sEx = ioEx.InnerException as SocketException;
                     if(sEx != null){
                        if (sEx.ErrorCode == (int)SocketError.TimedOut) {
                            SetException(new WebException(SR.GetString(SR.net_timeout), WebExceptionStatus.Timeout));
                        }
                    }
                }

                SetException(webException);
            }
            catch (Exception exception) {
                SetException(exception);
            }
        }
 internal void GetConnection(ServicePoint servicePoint)
 {
     if (this.isConnected)
     {
         throw new InvalidOperationException(SR.GetString("SmtpAlreadyConnected"));
     }
     if (Logging.On)
     {
         Logging.Associate(Logging.Web, this, servicePoint);
     }
     this.connectionPool = ConnectionPoolManager.GetConnectionPool(servicePoint, "", m_CreateConnectionCallback);
     PooledStream pooledStream = this.connectionPool.GetConnection(this, null, this.Timeout);
     while ((((SmtpPooledStream) pooledStream).creds != null) && (((SmtpPooledStream) pooledStream).creds != this.credentials))
     {
         this.connectionPool.PutConnection(pooledStream, pooledStream.Owner, this.Timeout, false);
         pooledStream = this.connectionPool.GetConnection(this, null, this.Timeout);
     }
     if (Logging.On)
     {
         Logging.Associate(Logging.Web, this, pooledStream);
     }
     lock (this)
     {
         this.pooledStream = pooledStream;
     }
     ((SmtpPooledStream) pooledStream).creds = this.credentials;
     this.responseReader = new SmtpReplyReaderFactory(pooledStream.NetworkStream);
     pooledStream.UpdateLifetime();
     if (((SmtpPooledStream) pooledStream).previouslyUsed)
     {
         this.isConnected = true;
     }
     else
     {
         LineInfo info = this.responseReader.GetNextReplyReader().ReadLine();
         if (info.StatusCode != SmtpStatusCode.ServiceReady)
         {
             throw new SmtpException(info.StatusCode, info.Line, true);
         }
         try
         {
             this.extensions = EHelloCommand.Send(this, this.client.clientDomain);
             this.ParseExtensions(this.extensions);
         }
         catch (SmtpException exception)
         {
             if ((exception.StatusCode != SmtpStatusCode.CommandUnrecognized) && (exception.StatusCode != SmtpStatusCode.CommandNotImplemented))
             {
                 throw exception;
             }
             HelloCommand.Send(this, this.client.clientDomain);
             this.supportedAuth = SupportedAuth.Login;
         }
         if (this.enableSsl)
         {
             if (!this.serverSupportsStartTls && !(pooledStream.NetworkStream is TlsStream))
             {
                 throw new SmtpException(SR.GetString("MailServerDoesNotSupportStartTls"));
             }
             StartTlsCommand.Send(this);
             TlsStream stream2 = new TlsStream(servicePoint.Host, pooledStream.NetworkStream, this.clientCertificates, servicePoint, this.client, null);
             pooledStream.NetworkStream = stream2;
             this.channelBindingToken = stream2.GetChannelBinding(ChannelBindingKind.Unique);
             this.responseReader = new SmtpReplyReaderFactory(pooledStream.NetworkStream);
             this.extensions = EHelloCommand.Send(this, this.client.clientDomain);
             this.ParseExtensions(this.extensions);
         }
         if (this.credentials != null)
         {
             for (int i = 0; i < this.authenticationModules.Length; i++)
             {
                 Authorization authorization;
                 if (this.AuthSupported(this.authenticationModules[i]))
                 {
                     NetworkCredential credential = this.credentials.GetCredential(servicePoint.Host, servicePoint.Port, this.authenticationModules[i].AuthenticationType);
                     if (credential != null)
                     {
                         authorization = this.SetContextAndTryAuthenticate(this.authenticationModules[i], credential, null);
                         if ((authorization != null) && (authorization.Message != null))
                         {
                             info = AuthCommand.Send(this, this.authenticationModules[i].AuthenticationType, authorization.Message);
                             if (info.StatusCode != SmtpStatusCode.CommandParameterNotImplemented)
                             {
                                 goto Label_0363;
                             }
                         }
                     }
                 }
                 continue;
             Label_02F2:
                 authorization = this.authenticationModules[i].Authenticate(info.Line, null, this, this.client.TargetName, this.channelBindingToken);
                 if (authorization == null)
                 {
                     throw new SmtpException(SR.GetString("SmtpAuthenticationFailed"));
                 }
                 info = AuthCommand.Send(this, authorization.Message);
                 if (info.StatusCode == ((SmtpStatusCode) 0xeb))
                 {
                     this.authenticationModules[i].CloseContext(this);
                     this.isConnected = true;
                     return;
                 }
             Label_0363:
                 if (info.StatusCode == ((SmtpStatusCode) 0x14e))
                 {
                     goto Label_02F2;
                 }
             }
         }
         this.isConnected = true;
     }
 }
 internal CommandStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base(connectionPool, lifetime, checkLifetime)
 {
     this.m_Buffer = string.Empty;
     this.m_Encoding = System.Text.Encoding.UTF8;
     this.m_Decoder = this.m_Encoding.GetDecoder();
 }
示例#12
0
 /// <devdoc>
 ///    <para>
 ///     Setups and Creates a NetworkStream connection to the server
 ///     perform any initalization if needed
 ///    </para>
 /// </devdoc>
 internal FtpControlStream(
     ConnectionPool connectionPool,
     TimeSpan lifetime,
     bool checkLifetime
     ) : base(connectionPool, lifetime, checkLifetime) {
 }
 internal FtpControlStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base(connectionPool, lifetime, checkLifetime)
 {
     this.m_CurrentTypeSetting = string.Empty;
     this.m_ContentLength = -1L;
 }
示例#14
0
 internal CommandStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base(connectionPool, lifetime, checkLifetime)
 {
     this.m_Buffer   = string.Empty;
     this.m_Encoding = System.Text.Encoding.UTF8;
     this.m_Decoder  = this.m_Encoding.GetDecoder();
 }
 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;
 }
 private static PooledStream CreateSmtpPooledStream(ConnectionPool pool)
 {
     return new SmtpPooledStream(pool, TimeSpan.MaxValue, false);
 }
        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 FtpControlStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base(connectionPool, lifetime, checkLifetime)
 {
     this.m_CurrentTypeSetting = string.Empty;
     this.m_ContentLength      = -1L;
 }
        internal void GetConnection(ServicePoint servicePoint)
        {
            if (isConnected)
            {
                throw new InvalidOperationException(SR.GetString(SR.SmtpAlreadyConnected));
            }

            if (Logging.On) Logging.Associate(Logging.Web, this, servicePoint);
            Debug.Assert(servicePoint != null, "servicePoint was null from SmtpTransport");
            connectionPool = ConnectionPoolManager.GetConnectionPool(servicePoint, "", m_CreateConnectionCallback);

            PooledStream pooledStream = connectionPool.GetConnection((object)this, null, Timeout);

            while (((SmtpPooledStream)pooledStream).creds != null && ((SmtpPooledStream)pooledStream).creds != credentials) {
                // destroy this connection so that a new connection can be created 
                // in order to use the proper credentials.  Do not just close the 
                // connection since it's in a state where a QUIT could be sent
                connectionPool.PutConnection(pooledStream, pooledStream.Owner, Timeout, false);
                pooledStream = connectionPool.GetConnection((object)this, null, Timeout);
            }
            if (Logging.On) Logging.Associate(Logging.Web, this, pooledStream);

            lock (this) {
                this.pooledStream = pooledStream;
            }

            ((SmtpPooledStream)pooledStream).creds = credentials;

            responseReader = new SmtpReplyReaderFactory(pooledStream.NetworkStream);

            //set connectionlease
            pooledStream.UpdateLifetime();

            //if the stream was already used, then we've already done the handshake
            if (((SmtpPooledStream)pooledStream).previouslyUsed == true) {
                isConnected = true;
                return;
            }

            LineInfo info = responseReader.GetNextReplyReader().ReadLine();

            switch (info.StatusCode) 
            {
                case SmtpStatusCode.ServiceReady: 
                    {
                        break;
                    }
                default: 
                    {
                        throw new SmtpException(info.StatusCode, info.Line, true);
                    }
            }

            try
            {
                extensions = EHelloCommand.Send(this, client.clientDomain);
                ParseExtensions(extensions);
            }
            catch (SmtpException e)
            {
                if ((e.StatusCode != SmtpStatusCode.CommandUnrecognized)
                    && (e.StatusCode != SmtpStatusCode.CommandNotImplemented)) {
                    throw e;
                }

                HelloCommand.Send(this, client.clientDomain);
                //if ehello isn't supported, assume basic login
                supportedAuth = SupportedAuth.Login;
            }

#if !FEATURE_PAL
            // Establish TLS
            if (enableSsl) 
            {
                if (!serverSupportsStartTls) 
                {
                    // Either TLS is already established or server does not support TLS
                    if (!(pooledStream.NetworkStream is TlsStream)) 
                    {
                        throw new SmtpException(SR.GetString(SR.MailServerDoesNotSupportStartTls));
                    }
                }
                StartTlsCommand.Send(this);
                TlsStream TlsStream = new TlsStream(servicePoint.Host, pooledStream.NetworkStream, clientCertificates, servicePoint, client, null);

                pooledStream.NetworkStream = TlsStream;

                //for SMTP, the CBT should be unique
                this.channelBindingToken = TlsStream.GetChannelBinding(ChannelBindingKind.Unique);

                responseReader = new SmtpReplyReaderFactory(pooledStream.NetworkStream);

                // According to RFC 3207: The client SHOULD send an EHLO command 
                // as the first command after a successful TLS negotiation.
                extensions = EHelloCommand.Send(this, client.clientDomain);
                ParseExtensions(extensions);
            }
#endif // !FEATURE_PAL

            //if no credentials were supplied, try anonymous
            //servers don't appear to anounce that they support anonymous login.
            if (credentials != null) {

                for (int i = 0; i < authenticationModules.Length; i++) 
                {

                    //only authenticate if the auth protocol is supported  - [....]
                    if (!AuthSupported(authenticationModules[i])) {
                        continue;
                    }

                    NetworkCredential credential = credentials.GetCredential(servicePoint.Host, 
                        servicePoint.Port, authenticationModules[i].AuthenticationType);
                    if (credential == null)
                        continue;

                    Authorization auth = SetContextAndTryAuthenticate(authenticationModules[i], credential, null);

                    if (auth != null && auth.Message != null) 
                    {
                        info = AuthCommand.Send(this, authenticationModules[i].AuthenticationType, auth.Message);

                        if (info.StatusCode == SmtpStatusCode.CommandParameterNotImplemented) 
                        {
                            continue;
                        }

                        while ((int)info.StatusCode == 334) 
                        {
                            auth = authenticationModules[i].Authenticate(info.Line, null, this, this.client.TargetName, this.channelBindingToken);
                            if (auth == null)
                            {
                                throw new SmtpException(SR.GetString(SR.SmtpAuthenticationFailed));
                            }
                            info = AuthCommand.Send(this, auth.Message);

                            if ((int)info.StatusCode == 235)
                            {
                                authenticationModules[i].CloseContext(this);
                                isConnected = true;
                                return;
                            }
                        }
                    }
                }
            }
            isConnected = true;
        }
 /// <summary>
 ///    <para>builds networkStream from Socket</para>
 /// </summary>
 private static PooledStream CreateFtpConnection(ConnectionPool pool) {
     return (PooledStream) new FtpControlStream(pool, TimeSpan.MaxValue, false);
 }
 public AsyncConnectionPoolRequest(ConnectionPool pool, object owningObject, GeneralAsyncDelegate asyncCallback, int creationTimeout) {
     Pool = pool;
     OwningObject = owningObject;
     AsyncCallback = asyncCallback;
     CreationTimeout = creationTimeout;
 }
示例#22
0
 internal SmtpPooledStream(ConnectionPool connectionPool, TimeSpan lifetime, bool checkLifetime) : base (connectionPool,lifetime,checkLifetime) {
 }
 private void SubmitRequest(bool async)
 {
     try
     {
         FtpControlStream stream;
         this.m_Async = async;
         if (this.CheckCacheRetrieveBeforeSubmit())
         {
             this.RequestCallback(null);
             return;
         }
         if (this.m_ConnectionPool == null)
         {
             this.m_ConnectionPool = ConnectionPoolManager.GetConnectionPool(this.ServicePoint, this.GetConnectionGroupLine(), m_CreateConnectionCallback);
         }
     Label_003F:
         stream = this.m_Connection;
         if (stream == null)
         {
             stream = this.QueueOrCreateConnection();
             if (stream == null)
             {
                 return;
             }
         }
         if (!async && (this.Timeout != -1))
         {
             TimeSpan span = (TimeSpan) (DateTime.UtcNow - this.m_StartTime);
             this.m_RemainingTimeout = this.Timeout - ((int) span.TotalMilliseconds);
             if (this.m_RemainingTimeout <= 0)
             {
                 throw new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
             }
         }
         stream.SetSocketTimeoutOption(SocketShutdown.Both, this.RemainingTimeout, false);
         try
         {
             this.TimedSubmitRequestHelper(async);
         }
         catch (Exception exception)
         {
             if (!this.AttemptedRecovery(exception))
             {
                 throw;
             }
             if (!async && (this.Timeout != -1))
             {
                 TimeSpan span2 = (TimeSpan) (DateTime.UtcNow - this.m_StartTime);
                 this.m_RemainingTimeout = this.Timeout - ((int) span2.TotalMilliseconds);
                 if (this.m_RemainingTimeout <= 0)
                 {
                     throw;
                 }
             }
             goto Label_003F;
         }
     }
     catch (WebException exception2)
     {
         IOException innerException = exception2.InnerException as IOException;
         if (innerException != null)
         {
             SocketException exception4 = innerException.InnerException as SocketException;
             if ((exception4 != null) && (exception4.ErrorCode == 0x274c))
             {
                 this.SetException(new WebException(SR.GetString("net_timeout"), WebExceptionStatus.Timeout));
             }
         }
         this.SetException(exception2);
     }
     catch (Exception exception5)
     {
         this.SetException(exception5);
     }
 }