imapconn.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. package email
  2. /*
  3. imapconn.go
  4. Opening and authenticating IMAP connections.
  5. */
  6. import (
  7. "context"
  8. "errors"
  9. "fmt"
  10. "mime"
  11. "net"
  12. "strings"
  13. "github.com/emersion/go-imap/v2"
  14. "github.com/emersion/go-imap/v2/imapclient"
  15. "github.com/emersion/go-message/charset"
  16. "github.com/emersion/go-sasl"
  17. )
  18. // wordDecoder decodes RFC 2047 encoded words in any charset go-message knows
  19. // (GB2312, Big5, Shift_JIS, KOI8-R, …) so subjects and names in ENVELOPE
  20. // responses arrive as proper UTF-8.
  21. var wordDecoder = &mime.WordDecoder{CharsetReader: charset.Reader}
  22. // dialIMAP connects, authenticates and identifies a client for an account.
  23. func (m *Manager) dialIMAP(ctx context.Context, p Principal, account *Account) (*imapclient.Client, error) {
  24. server := account.IMAP
  25. if server.Security == SecurityNone && !m.allowInsecure(p) {
  26. return nil, ErrInsecureBlocked
  27. }
  28. client, err := connectIMAP(ctx, server, m.allowPrivate(p))
  29. if err != nil {
  30. return nil, err
  31. }
  32. if err := m.authenticateIMAP(ctx, client, account); err != nil {
  33. client.Close()
  34. return nil, err
  35. }
  36. //Some providers (NetEase 163/126) refuse SELECT from clients that did not
  37. //identify themselves. ID is harmless everywhere else.
  38. if client.Caps().Has(imap.CapID) {
  39. client.ID(&imap.IDData{Name: "ArozOS Mail", Version: "1.0", Vendor: "ArozOS"}).Wait()
  40. }
  41. return client, nil
  42. }
  43. // connectIMAP opens the transport and waits for the greeting.
  44. func connectIMAP(ctx context.Context, server ServerConfig, allowPrivate bool) (*imapclient.Client, error) {
  45. options := &imapclient.Options{WordDecoder: wordDecoder}
  46. var client *imapclient.Client
  47. switch server.Security {
  48. case SecuritySSL, "":
  49. conn, err := dialTLS(ctx, server.Host, server.Port, allowPrivate, "imap")
  50. if err != nil {
  51. return nil, describeDialError("IMAP", server, err)
  52. }
  53. client = imapclient.New(conn, options)
  54. case SecuritySTARTTLS:
  55. conn, err := dialGuarded(ctx, server.Host, server.Port, allowPrivate)
  56. if err != nil {
  57. return nil, describeDialError("IMAP", server, err)
  58. }
  59. options.TLSConfig = tlsConfigFor(server.Host, "")
  60. client, err = imapclient.NewStartTLS(conn, options)
  61. if err != nil {
  62. return nil, describeDialError("IMAP", server, describeTLSError(err))
  63. }
  64. case SecurityNone:
  65. conn, err := dialGuarded(ctx, server.Host, server.Port, allowPrivate)
  66. if err != nil {
  67. return nil, describeDialError("IMAP", server, err)
  68. }
  69. client = imapclient.New(conn, options)
  70. default:
  71. return nil, fmt.Errorf("unknown connection security %q", server.Security)
  72. }
  73. if err := client.WaitGreeting(); err != nil {
  74. client.Close()
  75. return nil, describeDialError("IMAP", server, err)
  76. }
  77. return client, nil
  78. }
  79. // authenticateIMAP signs in with a password or an OAuth access token.
  80. func (m *Manager) authenticateIMAP(ctx context.Context, client *imapclient.Client, account *Account) error {
  81. username := account.IMAP.Username
  82. if username == "" {
  83. username = account.Email
  84. }
  85. var err error
  86. switch account.Auth {
  87. case AuthOAuth2:
  88. var token string
  89. token, err = m.oauth.accessToken(ctx, account)
  90. if err != nil {
  91. return err
  92. }
  93. err = client.Authenticate(newXOAuth2Client(username, token))
  94. default:
  95. var password string
  96. password, err = m.box.Open(account.Secret)
  97. if err != nil {
  98. return &AuthError{Server: "IMAP", Detail: err.Error()}
  99. }
  100. caps := client.Caps()
  101. if caps.Has(imap.CapLoginDisabled) && caps.Has(imap.AuthCap(sasl.Plain)) {
  102. err = client.Authenticate(sasl.NewPlainClient("", username, password))
  103. } else {
  104. err = client.Login(username, password).Wait()
  105. }
  106. }
  107. if err != nil {
  108. return classifyLoginError("IMAP", account, err)
  109. }
  110. return nil
  111. }
  112. // classifyLoginError marks credential rejections as AuthError with a hint.
  113. func classifyLoginError(server string, account *Account, err error) error {
  114. var statusErr *imap.Error
  115. isAuth := false
  116. detail := err.Error()
  117. if errors.As(err, &statusErr) {
  118. detail = statusErr.Text
  119. switch statusErr.Code {
  120. case imap.ResponseCodeAuthenticationFailed, imap.ResponseCodeAuthorizationFailed,
  121. imap.ResponseCodeExpired, imap.ResponseCodeContactAdmin, imap.ResponseCodePrivacyRequired:
  122. isAuth = true
  123. }
  124. transient := statusErr.Code == imap.ResponseCodeUnavailable || statusErr.Code == imap.ResponseCodeServerBug ||
  125. statusErr.Code == imap.ResponseCodeLimit || statusErr.Code == imap.ResponseCodeInUse
  126. if statusErr.Type == imap.StatusResponseTypeNo && !isAuth && !transient {
  127. //A NO to LOGIN / AUTHENTICATE is a rejection whatever the wording
  128. isAuth = true
  129. }
  130. }
  131. if !isAuth && looksLikeAuthFailure(detail) {
  132. isAuth = true
  133. }
  134. if !isAuth {
  135. return err
  136. }
  137. hint := ""
  138. if account.Auth == AuthOAuth2 {
  139. hint = "Your sign-in has expired or was revoked. Reconnect the account to sign in again."
  140. } else {
  141. hint = authHintFor(account.Provider)
  142. if hint == "" {
  143. hint = authHintFor(providerForServer(account.IMAP.Host))
  144. }
  145. }
  146. return &AuthError{Server: server, Detail: strings.TrimSpace(detail), Hint: hint}
  147. }
  148. // providerForServer recognises a preset from a server host name, so hints
  149. // also work for accounts created as "custom" with known servers.
  150. func providerForServer(host string) string {
  151. host = strings.ToLower(host)
  152. for _, preset := range presets {
  153. if host == preset.IMAP.Host || host == preset.SMTP.Host {
  154. return preset.ID
  155. }
  156. }
  157. return ""
  158. }
  159. // describeDialError adds the server to connection failures.
  160. func describeDialError(protocol string, server ServerConfig, err error) error {
  161. if errors.Is(err, ErrBlockedAddress) {
  162. return err
  163. }
  164. var dnsErr *net.DNSError
  165. if errors.As(err, &dnsErr) {
  166. return fmt.Errorf("%s server %s could not be found", protocol, server.Host)
  167. }
  168. var opErr *net.OpError
  169. if errors.As(err, &opErr) && opErr.Op == "dial" {
  170. return fmt.Errorf("cannot connect to %s server %s:%d (%v)", protocol, server.Host, server.Port, opErr.Err)
  171. }
  172. return fmt.Errorf("%s %s:%d: %w", protocol, server.Host, server.Port, err)
  173. }