forked from emersion/go-smtp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
1243 lines (1079 loc) · 31.1 KB
/
conn.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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package smtp
import (
"crypto/tls"
"encoding/base64"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/textproto"
"regexp"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
)
// Number of errors we'll tolerate per connection before closing. Defaults to 3.
const errThreshold = 3
type ConnectionState struct {
Hostname string
LocalAddr net.Addr
RemoteAddr net.Addr
TLS tls.ConnectionState
Original *ConnectionState
}
type Conn struct {
conn net.Conn
text *textproto.Conn
server *Server
helo string
nbrErrors int
// Number of errors witnessed on this connection
errCount int
session Session
locker sync.Mutex
binarymime bool
bdatPipe *io.PipeWriter
bdatStatus *statusCollector // used for BDAT on LMTP
dataResult chan error
bytesReceived int // counts total size of chunks when BDAT is used
fromReceived bool
recipients []string
// We store ConnectionState built from XCLIENT command as multiple commands can be sent with
// different fields.
xclientState *ConnectionState
}
func newConn(c net.Conn, s *Server) *Conn {
sc := &Conn{
server: s,
conn: c,
}
sc.init()
return sc
}
func (c *Conn) init() {
rwc := struct {
io.Reader
io.Writer
io.Closer
}{
Reader: &lineLimitReader{
R: c.conn,
LineLimit: c.server.MaxLineLength,
},
Writer: c.conn,
Closer: c.conn,
}
if c.server.Debug != nil {
rwc = struct {
io.Reader
io.Writer
io.Closer
}{
io.TeeReader(rwc.Reader, c.server.Debug),
io.MultiWriter(rwc.Writer, c.server.Debug),
rwc.Closer,
}
}
c.text = textproto.NewConn(rwc)
}
func (c *Conn) unrecognizedCommand(cmd string) {
c.WriteResponse(500, EnhancedCode{5, 5, 2}, fmt.Sprintf("Syntax error, %v command unrecognized", cmd))
c.nbrErrors++
if c.nbrErrors > 3 {
c.WriteResponse(500, EnhancedCode{5, 5, 2}, "Too many unrecognized commands")
c.Close()
}
}
// Commands are dispatched to the appropriate handler functions.
func (c *Conn) handle(cmd string, arg string) {
// If panic happens during command handling - send 421 response
// and close connection.
defer func() {
if err := recover(); err != nil {
c.WriteResponse(421, EnhancedCode{4, 0, 0}, "Internal server error")
c.Close()
stack := debug.Stack()
c.server.ErrorLog.Printf("panic serving %v: %v\n%s", c.State().RemoteAddr, err, stack)
}
}()
if cmd == "" {
c.protocolError(500, EnhancedCode{5, 5, 2}, "Error: bad syntax")
return
}
cmd = strings.ToUpper(cmd)
switch cmd {
case "SEND", "SOML", "SAML", "EXPN", "HELP", "TURN":
// These commands are not implemented in any state
c.WriteResponse(502, EnhancedCode{5, 5, 1}, fmt.Sprintf("%v command not implemented", cmd))
case "HELO", "EHLO", "LHLO":
lmtp := cmd == "LHLO"
enhanced := lmtp || cmd == "EHLO"
if c.server.LMTP && !lmtp {
c.WriteResponse(500, EnhancedCode{5, 5, 1}, "This is a LMTP server, use LHLO")
return
}
if !c.server.LMTP && lmtp {
c.WriteResponse(500, EnhancedCode{5, 5, 1}, "This is not a LMTP server")
return
}
c.handleGreet(enhanced, arg)
case "XCLIENT":
c.handleXclient(arg)
case "MAIL":
c.handleMail(arg)
case "RCPT":
c.handleRcpt(arg)
case "VRFY":
c.WriteResponse(252, EnhancedCode{2, 5, 0}, "Cannot VRFY user, but will accept message")
case "NOOP":
c.WriteResponse(250, EnhancedCode{2, 0, 0}, "I have sucessfully done nothing")
case "RSET": // Reset session
c.reset()
c.WriteResponse(250, EnhancedCode{2, 0, 0}, "Session reset")
case "BDAT":
c.handleBdat(arg)
case "DATA":
c.handleData(arg)
case "QUIT":
c.WriteResponse(221, EnhancedCode{2, 0, 0}, "Bye")
c.Close()
case "AUTH":
if c.server.AuthDisabled {
c.protocolError(500, EnhancedCode{5, 5, 2}, "Syntax error, AUTH command unrecognized")
} else {
c.handleAuth(arg)
}
case "STARTTLS":
c.handleStartTLS()
default:
msg := fmt.Sprintf("Syntax errors, %v command unrecognized", cmd)
c.protocolError(500, EnhancedCode{5, 5, 2}, msg)
}
}
func (c *Conn) Server() *Server {
return c.server
}
func (c *Conn) Session() Session {
c.locker.Lock()
defer c.locker.Unlock()
return c.session
}
// Setting the user resets any message being generated
func (c *Conn) SetSession(session Session) {
c.locker.Lock()
defer c.locker.Unlock()
c.session = session
}
func (c *Conn) Close() error {
c.locker.Lock()
defer c.locker.Unlock()
if c.bdatPipe != nil {
c.bdatPipe.CloseWithError(ErrDataReset)
c.bdatPipe = nil
}
if c.session != nil {
c.session.Logout()
c.session = nil
}
return c.conn.Close()
}
// TLSConnectionState returns the connection's TLS connection state.
// Zero values are returned if the connection doesn't use TLS.
func (c *Conn) TLSConnectionState() (state tls.ConnectionState, ok bool) {
tc, ok := c.conn.(*tls.Conn)
if !ok {
return
}
return tc.ConnectionState(), true
}
func (c *Conn) State() ConnectionState {
if c.xclientState != nil {
return *c.xclientState
}
state := ConnectionState{}
tlsState, ok := c.TLSConnectionState()
if ok {
state.TLS = tlsState
}
state.Hostname = c.helo
state.LocalAddr = c.conn.LocalAddr()
state.RemoteAddr = c.conn.RemoteAddr()
return state
}
func (c *Conn) authAllowed() bool {
_, isTLS := c.TLSConnectionState()
canAuthResult := !c.server.AuthDisabled && (isTLS || c.server.AllowInsecureAuth)
//check secure network
if canAuthResult == false {
remoteIpStr, _, _ := net.SplitHostPort(c.State().RemoteAddr.String())
remoteIp := net.ParseIP(remoteIpStr)
for _, ipNet := range c.server.SecureNet {
if ipNet.Contains(remoteIp) {
return true
}
}
}
return canAuthResult
}
// protocolError writes errors responses and closes the connection once too many
// have occurred.
func (c *Conn) protocolError(code int, ec EnhancedCode, msg string) {
c.WriteResponse(code, ec, msg)
c.errCount++
if c.errCount > errThreshold {
c.WriteResponse(500, EnhancedCode{5, 5, 1}, "Too many errors. Quiting now")
c.Close()
}
}
// GREET state -> waiting for HELO
func (c *Conn) handleGreet(enhanced bool, arg string) {
if !enhanced {
domain, err := parseHelloArgument(arg)
if err != nil {
c.WriteResponse(501, EnhancedCode{5, 5, 2}, "Domain/address argument required for HELO")
return
}
c.helo = domain
c.WriteResponse(250, EnhancedCode{2, 0, 0}, fmt.Sprintf("Hello %s", domain))
} else {
domain, err := parseHelloArgument(arg)
if err != nil {
c.WriteResponse(501, EnhancedCode{5, 5, 2}, "Domain/address argument required for EHLO")
return
}
c.helo = domain
caps := []string{}
caps = append(caps, c.server.caps...)
if _, isTLS := c.TLSConnectionState(); c.server.TLSConfig != nil && !isTLS {
caps = append(caps, "STARTTLS")
}
if c.authAllowed() {
authCap := "AUTH"
for name := range c.server.auths {
authCap += " " + name
}
caps = append(caps, authCap)
}
if c.server.EnableSMTPUTF8 {
caps = append(caps, "SMTPUTF8")
}
if _, isTLS := c.TLSConnectionState(); isTLS && c.server.EnableREQUIRETLS {
caps = append(caps, "REQUIRETLS")
}
if c.server.EnableBINARYMIME {
caps = append(caps, "BINARYMIME")
}
if c.server.EnableDSN {
caps = append(caps, "DSN")
}
if c.server.MaxMessageBytes > 0 {
caps = append(caps, fmt.Sprintf("SIZE %v", c.server.MaxMessageBytes))
} else {
caps = append(caps, "SIZE")
}
if _, ok := c.server.Backend.(ProxyBackend); ok {
// We list fields we can convert into ConnectionState plus PROTO that does not really matter in practice.
// Notable omission here is LOGIN for SASL username assertion and NAME which cannot be represented
// by ConnectionState fields.
caps = append(caps, "XCLIENT ADDR PORT DESTADDR DESTPORT HELO PROTO")
}
args := []string{"Hello " + domain}
args = append(args, caps...)
c.WriteResponse(250, NoEnhancedCode, args...)
}
}
// READY state -> waiting for MAIL
func (c *Conn) handleMail(arg string) {
if c.helo == "" {
c.WriteResponse(502, EnhancedCode{2, 5, 1}, "Please introduce yourself first.")
return
}
if c.bdatPipe != nil {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "MAIL not allowed during message transfer")
return
}
if c.Session() == nil {
state := c.State()
session, err := c.server.Backend.AnonymousLogin(&state)
if err != nil {
if smtpErr, ok := err.(*SMTPError); ok {
c.WriteResponse(smtpErr.Code, smtpErr.EnhancedCode, smtpErr.Message)
} else {
c.WriteResponse(502, EnhancedCode{5, 7, 0}, err.Error())
}
return
}
c.SetSession(session)
}
if len(arg) < 6 || strings.ToUpper(arg[0:5]) != "FROM:" {
c.WriteResponse(501, EnhancedCode{5, 5, 2}, "Was expecting MAIL arg syntax of FROM:<address>")
return
}
fromArgs := strings.Split(strings.Trim(arg[5:], " "), " ")
if c.server.Strict {
if !strings.HasPrefix(fromArgs[0], "<") || !strings.HasSuffix(fromArgs[0], ">") {
c.WriteResponse(501, EnhancedCode{5, 5, 2}, "Was expecting MAIL arg syntax of FROM:<address>")
return
}
}
from := fromArgs[0]
if from == "" {
c.WriteResponse(501, EnhancedCode{5, 5, 2}, "Was expecting MAIL arg syntax of FROM:<address>")
return
}
from = strings.Trim(from, "<>")
opts := MailOptions{}
c.binarymime = false
// This is where the Conn may put BODY=8BITMIME, but we already
// read the DATA as bytes, so it does not effect our processing.
if len(fromArgs) > 1 {
args, err := parseArgs(fromArgs[1:])
if err != nil {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Unable to parse MAIL ESMTP parameters")
return
}
for key, value := range args {
switch key {
case "SIZE":
size, err := strconv.ParseInt(value, 10, 32)
if err != nil {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Unable to parse SIZE as an integer")
return
}
if c.server.MaxMessageBytes > 0 && int(size) > c.server.MaxMessageBytes {
c.WriteResponse(552, EnhancedCode{5, 3, 4}, "Max message size exceeded")
return
}
opts.Size = int(size)
case "SMTPUTF8":
if !c.server.EnableSMTPUTF8 {
c.WriteResponse(504, EnhancedCode{5, 5, 4}, "SMTPUTF8 is not implemented")
return
}
opts.UTF8 = true
case "REQUIRETLS":
if !c.server.EnableREQUIRETLS {
c.WriteResponse(504, EnhancedCode{5, 5, 4}, "REQUIRETLS is not implemented")
return
}
opts.RequireTLS = true
case "BODY":
switch value {
case "BINARYMIME":
if !c.server.EnableBINARYMIME {
c.WriteResponse(504, EnhancedCode{5, 5, 4}, "BINARYMIME is not implemented")
return
}
c.binarymime = true
case "7BIT", "8BITMIME":
default:
c.WriteResponse(500, EnhancedCode{5, 5, 4}, "Unknown BODY value")
return
}
opts.Body = BodyType(value)
case "AUTH":
value, err := decodeXtext(value)
if err != nil {
c.WriteResponse(500, EnhancedCode{5, 5, 4}, "Malformed AUTH parameter value")
return
}
if !strings.HasPrefix(value, "<") {
c.WriteResponse(500, EnhancedCode{5, 5, 4}, "Missing opening angle bracket")
return
}
if !strings.HasSuffix(value, ">") {
c.WriteResponse(500, EnhancedCode{5, 5, 4}, "Missing closing angle bracket")
return
}
decodedMbox := value[1 : len(value)-1]
opts.Auth = &decodedMbox
case "RET":
value := DSNReturn(strings.ToUpper(value))
if value != ReturnFull && value != ReturnHeaders {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Unsupported RET value")
return
}
opts.Return = value
case "ENVID":
value, err := decodeXtext(value)
if err != nil {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Malformed xtext in ENVID")
return
}
if !checkPrintableASCII(value) {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Only printable ASCII allowed in ENVID")
return
}
opts.EnvelopeID = value
default:
c.WriteResponse(500, EnhancedCode{5, 5, 4}, "Unknown MAIL FROM argument")
return
}
}
}
if err := c.Session().Mail(from, opts); err != nil {
if smtpErr, ok := err.(*SMTPError); ok {
c.WriteResponse(smtpErr.Code, smtpErr.EnhancedCode, smtpErr.Message)
return
}
c.WriteResponse(451, EnhancedCode{4, 0, 0}, err.Error())
return
}
c.WriteResponse(250, EnhancedCode{2, 0, 0}, fmt.Sprintf("Roger, accepting mail from <%v>", from))
c.fromReceived = true
}
// This regexp matches 'hexchar' token defined in
// https://tools.ietf.org/html/rfc4954#section-8 however it is intentionally
// relaxed by requiring only '+' to be present. It allows us to detect
// malformed values such as +A or +HH and report them appropriately.
var hexcharRe = regexp.MustCompile(`\+[0-9A-F]?[0-9A-F]?`)
func decodeXtext(val string) (string, error) {
if !strings.Contains(val, "+") {
return val, nil
}
var replaceErr error
decoded := hexcharRe.ReplaceAllStringFunc(val, func(match string) string {
if len(match) != 3 {
replaceErr = errors.New("incomplete hexchar")
return ""
}
char, err := strconv.ParseInt(match, 16, 8)
if err != nil {
replaceErr = err
return ""
}
return string(rune(char))
})
if replaceErr != nil {
return "", replaceErr
}
return decoded, nil
}
func encodeXtext(raw string) string {
var out strings.Builder
out.Grow(len(raw))
for _, ch := range raw {
if ch == '+' || ch == '=' {
out.WriteRune('+')
out.WriteString(strings.ToUpper(strconv.FormatInt(int64(ch), 16)))
}
if ch > '!' && ch < '~' { // printable non-space US-ASCII
out.WriteRune(ch)
}
// Non-ASCII.
out.WriteRune('+')
out.WriteString(strings.ToUpper(strconv.FormatInt(int64(ch), 16)))
}
return out.String()
}
func checkPrintableASCII(s string) bool {
for _, c := range s {
if c < 32 && c > 127 {
return false
}
}
return true
}
// MAIL state -> waiting for RCPTs followed by DATA
func (c *Conn) handleRcpt(arg string) {
if !c.fromReceived {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "Missing MAIL FROM command.")
return
}
if c.bdatPipe != nil {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "RCPT not allowed during message transfer")
return
}
if len(arg) < 4 || strings.ToUpper(arg[0:3]) != "TO:" {
c.WriteResponse(501, EnhancedCode{5, 5, 1}, "Was expecting TO arg syntax of TO:<address>")
return
}
toArgs := strings.Split(strings.Trim(arg[3:], " "), " ")
if c.server.Strict {
if !strings.HasPrefix(toArgs[0], "<") || !strings.HasSuffix(toArgs[0], ">") {
c.WriteResponse(501, EnhancedCode{5, 5, 1}, "Was expecting TO arg syntax of TO:<address>")
return
}
}
recipient := toArgs[0]
if recipient == "" {
c.WriteResponse(501, EnhancedCode{5, 5, 2}, "Was expecting MAIL arg syntax of FROM:<address>")
return
}
recipient = strings.Trim(recipient, "<>")
if c.server.MaxRecipients > 0 && len(c.recipients) >= c.server.MaxRecipients {
c.WriteResponse(552, EnhancedCode{5, 5, 3}, fmt.Sprintf("Maximum limit of %v recipients reached", c.server.MaxRecipients))
return
}
opts := RcptOptions{}
if len(toArgs) > 1 {
args, err := parseArgs(toArgs[1:])
if err != nil {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Unable to parse TO ESMTP parameters")
return
}
for key, value := range args {
switch key {
case "ORCPT":
case "NOTIFY":
notifyFlags := strings.Split(strings.ToUpper(value), ",")
seenFlags := make(map[string]struct{})
for _, f := range notifyFlags {
if _, ok := seenFlags[f]; ok {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "NOTIFY parameters cannot be specified multiple times")
return
}
switch DSNNotify(f) {
case NotifyNever:
if len(notifyFlags) != 1 {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "NOTIFY=NEVER cannot be combined with other options")
return
}
case NotifyDelayed, NotifySuccess, NotifyFailure:
default:
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Unknown NOTIFY parameter")
return
}
seenFlags[f] = struct{}{}
opts.Notify = append(opts.Notify, DSNNotify(f))
}
}
}
}
if err := c.Session().Rcpt(recipient, RcptOptions{}); err != nil {
if smtpErr, ok := err.(*SMTPError); ok {
c.WriteResponse(smtpErr.Code, smtpErr.EnhancedCode, smtpErr.Message)
return
}
c.WriteResponse(451, EnhancedCode{4, 0, 0}, err.Error())
return
}
c.recipients = append(c.recipients, recipient)
c.WriteResponse(250, EnhancedCode{2, 0, 0}, fmt.Sprintf("I'll make sure <%v> gets this", recipient))
}
func (c *Conn) handleAuth(arg string) {
if c.helo == "" {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "Please introduce yourself first.")
return
}
parts := strings.Fields(arg)
if len(parts) == 0 {
c.WriteResponse(502, EnhancedCode{5, 5, 4}, "Missing parameter")
return
}
if _, isTLS := c.TLSConnectionState(); !isTLS && !c.server.AllowInsecureAuth {
c.WriteResponse(523, EnhancedCode{5, 7, 10}, "TLS is required")
return
}
mechanism := strings.ToUpper(parts[0])
// Parse client initial response if there is one
var ir []byte
if len(parts) > 1 {
var err error
ir, err = base64.StdEncoding.DecodeString(parts[1])
if err != nil {
return
}
}
newSasl, ok := c.server.auths[mechanism]
if !ok {
c.WriteResponse(504, EnhancedCode{5, 7, 4}, "Unsupported authentication mechanism")
return
}
sasl := newSasl(c)
response := ir
for {
challenge, done, err := sasl.Next(response)
if err != nil {
if smtpErr, ok := err.(*SMTPError); ok {
c.WriteResponse(smtpErr.Code, smtpErr.EnhancedCode, smtpErr.Message)
return
}
c.WriteResponse(454, EnhancedCode{4, 7, 0}, err.Error())
return
}
if done {
break
}
encoded := ""
if len(challenge) > 0 {
encoded = base64.StdEncoding.EncodeToString(challenge)
}
c.WriteResponse(334, NoEnhancedCode, encoded)
encoded, err = c.ReadLine()
if err != nil {
return // TODO: error handling
}
if encoded == "*" {
// https://tools.ietf.org/html/rfc4954#page-4
c.WriteResponse(501, EnhancedCode{5, 0, 0}, "Negotiation cancelled")
return
}
response, err = base64.StdEncoding.DecodeString(encoded)
if err != nil {
c.WriteResponse(454, EnhancedCode{4, 7, 0}, "Invalid base64 data")
return
}
}
if c.Session() != nil {
c.WriteResponse(235, EnhancedCode{2, 0, 0}, "Authentication succeeded")
}
}
func (c *Conn) handleStartTLS() {
if _, isTLS := c.TLSConnectionState(); isTLS {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "Already running in TLS")
return
}
if c.server.TLSConfig == nil {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "TLS not supported")
return
}
c.WriteResponse(220, EnhancedCode{2, 0, 0}, "Ready to start TLS")
// Upgrade to TLS
tlsConn := tls.Server(c.conn, c.server.TLSConfig)
if err := tlsConn.Handshake(); err != nil {
c.server.ErrorLog.Printf("TLS handshake error for %s: %v", c.conn.RemoteAddr(), err)
c.WriteResponse(550, EnhancedCode{5, 0, 0}, "Handshake error")
}
c.conn = tlsConn
c.init()
// Reset all state and close the previous Session.
// This is different from just calling reset() since we want the Backend to
// be able to see the information about TLS connection in the
// ConnectionState object passed to it.
if session := c.Session(); session != nil {
session.Logout()
c.SetSession(nil)
}
c.reset()
}
// DATA
func (c *Conn) handleData(arg string) {
if arg != "" {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "DATA command should not have any arguments")
return
}
if c.bdatPipe != nil {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "DATA not allowed during message transfer")
return
}
if c.binarymime {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "DATA not allowed for BINARYMIME messages")
return
}
if !c.fromReceived || len(c.recipients) == 0 {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "Missing RCPT TO command.")
return
}
// We have recipients, go to accept data
c.WriteResponse(354, EnhancedCode{2, 0, 0}, "Go ahead. End your data with <CR><LF>.<CR><LF>")
defer c.reset()
if c.server.LMTP {
c.handleDataLMTP()
return
}
r := newDataReader(c)
code, enhancedCode, msg := toSMTPStatus(c.Session().Data(r))
r.limited = false
io.Copy(ioutil.Discard, r) // Make sure all the data has been consumed
c.WriteResponse(code, enhancedCode, msg)
}
func (c *Conn) handleBdat(arg string) {
args := strings.Fields(arg)
if len(args) == 0 {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Missing chunk size argument")
return
}
if len(args) > 2 {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Too many arguments")
return
}
if !c.fromReceived || len(c.recipients) == 0 {
c.WriteResponse(502, EnhancedCode{5, 5, 1}, "Missing RCPT TO command.")
return
}
last := false
if len(args) == 2 {
if !strings.EqualFold(args[1], "LAST") {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Unknown BDAT argument")
return
}
last = true
}
// ParseUint instead of Atoi so we will not accept negative values.
size, err := strconv.ParseUint(args[0], 10, 32)
if err != nil {
c.WriteResponse(501, EnhancedCode{5, 5, 4}, "Malformed size argument")
return
}
if c.server.MaxMessageBytes != 0 && c.bytesReceived+int(size) > c.server.MaxMessageBytes {
c.WriteResponse(552, EnhancedCode{5, 3, 4}, "Max message size exceeded")
// Discard chunk itself without passing it to backend.
io.Copy(ioutil.Discard, io.LimitReader(c.text.R, int64(size)))
c.reset()
return
}
if c.bdatStatus == nil && c.server.LMTP {
c.bdatStatus = c.createStatusCollector()
}
if c.bdatPipe == nil {
var r *io.PipeReader
r, c.bdatPipe = io.Pipe()
c.dataResult = make(chan error, 1)
go func() {
defer func() {
if err := recover(); err != nil {
c.handlePanic(err, c.bdatStatus)
c.dataResult <- errPanic
r.CloseWithError(errPanic)
}
}()
var err error
if !c.server.LMTP {
err = c.Session().Data(r)
} else {
lmtpSession, ok := c.Session().(LMTPSession)
if !ok {
err = c.Session().Data(r)
for _, rcpt := range c.recipients {
c.bdatStatus.SetStatus(rcpt, err)
}
} else {
err = lmtpSession.LMTPData(r, c.bdatStatus)
}
}
c.dataResult <- err
r.CloseWithError(err)
}()
}
chunk := io.LimitReader(c.text.R, int64(size))
_, err = io.Copy(c.bdatPipe, chunk)
if err != nil {
// Backend might return an error early using CloseWithError without consuming
// the whole chunk.
io.Copy(ioutil.Discard, chunk)
c.WriteResponse(toSMTPStatus(err))
if err == errPanic {
c.Close()
}
c.reset()
return
}
c.bytesReceived += int(size)
if last {
c.bdatPipe.Close()
err := <-c.dataResult
if c.server.LMTP {
c.bdatStatus.fillRemaining(err)
for i, rcpt := range c.recipients {
code, enchCode, msg := toSMTPStatus(<-c.bdatStatus.status[i])
c.WriteResponse(code, enchCode, "<"+rcpt+"> "+msg)
}
} else {
c.WriteResponse(toSMTPStatus(err))
}
if err == errPanic {
c.Close()
return
}
c.reset()
} else {
c.WriteResponse(250, EnhancedCode{2, 0, 0}, "Continue")
}
}
// ErrDataReset is returned by Reader pased to Data function if client does not
// send another BDAT command and instead closes connection or issues RSET command.
var ErrDataReset = errors.New("smtp: message transmission aborted")
var errPanic = &SMTPError{
Code: 421,
EnhancedCode: EnhancedCode{4, 0, 0},
Message: "Internal server error",
}
func (c *Conn) handlePanic(err interface{}, status *statusCollector) {
if status != nil {
status.fillRemaining(errPanic)
}
stack := debug.Stack()
c.server.ErrorLog.Printf("panic serving %v: %v\n%s", c.State().RemoteAddr, err, stack)
}
func (c *Conn) createStatusCollector() *statusCollector {
rcptCounts := make(map[string]int, len(c.recipients))
status := &statusCollector{
statusMap: make(map[string]chan error, len(c.recipients)),
status: make([]chan error, 0, len(c.recipients)),
}
for _, rcpt := range c.recipients {
rcptCounts[rcpt]++
}
// Create channels with buffer sizes necessary to fit all
// statuses for a single recipient to avoid deadlocks.
for rcpt, count := range rcptCounts {
status.statusMap[rcpt] = make(chan error, count)
}
for _, rcpt := range c.recipients {
status.status = append(status.status, status.statusMap[rcpt])
}
return status
}
type statusCollector struct {
// Contains map from recipient to list of channels that are used for that
// recipient.
statusMap map[string]chan error
// Contains channels from statusMap, in the same
// order as Conn.recipients.
status []chan error
}
// fillRemaining sets status for all recipients SetStatus was not called for before.
func (s *statusCollector) fillRemaining(err error) {
// Amount of times certain recipient was specified is indicated by the channel
// buffer size, so once we fill it, we can be confident that we sent
// at least as much statuses as needed. Extra statuses will be ignored anyway.
chLoop:
for _, ch := range s.statusMap {
for {
select {
case ch <- err:
default:
continue chLoop
}
}
}
}
func (s *statusCollector) SetStatus(rcptTo string, err error) {
ch := s.statusMap[rcptTo]
if ch == nil {
panic("SetStatus is called for recipient that was not specified before")
}
select {
case ch <- err:
default:
// There enough buffer space to fit all statuses at once, if this is
// not the case - backend is doing something wrong.
panic("SetStatus is called more times than particular recipient was specified")
}
}
func (c *Conn) handleDataLMTP() {
r := newDataReader(c)
status := c.createStatusCollector()
done := make(chan bool, 1)
lmtpSession, ok := c.Session().(LMTPSession)
if !ok {
// Fallback to using a single status for all recipients.
err := c.Session().Data(r)
io.Copy(ioutil.Discard, r) // Make sure all the data has been consumed