Debian Codegraph @

config/accounts.go

raw
1 package config
2
3 import (
4 "bytes"
5 "cmp"
6 "errors"
7 "fmt"
8 "net/url"
9 "os"
10 "os/exec"
11 "path"
12 "reflect"
13 "regexp"
14 "slices"
15 "strings"
16 "time"
17
18 "git.sr.ht/~rjarry/aerc/lib/log"
19 "git.sr.ht/~rjarry/aerc/lib/xdg"
20 "github.com/emersion/go-message/mail"
21 "github.com/go-ini/ini"
22 )
23
24 var (
25 EnablePinentry func()
26 DisablePinentry func()
27 SetPinentryEnv func(*exec.Cmd)
28 )
29
30 type RemoteConfig struct {
31 Value string
32 PasswordCmd string
33 CacheCmd bool
34 cache string
35 }
36
37 func (c *RemoteConfig) parseValue() (*url.URL, error) {
38 return url.Parse(c.Value)
39 }
40
41 func (c *RemoteConfig) ConnectionString() (string, error) {
42 if c.Value == "" || c.PasswordCmd == "" {
43 return c.Value, nil
44 }
45
46 u, err := c.parseValue()
47 if err != nil {
48 return "", err
49 }
50
51 // ignore the command if a password is specified
52 if _, exists := u.User.Password(); exists {
53 return c.Value, nil
54 }
55
56 // don't attempt to parse the command if the url is a path (ie /usr/bin/sendmail)
57 if !u.IsAbs() {
58 return c.Value, nil
59 }
60
61 pw := c.cache
62
63 if pw == "" {
64 usePinentry := EnablePinentry != nil &&
65 DisablePinentry != nil &&
66 SetPinentryEnv != nil
67
68 cmd := exec.Command("sh", "-c", c.PasswordCmd)
69 cmd.Stdin = os.Stdin
70
71 buf := new(bytes.Buffer)
72 cmd.Stderr = buf
73
74 if usePinentry {
75 EnablePinentry()
76 defer DisablePinentry()
77 SetPinentryEnv(cmd)
78 }
79
80 output, err := cmd.Output()
81 if err != nil {
82 return "", fmt.Errorf("failed to read password: %v: %w",
83 buf.String(), err)
84 }
85 pw = strings.TrimSpace(string(output))
86 }
87 u.User = url.UserPassword(u.User.Username(), pw)
88 if c.CacheCmd {
89 c.cache = pw
90 }
91
92 return u.String(), nil
93 }
94
95 type AccountConfig struct {
96 Name string
97 Backend string
98 // backend specific
99 Params map[string]string
100
101 Archive string `ini:"archive" default:"Archive"`
102 CopyTo []string `ini:"copy-to" delim:","`
103 CopyToReplied bool `ini:"copy-to-replied" default:"false"`
104 StripBcc bool `ini:"strip-bcc" default:"true"`
105 Default string `ini:"default" default:"INBOX"`
106 Postpone string `ini:"postpone" default:"Drafts"`
107 From *mail.Address `ini:"from"`
108 UseEnvelopeFrom bool `ini:"use-envelope-from" default:"false"`
109 OriginalToHeader string `ini:"original-to-header"`
110 Aliases []*mail.Address `ini:"aliases"`
111 Source string `ini:"source" parse:"ParseSource"`
112 Folders []string `ini:"folders" delim:","`
113 FoldersExclude []string `ini:"folders-exclude" delim:","`
114 Headers []string `ini:"headers" delim:","`
115 HeadersExclude []string `ini:"headers-exclude" delim:","`
116 Outgoing RemoteConfig `ini:"outgoing" parse:"ParseOutgoing"`
117 SignatureFile string `ini:"signature-file"`
118 SignatureCmd string `ini:"signature-cmd"`
119 EnableFoldersSort bool `ini:"enable-folders-sort" default:"true"`
120 FoldersSort []string `ini:"folders-sort" delim:","`
121 AddressBookCmd string `ini:"address-book-cmd"`
122 SendAsUTC bool `ini:"send-as-utc" default:"false"`
123 SendWithHostname bool `ini:"send-with-hostname" default:"false"`
124 LocalizedRe *regexp.Regexp `ini:"subject-re-pattern" default:"(?i)^((AW|RE|SV|VS|ODP|R): ?)+"`
125 RestrictedDeletes bool `ini:"restrict-delete" default:"false"`
126
127 // CheckMail
128 CheckMail time.Duration `ini:"check-mail"`
129 CheckMailCmd string `ini:"check-mail-cmd"`
130 CheckMailTimeout time.Duration `ini:"check-mail-timeout" default:"10s"`
131 CheckMailInclude []string `ini:"check-mail-include"`
132 CheckMailExclude []string `ini:"check-mail-exclude"`
133
134 // Reconnection
135 ReconnectMaxWait time.Duration `ini:"reconnect-maxwait" default:"30s"`
136
137 // PGP Config
138 PgpKeyId string `ini:"pgp-key-id"`
139 PgpAutoSign bool `ini:"pgp-auto-sign"`
140 PgpAttachKey bool `ini:"pgp-attach-key"`
141 PgpOpportunisticEncrypt bool `ini:"pgp-opportunistic-encrypt"`
142 PgpErrorLevel int `ini:"pgp-error-level" parse:"ParsePgpErrorLevel" default:"warn"`
143 PgpSelfEncrypt bool `ini:"pgp-self-encrypt"`
144
145 // AuthRes
146 TrustedAuthRes []string `ini:"trusted-authres" delim:","`
147 }
148
149 const (
150 PgpErrorLevelNone = iota
151 PgpErrorLevelWarn
152 PgpErrorLevelError
153 )
154
155 var Accounts []*AccountConfig
156
157 func parseAccountsFromFile(root string, accts []string, filename string) error {
158 log.Debugf("Parsing accounts configuration from %s", filename)
159
160 file, err := ini.LoadSources(ini.LoadOptions{
161 KeyValueDelimiters: "=",
162 }, filename)
163 if err != nil {
164 return err
165 }
166
167 starttls_warned := false
168 var globals *ini.Section
169 for _, _sec := range file.SectionStrings() {
170 if _sec == "DEFAULT" {
171 globals = file.Section(_sec)
172 continue
173 }
174 if len(accts) > 0 && !contains(accts, _sec) {
175 continue
176 }
177 sec := file.Section(_sec)
178 for key, val := range globals.KeysHash() {
179 if !sec.HasKey(key) {
180 _, _ = sec.NewKey(key, val)
181 }
182 }
183
184 account, err := ParseAccountConfig(_sec, sec)
185 if err != nil {
186 log.Errorf("failed to load account [%s]: %s", _sec, err)
187 Warnings = append(Warnings, Warning{
188 Title: "accounts.conf: error",
189 Body: fmt.Sprintf(
190 "Failed to load account [%s]:\n\n%s",
191 _sec, err,
192 ),
193 })
194 continue
195 }
196 if _, ok := account.Params["smtp-starttls"]; ok && !starttls_warned {
197 Warnings = append(Warnings, Warning{
198 Title: "accounts.conf: smtp-starttls is deprecated",
199 Body: `
200 SMTP connections now use STARTTLS by default and the smtp-starttls setting is ignored.
201
202 If you want to disable STARTTLS, append +insecure to the schema.
203 `,
204 })
205 starttls_warned = true
206 }
207
208 if strings.HasPrefix(account.Source, "notmuch://") {
209 if _, ok := account.Params["maildir-store"]; ok {
210 Warnings = append(Warnings, Warning{
211 Title: "accounts.conf: maildir-store is deprecated",
212 Body: fmt.Sprintf(`
213 [%s] stripping maildir-store
214
215 The maildir-store option has been replaced by enable-maildir (default: true).
216 The maildir root is now always obtained from the notmuch database.
217
218 Please remove maildir-store from your accounts.conf.
219 `, account.Name),
220 })
221 delete(account.Params, "maildir-store")
222 }
223
224 u, err := url.Parse(account.Source)
225 if err == nil && (u.Hostname()+u.Path) != "" {
226 p := xdg.ExpandHome(u.Hostname() + u.Path)
227 if _, serr := os.Stat(p); serr == nil {
228 Warnings = append(Warnings, Warning{
229 Title: "accounts.conf: notmuch source URL is deprecated",
230 Body: fmt.Sprintf(`
231 [%s] stripping database path from source URL
232
233 Explicit database paths in the notmuch source URL are no longer supported.
234
235 The database is now discovered automatically via environment variables
236 (NOTMUCH_CONFIG, NOTMUCH_DATABASE, NOTMUCH_PROFILE) or XDG conventions.
237
238 Please update your accounts.conf:
239
240 source = notmuch://
241 `, account.Name),
242 })
243 account.Source = "notmuch://"
244 }
245 }
246 }
247
248 log.Debugf("accounts.conf: [%s] from = %s", account.Name, account.From)
249 Accounts = append(Accounts, account)
250 }
251 if len(accts) > 0 {
252 // Sort accounts struct to match the specified order, if we
253 // have one
254 var acctnames []string
255 for _, acc := range Accounts {
256 acctnames = append(acctnames, acc.Name)
257 }
258 var sortaccts []string
259 for _, acc := range accts {
260 if contains(acctnames, acc) {
261 sortaccts = append(sortaccts, acc)
262 } else {
263 log.Errorf("account [%s] not found", acc)
264 }
265 }
266
267 idx := make(map[string]int)
268 for i, acct := range sortaccts {
269 idx[acct] = i
270 }
271 slices.SortFunc(Accounts, func(a, b *AccountConfig) int {
272 return cmp.Compare(idx[a.Name], idx[b.Name])
273 })
274 }
275
276 return nil
277 }
278
279 func parseAccounts(root string, accts []string, filename string) error {
280 if filename == "" {
281 filename = path.Join(root, "accounts.conf")
282 err := checkConfigPerms(filename)
283 if errors.Is(err, os.ErrNotExist) {
284 // No config triggers account configuration wizard
285 return nil
286 } else if err != nil {
287 return err
288 }
289 }
290
291 if err := parseAccountsFromFile(root, accts, filename); err != nil {
292 return fmt.Errorf("%s: %w", filename, err)
293 }
294
295 return nil
296 }
297
298 func ParseAccountConfig(name string, section *ini.Section) (*AccountConfig, error) {
299 account := AccountConfig{
300 Name: name,
301 Params: make(map[string]string),
302 }
303 if err := MapToStruct(section, &account, true); err != nil {
304 return nil, err
305 }
306 for key, val := range section.KeysHash() {
307 backendSpecific := true
308 typ := reflect.TypeFor[AccountConfig]()
309 for i := 0; i < typ.NumField(); i++ {
310 field := typ.Field(i)
311 if field.Tag.Get("ini") == key {
312 backendSpecific = false
313 break
314 }
315 }
316 if backendSpecific {
317 account.Params[key] = val
318 }
319 }
320 if account.Source == "" {
321 return nil, fmt.Errorf("missing 'source' parameter")
322 }
323
324 account.Backend = parseBackend(account.Source)
325 if account.From == nil {
326 return nil, fmt.Errorf("missing 'from' parameter")
327 }
328 if len(account.Headers) > 0 {
329 defaults := []string{
330 "date",
331 "subject",
332 "from",
333 "sender",
334 "reply-to",
335 "to",
336 "cc",
337 "bcc",
338 "in-reply-to",
339 "message-id",
340 "references",
341 }
342 account.Headers = append(account.Headers, defaults...)
343 }
344 return &account, nil
345 }
346
347 func parseBackend(source string) string {
348 u, err := url.Parse(source)
349 if err != nil {
350 return ""
351 }
352 if strings.HasPrefix(u.Scheme, "imap") {
353 return "imap"
354 }
355 if strings.HasPrefix(u.Scheme, "maildir") {
356 return "maildir"
357 }
358 if strings.HasPrefix(u.Scheme, "jmap") {
359 return "jmap"
360 }
361 return u.Scheme
362 }
363
364 func (a *AccountConfig) ParseSource(sec *ini.Section, key *ini.Key) (string, error) {
365 var remote RemoteConfig
366 remote.Value = key.String()
367 if k, err := sec.GetKey("source-cred-cmd"); err == nil {
368 remote.PasswordCmd = k.String()
369 }
370 return remote.ConnectionString()
371 }
372
373 func (a *AccountConfig) ParseOutgoing(sec *ini.Section, key *ini.Key) (RemoteConfig, error) {
374 var remote RemoteConfig
375 remote.Value = key.String()
376 if k, err := sec.GetKey("outgoing-cred-cmd"); err == nil {
377 remote.PasswordCmd = k.String()
378 }
379 if k, err := sec.GetKey("outgoing-cred-cmd-cache"); err == nil {
380 cache, err := k.Bool()
381 if err != nil {
382 return remote, err
383 }
384 remote.CacheCmd = cache
385 }
386 _, err := remote.parseValue()
387 return remote, err
388 }
389
390 func (a *AccountConfig) ParsePgpErrorLevel(sec *ini.Section, key *ini.Key) (int, error) {
391 var level int
392 var err error
393 switch strings.ToLower(key.String()) {
394 case "none":
395 level = PgpErrorLevelNone
396 case "warn":
397 level = PgpErrorLevelWarn
398 case "error":
399 level = PgpErrorLevelError
400 default:
401 err = fmt.Errorf("unknown level: %s", key.String())
402 }
403 return level, err
404 }
405
406 // checkConfigPerms checks for too open permissions
407 // printing the fix on stdout and returning an error
408 func checkConfigPerms(filename string) error {
409 info, err := os.Stat(filename)
410 if err != nil {
411 return err
412 }
413
414 perms := info.Mode().Perm()
415 if perms&0o44 != 0 && !General().UnsafeAccountsConf {
416 // group or others have read access
417 fmt.Fprintf(os.Stderr, "The file %v has too open permissions.\n", filename)
418 fmt.Fprintln(os.Stderr, "This is a security issue (it contains passwords).")
419 fmt.Fprintf(os.Stderr, "To fix it, run `chmod 600 %v`\n", filename)
420 return errors.New("account.conf permissions too lax")
421 }
422 return nil
423 }