-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
556 lines (487 loc) · 11.2 KB
/
main.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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
package main
import (
"context"
"crypto/tls"
"errors"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"os"
"os/signal"
"os/user"
"strconv"
"strings"
"syscall"
"time"
"github.com/emersion/go-smtp"
"github.com/goccy/go-yaml"
"golang.org/x/net/netutil"
)
type Config_service struct {
E_ bool
Addr string `yaml:"addr"`
LMTP bool
ESMTP_ bool `yaml:"esmtp"`
Domain string `yaml:"iam"`
MaxRecipients int `yaml:"max_rcpt"`
MaxMessageBytes int64 `yaml:"max_size"`
MaxLineLength int
AllowInsecureAuth bool `yaml:"allow_insecure_auth"`
ReadTimeout time.Duration
ReadTimeout_ uint `yaml:"read_timeout"`
WriteTimeout time.Duration
WriteTimeout_ uint `yaml:"write_timeout"`
EnableSMTPUTF8 bool
EnableREQUIRETLS bool
EnableBINARYMIME bool
AuthDisabled bool
MaxConnections int `yaml:"max_connections"`
Username string `yaml:"user"`
Groupname string `yaml:"group"`
SocketMode int
SocketMode_ string `yaml:"mode"`
FileUmask int
FileUmask_ string `yaml:"umask"`
}
type Config_custom struct {
E_ bool
EOL string `yaml:"eol"`
AddReceived bool `yaml:"add_received"`
}
type Config struct {
Domain string `yaml:"domain"`
Domains []string `yaml:"domains"`
Home string `yaml:"home"`
QueueIncoming string `yaml:"queue"`
QueueBounce string `yaml:"queuebounce"`
QueueAutomatic string `yaml:"queueautomatic"`
BounceEmailPrefix string `yaml:"bounce_email_prefix"`
ReturnPathSuffix string `yaml:"return_path_suffix"`
ListCheckSuffixes []string `yaml:"list_check_suffixes"`
Email string `yaml:"email"`
ListmasterEmail string `yaml:"listmaster_email"`
S Config_service `yaml:"service"`
C Config_custom `yaml:"custom"`
}
func NewConfig() (*Config, error) {
config := Config{
BounceEmailPrefix: "bounce",
ReturnPathSuffix: "-owner",
ListCheckSuffixes: []string{
"request", "owner", "editor",
"unsubscribe", "subscribe",
},
Email: "sympa",
ListmasterEmail: "listmaster",
}
config.S.E_ = true
config.S.Domain = "localhost"
config.S.MaxConnections = 100
config.S.MaxRecipients = 50
config.S.MaxMessageBytes = 5 * 1024 * 1024
config.S.SocketMode_ = "666"
config.S.FileUmask_ = "027"
config.S.ReadTimeout_ = 300
config.S.WriteTimeout_ = 300
config.C.E_ = true
config.C.EOL = "\n"
config.C.AddReceived = true
var file *os.File
var err error
buf := make([]byte, 8192)
if len(os.Args) > 1 {
file, err = os.Open(os.Args[1])
if err != nil {
return nil, err
}
defer file.Close()
} else {
file = os.Stdin
}
_, err = file.Read(buf)
if err != nil {
return nil, err
}
if err := yaml.Unmarshal([]byte(buf), &config); err != nil {
return nil, err
}
if !config.S.E_ || !config.C.E_ {
return nil, errors.New("empty configuration")
}
if config.S.FileUmask_ != "" {
mode64, err := strconv.ParseUint(config.S.FileUmask_, 8, 9)
if err != nil {
return nil, err
}
config.S.FileUmask = int(mode64)
}
if config.S.ESMTP_ {
// TODO: Handle "subsequent failure" with (E)SMTP
config.S.MaxRecipients = 1
} else {
config.S.LMTP = true
}
if config.S.SocketMode_ != "" {
mode64, err := strconv.ParseUint(config.S.SocketMode_, 8, 9)
if err != nil {
return nil, err
}
config.S.SocketMode = int(mode64)
}
if config.S.ReadTimeout_ > 0 {
config.S.ReadTimeout =
time.Duration(config.S.ReadTimeout_) * time.Second
}
if config.S.WriteTimeout_ > 0 {
config.S.WriteTimeout =
time.Duration(config.S.WriteTimeout_) * time.Second
}
config.S.AuthDisabled = true
return &config, nil
}
// Server is the smtp.Server extended
type Server struct {
*smtp.Server
MaxConnections int
Username string
Groupname string
SocketMode int
FileUmask int
}
func NewServer(be *Backend) *Server {
s := &Server{smtp.NewServer(be), 0, "", "", 0, 0}
s.Addr = be.Config.S.Addr
s.LMTP = be.Config.S.LMTP
s.Domain = be.Config.S.Domain
s.ReadTimeout = be.Config.S.ReadTimeout
s.WriteTimeout = be.Config.S.WriteTimeout
s.MaxMessageBytes = be.Config.S.MaxMessageBytes
s.MaxRecipients = be.Config.S.MaxRecipients
s.AllowInsecureAuth = be.Config.S.AllowInsecureAuth
s.AuthDisabled = be.Config.S.AuthDisabled
s.MaxConnections = be.Config.S.MaxConnections
s.Username = be.Config.S.Username
s.Groupname = be.Config.S.Groupname
s.SocketMode = be.Config.S.SocketMode
s.FileUmask = be.Config.S.FileUmask
return s
}
func (s *Server) ListenAndServe() error {
return listenAndServe(s, false)
}
func (s *Server) ListenAndServeTLS() error {
return listenAndServe(s, true)
}
func listenAndServe(s *Server, useTLS bool) error {
addr := s.Addr
if addr == "" {
if s.LMTP {
addr = ":24"
} else if useTLS {
addr = ":465"
} else {
addr = ":smtp"
}
}
network := "tcp"
if strings.Contains(addr, "/") {
network = "unix"
}
var (
l net.Listener
err error
)
if network == "unix" && s.SocketMode > 0 {
mode := s.SocketMode
umask := syscall.Umask(-1 &^ mode)
l, err = net.Listen(network, addr)
syscall.Umask(umask)
if err != nil {
return err
}
if err = os.Chmod(addr, os.FileMode(mode)); err != nil {
return err
}
} else {
l, err = net.Listen(network, addr)
if err != nil {
return err
}
}
if s.MaxConnections > 0 {
l = netutil.LimitListener(l, s.MaxConnections)
}
if useTLS {
l = tls.NewListener(l, s.TLSConfig)
}
if s.Username != "" {
var userU *user.User
var uid int
_, err = strconv.Atoi(s.Username)
if err == nil {
userU, err = user.LookupId(s.Username)
}
if err != nil {
userU, err = user.Lookup(s.Username)
}
if err != nil {
return err
}
uid, err = strconv.Atoi(userU.Uid)
if err != nil {
return err
}
var gids []int
if os.Getuid() == 0 {
groups, err := userU.GroupIds()
if err != nil {
return err
}
for _, g := range groups {
id, err := strconv.Atoi(g)
if err != nil {
return err
}
gids = append(gids, id)
}
}
var gid int
if s.Groupname != "" {
var userG *user.Group
_, err = strconv.Atoi(s.Groupname)
if err == nil {
userG, err = user.LookupGroupId(s.Groupname)
}
if err != nil {
userG, err = user.LookupGroup(s.Groupname)
}
if err != nil {
return err
}
gid, err = strconv.Atoi(userG.Gid)
} else {
gid, err = strconv.Atoi(userU.Gid)
}
if err != nil {
return err
}
if network == "unix" {
if err := os.Chown(addr, uid, gid); err != nil {
return err
}
}
if err := syscall.Setgid(gid); err != nil {
return err
}
if gids != nil {
if err := syscall.Setgroups(gids); err != nil {
return err
}
}
if err := syscall.Setuid(uid); err != nil {
return err
}
}
if s.FileUmask > 0 {
syscall.Umask(s.FileUmask)
}
if os.Getuid() == 0 {
os.Stderr.WriteString("*** You are running as root.")
os.Stderr.WriteString(
" Running as an unprivileged user is recommended.\n")
}
rand.Seed(time.Now().UnixNano())
return s.Serve(l)
}
// The Backend implements SMTP server methods.
type Backend struct {
Config *Config
}
func NewBackend(c *Config) *Backend {
return &Backend{Config: c}
}
func (be *Backend) NewSession(c *smtp.Conn) (smtp.Session, error) {
id := uniqueId()
ra := c.Conn().RemoteAddr().String()
la := c.Conn().LocalAddr().String()
hh := c.Hostname()
log.Printf("%s client=<%s>, hello=<%s>, bound=<%s>", id, ra, hh, la)
if be.Config.S.LMTP {
return &LMTPSession{Session{
Id: id,
Backend: be,
RemoteAddr: ra,
LocalAddr: la,
HelloHost: canonicDomain(hh),
}}, nil
} else {
return &Session{
Id: id,
Backend: be,
RemoteAddr: ra,
LocalAddr: la,
HelloHost: canonicDomain(hh),
}, nil
}
}
// A Session is returned after EHLO.
type Session struct {
Id string
Backend *Backend
RemoteAddr string
LocalAddr string
HelloHost string
MailFrom string
RcptTos []string
RcptLists []*List
DataErrors []error
}
type LMTPSession struct {
Session
}
func (s *Session) AuthPlain(username, password string) error {
if username != "username" || password != "password" {
return errors.New("Invalid username or password")
}
return nil
}
func (s *Session) Mail(from string, opts *smtp.MailOptions) error {
log.Printf("%s from=<%s>", s.Id, from)
if from == "" {
return nil
}
if err := validateEmail(from); err != nil {
return &smtp.SMTPError{
Code: 501,
EnhancedCode: smtp.EnhancedCode{5, 1, 7},
Message: "Bad sender address syntax",
}
}
s.MailFrom = from
return nil
}
func (s *Session) Rcpt(to string, opts *smtp.RcptOptions) error {
log.Printf("%s to=<%s>", s.Id, to)
if err := validateEmail(to); err != nil {
return &smtp.SMTPError{
Code: 501,
EnhancedCode: smtp.EnhancedCode{5, 1, 3},
Message: "Bad recipient address syntax",
}
}
l, err := s.Backend.NewList(to)
if err != nil {
return err
}
if l.Name != "" && l.Status != "open" {
return &smtp.SMTPError{
Code: 550,
EnhancedCode: smtp.EnhancedCode{5, 1, 1},
Message: "Recipient address rejected: User unknown ",
}
}
s.RcptTos = append(s.RcptTos, to)
s.RcptLists = append(s.RcptLists, l)
return nil
}
func (s *Session) storeData(r io.Reader) error {
var message *Message
if b, err := ioutil.ReadAll(r); err != nil {
return err
} else {
log.Printf("%s data(%d bytes)", s.Id, len(b))
message = s.Backend.NewMessage(s, b)
}
ispool, err := s.Backend.NewSpoolIncoming()
if err != nil {
return err
}
bspool, err := s.Backend.NewSpoolBounce()
if err != nil {
return err
}
sent := make(map[string]error)
for _, l := range s.RcptLists {
a := l.String()
var err error
if _, ok := sent[a]; ok {
err = sent[a]
} else {
if l.Type == "return_path" {
err = bspool.Store(l, message)
} else {
err = ispool.Store(l, message)
}
sent[a] = err
log.Printf("%s to=<%s>, error=<%v>", s.Id, l, err)
}
s.DataErrors = append(s.DataErrors, err)
}
return nil
}
func (s *Session) Data(r io.Reader) error {
if err := s.storeData(r); err != nil {
return err
}
var succ, fail bool
for _, err := range s.DataErrors {
if err == nil {
succ = true
} else {
fail = true
}
}
if succ {
if fail {
// FIXME: handle partial errors
}
return nil
} else {
return errors.New("Internal error")
}
}
func (s *Session) LMTPData(r io.Reader, status smtp.StatusCollector) error {
if err := s.storeData(r); err != nil {
return err
}
for i, err := range s.DataErrors {
status.SetStatus(s.RcptTos[i], err)
}
return nil
}
func (s *Session) Reset() {
log.Printf("%s rset", s.Id)
s.Id = uniqueId()
s.MailFrom = ""
s.RcptTos = nil
s.RcptLists = nil
s.DataErrors = nil
}
func (s *Session) Logout() error {
log.Printf("%s quit", s.Id)
return nil
}
func main() {
ctx, stop := signal.NotifyContext(context.Background(),
os.Interrupt, syscall.SIGTERM)
defer stop()
c, err := NewConfig()
if err != nil {
log.Fatal(err)
}
be := NewBackend(c)
s := NewServer(be)
go func() {
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.Background(),
60*time.Second)
defer cancel()
s.Shutdown(ctx)
}()
log.Println("Starting server at", s.Addr)
if err := s.ListenAndServe(); err != nil {
log.Fatal(err)
}
}