Beispiel #1
0
        public StlsTransaction(PopConnection connection, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
            : base(connection)
        {
            if (createAuthenticatedStreamCallback == null)
            throw new ArgumentNullException("createAuthenticatedStreamCallback");

              this.createAuthenticatedStreamCallback = createAuthenticatedStreamCallback;
        }
 protected override void Connect(string host, int port, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
 {
     try {
     base.Connect(host, port, createAuthenticatedStreamCallback);
       }
       catch (ConnectionException ex) {
     throw new PopConnectionException(ex.Message, ex.InnerException);
       }
 }
 public override void UpgradeStream(UpgradeConnectionStreamCallback upgradeStreamCallback)
 {
     try {
     base.UpgradeStream(upgradeStreamCallback);
       }
       catch (ConnectionException ex) {
     throw new ImapUpgradeConnectionException(ex.Message, ex.InnerException);
       }
 }
Beispiel #4
0
        public PopConnection(string host, int port, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
            : base(popConnectionTraceSource)
        {
            if (port == -1) {
            if (createAuthenticatedStreamCallback == null)
              port = PopDefaultPorts.Pop;
            else
              port = PopDefaultPorts.Pops;
              }

              Connect(host, port, createAuthenticatedStreamCallback);
        }
        public static PopSession CreateSession(IPopSessionProfile profile,
                                           SaslClientMechanism authMechanismSpecified,
                                           UpgradeConnectionStreamCallback createSslStreamCallback)
        {
            PopSession session;

              var result = CreateSession(profile, authMechanismSpecified, createSslStreamCallback, out session);

              if (result.Succeeded)
            return session;
              else
            throw new PopAuthenticationException(result);
        }
Beispiel #6
0
        public void Connect(string password, UpgradeConnectionStreamCallback createSslStreamCallback)
        {
            ThrowIfAlreadyConnectedOrAsyncConnectRunning();

              SetSession(ConnectCore(new ConnectParams(profile,
                                               new NetworkCredential(profile.UserName, password),
                                               createSslStreamCallback)));
        }
Beispiel #7
0
        public void Connect(ICredentialsByHost credentials, UpgradeConnectionStreamCallback createSslStreamCallback)
        {
            ThrowIfAlreadyConnectedOrAsyncConnectRunning();

              SetSession(ConnectCore(new ConnectParams(profile,
                                               credentials,
                                               createSslStreamCallback)));
        }
Beispiel #8
0
 public ImapSession(string host, int port, int transactionTimeout, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
     : this(host, port, false, transactionTimeout, createAuthenticatedStreamCallback)
 {
 }
Beispiel #9
0
 public IAsyncResult BeginConnect(SaslClientMechanism authMechanism,
                              UpgradeConnectionStreamCallback createSslStreamCallback,
                              AsyncCallback asyncCallback,
                              object asyncState)
 {
     return BeginConnect(new ConnectParams(profile,
                                     authMechanism,
                                     createSslStreamCallback),
                   asyncCallback,
                   asyncState);
 }
Beispiel #10
0
        /*
         * transaction methods : connect/disconnect
         */
        private void Connect(string host, int port, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
        {
            TraceInfo("connecting");

              this.connection = new PopConnection(host, port, createAuthenticatedStreamCallback);

              TraceInfo("connected");

              using (var t = new GreetingTransaction(connection)) {
            try {
              if (ProcessTransaction(t).Failed)
            throw new PopConnectionException(string.Concat("connection refused or establishment failed: ", t.Result.ResultText));
            }
            catch (TimeoutException ex) {
              throw new PopConnectionException("connection timed out", ex);
            }

            timestamp = t.Result.Value;

            TransitStateTo(PopSessionState.Authorization);
              }

              if (ApopAvailable)
            TraceInfo("APOP is available, timestamp is {0}", timestamp);
        }
Beispiel #11
0
        public PopSession(string host, int port, int transactionTimeout, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
        {
            if (transactionTimeout < -1)
            throw new ArgumentOutOfRangeException("transactionTimeout", transactionTimeout, "must be greater than or equals to -1");

              this.transactionTimeout = transactionTimeout;

              Connect(host, port, createAuthenticatedStreamCallback);
        }
Beispiel #12
0
 public IAsyncResult BeginConnect(string password,
                              UpgradeConnectionStreamCallback createSslStreamCallback)
 {
     return BeginConnect(password, createSslStreamCallback, null, null);
 }
Beispiel #13
0
 public ConnectParams(ImapClientProfile profile,
                SaslClientMechanism authMechanism,
                UpgradeConnectionStreamCallback createSslStreamCallback)
 {
     Profile = profile.Clone();
     AuthMechanism = authMechanism;
     CreateSslStreamCallback = createSslStreamCallback;
 }
Beispiel #14
0
 public PopConnection(string host, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
     : this(host, -1, createAuthenticatedStreamCallback)
 {
 }
Beispiel #15
0
        public ImapSession(string host, int port, bool handlesReferralAsException, int transactionTimeout, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
        {
            if (transactionTimeout < -1)
            throw new ArgumentOutOfRangeException("transactionTimeout", transactionTimeout, "must be greater than or equals to -1");

              this.handlesReferralAsException = handlesReferralAsException;
              this.transactionTimeout = transactionTimeout;

              this.readonlyHierarchyDelimiters = hierarchyDelimiters.AsReadOnly();

              Connect(host, port, createAuthenticatedStreamCallback);
        }
Beispiel #16
0
        protected virtual void Connect(string host, int port, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
        {
            if (host == null)
            throw new ArgumentNullException("host");
              if (port < IPEndPoint.MinPort || IPEndPoint.MaxPort < port)
            throw new ArgumentOutOfRangeException("port", port, "out of range");

              if (client != null)
            throw new InvalidOperationException("already connected");

              TcpClient c = null;

              try {

            c = new TcpClient();

            c.ReceiveTimeout = DefaultTimeoutMilliseconds;
            c.SendTimeout    = DefaultTimeoutMilliseconds;

            ConnectionTrace.Log(this, "connecting to {0}:{1}", host, port);

            c.Connect(host, port);

            this.host = host;
            this.client = c;
            this.remoteEndPoint = c.Client.RemoteEndPoint as IPEndPoint;
            this.localEndPoint  = c.Client.LocalEndPoint as IPEndPoint;
            this.stream = CreateBufferedStream(ConnectionTrace.CreateTracingStream(this, client.GetStream()));

            ConnectionTrace.Log(this, "connected: {0} ({1})", remoteEndPoint, host);
              }
              catch (Exception ex) {
            ConnectionTrace.Log(this, ex);

            if (c != null)
              c.Close();

            this.client = null;

            throw new ConnectionException("connect failed", ex);
              }

              try {
            if (createAuthenticatedStreamCallback != null) {
              UpgradeStream(createAuthenticatedStreamCallback);

              isSecurePortConnection = true;
            }
              }
              catch {
            this.client.Close();
            this.client = null;

            throw;
              }
        }
Beispiel #17
0
        public virtual void UpgradeStream(UpgradeConnectionStreamCallback upgradeStreamCallback)
        {
            if (upgradeStreamCallback == null)
            throw new ArgumentNullException("upgradeStreamCallback");

              try {
            var upgradedStream = upgradeStreamCallback(this, RawStream);
            var sslStream = upgradedStream as SslStream;

            if (sslStream != null)
              ConnectionTrace.Log(this, "TLS started: {0}, {1}, {2}, {3}{4}",
                              sslStream.SslProtocol,
                              sslStream.CipherAlgorithm,
                              sslStream.HashAlgorithm,
                              sslStream.KeyExchangeAlgorithm,
                              sslStream.IsMutuallyAuthenticated ? ", mutually authenticated" : string.Empty);

            stream = CreateBufferedStream(ConnectionTrace.CreateTracingStream(this, upgradedStream));
              }
              catch (AuthenticationException ex) {
            ConnectionTrace.Log(this, ex);

            throw new ConnectionException(string.Format("upgrading stream failed (callback: {0})", upgradeStreamCallback.Method), ex);
              }
              catch (IOException ex) {
            ConnectionTrace.Log(this, ex);

            throw new ConnectionException(string.Format("upgrading stream failed (callback: {0})", upgradeStreamCallback.Method), ex);
              }
        }
        protected override ProcessTransactionDelegate Reset()
        {
            #if DEBUG
              if (!RequestArguments.ContainsKey("compression mechanism"))
            return ProcessArgumentNotSetted;
            #endif

              var compressionMechanism = RequestArguments["compression mechanism"] as ImapCompressionMechanism;

              foreach (var decompression in new[] {
            new {Mechanism = ImapCompressionMechanism.Deflate, CreateStreamCallback = new UpgradeConnectionStreamCallback(CreateDeflateStream)},
              }) {
            if (decompression.Mechanism != compressionMechanism)
              continue;

            createDecompressingStreamCallback = decompression.CreateStreamCallback;

            return ProcessCompress;
              }

              return ProcessUnsupported;
        }
Beispiel #19
0
        public void Connect(SaslClientMechanism authMechanism, UpgradeConnectionStreamCallback createSslStreamCallback)
        {
            if (authMechanism == null)
            throw new ArgumentNullException("authMechanism");

              ThrowIfAlreadyConnectedOrAsyncConnectRunning();

              SetSession(ConnectCore(new ConnectParams(profile,
                                               authMechanism,
                                               createSslStreamCallback)));
        }
Beispiel #20
0
 public IAsyncResult BeginConnect(string password,
                              UpgradeConnectionStreamCallback createSslStreamCallback,
                              AsyncCallback asyncCallback,
                              object asyncState)
 {
     return BeginConnect(new ConnectParams(profile,
                                     new NetworkCredential(profile.UserName, password),
                                     createSslStreamCallback),
                   asyncCallback,
                   asyncState);
 }
Beispiel #21
0
            public ConnectParams(ImapClientProfile profile,
                           ICredentialsByHost credentials,
                           UpgradeConnectionStreamCallback createSslStreamCallback)
            {
                Profile = profile.Clone();
                Profile.SetCredentials(credentials);

                CreateSslStreamCallback = createSslStreamCallback;
            }
 /*
  * transaction methods : non-authenticated state
  */
 /// <summary>sends STARTTLS command</summary>
 /// <remarks>valid in non-authenticated state</remarks>
 public ImapCommandResult StartTls(UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
 {
     return StartTls(createAuthenticatedStreamCallback, false);
 }
Beispiel #23
0
 public ImapSession(string host, int port, bool handlesReferralAsException, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
     : this(host, port, handlesReferralAsException, DefaultTransactionTimeout, createAuthenticatedStreamCallback)
 {
 }
        /// <summary>sends STLS command</summary>
        /// <remarks>valid in authorization state</remarks>
        public PopCommandResult Stls(UpgradeConnectionStreamCallback createAuthenticatedStreamCallback, bool reissueCapability)
        {
            RejectNonAuthorizationState();

              if (createAuthenticatedStreamCallback == null)
            throw new ArgumentNullException("createAuthenticatedStreamCallback");

              PopCommandResult result;

              using (var t = new StlsTransaction(connection, createAuthenticatedStreamCallback)) {
            if ((result = ProcessTransaction(t)).Succeeded)
              // RFC 2595 Using TLS with IMAP, POP3 and ACAP
              // http://tools.ietf.org/html/rfc2595
              // 4. POP3 STARTTLS extension
              //              Once TLS has been started, the client MUST discard cached
              //              information about server capabilities and SHOULD re-issue
              //              the CAPA command.  This is necessary to protect against
              //              man-in-the-middle attacks which alter the capabilities list
              //              prior to STLS.  The server MAY advertise different
              //              capabilities after STLS.
              SetServerCapabilities(new PopCapabilityList());
            else
              return result;
              }

              if (reissueCapability)
            Capa();

              return result;
        }
Beispiel #25
0
 public PopSession(string host, int port, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
     : this(host, port, DefaultTransactionTimeout, createAuthenticatedStreamCallback)
 {
 }
Beispiel #26
0
 public IAsyncResult BeginConnect(SaslClientMechanism authMechanism,
                              UpgradeConnectionStreamCallback createSslStreamCallback)
 {
     return BeginConnect(authMechanism, createSslStreamCallback, null, null);
 }
Beispiel #27
0
 public IAsyncResult BeginConnect(ICredentialsByHost credentials,
                              UpgradeConnectionStreamCallback createSslStreamCallback)
 {
     return BeginConnect(credentials, createSslStreamCallback, null, null);
 }
Beispiel #28
0
        /*
         * transaction methods : connect/disconnect
         */
        private void Connect(string host, int port, UpgradeConnectionStreamCallback createAuthenticatedStreamCallback)
        {
            TraceInfo("connecting");

              this.connection = new ImapConnection(host, port, createAuthenticatedStreamCallback);

              TraceInfo("connected");

              SetServerCapabilities(new ImapCapabilityList(new[] {
            ImapCapability.Imap4Rev1 /* required by GreetingTransaction */
              }));

              ImapCommandResult result;

              using (var t = new GreetingTransaction(connection)) {
            try {
              result = ProcessTransaction(t);

              if (result.Code == ImapCommandResultCode.Bye) {
            var refferalResponseCode = result.GetResponseCode(ImapResponseCode.Referral);

            if (refferalResponseCode != null) {
              // RFC 2221 IMAP4 Login Referrals
              // http://tools.ietf.org/html/rfc2221
              // 4.2. BYE at connection startup referral
              //    An IMAP4 server MAY respond with an untagged BYE and a REFERRAL
              //    response code that contains an IMAP URL to a home server if it is not
              //    willing to accept connections and wishes to direct the client to
              //    another IMAP4 server.
              var referToUri = ImapResponseTextConverter.FromReferral(refferalResponseCode.ResponseText)[0];

              if (handlesReferralAsException) {
                throw new ImapLoginReferralException(string.Format("try another server: '{0}'", refferalResponseCode.ResponseText.Text),
                                                     referToUri);
              }
              else {
                Trace.Info("login referral: '{0}'", refferalResponseCode.ResponseText.Text);
                Trace.Info("  try to connect to {0}", referToUri);
              }
            }
              }

              if (result.Failed)
            throw new ImapConnectionException(string.Concat("connection refused or establishment failed: ", result.ResultText));
            }
            catch (TimeoutException ex) {
              throw new ImapConnectionException("connection timed out", ex);
            }

            if (result.Code == ImapCommandResultCode.PreAuth) {
              UpdateAuthority(null, null);
              TransitStateTo(ImapSessionState.Authenticated);
            }
            else {
              TransitStateTo(ImapSessionState.NotAuthenticated);
            }

            // 7.1. Server Responses - Status Responses
            //       CAPABILITY
            //          Followed by a list of capabilities.  This can appear in the
            //          initial OK or PREAUTH response to transmit an initial
            //          capabilities list.  This makes it unnecessary for a client to
            //          send a separate CAPABILITY command if it recognizes this
            //          response.
            var capabilityResponseCode = result.GetResponseCode(ImapResponseCode.Capability);

            if (capabilityResponseCode == null)
              // clear server capabilities
              SetServerCapabilities(new ImapCapabilityList());
            else
              SetServerCapabilities(ImapResponseTextConverter.FromCapability(capabilityResponseCode.ResponseText));
              }
        }
        /// <summary>sends STARTTLS command</summary>
        /// <remarks>valid in non-authenticated state</remarks>
        public ImapCommandResult StartTls(UpgradeConnectionStreamCallback createAuthenticatedStreamCallback, bool reissueCapability)
        {
            RejectNonConnectedState();

              if (state != ImapSessionState.NotAuthenticated)
            throw new ImapProtocolViolationException("already authenticated");

              if (createAuthenticatedStreamCallback == null)
            throw new ArgumentNullException("createAuthenticatedStreamCallback");

              ImapCommandResult result;

              using (var t = new StartTlsTransaction(connection, createAuthenticatedStreamCallback)) {
            if ((result = ProcessTransaction(t)).Succeeded)
              // 6.2.1. STARTTLS Command
              //       Once [TLS] has been started, the client MUST discard cached
              //       information about server capabilities and SHOULD re-issue the
              //       CAPABILITY command.
              SetServerCapabilities(new ImapCapabilityList());
            else
              return result;
              }

              if (reissueCapability)
            Capability();

              return result;
        }
Beispiel #30
0
 public IAsyncResult BeginConnect(ICredentialsByHost credentials,
                              UpgradeConnectionStreamCallback createSslStreamCallback,
                              AsyncCallback asyncCallback,
                              object asyncState)
 {
     return BeginConnect(new ConnectParams(profile,
                                     credentials,
                                     createSslStreamCallback),
                   asyncCallback,
                   asyncState);
 }