27 "golang.org/x/text/unicode/norm"
29 "github.com/mjl-/sconf"
31 "github.com/mjl-/mox/autotls"
32 "github.com/mjl-/mox/config"
33 "github.com/mjl-/mox/dns"
34 "github.com/mjl-/mox/mlog"
35 "github.com/mjl-/mox/moxio"
36 "github.com/mjl-/mox/moxvar"
37 "github.com/mjl-/mox/mtasts"
38 "github.com/mjl-/mox/smtp"
41var xlog = mlog.New("mox")
43// Config paths are set early in program startup. They will point to files in
46 ConfigStaticPath string
47 ConfigDynamicPath string
48 Conf = Config{Log: map[string]mlog.Level{"": mlog.LevelError}}
51// Config as used in the code, a processed version of what is in the config file.
53// Use methods to lookup a domain/account/address in the dynamic configuration.
55 Static config.Static // Does not change during the lifetime of a running instance.
57 logMutex sync.Mutex // For accessing the log levels.
58 Log map[string]mlog.Level
60 dynamicMutex sync.Mutex
61 Dynamic config.Dynamic // Can only be accessed directly by tests. Use methods on Config for locked access.
62 dynamicMtime time.Time
63 DynamicLastCheck time.Time // For use by quickstart only to skip checks.
64 // From canonical full address (localpart@domain, lower-cased when
65 // case-insensitive, stripped of catchall separator) to account and address.
66 // Domains are IDNA names in utf8.
67 accountDestinations map[string]AccountDestination
70type AccountDestination struct {
71 Catchall bool // If catchall destination for its domain.
72 Localpart smtp.Localpart // In original casing as written in config file.
74 Destination config.Destination
77// LogLevelSet sets a new log level for pkg. An empty pkg sets the default log
78// value that is used if no explicit log level is configured for a package.
79// This change is ephemeral, no config file is changed.
80func (c *Config) LogLevelSet(pkg string, level mlog.Level) {
82 defer c.logMutex.Unlock()
83 l := c.copyLogLevels()
86 xlog.Print("log level changed", mlog.Field("pkg", pkg), mlog.Field("level", mlog.LevelStrings[level]))
90// LogLevelRemove removes a configured log level for a package.
91func (c *Config) LogLevelRemove(pkg string) {
93 defer c.logMutex.Unlock()
94 l := c.copyLogLevels()
97 xlog.Print("log level cleared", mlog.Field("pkg", pkg))
101// copyLogLevels returns a copy of c.Log, for modifications.
102// must be called with log lock held.
103func (c *Config) copyLogLevels() map[string]mlog.Level {
104 m := map[string]mlog.Level{}
105 for pkg, level := range c.Log {
111// LogLevels returns a copy of the current log levels.
112func (c *Config) LogLevels() map[string]mlog.Level {
114 defer c.logMutex.Unlock()
115 return c.copyLogLevels()
118func (c *Config) withDynamicLock(fn func()) {
119 c.dynamicMutex.Lock()
120 defer c.dynamicMutex.Unlock()
122 if now.Sub(c.DynamicLastCheck) > time.Second {
123 c.DynamicLastCheck = now
124 if fi, err := os.Stat(ConfigDynamicPath); err != nil {
125 xlog.Errorx("stat domains config", err)
126 } else if !fi.ModTime().Equal(c.dynamicMtime) {
127 if errs := c.loadDynamic(); len(errs) > 0 {
128 xlog.Errorx("loading domains config", errs[0], mlog.Field("errors", errs))
130 xlog.Info("domains config reloaded")
131 c.dynamicMtime = fi.ModTime()
138// must be called with dynamic lock held.
139func (c *Config) loadDynamic() []error {
140 d, mtime, accDests, err := ParseDynamicConfig(context.Background(), ConfigDynamicPath, c.Static)
145 c.dynamicMtime = mtime
146 c.accountDestinations = accDests
147 c.allowACMEHosts(true)
151func (c *Config) Domains() (l []string) {
152 c.withDynamicLock(func() {
153 for name := range c.Dynamic.Domains {
157 sort.Slice(l, func(i, j int) bool {
163func (c *Config) Accounts() (l []string) {
164 c.withDynamicLock(func() {
165 for name := range c.Dynamic.Accounts {
172// DomainLocalparts returns a mapping of encoded localparts to account names for a
173// domain. An empty localpart is a catchall destination for a domain.
174func (c *Config) DomainLocalparts(d dns.Domain) map[string]string {
175 suffix := "@" + d.Name()
176 m := map[string]string{}
177 c.withDynamicLock(func() {
178 for addr, ad := range c.accountDestinations {
179 if strings.HasSuffix(addr, suffix) {
183 m[ad.Localpart.String()] = ad.Account
191func (c *Config) Domain(d dns.Domain) (dom config.Domain, ok bool) {
192 c.withDynamicLock(func() {
193 dom, ok = c.Dynamic.Domains[d.Name()]
198func (c *Config) Account(name string) (acc config.Account, ok bool) {
199 c.withDynamicLock(func() {
200 acc, ok = c.Dynamic.Accounts[name]
205func (c *Config) AccountDestination(addr string) (accDests AccountDestination, ok bool) {
206 c.withDynamicLock(func() {
207 accDests, ok = c.accountDestinations[addr]
212func (c *Config) WebServer() (r map[dns.Domain]dns.Domain, l []config.WebHandler) {
213 c.withDynamicLock(func() {
214 r = c.Dynamic.WebDNSDomainRedirects
215 l = c.Dynamic.WebHandlers
220func (c *Config) Routes(accountName string, domain dns.Domain) (accountRoutes, domainRoutes, globalRoutes []config.Route) {
221 c.withDynamicLock(func() {
222 acc := c.Dynamic.Accounts[accountName]
223 accountRoutes = acc.Routes
225 dom := c.Dynamic.Domains[domain.Name()]
226 domainRoutes = dom.Routes
228 globalRoutes = c.Dynamic.Routes
233func (c *Config) allowACMEHosts(checkACMEHosts bool) {
234 for _, l := range c.Static.Listeners {
235 if l.TLS == nil || l.TLS.ACME == "" {
239 m := c.Static.ACME[l.TLS.ACME].Manager
240 hostnames := map[dns.Domain]struct{}{}
242 hostnames[c.Static.HostnameDomain] = struct{}{}
243 if l.HostnameDomain.ASCII != "" {
244 hostnames[l.HostnameDomain] = struct{}{}
247 for _, dom := range c.Dynamic.Domains {
248 if l.AutoconfigHTTPS.Enabled && !l.AutoconfigHTTPS.NonTLS {
249 if d, err := dns.ParseDomain("autoconfig." + dom.Domain.ASCII); err != nil {
250 xlog.Errorx("parsing autoconfig domain", err, mlog.Field("domain", dom.Domain))
252 hostnames[d] = struct{}{}
256 if l.MTASTSHTTPS.Enabled && dom.MTASTS != nil && !l.MTASTSHTTPS.NonTLS {
257 d, err := dns.ParseDomain("mta-sts." + dom.Domain.ASCII)
259 xlog.Errorx("parsing mta-sts domain", err, mlog.Field("domain", dom.Domain))
261 hostnames[d] = struct{}{}
266 if l.WebserverHTTPS.Enabled {
267 for from := range c.Dynamic.WebDNSDomainRedirects {
268 hostnames[from] = struct{}{}
270 for _, wh := range c.Dynamic.WebHandlers {
271 hostnames[wh.DNSDomain] = struct{}{}
275 public := c.Static.Listeners["public"]
277 if len(public.NATIPs) > 0 {
283 m.SetAllowedHostnames(dns.StrictResolver{Pkg: "autotls"}, hostnames, ips, checkACMEHosts)
287// todo future: write config parsing & writing code that can read a config and remembers the exact tokens including newlines and comments, and can write back a modified file. the goal is to be able to write a config file automatically (after changing fields through the ui), but not loose comments and whitespace, to still get useful diffs for storing the config in a version control system.
289// must be called with lock held.
290func writeDynamic(ctx context.Context, log *mlog.Log, c config.Dynamic) error {
291 accDests, errs := prepareDynamicConfig(ctx, ConfigDynamicPath, Conf.Static, &c)
297 err := sconf.Write(&b, c)
301 f, err := os.OpenFile(ConfigDynamicPath, os.O_WRONLY, 0660)
308 log.Check(err, "closing file after error")
312 if _, err := f.Write(buf); err != nil {
313 return fmt.Errorf("write domains.conf: %v", err)
315 if err := f.Truncate(int64(len(buf))); err != nil {
316 return fmt.Errorf("truncate domains.conf after write: %v", err)
318 if err := f.Sync(); err != nil {
319 return fmt.Errorf("sync domains.conf after write: %v", err)
321 if err := moxio.SyncDir(filepath.Dir(ConfigDynamicPath)); err != nil {
322 return fmt.Errorf("sync dir of domains.conf after write: %v", err)
327 return fmt.Errorf("stat after writing domains.conf: %v", err)
330 if err := f.Close(); err != nil {
331 return fmt.Errorf("close written domains.conf: %v", err)
335 Conf.dynamicMtime = fi.ModTime()
336 Conf.DynamicLastCheck = time.Now()
338 Conf.accountDestinations = accDests
340 Conf.allowACMEHosts(true)
345// MustLoadConfig loads the config, quitting on errors.
346func MustLoadConfig(doLoadTLSKeyCerts, checkACMEHosts bool) {
347 errs := LoadConfig(context.Background(), doLoadTLSKeyCerts, checkACMEHosts)
349 xlog.Error("loading config file: multiple errors")
350 for _, err := range errs {
351 xlog.Errorx("config error", err)
353 xlog.Fatal("stopping after multiple config errors")
354 } else if len(errs) == 1 {
355 xlog.Fatalx("loading config file", errs[0])
359// LoadConfig attempts to parse and load a config, returning any errors
361func LoadConfig(ctx context.Context, doLoadTLSKeyCerts, checkACMEHosts bool) []error {
362 Shutdown, ShutdownCancel = context.WithCancel(context.Background())
363 Context, ContextCancel = context.WithCancel(context.Background())
365 c, errs := ParseConfig(ctx, ConfigStaticPath, false, doLoadTLSKeyCerts, checkACMEHosts)
370 mlog.SetConfig(c.Log)
375// SetConfig sets a new config. Not to be used during normal operation.
376func SetConfig(c *Config) {
377 // Cannot just assign *c to Conf, it would copy the mutex.
378 Conf = Config{c.Static, sync.Mutex{}, c.Log, sync.Mutex{}, c.Dynamic, c.dynamicMtime, c.DynamicLastCheck, c.accountDestinations}
380 // If we have non-standard CA roots, use them for all HTTPS requests.
381 if Conf.Static.TLS.CertPool != nil {
382 http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{
383 RootCAs: Conf.Static.TLS.CertPool,
387 moxvar.Pedantic = c.Static.Pedantic
390// ParseConfig parses the static config at path p. If checkOnly is true, no changes
391// are made, such as registering ACME identities. If doLoadTLSKeyCerts is true,
392// the TLS KeyCerts configuration is loaded and checked. This is used during the
393// quickstart in the case the user is going to provide their own certificates.
394// If checkACMEHosts is true, the hosts allowed for acme are compared with the
395// explicitly configured ips we are listening on.
396func ParseConfig(ctx context.Context, p string, checkOnly, doLoadTLSKeyCerts, checkACMEHosts bool) (c *Config, errs []error) {
398 Static: config.Static{
405 if os.IsNotExist(err) && os.Getenv("MOXCONF") == "" {
406 return nil, []error{fmt.Errorf("open config file: %v (hint: use mox -config ... or set MOXCONF=...)", err)}
408 return nil, []error{fmt.Errorf("open config file: %v", err)}
411 if err := sconf.Parse(f, &c.Static); err != nil {
412 return nil, []error{fmt.Errorf("parsing %s%v", p, err)}
415 if xerrs := PrepareStaticConfig(ctx, p, c, checkOnly, doLoadTLSKeyCerts); len(xerrs) > 0 {
419 pp := filepath.Join(filepath.Dir(p), "domains.conf")
420 c.Dynamic, c.dynamicMtime, c.accountDestinations, errs = ParseDynamicConfig(ctx, pp, c.Static)
423 c.allowACMEHosts(checkACMEHosts)
429// PrepareStaticConfig parses the static config file and prepares data structures
430// for starting mox. If checkOnly is set no substantial changes are made, like
431// creating an ACME registration.
432func PrepareStaticConfig(ctx context.Context, configFile string, conf *Config, checkOnly, doLoadTLSKeyCerts bool) (errs []error) {
433 addErrorf := func(format string, args ...any) {
434 errs = append(errs, fmt.Errorf(format, args...))
439 // check that mailbox is in unicode NFC normalized form.
440 checkMailboxNormf := func(mailbox string, format string, args ...any) {
441 s := norm.NFC.String(mailbox)
443 msg := fmt.Sprintf(format, args...)
444 addErrorf("%s: mailbox %q is not in NFC normalized form, should be %q", msg, mailbox, s)
448 // Post-process logging config.
449 if logLevel, ok := mlog.Levels[c.LogLevel]; ok {
450 conf.Log = map[string]mlog.Level{"": logLevel}
452 addErrorf("invalid log level %q", c.LogLevel)
454 for pkg, s := range c.PackageLogLevels {
455 if logLevel, ok := mlog.Levels[s]; ok {
456 conf.Log[pkg] = logLevel
458 addErrorf("invalid package log level %q", s)
465 u, err := user.Lookup(c.User)
466 var userErr user.UnknownUserError
467 if err != nil && errors.As(err, &userErr) {
468 uid, err := strconv.ParseUint(c.User, 10, 32)
470 addErrorf("parsing unknown user %s as uid: %v (hint: add user mox with \"useradd -d $PWD mox\" or specify a different username on the quickstart command-line)", c.User, err)
472 // We assume the same gid as uid.
476 } else if err != nil {
477 addErrorf("looking up user: %v", err)
479 if uid, err := strconv.ParseUint(u.Uid, 10, 32); err != nil {
480 addErrorf("parsing uid %s: %v", u.Uid, err)
484 if gid, err := strconv.ParseUint(u.Gid, 10, 32); err != nil {
485 addErrorf("parsing gid %s: %v", u.Gid, err)
491 hostname, err := dns.ParseDomain(c.Hostname)
493 addErrorf("parsing hostname: %s", err)
494 } else if hostname.Name() != c.Hostname {
495 addErrorf("hostname must be in IDNA form %q", hostname.Name())
497 c.HostnameDomain = hostname
499 for name, acme := range c.ACME {
503 acmeDir := dataDirPath(configFile, c.DataDir, "acme")
504 os.MkdirAll(acmeDir, 0770)
505 manager, err := autotls.Load(name, acmeDir, acme.ContactEmail, acme.DirectoryURL, Shutdown.Done())
507 addErrorf("loading ACME identity for %q: %s", name, err)
509 acme.Manager = manager
513 var haveUnspecifiedSMTPListener bool
514 for name, l := range c.Listeners {
515 if l.Hostname != "" {
516 d, err := dns.ParseDomain(l.Hostname)
518 addErrorf("bad listener hostname %q: %s", l.Hostname, err)
523 if l.TLS.ACME != "" && len(l.TLS.KeyCerts) != 0 {
524 addErrorf("listener %q: cannot have ACME and static key/certificates", name)
525 } else if l.TLS.ACME != "" {
526 acme, ok := c.ACME[l.TLS.ACME]
528 addErrorf("listener %q: unknown ACME provider %q", name, l.TLS.ACME)
531 // If only checking or with missing ACME definition, we don't have an acme manager,
532 // so set an empty tls config to continue.
533 var tlsconfig *tls.Config
534 if checkOnly || acme.Manager == nil {
535 tlsconfig = &tls.Config{}
537 tlsconfig = acme.Manager.TLSConfig.Clone()
538 l.TLS.ACMEConfig = acme.Manager.ACMETLSConfig
540 // SMTP STARTTLS connections are commonly made without SNI, because certificates
541 // often aren't validated.
542 hostname := c.HostnameDomain
543 if l.Hostname != "" {
544 hostname = l.HostnameDomain
546 getCert := tlsconfig.GetCertificate
547 tlsconfig.GetCertificate = func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
548 if hello.ServerName == "" {
549 hello.ServerName = hostname.ASCII
551 return getCert(hello)
554 l.TLS.Config = tlsconfig
555 } else if len(l.TLS.KeyCerts) != 0 {
556 if doLoadTLSKeyCerts {
557 if err := loadTLSKeyCerts(configFile, "listener "+name, l.TLS); err != nil {
562 addErrorf("listener %q: cannot have TLS config without ACME and without static keys/certificates", name)
566 var minVersion uint16 = tls.VersionTLS12
567 if l.TLS.MinVersion != "" {
568 versions := map[string]uint16{
569 "TLSv1.0": tls.VersionTLS10,
570 "TLSv1.1": tls.VersionTLS11,
571 "TLSv1.2": tls.VersionTLS12,
572 "TLSv1.3": tls.VersionTLS13,
574 v, ok := versions[l.TLS.MinVersion]
576 addErrorf("listener %q: unknown TLS mininum version %q", name, l.TLS.MinVersion)
580 if l.TLS.Config != nil {
581 l.TLS.Config.MinVersion = minVersion
583 if l.TLS.ACMEConfig != nil {
584 l.TLS.ACMEConfig.MinVersion = minVersion
587 var needsTLS []string
588 needtls := func(s string, v bool) {
590 needsTLS = append(needsTLS, s)
593 needtls("IMAPS", l.IMAPS.Enabled)
594 needtls("SMTP", l.SMTP.Enabled && !l.SMTP.NoSTARTTLS)
595 needtls("Submissions", l.Submissions.Enabled)
596 needtls("Submission", l.Submission.Enabled && !l.Submission.NoRequireSTARTTLS)
597 needtls("AccountHTTPS", l.AccountHTTPS.Enabled)
598 needtls("AdminHTTPS", l.AdminHTTPS.Enabled)
599 needtls("AutoconfigHTTPS", l.AutoconfigHTTPS.Enabled && !l.AutoconfigHTTPS.NonTLS)
600 needtls("MTASTSHTTPS", l.MTASTSHTTPS.Enabled && !l.MTASTSHTTPS.NonTLS)
601 needtls("WebserverHTTPS", l.WebserverHTTPS.Enabled)
602 if len(needsTLS) > 0 {
603 addErrorf("listener %q does not specify tls config, but requires tls for %s", name, strings.Join(needsTLS, ", "))
606 if l.AutoconfigHTTPS.Enabled && l.MTASTSHTTPS.Enabled && l.AutoconfigHTTPS.Port == l.MTASTSHTTPS.Port && l.AutoconfigHTTPS.NonTLS != l.MTASTSHTTPS.NonTLS {
607 addErrorf("listener %q tries to enable autoconfig and mta-sts enabled on same port but with both http and https", name)
611 haveUnspecifiedSMTPListener = true
613 for _, ipstr := range l.IPs {
614 ip := net.ParseIP(ipstr)
616 addErrorf("listener %q has invalid IP %q", name, ipstr)
619 if ip.IsUnspecified() {
620 haveUnspecifiedSMTPListener = true
623 if len(c.SpecifiedSMTPListenIPs) >= 2 {
624 haveUnspecifiedSMTPListener = true
625 } else if len(c.SpecifiedSMTPListenIPs) > 0 && (c.SpecifiedSMTPListenIPs[0].To4() == nil) == (ip.To4() == nil) {
626 haveUnspecifiedSMTPListener = true
628 c.SpecifiedSMTPListenIPs = append(c.SpecifiedSMTPListenIPs, ip)
632 for _, s := range l.SMTP.DNSBLs {
633 d, err := dns.ParseDomain(s)
635 addErrorf("listener %q has invalid DNSBL zone %q", name, s)
638 l.SMTP.DNSBLZones = append(l.SMTP.DNSBLZones, d)
640 if l.IPsNATed && len(l.NATIPs) > 0 {
641 addErrorf("listener %q has both IPsNATed and NATIPs (remove deprecated IPsNATed)", name)
643 for _, ipstr := range l.NATIPs {
644 ip := net.ParseIP(ipstr)
646 addErrorf("listener %q has invalid ip %q", name, ipstr)
647 } else if ip.IsUnspecified() || ip.IsLoopback() {
648 addErrorf("listener %q has NAT ip that is the unspecified or loopback address %s", name, ipstr)
651 checkPath := func(kind string, enabled bool, path string) {
652 if enabled && path != "" && !strings.HasPrefix(path, "/") {
653 addErrorf("listener %q has %s with path %q that must start with a slash", name, kind, path)
656 checkPath("AccountHTTP", l.AccountHTTP.Enabled, l.AccountHTTP.Path)
657 checkPath("AccountHTTPS", l.AccountHTTPS.Enabled, l.AccountHTTPS.Path)
658 checkPath("AdminHTTP", l.AdminHTTP.Enabled, l.AdminHTTP.Path)
659 checkPath("AdminHTTPS", l.AdminHTTPS.Enabled, l.AdminHTTPS.Path)
660 c.Listeners[name] = l
662 if haveUnspecifiedSMTPListener {
663 c.SpecifiedSMTPListenIPs = nil
666 var zerouse config.SpecialUseMailboxes
667 if len(c.DefaultMailboxes) > 0 && (c.InitialMailboxes.SpecialUse != zerouse || len(c.InitialMailboxes.Regular) > 0) {
668 addErrorf("cannot have both DefaultMailboxes and InitialMailboxes")
670 // DefaultMailboxes is deprecated.
671 for _, mb := range c.DefaultMailboxes {
672 checkMailboxNormf(mb, "default mailbox")
674 checkSpecialUseMailbox := func(nameOpt string) {
676 checkMailboxNormf(nameOpt, "special-use initial mailbox")
677 if strings.EqualFold(nameOpt, "inbox") {
678 addErrorf("initial mailbox cannot be set to Inbox (Inbox is always created)")
682 checkSpecialUseMailbox(c.InitialMailboxes.SpecialUse.Archive)
683 checkSpecialUseMailbox(c.InitialMailboxes.SpecialUse.Draft)
684 checkSpecialUseMailbox(c.InitialMailboxes.SpecialUse.Junk)
685 checkSpecialUseMailbox(c.InitialMailboxes.SpecialUse.Sent)
686 checkSpecialUseMailbox(c.InitialMailboxes.SpecialUse.Trash)
687 for _, name := range c.InitialMailboxes.Regular {
688 checkMailboxNormf(name, "regular initial mailbox")
689 if strings.EqualFold(name, "inbox") {
690 addErrorf("initial regular mailbox cannot be set to Inbox (Inbox is always created)")
694 checkTransportSMTP := func(name string, isTLS bool, t *config.TransportSMTP) {
696 t.DNSHost, err = dns.ParseDomain(t.Host)
698 addErrorf("transport %s: bad host %s: %v", name, t.Host, err)
701 if isTLS && t.STARTTLSInsecureSkipVerify {
702 addErrorf("transport %s: cannot have STARTTLSInsecureSkipVerify with immediate TLS")
704 if isTLS && t.NoSTARTTLS {
705 addErrorf("transport %s: cannot have NoSTARTTLS with immediate TLS")
711 seen := map[string]bool{}
712 for _, m := range t.Auth.Mechanisms {
714 addErrorf("transport %s: duplicate authentication mechanism %s", name, m)
718 case "SCRAM-SHA-256":
723 addErrorf("transport %s: unknown authentication mechanism %s", name, m)
727 t.Auth.EffectiveMechanisms = t.Auth.Mechanisms
728 if len(t.Auth.EffectiveMechanisms) == 0 {
729 t.Auth.EffectiveMechanisms = []string{"SCRAM-SHA-256", "SCRAM-SHA-1", "CRAM-MD5"}
733 checkTransportSocks := func(name string, t *config.TransportSocks) {
734 _, _, err := net.SplitHostPort(t.Address)
736 addErrorf("transport %s: bad address %s: %v", name, t.Address, err)
738 for _, ipstr := range t.RemoteIPs {
739 ip := net.ParseIP(ipstr)
741 addErrorf("transport %s: bad ip %s", name, ipstr)
743 t.IPs = append(t.IPs, ip)
746 t.Hostname, err = dns.ParseDomain(t.RemoteHostname)
748 addErrorf("transport %s: bad hostname %s: %v", name, t.RemoteHostname, err)
752 for name, t := range c.Transports {
754 if t.Submissions != nil {
756 checkTransportSMTP(name, true, t.Submissions)
758 if t.Submission != nil {
760 checkTransportSMTP(name, false, t.Submission)
764 checkTransportSMTP(name, false, t.SMTP)
768 checkTransportSocks(name, t.Socks)
771 addErrorf("transport %s: cannot have multiple methods in a transport", name)
775 // Load CA certificate pool.
777 if c.TLS.CA.AdditionalToSystem {
779 c.TLS.CertPool, err = x509.SystemCertPool()
781 addErrorf("fetching system CA cert pool: %v", err)
784 c.TLS.CertPool = x509.NewCertPool()
786 for _, certfile := range c.TLS.CA.CertFiles {
787 p := configDirPath(configFile, certfile)
788 pemBuf, err := os.ReadFile(p)
790 addErrorf("reading TLS CA cert file: %v", err)
792 } else if !c.TLS.CertPool.AppendCertsFromPEM(pemBuf) {
793 // todo: can we check more fully if we're getting some useful data back?
794 addErrorf("no CA certs added from %q", p)
801// PrepareDynamicConfig parses the dynamic config file given a static file.
802func ParseDynamicConfig(ctx context.Context, dynamicPath string, static config.Static) (c config.Dynamic, mtime time.Time, accDests map[string]AccountDestination, errs []error) {
803 addErrorf := func(format string, args ...any) {
804 errs = append(errs, fmt.Errorf(format, args...))
807 f, err := os.Open(dynamicPath)
809 addErrorf("parsing domains config: %v", err)
815 addErrorf("stat domains config: %v", err)
817 if err := sconf.Parse(f, &c); err != nil {
818 addErrorf("parsing dynamic config file: %v", err)
822 accDests, errs = prepareDynamicConfig(ctx, dynamicPath, static, &c)
823 return c, fi.ModTime(), accDests, errs
826func prepareDynamicConfig(ctx context.Context, dynamicPath string, static config.Static, c *config.Dynamic) (accDests map[string]AccountDestination, errs []error) {
827 log := xlog.WithContext(ctx)
829 addErrorf := func(format string, args ...any) {
830 errs = append(errs, fmt.Errorf(format, args...))
833 // Check that mailbox is in unicode NFC normalized form.
834 checkMailboxNormf := func(mailbox string, format string, args ...any) {
835 s := norm.NFC.String(mailbox)
837 msg := fmt.Sprintf(format, args...)
838 addErrorf("%s: mailbox %q is not in NFC normalized form, should be %q", msg, mailbox, s)
842 // Validate postmaster account exists.
843 if _, ok := c.Accounts[static.Postmaster.Account]; !ok {
844 addErrorf("postmaster account %q does not exist", static.Postmaster.Account)
846 checkMailboxNormf(static.Postmaster.Mailbox, "postmaster mailbox")
848 var haveSTSListener, haveWebserverListener bool
849 for _, l := range static.Listeners {
850 if l.MTASTSHTTPS.Enabled {
851 haveSTSListener = true
853 if l.WebserverHTTP.Enabled || l.WebserverHTTPS.Enabled {
854 haveWebserverListener = true
858 checkRoutes := func(descr string, routes []config.Route) {
859 parseRouteDomains := func(l []string) []string {
861 for _, e := range l {
867 if strings.HasPrefix(e, ".") {
871 d, err := dns.ParseDomain(e)
873 addErrorf("%s: invalid domain %s: %v", descr, e, err)
875 r = append(r, prefix+d.ASCII)
880 for i := range routes {
881 routes[i].FromDomainASCII = parseRouteDomains(routes[i].FromDomain)
882 routes[i].ToDomainASCII = parseRouteDomains(routes[i].ToDomain)
884 routes[i].ResolvedTransport, ok = static.Transports[routes[i].Transport]
886 addErrorf("%s: route references undefined transport %s", descr, routes[i].Transport)
891 checkRoutes("global routes", c.Routes)
894 for d, domain := range c.Domains {
895 dnsdomain, err := dns.ParseDomain(d)
897 addErrorf("bad domain %q: %s", d, err)
898 } else if dnsdomain.Name() != d {
899 addErrorf("domain %s must be specified in IDNA form, %s", d, dnsdomain.Name())
902 domain.Domain = dnsdomain
904 for _, sign := range domain.DKIM.Sign {
905 if _, ok := domain.DKIM.Selectors[sign]; !ok {
906 addErrorf("selector %s for signing is missing in domain %s", sign, d)
909 for name, sel := range domain.DKIM.Selectors {
910 seld, err := dns.ParseDomain(name)
912 addErrorf("bad selector %q: %s", name, err)
913 } else if seld.Name() != name {
914 addErrorf("selector %q must be specified in IDNA form, %q", name, seld.Name())
918 if sel.Expiration != "" {
919 exp, err := time.ParseDuration(sel.Expiration)
921 addErrorf("selector %q has invalid expiration %q: %v", name, sel.Expiration, err)
923 sel.ExpirationSeconds = int(exp / time.Second)
927 sel.HashEffective = sel.Hash
928 switch sel.HashEffective {
930 sel.HashEffective = "sha256"
932 log.Error("using sha1 with DKIM is deprecated as not secure enough, switch to sha256")
935 addErrorf("unsupported hash %q for selector %q in domain %s", sel.HashEffective, name, d)
938 pemBuf, err := os.ReadFile(configDirPath(dynamicPath, sel.PrivateKeyFile))
940 addErrorf("reading private key for selector %s in domain %s: %s", name, d, err)
943 p, _ := pem.Decode(pemBuf)
945 addErrorf("private key for selector %s in domain %s has no PEM block", name, d)
948 key, err := x509.ParsePKCS8PrivateKey(p.Bytes)
950 addErrorf("parsing private key for selector %s in domain %s: %s", name, d, err)
953 switch k := key.(type) {
954 case *rsa.PrivateKey:
955 if k.N.BitLen() < 1024 {
957 // Let's help user do the right thing.
958 addErrorf("rsa keys should be >= 1024 bits")
961 case ed25519.PrivateKey:
962 if sel.HashEffective != "sha256" {
963 addErrorf("hash algorithm %q is not supported with ed25519, only sha256 is", sel.HashEffective)
967 addErrorf("private key type %T not yet supported, at selector %s in domain %s", key, name, d)
970 if len(sel.Headers) == 0 {
974 // By default we seal signed headers, and we sign user-visible headers to
975 // prevent/limit reuse of previously signed messages: All addressing fields, date
976 // and subject, message-referencing fields, parsing instructions (content-type).
977 sel.HeadersEffective = strings.Split("From,To,Cc,Bcc,Reply-To,References,In-Reply-To,Subject,Date,Message-Id,Content-Type", ",")
980 for _, h := range sel.Headers {
981 from = from || strings.EqualFold(h, "From")
983 if strings.EqualFold(h, "DKIM-Signature") || strings.EqualFold(h, "Received") || strings.EqualFold(h, "Return-Path") {
984 log.Error("DKIM-signing header %q is recommended against as it may be modified in transit")
988 addErrorf("From-field must always be DKIM-signed")
990 sel.HeadersEffective = sel.Headers
993 domain.DKIM.Selectors[name] = sel
996 if domain.MTASTS != nil {
997 if !haveSTSListener {
998 addErrorf("MTA-STS enabled for domain %q, but there is no listener for MTASTS", d)
1000 sts := domain.MTASTS
1001 if sts.PolicyID == "" {
1002 addErrorf("invalid empty MTA-STS PolicyID")
1005 case mtasts.ModeNone, mtasts.ModeTesting, mtasts.ModeEnforce:
1007 addErrorf("invalid mtasts mode %q", sts.Mode)
1011 checkRoutes("routes for domain", domain.Routes)
1013 c.Domains[d] = domain
1016 // Validate email addresses.
1017 accDests = map[string]AccountDestination{}
1018 for accName, acc := range c.Accounts {
1020 acc.DNSDomain, err = dns.ParseDomain(acc.Domain)
1022 addErrorf("parsing domain %s for account %q: %s", acc.Domain, accName, err)
1025 if strings.EqualFold(acc.RejectsMailbox, "Inbox") {
1026 addErrorf("account %q: cannot set RejectsMailbox to inbox, messages will be removed automatically from the rejects mailbox", accName)
1028 checkMailboxNormf(acc.RejectsMailbox, "account %q", accName)
1030 if acc.AutomaticJunkFlags.JunkMailboxRegexp != "" {
1031 r, err := regexp.Compile(acc.AutomaticJunkFlags.JunkMailboxRegexp)
1033 addErrorf("invalid JunkMailboxRegexp regular expression: %v", err)
1037 if acc.AutomaticJunkFlags.NeutralMailboxRegexp != "" {
1038 r, err := regexp.Compile(acc.AutomaticJunkFlags.NeutralMailboxRegexp)
1040 addErrorf("invalid NeutralMailboxRegexp regular expression: %v", err)
1042 acc.NeutralMailbox = r
1044 if acc.AutomaticJunkFlags.NotJunkMailboxRegexp != "" {
1045 r, err := regexp.Compile(acc.AutomaticJunkFlags.NotJunkMailboxRegexp)
1047 addErrorf("invalid NotJunkMailboxRegexp regular expression: %v", err)
1049 acc.NotJunkMailbox = r
1051 c.Accounts[accName] = acc
1053 // todo deprecated: only localpart as keys for Destinations, we are replacing them with full addresses. if domains.conf is written, we won't have to do this again.
1054 replaceLocalparts := map[string]string{}
1056 for addrName, dest := range acc.Destinations {
1057 checkMailboxNormf(dest.Mailbox, "account %q, destination %q", accName, addrName)
1059 for i, rs := range dest.Rulesets {
1060 checkMailboxNormf(rs.Mailbox, "account %q, destination %q, ruleset %d", accName, addrName, i+1)
1064 if rs.SMTPMailFromRegexp != "" {
1066 r, err := regexp.Compile(rs.SMTPMailFromRegexp)
1068 addErrorf("invalid SMTPMailFrom regular expression: %v", err)
1070 c.Accounts[accName].Destinations[addrName].Rulesets[i].SMTPMailFromRegexpCompiled = r
1072 if rs.VerifiedDomain != "" {
1074 d, err := dns.ParseDomain(rs.VerifiedDomain)
1076 addErrorf("invalid VerifiedDomain: %v", err)
1078 c.Accounts[accName].Destinations[addrName].Rulesets[i].VerifiedDNSDomain = d
1081 var hdr [][2]*regexp.Regexp
1082 for k, v := range rs.HeadersRegexp {
1084 if strings.ToLower(k) != k {
1085 addErrorf("header field %q must only have lower case characters", k)
1087 if strings.ToLower(v) != v {
1088 addErrorf("header value %q must only have lower case characters", v)
1090 rk, err := regexp.Compile(k)
1092 addErrorf("invalid rule header regexp %q: %v", k, err)
1094 rv, err := regexp.Compile(v)
1096 addErrorf("invalid rule header regexp %q: %v", v, err)
1098 hdr = append(hdr, [...]*regexp.Regexp{rk, rv})
1100 c.Accounts[accName].Destinations[addrName].Rulesets[i].HeadersRegexpCompiled = hdr
1103 addErrorf("ruleset must have at least one rule")
1106 if rs.IsForward && rs.ListAllowDomain != "" {
1107 addErrorf("ruleset cannot have both IsForward and ListAllowDomain")
1110 if rs.SMTPMailFromRegexp == "" || rs.VerifiedDomain == "" {
1111 addErrorf("ruleset with IsForward must have both SMTPMailFromRegexp and VerifiedDomain too")
1114 if rs.ListAllowDomain != "" {
1115 d, err := dns.ParseDomain(rs.ListAllowDomain)
1117 addErrorf("invalid ListAllowDomain %q: %v", rs.ListAllowDomain, err)
1119 c.Accounts[accName].Destinations[addrName].Rulesets[i].ListAllowDNSDomain = d
1122 checkMailboxNormf(rs.AcceptRejectsToMailbox, "account %q, destination %q, ruleset %d, rejects mailbox", accName, addrName, i+1)
1123 if strings.EqualFold(rs.AcceptRejectsToMailbox, "inbox") {
1124 addErrorf("account %q, destination %q, ruleset %d: AcceptRejectsToMailbox cannot be set to Inbox", accName, addrName, i+1)
1128 // Catchall destination for domain.
1129 if strings.HasPrefix(addrName, "@") {
1130 d, err := dns.ParseDomain(addrName[1:])
1132 addErrorf("parsing domain %q in account %q", addrName[1:], accName)
1134 } else if _, ok := c.Domains[d.Name()]; !ok {
1135 addErrorf("unknown domain for address %q in account %q", addrName, accName)
1138 addrFull := "@" + d.Name()
1139 if _, ok := accDests[addrFull]; ok {
1140 addErrorf("duplicate canonicalized catchall destination address %s", addrFull)
1142 accDests[addrFull] = AccountDestination{true, "", accName, dest}
1146 // todo deprecated: remove support for parsing destination as just a localpart instead full address.
1147 var address smtp.Address
1148 if localpart, err := smtp.ParseLocalpart(addrName); err != nil && errors.Is(err, smtp.ErrBadLocalpart) {
1149 address, err = smtp.ParseAddress(addrName)
1151 addErrorf("invalid email address %q in account %q", addrName, accName)
1153 } else if _, ok := c.Domains[address.Domain.Name()]; !ok {
1154 addErrorf("unknown domain for address %q in account %q", addrName, accName)
1159 addErrorf("invalid localpart %q in account %q", addrName, accName)
1162 address = smtp.NewAddress(localpart, acc.DNSDomain)
1163 if _, ok := c.Domains[acc.DNSDomain.Name()]; !ok {
1164 addErrorf("unknown domain %s for account %q", acc.DNSDomain.Name(), accName)
1167 replaceLocalparts[addrName] = address.Pack(true)
1170 origLP := address.Localpart
1171 dc := c.Domains[address.Domain.Name()]
1172 if lp, err := CanonicalLocalpart(address.Localpart, dc); err != nil {
1173 addErrorf("canonicalizing localpart %s: %v", address.Localpart, err)
1174 } else if dc.LocalpartCatchallSeparator != "" && strings.Contains(string(address.Localpart), dc.LocalpartCatchallSeparator) {
1175 addErrorf("localpart of address %s includes domain catchall separator %s", address, dc.LocalpartCatchallSeparator)
1177 address.Localpart = lp
1179 addrFull := address.Pack(true)
1180 if _, ok := accDests[addrFull]; ok {
1181 addErrorf("duplicate canonicalized destination address %s", addrFull)
1183 accDests[addrFull] = AccountDestination{false, origLP, accName, dest}
1186 for lp, addr := range replaceLocalparts {
1187 dest, ok := acc.Destinations[lp]
1189 addErrorf("could not find localpart %q to replace with address in destinations", lp)
1191 log.Error(`deprecation warning: support for account destination addresses specified as just localpart ("username") instead of full email address will be removed in the future; update domains.conf, for each Account, for each Destination, ensure each key is an email address by appending "@" and the default domain for the account`, mlog.Field("localpart", lp), mlog.Field("address", addr), mlog.Field("account", accName))
1192 acc.Destinations[addr] = dest
1193 delete(acc.Destinations, lp)
1197 checkRoutes("routes for account", acc.Routes)
1200 // Set DMARC destinations.
1201 for d, domain := range c.Domains {
1202 dmarc := domain.DMARC
1206 if _, ok := c.Accounts[dmarc.Account]; !ok {
1207 addErrorf("DMARC account %q does not exist", dmarc.Account)
1209 lp, err := smtp.ParseLocalpart(dmarc.Localpart)
1211 addErrorf("invalid DMARC localpart %q: %s", dmarc.Localpart, err)
1213 if lp.IsInternational() {
1215 addErrorf("DMARC localpart %q is an internationalized address, only conventional ascii-only address possible for interopability", lp)
1217 addrdom := domain.Domain
1218 if dmarc.Domain != "" {
1219 addrdom, err = dns.ParseDomain(dmarc.Domain)
1221 addErrorf("DMARC domain %q: %s", dmarc.Domain, err)
1222 } else if _, ok := c.Domains[addrdom.Name()]; !ok {
1223 addErrorf("unknown domain %q for DMARC address in domain %q", dmarc.Domain, d)
1227 domain.DMARC.ParsedLocalpart = lp
1228 domain.DMARC.DNSDomain = addrdom
1229 c.Domains[d] = domain
1230 addrFull := smtp.NewAddress(lp, addrdom).String()
1231 dest := config.Destination{
1232 Mailbox: dmarc.Mailbox,
1235 checkMailboxNormf(dmarc.Mailbox, "DMARC mailbox for account %q", dmarc.Account)
1236 accDests[addrFull] = AccountDestination{false, lp, dmarc.Account, dest}
1239 // Set TLSRPT destinations.
1240 for d, domain := range c.Domains {
1241 tlsrpt := domain.TLSRPT
1245 if _, ok := c.Accounts[tlsrpt.Account]; !ok {
1246 addErrorf("TLSRPT account %q does not exist", tlsrpt.Account)
1248 lp, err := smtp.ParseLocalpart(tlsrpt.Localpart)
1250 addErrorf("invalid TLSRPT localpart %q: %s", tlsrpt.Localpart, err)
1252 if lp.IsInternational() {
1253 // Does not appear documented in
../rfc/8460, but similar to DMARC it makes sense
1254 // to keep this ascii-only addresses.
1255 addErrorf("TLSRPT localpart %q is an internationalized address, only conventional ascii-only address allowed for interopability", lp)
1257 addrdom := domain.Domain
1258 if tlsrpt.Domain != "" {
1259 addrdom, err = dns.ParseDomain(tlsrpt.Domain)
1261 addErrorf("TLSRPT domain %q: %s", tlsrpt.Domain, err)
1262 } else if _, ok := c.Domains[addrdom.Name()]; !ok {
1263 addErrorf("unknown domain %q for TLSRPT address in domain %q", tlsrpt.Domain, d)
1267 domain.TLSRPT.ParsedLocalpart = lp
1268 domain.TLSRPT.DNSDomain = addrdom
1269 c.Domains[d] = domain
1270 addrFull := smtp.NewAddress(lp, addrdom).String()
1271 dest := config.Destination{
1272 Mailbox: tlsrpt.Mailbox,
1275 checkMailboxNormf(tlsrpt.Mailbox, "TLSRPT mailbox for account %q", tlsrpt.Account)
1276 accDests[addrFull] = AccountDestination{false, lp, tlsrpt.Account, dest}
1279 // Check webserver configs.
1280 if (len(c.WebDomainRedirects) > 0 || len(c.WebHandlers) > 0) && !haveWebserverListener {
1281 addErrorf("WebDomainRedirects or WebHandlers configured but no listener with WebserverHTTP or WebserverHTTPS enabled")
1284 c.WebDNSDomainRedirects = map[dns.Domain]dns.Domain{}
1285 for from, to := range c.WebDomainRedirects {
1286 fromdom, err := dns.ParseDomain(from)
1288 addErrorf("parsing domain for redirect %s: %v", from, err)
1290 todom, err := dns.ParseDomain(to)
1292 addErrorf("parsing domain for redirect %s: %v", to, err)
1293 } else if fromdom == todom {
1294 addErrorf("will not redirect domain %s to itself", todom)
1296 var zerodom dns.Domain
1297 if _, ok := c.WebDNSDomainRedirects[fromdom]; ok && fromdom != zerodom {
1298 addErrorf("duplicate redirect domain %s", from)
1300 c.WebDNSDomainRedirects[fromdom] = todom
1303 for i := range c.WebHandlers {
1304 wh := &c.WebHandlers[i]
1306 if wh.LogName == "" {
1307 wh.Name = fmt.Sprintf("%d", i)
1309 wh.Name = wh.LogName
1312 dom, err := dns.ParseDomain(wh.Domain)
1314 addErrorf("webhandler %s %s: parsing domain: %v", wh.Domain, wh.PathRegexp, err)
1318 if !strings.HasPrefix(wh.PathRegexp, "^") {
1319 addErrorf("webhandler %s %s: path regexp must start with a ^", wh.Domain, wh.PathRegexp)
1321 re, err := regexp.Compile(wh.PathRegexp)
1323 addErrorf("webhandler %s %s: compiling regexp: %v", wh.Domain, wh.PathRegexp, err)
1328 if wh.WebStatic != nil {
1331 if ws.StripPrefix != "" && !strings.HasPrefix(ws.StripPrefix, "/") {
1332 addErrorf("webstatic %s %s: prefix to strip %s must start with a slash", wh.Domain, wh.PathRegexp, ws.StripPrefix)
1334 for k := range ws.ResponseHeaders {
1336 k := strings.TrimSpace(xk)
1337 if k != xk || k == "" {
1338 addErrorf("webstatic %s %s: bad header %q", wh.Domain, wh.PathRegexp, xk)
1342 if wh.WebRedirect != nil {
1344 wr := wh.WebRedirect
1345 if wr.BaseURL != "" {
1346 u, err := url.Parse(wr.BaseURL)
1348 addErrorf("webredirect %s %s: parsing redirect url %s: %v", wh.Domain, wh.PathRegexp, wr.BaseURL, err)
1354 addErrorf("webredirect %s %s: BaseURL must have empty path", wh.Domain, wh.PathRegexp, wr.BaseURL)
1358 if wr.OrigPathRegexp != "" && wr.ReplacePath != "" {
1359 re, err := regexp.Compile(wr.OrigPathRegexp)
1361 addErrorf("webredirect %s %s: compiling regexp %s: %v", wh.Domain, wh.PathRegexp, wr.OrigPathRegexp, err)
1364 } else if wr.OrigPathRegexp != "" || wr.ReplacePath != "" {
1365 addErrorf("webredirect %s %s: must have either both OrigPathRegexp and ReplacePath, or neither", wh.Domain, wh.PathRegexp)
1366 } else if wr.BaseURL == "" {
1367 addErrorf("webredirect %s %s: must at least one of BaseURL and OrigPathRegexp+ReplacePath", wh.Domain, wh.PathRegexp)
1369 if wr.StatusCode != 0 && (wr.StatusCode < 300 || wr.StatusCode >= 400) {
1370 addErrorf("webredirect %s %s: invalid redirect status code %d", wh.Domain, wh.PathRegexp, wr.StatusCode)
1373 if wh.WebForward != nil {
1376 u, err := url.Parse(wf.URL)
1378 addErrorf("webforward %s %s: parsing url %s: %v", wh.Domain, wh.PathRegexp, wf.URL, err)
1382 for k := range wf.ResponseHeaders {
1384 k := strings.TrimSpace(xk)
1385 if k != xk || k == "" {
1386 addErrorf("webforward %s %s: bad header %q", wh.Domain, wh.PathRegexp, xk)
1391 addErrorf("webhandler %s %s: must have exactly one handler, not %d", wh.Domain, wh.PathRegexp, n)
1398func loadTLSKeyCerts(configFile, kind string, ctls *config.TLS) error {
1399 certs := []tls.Certificate{}
1400 for _, kp := range ctls.KeyCerts {
1401 certPath := configDirPath(configFile, kp.CertFile)
1402 keyPath := configDirPath(configFile, kp.KeyFile)
1403 cert, err := loadX509KeyPairPrivileged(certPath, keyPath)
1405 return fmt.Errorf("tls config for %q: parsing x509 key pair: %v", kind, err)
1407 certs = append(certs, cert)
1409 ctls.Config = &tls.Config{
1410 Certificates: certs,
1415// load x509 key/cert files from file descriptor possibly passed in by privileged
1417func loadX509KeyPairPrivileged(certPath, keyPath string) (tls.Certificate, error) {
1418 certBuf, err := readFilePrivileged(certPath)
1420 return tls.Certificate{}, fmt.Errorf("reading tls certificate: %v", err)
1422 keyBuf, err := readFilePrivileged(keyPath)
1424 return tls.Certificate{}, fmt.Errorf("reading tls key: %v", err)
1426 return tls.X509KeyPair(certBuf, keyBuf)
1429// like os.ReadFile, but open privileged file possibly passed in by root process.
1430func readFilePrivileged(path string) ([]byte, error) {
1431 f, err := OpenPrivileged(path)
1436 return io.ReadAll(f)