maddy

Fork https://github.com/foxcpp/maddy

git clone git://git.lin.moe/go/maddy.git

 1/*
 2Maddy Mail Server - Composable all-in-one email server.
 3Copyright © 2019-2020 Max Mazurov <fox.cpp@disroot.org>, Maddy Mail Server contributors
 4
 5This program is free software: you can redistribute it and/or modify
 6it under the terms of the GNU General Public License as published by
 7the Free Software Foundation, either version 3 of the License, or
 8(at your option) any later version.
 9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program.  If not, see <https://www.gnu.org/licenses/>.
17*/
18
19package table
20
21import (
22	"context"
23	"fmt"
24
25	"github.com/foxcpp/maddy/framework/address"
26	"github.com/foxcpp/maddy/framework/config"
27	"github.com/foxcpp/maddy/framework/log"
28	"github.com/foxcpp/maddy/framework/module"
29)
30
31type EmailWithDomain struct {
32	modName  string
33	instName string
34	domains  []string
35	log      log.Logger
36}
37
38func NewEmailWithDomain(modName, instName string, _, inlineArgs []string) (module.Module, error) {
39	return &EmailWithDomain{
40		modName:  modName,
41		instName: instName,
42		domains:  inlineArgs,
43		log:      log.Logger{Name: modName},
44	}, nil
45}
46
47func (s *EmailWithDomain) Init(cfg *config.Map) error {
48	for _, d := range s.domains {
49		if !address.ValidDomain(d) {
50			return fmt.Errorf("%s: invalid domain: %s", s.modName, d)
51		}
52	}
53	if len(s.domains) == 0 {
54		return fmt.Errorf("%s: at least one domain is required", s.modName)
55	}
56
57	return nil
58}
59
60func (s *EmailWithDomain) Name() string {
61	return s.modName
62}
63
64func (s *EmailWithDomain) InstanceName() string {
65	return s.modName
66}
67
68func (s *EmailWithDomain) Lookup(ctx context.Context, key string) (string, bool, error) {
69	quotedMbox := address.QuoteMbox(key)
70
71	if len(s.domains) == 0 {
72		s.log.Msg("only first domain is used when expanding key", "key", key, "domain", s.domains[0])
73	}
74
75	return quotedMbox + "@" + s.domains[0], true, nil
76}
77
78func (s *EmailWithDomain) LookupMulti(ctx context.Context, key string) ([]string, error) {
79	quotedMbox := address.QuoteMbox(key)
80	emails := make([]string, len(s.domains))
81	for i, domain := range s.domains {
82		emails[i] = quotedMbox + "@" + domain
83	}
84	return emails, nil
85}
86
87func init() {
88	module.Register("table.email_with_domain", NewEmailWithDomain)
89}