コード例 #1
0
            public async Task <Exception> LoginAsync(cMethodControl pMC, cAccountId pAccountId, cLogin pLogin, cTrace.cContext pParentContext)
            {
                var lContext = pParentContext.NewMethod(nameof(cSession), nameof(LoginAsync), pMC, pAccountId);

                if (mDisposed)
                {
                    throw new ObjectDisposedException(nameof(cSession));
                }
                if (_ConnectionState != eConnectionState.notauthenticated)
                {
                    throw new InvalidOperationException(kInvalidOperationExceptionMessage.NotUnauthenticated);
                }

                using (var lBuilder = new cCommandDetailsBuilder())
                {
                    //  note the lack of locking - this is only called during connect

                    lBuilder.Add(kLoginCommandPartLogin, cCommandPartFactory.AsASCIILiteral(pLogin.UserId), cCommandPart.Space, cCommandPartFactory.AsASCIILiteral(pLogin.Password));

                    var lHook = new cCommandHookInitial();
                    lBuilder.Add(lHook);

                    var lCapabilities = mPipeline.Capabilities;

                    var lResult = await mPipeline.ExecuteAsync(pMC, lBuilder.EmitCommandDetails(), lContext).ConfigureAwait(false);

                    if (lResult.ResultType == eCommandResultType.ok)
                    {
                        lContext.TraceInformation("login success");
                        ZAuthenticated(lCapabilities, lHook, lResult.ResponseText, pAccountId, lContext);
                        return(null);
                    }

                    if (lHook.Capabilities != null)
                    {
                        lContext.TraceError("received capability on a failed login");
                    }

                    if (lResult.ResultType == eCommandResultType.no)
                    {
                        lContext.TraceInformation("login failed: {0}", lResult.ResponseText);

                        if (ZSetHomeServerReferral(lResult.ResponseText, lContext))
                        {
                            return(new cHomeServerReferralException(lResult.ResponseText, lContext));
                        }

                        if (lResult.ResponseText.Code == eResponseTextCode.authenticationfailed || lResult.ResponseText.Code == eResponseTextCode.authorizationfailed || lResult.ResponseText.Code == eResponseTextCode.expired)
                        {
                            return(new cCredentialsException(lResult.ResponseText, lContext));
                        }

                        return(null);
                    }

                    throw new cProtocolErrorException(lResult, 0, lContext);
                }
            }
コード例 #2
0
ファイル: base.cs プロジェクト: bacome/imapclient
            private void ZSetConnectedAccountId(cAccountId pAccountId, cTrace.cContext pParentContext)
            {
                var lContext = pParentContext.NewMethod(nameof(cSession), nameof(ZSetConnectedAccountId), pAccountId);

                if (_ConnectedAccountId != null)
                {
                    throw new InvalidOperationException(kInvalidOperationExceptionMessage.AlreadyConnected);                              // can only be set once
                }
                _ConnectedAccountId = pAccountId ?? throw new ArgumentNullException(nameof(pAccountId));
                ZSetState(eConnectionState.authenticated, lContext);
                mSynchroniser.InvokePropertyChanged(nameof(cIMAPClient.ConnectedAccountId), lContext);
            }
コード例 #3
0
ファイル: authenticate.cs プロジェクト: bacome/imapclient
            public async Task <Exception> AuthenticateAsync(cMethodControl pMC, cAccountId pAccountId, cSASL pSASL, cTrace.cContext pParentContext)
            {
                var lContext = pParentContext.NewMethod(nameof(cSession), nameof(AuthenticateAsync), pMC, pAccountId, pSASL.MechanismName);

                if (mDisposed)
                {
                    throw new ObjectDisposedException(nameof(cSession));
                }
                if (_ConnectionState != eConnectionState.notauthenticated)
                {
                    throw new InvalidOperationException(kInvalidOperationExceptionMessage.NotUnauthenticated);
                }

                using (var lBuilder = new cCommandDetailsBuilder())
                {
                    //  note the lack of locking - this is only called during connect

                    lBuilder.Add(kAuthenticateCommandPartAuthenticate);
                    lBuilder.Add(new cTextCommandPart(pSASL.MechanismName));

                    var lAuthentication = pSASL.GetAuthentication();
                    lBuilder.Add(lAuthentication);
                    pSASL.LastAuthentication = lAuthentication;

                    if (_Capabilities.SASL_IR)
                    {
                        IList <byte> lAuthenticationResponse;

                        try { lAuthenticationResponse = lAuthentication.GetResponse(null); }
                        catch (Exception e)
                        {
                            lContext.TraceException("SASL authentication object threw when getting initial response", e);
                            return(null);
                        }

                        if (lAuthenticationResponse != null)
                        {
                            lBuilder.Add(cCommandPart.Space);
                            if (lAuthenticationResponse.Count == 0)
                            {
                                lBuilder.Add(kAuthenticateCommandPartEqual);                                     // special case where the initial response is an empty string
                            }
                            else
                            {
                                lBuilder.Add(new cTextCommandPart(cBase64.Encode(lAuthenticationResponse), true));
                            }
                        }
                    }

                    var lHook = new cCommandHookAuthenticate(mPipeline, lAuthentication, _Capabilities.LoginReferrals);
                    lBuilder.Add(lHook);

                    var lCapabilities = mPipeline.Capabilities;

                    var lResult = await mPipeline.ExecuteAsync(pMC, lBuilder.EmitCommandDetails(), lContext).ConfigureAwait(false);

                    if (lResult.ResultType == eCommandResultType.ok)
                    {
                        lContext.TraceInformation("authenticate success");
                        ZAuthenticated(lCapabilities, lHook, lResult.ResponseText, pAccountId, lContext);
                        return(null);
                    }

                    if (lResult.ResultType == eCommandResultType.no)
                    {
                        lContext.TraceInformation("authenticate failed: {0}", lResult.ResponseText);

                        if (ZSetHomeServerReferral(lResult.ResponseText, lContext))
                        {
                            return(new cHomeServerReferralException(lResult.ResponseText, lContext));
                        }

                        if (lResult.ResponseText.Code == eResponseTextCode.authenticationfailed || lResult.ResponseText.Code == eResponseTextCode.authorizationfailed || lResult.ResponseText.Code == eResponseTextCode.expired)
                        {
                            return(new cCredentialsException(lResult.ResponseText, lContext));
                        }

                        return(null);
                    }

                    lContext.TraceInformation("authenticate cancelled");

                    return(null);
                }
            }
コード例 #4
0
        private async Task ZConnectAsync(cTrace.cContext pParentContext)
        {
            var lContext = mRootContext.NewMethod(nameof(cIMAPClient), nameof(ZConnectAsync));

            if (mDisposed)
            {
                throw new ObjectDisposedException(nameof(cIMAPClient));
            }

            cServer      lServer      = Server;
            cCredentials lCredentials = Credentials;

            if (lServer == null)
            {
                throw new InvalidOperationException("connect requires server to be set");
            }
            if (lCredentials == null)
            {
                throw new InvalidOperationException("connect requires credentials to be set");
            }

            bool lSessionReplaced;

            if (mSession == null)
            {
                lSessionReplaced = false;
            }
            else
            {
                if (!mSession.IsUnconnected)
                {
                    throw new InvalidOperationException(kInvalidOperationExceptionMessage.NotUnconnected);
                }
                mSession.Dispose();

                lSessionReplaced = true;

                mNamespaces = null;

                mInbox = null;
                mSynchroniser.InvokePropertyChanged(nameof(Inbox), lContext);
            }

            // initialise the SASLs
            foreach (var lSASL in lCredentials.SASLs)
            {
                lSASL.LastAuthentication = null;
            }

            mSession = new cSession(mSynchroniser, mIgnoreCapabilities, mMailboxCacheDataItems, mNetworkWriteConfiguration, mIdleConfiguration, mFetchCacheItemsConfiguration, mFetchBodyReadConfiguration, mEncoding, lContext);
            var lSession = mSession;

            if (lSessionReplaced)
            {
                mSynchroniser.InvokePropertyChanged(nameof(Capabilities), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(ConnectionState), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(IsConnected), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(IsUnconnected), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(ConnectedAccountId), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(EnabledExtensions), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(HomeServerReferral), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(ServerId), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(Namespaces), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(SelectedMailbox), lContext);
                mSynchroniser.InvokePropertyChanged(nameof(SelectedMailboxDetails), lContext);
            }

            using (var lToken = mCancellationManager.GetToken(lContext))
            {
                var lMC = new cMethodControl(mTimeout, lToken.CancellationToken);

                try
                {
                    await lSession.ConnectAsync(lMC, lServer, lContext).ConfigureAwait(false);

                    if (lSession.Capabilities == null)
                    {
                        await lSession.CapabilityAsync(lMC, lContext).ConfigureAwait(false);
                    }

                    if (lSession.ConnectionState == eConnectionState.notauthenticated && !lSession.TLSInstalled && lSession.Capabilities.StartTLS)
                    {
                        await lSession.StartTLSAsync(lMC, lContext).ConfigureAwait(false);

                        await lSession.CapabilityAsync(lMC, lContext).ConfigureAwait(false);
                    }

                    object        lOriginalCapabilities = lSession.Capabilities;
                    cCapabilities lCurrentCapabilities  = lSession.Capabilities;

                    if (lSession.ConnectionState == eConnectionState.notauthenticated)
                    {
                        bool      lTLSIssue              = false;
                        bool      lTriedCredentials      = false;
                        Exception lAuthenticateException = null;

                        cAccountId lAccountId = new cAccountId(lServer.Host, lCredentials.Type, lCredentials.UserId);

                        bool lTLSInstalled = lSession.TLSInstalled;

                        if (lCredentials.TryAllSASLs)
                        {
                            foreach (var lSASL in lCredentials.SASLs)
                            {
                                if ((lSASL.TLSRequirement == eTLSRequirement.required && !lTLSInstalled) || (lSASL.TLSRequirement == eTLSRequirement.disallowed && lTLSInstalled))
                                {
                                    lTLSIssue = true;
                                }
                                else
                                {
                                    lTriedCredentials      = true;
                                    lAuthenticateException = await lSession.AuthenticateAsync(lMC, lAccountId, lSASL, lContext).ConfigureAwait(false);

                                    if (lSession.ConnectionState != eConnectionState.notauthenticated || lAuthenticateException != null)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            foreach (var lSASL in lCredentials.SASLs)
                            {
                                if (lCurrentCapabilities.AuthenticationMechanisms.Contains(lSASL.MechanismName)) // no case-invariance required because SASL (rfc 2222) says only uppercase is allowed
                                {
                                    if ((lSASL.TLSRequirement == eTLSRequirement.required && !lTLSInstalled) || (lSASL.TLSRequirement == eTLSRequirement.disallowed && lTLSInstalled))
                                    {
                                        lTLSIssue = true;
                                    }
                                    else
                                    {
                                        lTriedCredentials      = true;
                                        lAuthenticateException = await lSession.AuthenticateAsync(lMC, lAccountId, lSASL, lContext).ConfigureAwait(false);

                                        if (lSession.ConnectionState != eConnectionState.notauthenticated || lAuthenticateException != null)
                                        {
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (lSession.ConnectionState == eConnectionState.notauthenticated && lAuthenticateException == null && !lCurrentCapabilities.LoginDisabled && lCredentials.Login != null)
                        {
                            if ((lCredentials.Login.TLSRequirement == eTLSRequirement.required && !lTLSInstalled) || (lCredentials.Login.TLSRequirement == eTLSRequirement.disallowed && lTLSInstalled))
                            {
                                lTLSIssue = true;
                            }
                            else
                            {
                                lTriedCredentials      = true;
                                lAuthenticateException = await lSession.LoginAsync(lMC, lAccountId, lCredentials.Login, lContext).ConfigureAwait(false);
                            }
                        }

                        if (lSession.ConnectionState != eConnectionState.authenticated)
                        {
                            lContext.TraceError("could not authenticate");

                            // log out
                            await lSession.LogoutAsync(lMC, lContext).ConfigureAwait(false);

                            // throw an exception that indicates why we couldn't connect

                            if (lTriedCredentials)
                            {
                                if (lAuthenticateException != null)
                                {
                                    throw lAuthenticateException;
                                }
                                throw new cCredentialsException(lContext);
                            }

                            throw new cAuthenticationMechanismsException(lTLSIssue, lContext); // the server has no mechanisms that we can try
                        }

                        // re-get the capabilities if we didn't get new ones as part of the authentication/ login OR if a security layer was installed (SASL requires this)
                        if (ReferenceEquals(lOriginalCapabilities, lSession.Capabilities) || lSession.SASLSecurityInstalled)
                        {
                            await lSession.CapabilityAsync(lMC, lContext).ConfigureAwait(false);
                        }
                        lCurrentCapabilities = lSession.Capabilities;
                    }

                    if (lCurrentCapabilities.Enable)
                    {
                        fEnableableExtensions lExtensions = fEnableableExtensions.none;
                        if (lCurrentCapabilities.UTF8Accept || lCurrentCapabilities.UTF8Only)
                        {
                            lExtensions = lExtensions | fEnableableExtensions.utf8;
                        }
                        if (lExtensions != fEnableableExtensions.none)
                        {
                            await lSession.EnableAsync(lMC, lExtensions, lContext).ConfigureAwait(false);
                        }
                    }

                    // enabled (lock in the capabilities and enabled extensions)
                    lSession.SetEnabled(lContext);

                    Task lIdTask;

                    if (lCurrentCapabilities.Id)
                    {
                        cId lClientId;

                        if ((lSession.EnabledExtensions & fEnableableExtensions.utf8) == 0)
                        {
                            lClientId = mClientId;
                        }
                        else
                        {
                            lClientId = mClientIdUTF8 ?? mClientId;
                        }

                        lIdTask = lSession.IdAsync(lMC, lClientId, lContext);
                    }
                    else
                    {
                        lIdTask = null;
                    }

                    if (lCurrentCapabilities.Namespace)
                    {
                        await lSession.NamespaceAsync(lMC, lContext).ConfigureAwait(false);

                        var lPersonalNamespaceNames = lSession.NamespaceNames?.Personal;

                        if (lPersonalNamespaceNames != null)
                        {
                            foreach (var lName in lPersonalNamespaceNames)
                            {
                                // special case, where the personal namespace is "INBOX/" (where "/" is the delimiter)
                                if (lName.Delimiter != null && lName.Prefix.Equals(cMailboxName.InboxString + lName.Delimiter, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    mInbox = new cMailbox(this, lSession.GetMailboxHandle(new cMailboxName(cMailboxName.InboxString, lName.Delimiter)));
                                    mSynchroniser.InvokePropertyChanged(nameof(Inbox), lContext);
                                    break;
                                }

                                cMailboxPathPattern lPattern = new cMailboxPathPattern(lName.Prefix, "%", lName.Delimiter);

                                if (lPattern.Matches(cMailboxName.InboxString))
                                {
                                    mInbox = new cMailbox(this, lSession.GetMailboxHandle(new cMailboxName(cMailboxName.InboxString, lName.Delimiter)));
                                    mSynchroniser.InvokePropertyChanged(nameof(Inbox), lContext);
                                    break;
                                }
                            }
                        }
                    }

                    if (mInbox == null)
                    {
                        var lDelimiter = await lSession.ListDelimiterAsync(lMC, lContext).ConfigureAwait(false);

                        if (!lCurrentCapabilities.Namespace)
                        {
                            mNamespaces = new cNamespaces(this, new cNamespaceName[] { new cNamespaceName("", lDelimiter) }, null, null);
                            mSynchroniser.InvokePropertyChanged(nameof(Namespaces), lContext);
                        }

                        mInbox = new cMailbox(this, lSession.GetMailboxHandle(new cMailboxName(cMailboxName.InboxString, lDelimiter)));
                        mSynchroniser.InvokePropertyChanged(nameof(Inbox), lContext);
                    }

                    // wait for id to complete
                    if (lIdTask != null)
                    {
                        await lIdTask.ConfigureAwait(false);
                    }

                    // initialised (namespaces set, inbox available, id available (if server supports it); user may now issue commands)
                    lSession.SetInitialised(lContext);
                }
                catch when(lSession.ConnectionState != eConnectionState.disconnected)
                {
                    lSession.Disconnect(lContext);
                    throw;
                }
            }
        }
コード例 #5
0
            private void ZAuthenticated(cStrings pOldPipelineCapabilities, cCommandHookInitial pHook, cResponseText pResponseText, cAccountId pAccountId, cTrace.cContext pParentContext)
            {
                var lContext = pParentContext.NewMethod(nameof(cSession), nameof(ZAuthenticated));

                if (pHook.Capabilities != null)
                {
                    ZSetCapabilities(pHook.Capabilities, pHook.AuthenticationMechanisms, lContext);
                }
                else if (!ReferenceEquals(pOldPipelineCapabilities, mPipeline.Capabilities))
                {
                    ZSetCapabilities(mPipeline.Capabilities, mPipeline.AuthenticationMechanisms, lContext);
                }

                ZSetHomeServerReferral(pResponseText, lContext);
                ZSetConnectedAccountId(pAccountId, lContext);
            }