forked from albertito/chasquid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chasquid.go
286 lines (242 loc) · 7.21 KB
/
chasquid.go
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
281
282
283
284
285
286
// chasquid is an SMTP (email) server, with a focus on simplicity, security,
// and ease of operation.
//
// See https://blitiri.com.ar/p/chasquid for more details.
package main
import (
"context"
"flag"
"fmt"
"math/rand"
"net"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"blitiri.com.ar/go/chasquid/internal/config"
"blitiri.com.ar/go/chasquid/internal/courier"
"blitiri.com.ar/go/chasquid/internal/dovecot"
"blitiri.com.ar/go/chasquid/internal/maillog"
"blitiri.com.ar/go/chasquid/internal/normalize"
"blitiri.com.ar/go/chasquid/internal/smtpsrv"
"blitiri.com.ar/go/chasquid/internal/sts"
"blitiri.com.ar/go/chasquid/internal/userdb"
"blitiri.com.ar/go/log"
"blitiri.com.ar/go/systemd"
)
// Command-line flags.
var (
configDir = flag.String("config_dir", "/etc/chasquid",
"configuration directory")
configOverrides = flag.String("config_overrides", "",
"override configuration values (in text protobuf format)")
showVer = flag.Bool("version", false, "show version and exit")
)
func main() {
flag.Parse()
log.Init()
parseVersionInfo()
if *showVer {
fmt.Printf("chasquid %s (source date: %s)\n", version, sourceDate)
return
}
log.Infof("chasquid starting (version %s)", version)
// Seed the PRNG, just to prevent for it to be totally predictable.
rand.Seed(time.Now().UnixNano())
conf, err := config.Load(*configDir+"/chasquid.conf", *configOverrides)
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
config.LogConfig(conf)
// Change to the config dir.
// This allow us to use relative paths for configuration directories.
// It also can be useful in unusual environments and for testing purposes,
// where paths inside the configuration itself could be relative, and this
// fixes the point of reference.
err = os.Chdir(*configDir)
if err != nil {
log.Fatalf("Error changing to config dir %q: %v", *configDir, err)
}
initMailLog(conf.MailLogPath)
go signalHandler()
if conf.MonitoringAddress != "" {
go launchMonitoringServer(conf)
}
s := smtpsrv.NewServer()
s.Hostname = conf.Hostname
s.MaxDataSize = conf.MaxDataSizeMb * 1024 * 1024
s.HookPath = "hooks/"
s.HAProxyEnabled = conf.HaproxyIncoming
s.SetAliasesConfig(*conf.SuffixSeparators, *conf.DropCharacters)
if conf.DovecotAuth {
loadDovecot(s, conf.DovecotUserdbPath, conf.DovecotClientPath)
}
// Load certificates from "certs/<directory>/{fullchain,privkey}.pem".
// The structure matches letsencrypt's, to make it easier for that case.
log.Infof("Loading certificates")
for _, info := range mustReadDir("certs/") {
if !info.IsDir() {
// Skip non-directories.
continue
}
name := info.Name()
dir := filepath.Join("certs/", name)
log.Infof(" %s", name)
certPath := filepath.Join(dir, "fullchain.pem")
if _, err := os.Stat(certPath); os.IsNotExist(err) {
continue
}
keyPath := filepath.Join(dir, "privkey.pem")
if _, err := os.Stat(keyPath); os.IsNotExist(err) {
continue
}
err := s.AddCerts(certPath, keyPath)
if err != nil {
log.Fatalf(" %v", err)
}
}
// Load domains from "domains/".
log.Infof("Domain config paths:")
for _, info := range mustReadDir("domains/") {
domain, err := normalize.Domain(info.Name())
if err != nil {
log.Fatalf("Invalid name %+q: %v", info.Name(), err)
}
dir := filepath.Join("domains", info.Name())
loadDomain(domain, dir, s)
}
// Always include localhost as local domain.
// This can prevent potential trouble if we were to accidentally treat it
// as a remote domain (for loops, alias resolutions, etc.).
s.AddDomain("localhost")
dinfo := s.InitDomainInfo(conf.DataDir + "/domaininfo")
stsCache, err := sts.NewCache(conf.DataDir + "/sts-cache")
if err != nil {
log.Fatalf("Failed to initialize STS cache: %v", err)
}
go stsCache.PeriodicallyRefresh(context.Background())
localC := &courier.MDA{
Binary: conf.MailDeliveryAgentBin,
Args: conf.MailDeliveryAgentArgs,
Timeout: 30 * time.Second,
}
remoteC := &courier.SMTP{
HelloDomain: conf.Hostname,
Dinfo: dinfo,
STSCache: stsCache,
}
s.InitQueue(conf.DataDir+"/queue", localC, remoteC)
// Load the addresses and listeners.
systemdLs, err := systemd.Listeners()
if err != nil {
log.Fatalf("Error getting systemd listeners: %v", err)
}
naddr := loadAddresses(s, conf.SmtpAddress,
systemdLs["smtp"], smtpsrv.ModeSMTP)
naddr += loadAddresses(s, conf.SubmissionAddress,
systemdLs["submission"], smtpsrv.ModeSubmission)
naddr += loadAddresses(s, conf.SubmissionOverTlsAddress,
systemdLs["submission_tls"], smtpsrv.ModeSubmissionTLS)
if naddr == 0 {
log.Fatalf("No address to listen on")
}
s.ListenAndServe()
}
func loadAddresses(srv *smtpsrv.Server, addrs []string, ls []net.Listener, mode smtpsrv.SocketMode) int {
naddr := 0
for _, addr := range addrs {
// The "systemd" address indicates we get listeners via systemd.
if addr == "systemd" {
srv.AddListeners(ls, mode)
naddr += len(ls)
} else {
srv.AddAddr(addr, mode)
naddr++
}
}
if naddr == 0 {
log.Errorf("Warning: No %v addresses/listeners", mode)
log.Errorf("If using systemd, check that you named the sockets")
}
return naddr
}
func initMailLog(path string) {
var err error
switch path {
case "<syslog>":
maillog.Default, err = maillog.NewSyslog()
case "<stdout>":
maillog.Default = maillog.New(os.Stdout)
case "<stderr>":
maillog.Default = maillog.New(os.Stderr)
default:
_ = os.MkdirAll(filepath.Dir(path), 0775)
maillog.Default, err = maillog.NewFile(path)
}
if err != nil {
log.Fatalf("Error opening mail log: %v", err)
}
}
func signalHandler() {
var err error
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGINT)
for {
switch sig := <-signals; sig {
case syscall.SIGHUP:
// SIGHUP triggers a reopen of the log files. This is used for log
// rotation.
err = log.Default.Reopen()
if err != nil {
log.Fatalf("Error reopening log: %v", err)
}
err = maillog.Default.Reopen()
if err != nil {
log.Fatalf("Error reopening maillog: %v", err)
}
case syscall.SIGTERM, syscall.SIGINT:
log.Fatalf("Got signal to exit: %v", sig)
default:
log.Errorf("Unexpected signal %v", sig)
}
}
}
// Helper to load a single domain configuration into the server.
func loadDomain(name, dir string, s *smtpsrv.Server) {
log.Infof(" %s", name)
s.AddDomain(name)
if _, err := os.Stat(dir + "/users"); err == nil {
log.Infof(" adding users")
udb, err := userdb.Load(dir + "/users")
if err != nil {
log.Errorf(" error: %v", err)
} else {
s.AddUserDB(name, udb)
}
}
log.Infof(" adding aliases")
err := s.AddAliasesFile(name, dir+"/aliases")
if err != nil {
log.Errorf(" error: %v", err)
}
}
func loadDovecot(s *smtpsrv.Server, userdb, client string) {
a := dovecot.NewAuth(userdb, client)
s.SetAuthFallback(a)
log.Infof("Fallback authenticator: %v", a)
if err := a.Check(); err != nil {
log.Errorf("Warning: Dovecot auth is not responding: %v", err)
}
}
// Read a directory, which must have at least some entries.
func mustReadDir(path string) []os.DirEntry {
dirs, err := os.ReadDir(path)
if err != nil {
log.Fatalf("Error reading %q directory: %v", path, err)
}
if len(dirs) == 0 {
log.Fatalf("No entries found in %q", path)
}
return dirs
}