aboutsummaryrefslogtreecommitdiffstats
path: root/config/accounts.go
blob: eec6ca445731a786044fc969c618eb769ad3cc24 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package config

import (
	"errors"
	"fmt"
	"net/url"
	"os"
	"os/exec"
	"path"
	"reflect"
	"regexp"
	"sort"
	"strings"
	"time"

	"git.sr.ht/~rjarry/aerc/log"
	"github.com/emersion/go-message/mail"
	"github.com/go-ini/ini"
)

type RemoteConfig struct {
	Value       string
	PasswordCmd string
	CacheCmd    bool
	cache       string
}

func (c *RemoteConfig) parseValue() (*url.URL, error) {
	return url.Parse(c.Value)
}

func (c *RemoteConfig) ConnectionString() (string, error) {
	if c.Value == "" || c.PasswordCmd == "" {
		return c.Value, nil
	}

	u, err := c.parseValue()
	if err != nil {
		return "", err
	}

	// ignore the command if a password is specified
	if _, exists := u.User.Password(); exists {
		return c.Value, nil
	}

	// don't attempt to parse the command if the url is a path (ie /usr/bin/sendmail)
	if !u.IsAbs() {
		return c.Value, nil
	}

	pw := c.cache

	if pw == "" {
		cmd := exec.Command("sh", "-c", c.PasswordCmd)
		cmd.Stdin = os.Stdin
		output, err := cmd.Output()
		if err != nil {
			return "", fmt.Errorf("failed to read password: %w", err)
		}
		pw = strings.TrimSpace(string(output))
	}
	u.User = url.UserPassword(u.User.Username(), pw)
	if c.CacheCmd {
		c.cache = pw
	}

	return u.String(), nil
}

type AccountConfig struct {
	Name string
	// backend specific
	Params map[string]string

	Archive           string          `ini:"archive" default:"Archive"`
	CopyTo            string          `ini:"copy-to"`
	Default           string          `ini:"default" default:"INBOX"`
	Postpone          string          `ini:"postpone" default:"Drafts"`
	From              *mail.Address   `ini:"from"`
	Aliases           []*mail.Address `ini:"aliases"`
	Source            string          `ini:"source" parse:"ParseSource"`
	Folders           []string        `ini:"folders" delim:","`
	FoldersExclude    []string        `ini:"folders-exclude" delim:","`
	Headers           []string        `ini:"headers" delim:","`
	HeadersExclude    []string        `ini:"headers-exclude" delim:","`
	Outgoing          RemoteConfig    `ini:"outgoing" parse:"ParseOutgoing"`
	SignatureFile     string          `ini:"signature-file"`
	SignatureCmd      string          `ini:"signature-cmd"`
	EnableFoldersSort bool            `ini:"enable-folders-sort" default:"true"`
	FoldersSort       []string        `ini:"folders-sort" delim:","`
	AddressBookCmd    string          `ini:"address-book-cmd"`
	SendAsUTC         bool            `ini:"send-as-utc" default:"false"`
	LocalizedRe       *regexp.Regexp  `ini:"subject-re-pattern" default:"(?i)^((AW|RE|SV|VS|ODP|R): ?)+"`

	// CheckMail
	CheckMail        time.Duration `ini:"check-mail"`
	CheckMailCmd     string        `ini:"check-mail-cmd"`
	CheckMailTimeout time.Duration `ini:"check-mail-timeout" default:"10s"`
	CheckMailInclude []string      `ini:"check-mail-include"`
	CheckMailExclude []string      `ini:"check-mail-exclude"`

	// PGP Config
	PgpKeyId                string `ini:"pgp-key-id"`
	PgpAutoSign             bool   `ini:"pgp-auto-sign"`
	PgpOpportunisticEncrypt bool   `ini:"pgp-opportunistic-encrypt"`
	PgpErrorLevel           int    `ini:"pgp-error-level" parse:"ParsePgpErrorLevel" default:"warn"`

	// AuthRes
	TrustedAuthRes []string `ini:"trusted-authres" delim:","`
}

const (
	PgpErrorLevelNone = iota
	PgpErrorLevelWarn
	PgpErrorLevelError
)

var Accounts []*AccountConfig

func parseAccounts(root string, accts []string) error {
	filename := path.Join(root, "accounts.conf")
	err := checkConfigPerms(filename)
	if errors.Is(err, os.ErrNotExist) {
		// No config triggers account configuration wizard
		return nil
	} else if err != nil {
		return err
	}

	log.Debugf("Parsing accounts configuration from %s", filename)

	file, err := ini.LoadSources(ini.LoadOptions{
		KeyValueDelimiters: "=",
	}, filename)
	if err != nil {
		return err
	}

	starttls_warned := false
	for _, _sec := range file.SectionStrings() {
		if _sec == "DEFAULT" {
			continue
		}
		if len(accts) > 0 && !contains(accts, _sec) {
			continue
		}
		sec := file.Section(_sec)
		account := AccountConfig{
			Name:   _sec,
			Params: make(map[string]string),
		}
		if err = MapToStruct(sec, &account, true); err != nil {
			return err
		}
		for key, val := range sec.KeysHash() {
			backendSpecific := true
			typ := reflect.TypeOf(account)
			for i := 0; i < typ.NumField(); i++ {
				field := typ.Field(i)
				if field.Tag.Get("ini") == key {
					backendSpecific = false
					break
				}
			}
			if backendSpecific {
				account.Params[key] = val
			}
		}
		if _, ok := account.Params["smtp-starttls"]; ok && !starttls_warned {
			Warnings = append(Warnings, Warning{
				Title: "accounts.conf: smtp-starttls is deprecated",
				Body: `
SMTP connections now use STARTTLS by default and the smtp-starttls setting is ignored.

If you want to disable STARTTLS, append +insecure to the schema.
`,
			})
			starttls_warned = true
		}
		if account.Source == "" {
			return fmt.Errorf("Expected source for account %s", _sec)
		}
		if account.From == nil {
			return fmt.Errorf("Expected from for account %s", _sec)
		}
		if len(account.Headers) > 0 {
			defaults := []string{
				"date",
				"subject",
				"from",
				"sender",
				"reply-to",
				"to",
				"cc",
				"bcc",
				"in-reply-to",
				"message-id",
				"references",
			}
			account.Headers = append(account.Headers, defaults...)
		}

		log.Debugf("accounts.conf: [%s] from = %s", account.Name, account.From)
		Accounts = append(Accounts, &account)
	}
	if len(accts) > 0 {
		// Sort accounts struct to match the specified order, if we
		// have one
		if len(Accounts) != len(accts) {
			return errors.New("account(s) not found")
		}
		sort.Slice(Accounts, func(i, j int) bool {
			return strings.ToLower(accts[i]) < strings.ToLower(accts[j])
		})
	}

	return nil
}

func (a *AccountConfig) ParseSource(sec *ini.Section, key *ini.Key) (string, error) {
	var remote RemoteConfig
	remote.Value = key.String()
	if k, err := sec.GetKey("source-cred-cmd"); err == nil {
		remote.PasswordCmd = k.String()
	}
	return remote.ConnectionString()
}

func (a *AccountConfig) ParseOutgoing(sec *ini.Section, key *ini.Key) (RemoteConfig, error) {
	var remote RemoteConfig
	remote.Value = key.String()
	if k, err := sec.GetKey("outgoing-cred-cmd"); err == nil {
		remote.PasswordCmd = k.String()
	}
	if k, err := sec.GetKey("outgoing-cred-cmd-cache"); err == nil {
		cache, err := k.Bool()
		if err != nil {
			return remote, err
		}
		remote.CacheCmd = cache
	}
	_, err := remote.parseValue()
	return remote, err
}

func (a *AccountConfig) ParsePgpErrorLevel(sec *ini.Section, key *ini.Key) (int, error) {
	var level int
	var err error
	switch strings.ToLower(key.String()) {
	case "none":
		level = PgpErrorLevelNone
	case "warn":
		level = PgpErrorLevelWarn
	case "error":
		level = PgpErrorLevelError
	default:
		err = fmt.Errorf("unknown level: %s", key.String())
	}
	return level, err
}

// checkConfigPerms checks for too open permissions
// printing the fix on stdout and returning an error
func checkConfigPerms(filename string) error {
	info, err := os.Stat(filename)
	if err != nil {
		return err
	}

	perms := info.Mode().Perm()
	if perms&0o44 != 0 && !General.UnsafeAccountsConf {
		// group or others have read access
		fmt.Fprintf(os.Stderr, "The file %v has too open permissions.\n", filename)
		fmt.Fprintln(os.Stderr, "This is a security issue (it contains passwords).")
		fmt.Fprintf(os.Stderr, "To fix it, run `chmod 600 %v`\n", filename)
		return errors.New("account.conf permissions too lax")
	}
	return nil
}