-
Notifications
You must be signed in to change notification settings - Fork 2
/
smtp.go
248 lines (208 loc) · 5.66 KB
/
smtp.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
// mailpopbox
// Copyright 2020 Blue Static <https://www.bluestatic.org>
// This program is free software licensed under the GNU General Public License,
// version 3.0. The full text of the license can be found in LICENSE.txt.
// SPDX-License-Identifier: GPL-3.0-only
package main
import (
"bytes"
"crypto/tls"
"fmt"
"net"
"net/mail"
"os"
"path"
"regexp"
"go.uber.org/zap"
"src.bluestatic.org/mailpopbox/smtp"
)
var sendAsSubject = regexp.MustCompile(`(?i)\[sendas:\s*([a-zA-Z0-9\.\-_]+)\]`)
func runSMTPServer(config Config, log *zap.Logger) <-chan ServerControlMessage {
server := smtpServer{
config: config,
controlChan: make(chan ServerControlMessage),
log: log.With(zap.String("server", "smtp")),
}
server.mta = smtp.NewDefaultMTA(&server, server.log)
go server.run()
return server.controlChan
}
type smtpServer struct {
config Config
tlsConfig *tls.Config
mta smtp.MTA
log *zap.Logger
controlChan chan ServerControlMessage
}
func (server *smtpServer) run() {
if !server.loadTLSConfig() {
return
}
addr := fmt.Sprintf(":%d", server.config.SMTPPort)
server.log.Info("starting server", zap.String("address", addr))
l, err := net.Listen("tcp", addr)
if err != nil {
server.log.Error("listen", zap.Error(err))
server.controlChan <- ServerControlFatalError
return
}
connChan := make(chan net.Conn)
go RunAcceptLoop(l, connChan, server.log)
reloadChan := CreateReloadSignal()
for {
select {
case <-reloadChan:
if !server.loadTLSConfig() {
return
}
case conn, ok := <-connChan:
if ok {
go smtp.AcceptConnection(conn, server, server.log)
} else {
break
}
}
}
}
func (server *smtpServer) loadTLSConfig() bool {
var err error
server.tlsConfig, err = server.config.GetTLSConfig()
if err != nil {
server.log.Error("failed to configure TLS", zap.Error(err))
server.controlChan <- ServerControlFatalError
return false
}
server.log.Info("loaded TLS config")
return true
}
func (server *smtpServer) Name() string {
return server.config.Hostname
}
func (server *smtpServer) TLSConfig() *tls.Config {
return server.tlsConfig
}
func (server *smtpServer) VerifyAddress(addr mail.Address) smtp.ReplyLine {
s := server.configForAddress(addr)
if s == nil {
return smtp.ReplyBadMailbox
}
for _, blocked := range s.BlockedAddresses {
if blocked == addr.Address {
return smtp.ReplyMailboxUnallowed
}
}
return smtp.ReplyOK
}
func (server *smtpServer) Authenticate(authz, authc, passwd string) bool {
authcAddr, err := mail.ParseAddress(authc)
if err != nil {
return false
}
authzAddr, err := mail.ParseAddress(authz)
if authz != "" && err != nil {
return false
}
domain := smtp.DomainForAddress(*authcAddr)
for _, s := range server.config.Servers {
if domain == s.Domain {
authOk := authc == MailboxAccount+s.Domain && passwd == s.MailboxPassword
if authzAddr != nil {
authOk = authOk && smtp.DomainForAddress(*authzAddr) == domain
}
return authOk
}
}
return false
}
func (server *smtpServer) DeliverMessage(en smtp.Envelope) *smtp.ReplyLine {
maildrop := server.maildropForAddress(en.RcptTo[0])
if maildrop == "" {
server.log.Error("faild to open maildrop to deliver message", zap.String("id", en.ID))
return &smtp.ReplyBadMailbox
}
f, err := os.Create(path.Join(maildrop, en.ID+".msg"))
if err != nil {
server.log.Error("failed to create message file", zap.String("id", en.ID), zap.Error(err))
return &smtp.ReplyBadMailbox
}
smtp.WriteEnvelopeForDelivery(f, en)
f.Close()
return nil
}
func (server *smtpServer) configForAddress(addr mail.Address) *Server {
domain := smtp.DomainForAddress(addr)
for _, s := range server.config.Servers {
if domain == s.Domain {
return &s
}
}
return nil
}
func (server *smtpServer) maildropForAddress(addr mail.Address) string {
s := server.configForAddress(addr)
if s != nil {
return s.MaildropPath
}
return ""
}
func (server *smtpServer) RelayMessage(en smtp.Envelope, authc string) {
go func() {
log := server.log.With(zap.String("id", en.ID))
server.handleSendAs(log, &en, authc)
server.mta.RelayMessage(en)
}()
}
func (server *smtpServer) handleSendAs(log *zap.Logger, en *smtp.Envelope, authc string) {
// Find the separator between the message header and body.
headerIdx := bytes.Index(en.Data, []byte("\n\n"))
if headerIdx == -1 {
log.Error("send-as: could not find headers index")
return
}
var buf bytes.Buffer
headers := bytes.SplitAfter(en.Data[:headerIdx], []byte("\n"))
var fromIdx, subjectIdx int
for i, header := range headers {
if bytes.HasPrefix(header, []byte("From:")) {
fromIdx = i
continue
}
if bytes.HasPrefix(header, []byte("Subject:")) {
subjectIdx = i
continue
}
}
if subjectIdx == -1 {
log.Error("send-as: could not find Subject header")
return
}
if fromIdx == -1 {
log.Error("send-as: could not find From header")
return
}
sendAs := sendAsSubject.FindSubmatchIndex(headers[subjectIdx])
if sendAs == nil {
// No send-as modification.
return
}
// Submatch 0 is the whole sendas magic. Submatch 1 is the address prefix.
sendAsUser := headers[subjectIdx][sendAs[2]:sendAs[3]]
sendAsAddress := string(sendAsUser) + "@" + smtp.DomainForAddressString(authc)
log.Info("handling send-as", zap.String("address", sendAsAddress))
for i, header := range headers {
if i == subjectIdx {
buf.Write(header[:sendAs[0]])
buf.Write(header[sendAs[1]:])
} else if i == fromIdx {
addressStart := bytes.LastIndexByte(header, byte('<'))
buf.Write(header[:addressStart+1])
buf.WriteString(sendAsAddress)
buf.WriteString(">\n")
} else {
buf.Write(header)
}
}
buf.Write(en.Data[headerIdx:])
en.Data = buf.Bytes()
en.MailFrom.Address = sendAsAddress
}