-
Notifications
You must be signed in to change notification settings - Fork 2
/
session.go
333 lines (297 loc) · 8.7 KB
/
session.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
// Copyright (C) 2019 Adrien Aury
//
// This file is part of Mailmock.
//
// Mailmock is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Mailmock is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Mailmock. If not, see <https://www.gnu.org/licenses/>.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
package smtpd
import (
"fmt"
"io"
"net"
"net/textproto"
"time"
"github.com/adrienaury/mailmock/internal/log"
)
// SessionState is the state of a Session.
type SessionState string
// Session States
const (
SSInitiated SessionState = "initiated"
SSReady SessionState = "ready"
SSBusy SessionState = "busy"
SSClosed SessionState = "closed"
)
// TransactionHandler will be called each time a transaction reach TSCompleted or TSAborted status.
type TransactionHandler func(*Transaction)
// Session represents a SMTP session of a client.
type Session struct {
State SessionState `json:"state"`
Client string `json:"client"`
Tr *Transaction `json:"transaction"`
Extended bool
conn *textproto.Conn
th *TransactionHandler
logger log.Logger
tcpConn *net.TCPConn
mustStop bool
}
// NewSession return a new Session.
func NewSession(c *textproto.Conn, th *TransactionHandler, logger log.Logger) *Session {
s := &Session{State: SSInitiated, conn: c, th: th, logger: nil}
if logger == nil {
logger = log.DefaultLogger
}
l := logger.WithFields(log.Fields{
log.FieldSession: s,
})
s.logger = l
s.logger.Info("Initiated new session")
return s
}
// Serve will reponds to any request until a QUIT command is received or connection is broken.
func (s *Session) Serve(stop <-chan struct{}) {
if s.State == SSClosed {
s.logger.Warn("Cannot serve a closed session")
if err := s.conn.PrintfLine("%v", r(NotAvailable)); err != nil {
s.logger.Error("Failed to send response to client", log.Fields{log.FieldError: err, log.FieldResponse: r(NotAvailable)})
}
return
}
if err := s.conn.PrintfLine("%v", r(Ready)); err != nil {
s.logger.Error("Failed to send greeting message, quitting session", log.Fields{log.FieldError: err, log.FieldResponse: r(Ready)})
s.quit()
return
}
shutdown := make(chan struct{})
defer close(shutdown)
go func() {
// Block until either stop or shutdown signal
select {
case <-stop:
s.mustStop = true
s.logger.Warn("Server must stop, session will timeout in 30 seconds (at most)")
<-time.After(30 * time.Second)
if s.tcpConn != nil {
_ = s.tcpConn.SetReadDeadline(time.Now())
}
case <-shutdown:
}
<-time.After(5 * time.Second)
s.conn.Close()
}()
s.serveLoop(stop)
}
func (s *Session) serveLoop(stop <-chan struct{}) {
for s.State != SSClosed {
var res *Response
if s.tcpConn != nil {
// SMTP server SHOULD have a timeout of at least 5 minutes while it
// is awaiting the next command from the sender (RFC 5321 4.5.3.2.7.)
if err := s.tcpConn.SetReadDeadline(time.Now().Add(time.Minute * 5)); err != nil {
s.logger.Error("SetDeadline on SMTP session failed", log.Fields{log.FieldError: err})
}
}
input, err := s.conn.ReadLine()
errop, ok := err.(net.Error)
switch {
case err == io.EOF || err == io.ErrClosedPipe:
s.logger.Error("Lost client connection, quitting", log.Fields{log.FieldError: err})
res = s.quit()
case ok && errop.Timeout():
if s.mustStop {
s.logger.Warn("Session interrupted because server is shutting down")
} else {
s.logger.Warn("Session timed out")
}
if err := s.conn.PrintfLine("%v", r(SessionTimeout)); err != nil {
s.logger.Error("Failed to send response to client", log.Fields{log.FieldError: err, log.FieldResponse: r(SessionTimeout)})
}
return
case err != nil:
s.logger.Error("Network error, requested action cannot be processed", log.Fields{log.FieldError: err})
res = r(Abort)
default:
s.logger.Debug("Received command", log.Fields{log.FieldCommand: input})
res = s.receive(input)
if res.IsError() {
s.logger.Warn("Processed command", log.Fields{log.FieldCommand: input, log.FieldResponse: res})
} else {
s.logger.Info("Processed command", log.Fields{log.FieldCommand: input, log.FieldResponse: res})
}
}
select {
case <-stop:
// We need to shutdown
s.logger.Warn("Session interrupted because server is shutting down")
if err := s.conn.PrintfLine("%v", r(ShuttingDown)); err != nil {
s.logger.Error("Failed to send response to client", log.Fields{log.FieldError: err, log.FieldResponse: r(ShuttingDown)})
}
return
default:
}
if err := s.conn.PrintfLine("%v", res); err != nil {
s.logger.Error("Network error, failed to send response, quitting", log.Fields{log.FieldError: err, log.FieldResponse: res})
s.quit()
return
}
s.handleTransaction()
}
}
func (s *Session) receive(input string) (res *Response) {
cmd, res := ParseCommand(input)
if res != nil {
return res
}
switch cmd.Name {
case "HELO":
res = s.hello(cmd.PositionalArgs[0], false)
case "EHLO":
res = s.hello(cmd.PositionalArgs[0], true)
case "MAIL":
res = s.mail(cmd)
case "RCPT":
res = s.rcpt(cmd)
case "DATA":
res = s.data(cmd)
case "NOOP":
res = s.noop()
case "RSET":
res = s.reset()
case "QUIT":
res = s.quit()
case "VRFY":
res = s.verify(cmd.PositionalArgs[0])
case "HELP":
res = s.help(cmd.PositionalArgs)
default:
s.logger.Error("Coding error, this should not happen")
}
return res
}
func (s *Session) hello(client string, extended bool) *Response {
s.Client = client
s.State = SSReady
if extended {
s.Extended = true
return r(Extensions)
}
return r(Success)
}
func (s *Session) mail(cmd *Command) *Response {
if s.State != SSReady {
return r(BadSequence)
}
s.Tr = NewTransaction()
s.logger.Debug("Started transaction")
res, err := s.Tr.Process(cmd)
if err != nil {
return r(Abort)
}
s.State = SSBusy
return res
}
func (s *Session) rcpt(cmd *Command) *Response {
if s.State != SSBusy {
return r(BadSequence)
}
res, err := s.Tr.Process(cmd)
if err != nil {
return r(Abort)
}
return res
}
func (s *Session) data(cmd *Command) *Response {
if s.State != SSBusy {
return r(BadSequence)
}
if len(s.Tr.Mail.Envelope.Recipients) == 0 {
return r(NoValidRecipients)
}
res, err := s.Tr.Process(cmd)
if err != nil {
return r(Abort)
}
if err = s.conn.PrintfLine("%v", res); err != nil {
s.logger.Error("Failed to send response to client", log.Fields{log.FieldError: err, log.FieldResponse: res})
return r(Abort)
}
data, err := s.conn.ReadDotLines()
if err != nil {
return r(Abort)
}
res, err = s.Tr.Data(data)
if err != nil {
return r(Abort)
}
s.State = SSReady
return res
}
func (s *Session) verify(string) *Response {
return r(CommandNotImplemented)
}
func (s *Session) noop() *Response {
return r(Success)
}
func (s *Session) reset() *Response {
err := s.Tr.Abort()
if err != nil {
return r(Abort)
}
if s.Client != "" {
s.State = SSReady
} else {
s.State = SSInitiated
}
return r(Success)
}
func (s *Session) quit() *Response {
s.State = SSClosed
_ = s.Tr.Abort()
return r(Closing)
}
func (s *Session) help([]string) *Response {
if !s.Extended {
return r(CommandUnrecognized)
}
return r(Help)
}
func (s *Session) handleTransaction() {
if s.Tr != nil && (s.Tr.State == TSCompleted || s.Tr.State == TSAborted) {
s.logger.Debug("Ended transaction")
if s.th != nil && (*s.th) != nil {
(*s.th)(s.Tr)
}
s.Tr = nil
}
}
func (s *Session) String() string {
return fmt.Sprintf("%p[%v]", s, s.State)
}