-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
594 lines (553 loc) · 17.2 KB
/
server.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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
package smtp
import (
"bytes"
"crypto/tls"
"encoding/base64"
"errors"
"io"
"log"
"net"
"net/textproto"
"regexp"
"strings"
"sync"
"time"
)
var emailRegExp = regexp.MustCompile(`^<((\S+)@(\S+\.\S+))>$`)
type Server struct {
Name string
Addr string
Handler Handler
// If a tls config is set then this server will broadcast support
// for the STARTTLS (RFC3207) extension.
TLSConfig *tls.Config
// Auth specifies an optional callback function that is called
// when a client attempts to authenticate. If left nil (the default)
// then the AUTH extension will not be supported.
Auth func(username, password, remoteAddress string) error
// Addressable specifies an optional callback function that is called
// when a client attempts to send a message to the given address. This
// allows the server to refuse messages that it doesn't own. If left nil
// (the default) then the server will assume true
Addressable func(user, address string) bool
Debug bool
ErrorLog *log.Logger
}
type conn struct {
remoteAddr string
server *Server
rwc net.Conn
text *textproto.Conn
tlsState *tls.ConnectionState
fromAgent string
user string
mailFrom string
mailTo []string
mailData *bytes.Buffer
helloRecieved bool
quitSent bool
mu sync.Mutex
}
type HandlerFunc func(envelope *Envelope) error
func (f HandlerFunc) ServeSMTP(envelope *Envelope) error {
return f(envelope)
}
type Envelope struct {
FromAgent string
RemoteAddr string
User string
MessageFrom string
MessageTo string
MessageData io.Reader
}
var (
ErrorRequestedActionAbortedLocalError = errors.New("Requested action aborted: local error in processing")
ErrorTransactionFailed = errors.New("Transaction failed")
ErrorServiceNotAvailable = errors.New("Service not available, closing transmission channel")
ErrorRequestedActionAbortedExceededStorage = errors.New("Requested mail action aborted: exceeded storage allocation")
)
type Handler interface {
ServeSMTP(envelope *Envelope) error
}
type ServeMux struct {
mu sync.RWMutex
m map[string]map[string]muxEntry
}
type muxEntry struct {
h Handler
pattern string
}
func (srv *Server) logfd(format string, args ...interface{}) {
if srv.Debug {
srv.logf(format, args...)
}
}
func (srv *Server) logf(format string, args ...interface{}) {
if srv.ErrorLog != nil {
srv.ErrorLog.Printf(format, args...)
} else {
log.Printf(format, args...)
}
}
func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) {
c = new(conn)
c.resetSession()
c.remoteAddr = rwc.RemoteAddr().String()
c.server = srv
c.rwc = rwc
c.text = textproto.NewConn(c.rwc)
c.tlsState = nil
return c, nil
}
func (srv *Server) ListenAndServe() error {
if srv.Name == "" {
srv.Name = "localhost"
}
addr := srv.Addr
if addr == "" {
addr = ":smtp"
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return srv.Serve(ln)
}
func (srv *Server) ListenAndServeTLS(certFile string, keyFile string) error {
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
}
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
srv.TLSConfig = config
return srv.ListenAndServe()
}
func (srv *Server) Serve(l net.Listener) error {
defer l.Close()
var tempDelay time.Duration
for {
rw, e := l.Accept()
if e != nil {
if ne, ok := e.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
srv.logf("smtp: Accept error: %v; retrying in %v", e, tempDelay)
time.Sleep(tempDelay)
continue
}
return e
}
tempDelay = 0
c, err := srv.newConn(rw)
if err != nil {
continue
}
go c.serve()
}
}
func (c *conn) serve() {
c.server.logfd("INFO: Handling new connection from " + c.remoteAddr)
c.server.logfd("<%d %s %s\n", 220, c.server.Name, "ESMTP")
err := c.text.PrintfLine("%d %s %s", 220, c.server.Name, "ESMTP")
if err != nil {
c.server.logf("%v\n", err)
return
}
for !c.quitSent && err == nil {
err = c.readCommand()
if err != nil {
c.server.logf("%v\n", err)
}
}
c.text.Close()
c.rwc.Close()
}
func (c *conn) resetSession() {
//TODO See if reseting will log out the currently authed user?
//c.user = ""
c.mailFrom = ""
c.mailTo = make([]string, 0)
c.mailData = nil
}
func (c *conn) readCommand() error {
s, err := c.text.ReadLine()
if err != nil {
return err
}
c.server.logfd(">%s\n", s)
parts := strings.Split(s, " ")
if len(parts) <= 0 {
c.server.logfd("<%d %s\n", 500, "Command not recognized")
return c.text.PrintfLine("%d %s", 500, "Command not recognized")
}
switch strings.ToUpper(parts[0]) {
case "HELO":
if len(parts) < 2 {
c.server.logfd("<%d %s\n", 501, "Not enough arguments")
return c.text.PrintfLine("%d %s", 501, "Not enough arguments")
}
c.fromAgent = parts[1]
c.resetSession()
c.helloRecieved = true
c.server.logfd("<%d %s %s\n", 250, "Hello", parts[1])
return c.text.PrintfLine("%d %s %s", 250, "Hello", parts[1])
case "EHLO":
if len(parts) < 2 {
c.server.logfd("<%d %s\n", 501, "Not enough arguments")
return c.text.PrintfLine("%d %s", 501, "Not enough arguments")
}
c.fromAgent = parts[1]
c.resetSession()
c.helloRecieved = true
c.server.logfd("<%d-%s %s\n", 250, "Greets", parts[1])
err := c.text.PrintfLine("%d-%s %s", 250, "Greets", parts[1])
if err != nil {
return err
}
if c.server.TLSConfig != nil && c.tlsState == nil {
c.server.logfd("<%d-%s\n", 250, "STARTTLS")
err = c.text.PrintfLine("%d-%s", 250, "STARTTLS")
if err != nil {
return err
}
}
if ((c.server.TLSConfig != nil && c.tlsState != nil) ||
c.server.TLSConfig == nil) &&
c.server.Auth != nil {
c.server.logfd("<%d-%s\n", 250, "AUTH PLAIN")
err = c.text.PrintfLine("%d-%s", 250, "AUTH PLAIN")
if err != nil {
return err
}
}
c.server.logfd("<%d-%s\n", 250, "PIPELINING")
err = c.text.PrintfLine("%d-%s", 250, "PIPELINING")
if err != nil {
return err
}
c.server.logfd("<%d-%s\n", 250, "SMTPUTF8")
err = c.text.PrintfLine("%d-%s", 250, "SMTPUTF8")
if err != nil {
return err
}
c.server.logfd("<%d %s\n", 250, "8BITMIME")
return c.text.PrintfLine("%d %s", 250, "8BITMIME")
case "STARTTLS":
//Check to see if the server supports
if c.server.TLSConfig == nil {
//Error out here
c.server.logfd("<%d %s\n", 454, "TLS unavailable on the server")
return c.text.PrintfLine("%d %s", 454, "TLS unavailable on the server")
}
if c.tlsState != nil {
//Already in a tls state send error
c.server.logfd("<%d %s\n", 454, "TLS session already active")
return c.text.PrintfLine("%d %s", 454, "TLS session already active")
}
//If there is support, write out the resp
c.server.logfd("<%d %s\n", 220, "Ready to start TLS")
err = c.text.PrintfLine("%d %s", 220, "Ready to start TLS")
if err != nil {
return err
}
//Remap the underlying connection to a tls connection
tlsconn := tls.Server(c.rwc, c.server.TLSConfig)
err = tlsconn.Handshake()
if err != nil {
return err
}
c.rwc = tlsconn
//Remap the underlying textproto connection to work on top of the tls conn
c.text = textproto.NewConn(c.rwc)
c.tlsState = new(tls.ConnectionState)
*c.tlsState = tlsconn.ConnectionState()
c.resetSession()
c.helloRecieved = false
case "AUTH":
if c.server.Auth == nil {
c.server.logfd("<%d %s\n", 502, "Command not implemented")
return c.text.PrintfLine("%d %s", 502, "Command not implemented")
}
//TODO All Auth must occur over TLS
//if c.tlsState == nil {
// c.server.logfd("<%d %s\n", 538, "5.7.11 Encryption required for requested authentication mechanism")
// return c.text.PrintfLine("%d %s", 538, "5.7.11 Encryption required for requested authentication mechanism")
//}
if len(parts) < 2 {
c.server.logfd("<%d %s\n", 501, "Not enough arguments")
return c.text.PrintfLine("%d %s", 501, "Not enough arguments")
}
ppwd := ""
if len(parts) == 2 && strings.ToUpper(parts[1]) == "PLAIN" {
c.server.logfd("<%d %s\n", 334, "")
err := c.text.PrintfLine("%d %s", 334, "")
if err != nil {
return err
}
//Now read the plain password
ppwd, err := c.text.ReadLine()
if err != nil {
return err
}
c.server.logfd(">%s\n", ppwd)
}
if len(parts) == 3 && strings.ToUpper(parts[1]) == "PLAIN" {
ppwd = parts[2]
}
//Call the call back method with the username and password
b, err := base64.StdEncoding.DecodeString(ppwd)
if err != nil {
c.server.logfd("<%d %s\n", 501, "Bad base64 encoding")
return c.text.PrintfLine("%d %s", 501, "Bad base64 encoding")
}
pparts := bytes.Split(b, []byte{0})
if len(pparts) != 3 {
c.server.logfd("<%d %s\n", 501, "Bad base64 encoding")
return c.text.PrintfLine("%d %s", 501, "Bad base64 encoding")
}
if err = c.server.Auth(string(pparts[1]), string(pparts[2]), c.remoteAddr); err == nil {
c.user = string(pparts[1])
c.server.logfd("<%d %s\n", 235, "2.7.0 Authentication successful")
return c.text.PrintfLine("%d %s", 235, "2.7.0 Authentication successful")
} else {
c.user = ""
c.server.logfd("<%d %s\n", 535, "5.7.8 Authentication credentials invalid")
return c.text.PrintfLine("%d %s", 535, "5.7.8 Authentication credentials invalid")
}
case "MAIL":
if c.mailFrom != "" {
c.server.logfd("<%d %s\n", 503, "MAIL command already recieved")
return c.text.PrintfLine("%d %s", 503, "MAIL command already recieved")
}
if len(parts) < 2 {
c.server.logfd("<%d %s\n", 501, "Not enough arguments")
return c.text.PrintfLine("%d %s", 501, "Not enough arguments")
}
if !strings.HasPrefix(strings.ToUpper(parts[1]), "FROM:") {
c.server.logfd("<%d %s\n", 501, "MAIL command must be immediately succeeded by 'FROM:'")
return c.text.PrintfLine("%d %s", 501, "MAIL command must be immediately succeeded by 'FROM:'")
}
i := strings.Index(parts[1], ":")
addr := strings.Join(parts[1:], " ")[i+1:]
addr = strings.TrimSpace(addr)
if !emailRegExp.MatchString(addr) {
c.server.logfd("<%d %s\n", 501, "MAIL command contained invalid address")
return c.text.PrintfLine("%d %s", 501, "MAIL command contained invalid address")
}
from := emailRegExp.FindStringSubmatch(addr)[1]
c.mailFrom = from
c.server.logfd("<%d %s\n", 250, "Ok")
return c.text.PrintfLine("%d %s", 250, "Ok")
case "RCPT":
if c.mailFrom == "" {
c.server.logfd("<%d %s\n", 503, "Bad sequence of commands")
return c.text.PrintfLine("%d %s", 503, "Bad sequence of commands")
}
if len(parts) < 2 {
c.server.logfd("<%d %s\n", 501, "Not enough arguments")
return c.text.PrintfLine("%d %s", 501, "Not enough arguments")
}
if !strings.HasPrefix(strings.ToUpper(parts[1]), "TO:") {
c.server.logfd("<%d %s\n", 501, "RCPT command must be immediately succeeded by 'TO:'")
return c.text.PrintfLine("%d %s", 501, "RCPT command must be immediately succeeded by 'TO:'")
}
i := strings.Index(parts[1], ":")
addr := strings.Join(parts[1:], " ")[i+1:]
addr = strings.TrimSpace(addr)
if !emailRegExp.MatchString(addr) {
c.server.logfd("<%d %s\n", 501, "RCPT command contained invalid address")
return c.text.PrintfLine("%d %s", 501, "RCPT command contained invalid address")
}
to := emailRegExp.FindStringSubmatch(addr)[1]
//Check the handler to see if the inbox has a registered listener
if c.server.Addressable != nil && !c.server.Addressable(c.user, to) {
c.server.logfd("<%d %s\n", 501, "no such user - "+to)
return c.text.PrintfLine("%d %s", 501, "no such user - "+to)
}
c.mailTo = append(c.mailTo, to)
c.server.logfd("<%d %s\n", 250, "Ok")
return c.text.PrintfLine("%d %s", 250, "Ok")
case "DATA":
if c.mailTo == nil || c.mailFrom == "" || len(c.mailTo) == 0 {
c.server.logfd("<%d %s\n", 503, "Bad sequence of commands")
return c.text.PrintfLine("%d %s", 503, "Bad sequence of commands")
}
c.server.logfd("<%d %s\n", 354, "End data with <CR><LF>.<CR><LF>")
err := c.text.PrintfLine("%d %s", 354, "End data with <CR><LF>.<CR><LF>")
if err != nil {
return err
}
b, err := c.text.ReadDotBytes()
if err != nil {
return err
}
c.server.logfd(">%s\n", b)
c.mailData = bytes.NewBuffer(b)
//Iterate over all of the to addresses, and include this message
for _, v := range c.mailTo {
err = c.server.Handler.ServeSMTP(&Envelope{c.fromAgent, c.remoteAddr, c.user, c.mailFrom, v, bytes.NewReader(c.mailData.Bytes())})
}
if err != nil {
c.resetSession()
c.server.logfd("<%d %s\n", 450, "Mailbox unavailable")
return c.text.PrintfLine("%d %s", 450, "Mailbox unavailable")
}
//Reset the to,from, and data fields
c.resetSession()
c.server.logfd("<%d %s\n", 250, "OK")
return c.text.PrintfLine("%d %s", 250, "OK")
case "RSET":
c.resetSession()
c.server.logfd("<%d %s\n", 250, "Ok")
return c.text.PrintfLine("%d %s", 250, "Ok")
case "VRFY":
//TODO By default this will check the handlers to see if the inbox is registered
c.server.logfd("<%d %s\n", 250, "OK")
return c.text.PrintfLine("%d %s", 250, "OK")
case "EXPN":
//TODO Call a callback to get the expanded list
c.server.logfd("<%d %s\n", 250, "OK")
return c.text.PrintfLine("%d %s", 250, "OK")
case "HELP":
c.server.logfd("<%d %s\n", 250, "OK")
return c.text.PrintfLine("%d %s", 250, "OK")
case "NOOP":
c.server.logfd("<%d %s\n", 250, "OK")
return c.text.PrintfLine("%d %s", 250, "OK")
case "QUIT":
c.server.logfd("<%d %s\n", 221, "OK")
c.quitSent = true
return c.text.PrintfLine("%d %s", 221, "OK")
default:
c.server.logfd("<%d %s\n", 500, "Command not recognized")
return c.text.PrintfLine("%d %s", 500, "Command not recognized")
}
return nil
}
func NewServeMux() *ServeMux { return &ServeMux{m: make(map[string]map[string]muxEntry)} }
var DefaultServeMux = NewServeMux()
func SplitAddress(address string) (string, string, error) {
sepInd := strings.LastIndex(address, "@")
if sepInd == -1 {
return "", "", errors.New("Invalid Address:" + address)
}
localPart := address[:sepInd]
domainPart := address[sepInd+1:]
return localPart, domainPart, nil
}
// Handle will register the given email pattern to be handled with the
// given handler. The Canonacalize method will be called on the pattern
// to help ensure expected matches will come through. The special '*'
// wildcard can be used for the local portion or the domain portion to
// broaden the match.
func (mux *ServeMux) Handle(pattern string, handler Handler) {
mux.mu.Lock()
l, d, err := SplitAddress(pattern)
if err != nil {
log.Fatal(err)
}
if l == "" {
l = "*"
}
//TODO Should I Canonicalize here, or just warn if the canonical doesn't match the input?
//Think scenario where [email protected]
cl := CanonicalizeEmail(l)
dp, ok := mux.m[d]
if !ok {
dp = make(map[string]muxEntry)
mux.m[d] = dp
}
ap, ok := dp[cl]
if ok {
log.Fatal("Handle Pattern already used!", pattern)
}
ap.h = handler
ap.pattern = pattern
dp[l] = ap
defer mux.mu.Unlock()
}
func Handle(pattern string, handler Handler) {
DefaultServeMux.Handle(pattern, handler)
}
func (mux *ServeMux) HandleFunc(pattern string, handler func(envelope *Envelope) error) {
mux.Handle(pattern, HandlerFunc(handler))
}
func HandleFunc(pattern string, handler func(envelope *Envelope) error) {
DefaultServeMux.HandleFunc(pattern, handler)
}
// I'm following googles example here. Basically all '.' dont matter in the local portion.
// Also you can append a '+' section to the end of your email and it will still route to you.
// This allows categorization of emails when they are given out. The muxer will canonicalize
// incoming email addresses to route them to a handler. The handler will still see the original
// email in the to portion.
func CanonicalizeEmail(local string) string {
//Shouldn't be needed
local = strings.TrimSpace(local)
//To lower it all
local = strings.ToLower(local)
//Get rid of punctuation
local = strings.Replace(local, ".", "", -1)
//Get rid of anything after the last +
if li := strings.LastIndex(local, "+"); li > 0 {
local = local[:li]
}
return local
}
func (mux *ServeMux) ServeSMTP(envelope *Envelope) error {
l, d, err := SplitAddress(envelope.MessageTo)
cl := CanonicalizeEmail(l)
if err != nil {
return errors.New("Invalid Address")
}
if dp, ok := mux.m[d]; ok {
if ap, ok := dp[cl]; ok {
return ap.h.ServeSMTP(envelope)
} else {
if ap, ok := dp["*"]; ok {
return ap.h.ServeSMTP(envelope)
} else {
return errors.New("Bad Address")
}
}
} else {
if dp, ok := mux.m["*"]; ok {
if ap, ok := dp[cl]; ok {
return ap.h.ServeSMTP(envelope)
} else {
if ap, ok := dp["*"]; ok {
return ap.h.ServeSMTP(envelope)
} else {
return errors.New("Bad Address")
}
}
} else {
return errors.New("Bad Address")
}
}
return nil
}
func ListenAndServe(addr string, handler Handler) error {
if handler == nil {
handler = DefaultServeMux
}
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServe()
}
func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
if handler == nil {
handler = DefaultServeMux
}
server := &Server{Addr: addr, Handler: handler}
return server.ListenAndServeTLS(certFile, keyFile)
}