-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathserver.go
302 lines (258 loc) · 8.36 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
package smtpmock
import (
"errors"
"fmt"
"net"
"strings"
"sync"
"time"
)
// WaitGroup interface
type waitGroup interface {
Add(int)
Done()
Wait()
}
// Server structure which implements SMTP mock server
type Server struct {
configuration *configuration
messages *messages
logger logger
listener net.Listener
wg waitGroup
quit chan interface{}
started bool
portNumber int
quitTimeout chan interface{}
sync.Mutex
}
// SMTP mock server builder, creates new server
func newServer(configuration *configuration) *Server {
return &Server{
configuration: configuration,
messages: new(messages),
logger: newLogger(configuration.logToStdout, configuration.logServerActivity),
wg: new(sync.WaitGroup),
}
}
// server methods
// Start binds and runs SMTP mock server on specified port or random free port. Returns error for
// case when server is active. Server port number will be assigned after successful start only
func (server *Server) Start() (err error) {
if server.isStarted() {
return errors.New(serverStartErrorMsg)
}
configuration, logger := server.configuration, server.logger
portNumber := configuration.portNumber
listener, err := net.Listen(networkProtocol, serverWithPortNumber(configuration.hostAddress, portNumber))
if err != nil {
errorMessage := fmt.Sprintf("%s: %d", serverErrorMsg, portNumber)
logger.error(errorMessage)
return errors.New(errorMessage)
}
portNumber = listener.Addr().(*net.TCPAddr).Port
server.setListener(listener)
server.setPortNumber(portNumber)
server.start()
server.quit, server.quitTimeout = make(chan interface{}), make(chan interface{})
logger.infoActivity(fmt.Sprintf("%s: %d", serverStartMsg, portNumber))
server.addToWaitGroup()
go func() {
defer server.removeFromWaitGroup()
for {
connection, err := server.listener.Accept()
if err != nil {
if _, ok := <-server.quit; !ok {
logger.warning(serverNotAcceptNewConnectionsMsg)
}
return
}
server.addToWaitGroup()
go func() {
server.handleSession(newSession(connection, logger))
server.removeFromWaitGroup()
}()
logger.infoActivity(sessionStartMsg)
}
}()
return err
}
// Stop shutdowns server gracefully or force by timeout.
// Returns error for case when server is not active
func (server *Server) Stop() (err error) {
if server.isStarted() {
close(server.quit)
server.listener.Close()
go func() {
server.wg.Wait()
server.quitTimeout <- true
server.stop()
server.logger.infoActivity(serverStopMsg)
}()
select {
case <-server.quitTimeout:
case <-time.After(time.Duration(server.configuration.shutdownTimeout) * time.Second):
server.stop()
server.logger.infoActivity(serverForceStopMsg)
}
return
}
return errors.New(serverStopErrorMsg)
}
// Public interface to get access to server messages.
// Returns slice with copy of messages
func (server *Server) Messages() []Message {
return server.messages.copy()
}
// WaitForMessages waits for the specified number of messages to arrive or until timeout is reached.
// Returns the messages and an error if timeout occurs before receiving expected number of messages.
func (server *Server) WaitForMessages(count int, timeout time.Duration) ([]Message, error) {
return server.fetchMessages(count, timeout, false)
}
// Public interface to get access to server messages
// and at the same time removes them.
// Returns slice with copy of messages
func (server *Server) MessagesAndPurge() []Message {
return server.messages.purge()
}
// WaitForMessagesAndPurge waits for the specified number of messages to arrive or until timeout is reached.
// Returns the messages and an error if timeout occurs before receiving expected number of messages.
// At the same time removes the messages from the server.
func (server *Server) WaitForMessagesAndPurge(count int, timeout time.Duration) ([]Message, error) {
return server.fetchMessages(count, timeout, true)
}
// Thread-safe getter of server port.
// Returns server.portNumber
func (server *Server) PortNumber() int {
server.Lock()
defer server.Unlock()
return server.portNumber
}
// fetchMessages fetches messages with timeout from the server with or without purging.
// Returns messages and an error if timeout occurs before receiving expected number of messages.
func (server *Server) fetchMessages(count int, timeout time.Duration, withPurge bool) ([]Message, error) {
deadline := time.Now().Add(timeout)
for {
messages := server.Messages()
messageCount := len(messages)
if messageCount >= count {
if withPurge {
server.messages.clear()
}
return messages, nil
}
if time.Now().After(deadline) {
return messages, fmt.Errorf("timeout waiting for %d messages, got %d", count, messageCount)
}
time.Sleep(1 * time.Millisecond)
}
}
// Thread-safe getter to check if server has been started.
// Returns server.started
func (server *Server) isStarted() bool {
server.Lock()
defer server.Unlock()
return server.started
}
// Thread-safe setter of server.listener
func (server *Server) setListener(listener net.Listener) {
server.Lock()
defer server.Unlock()
server.listener = listener
}
// Thread-safe setter of server.portNumber
func (server *Server) setPortNumber(port int) {
server.Lock()
defer server.Unlock()
server.portNumber = port
}
// Thread-safe setter of started-flag to indicate server has been started
func (server *Server) start() {
server.Lock()
defer server.Unlock()
server.started = true
}
// Thread-safe setter of started-flag to indicate server has been stopped
func (server *Server) stop() {
server.Lock()
defer server.Unlock()
server.started = false
}
// Creates and assigns new message with helo context from other message to server.messages
func (server *Server) newMessageWithHeloContext(otherMessage *Message) *Message {
newMessage := new(Message)
newMessage.heloRequest = otherMessage.heloRequest
newMessage.heloResponse = otherMessage.heloResponse
newMessage.helo = otherMessage.helo
server.messages.append(otherMessage)
return newMessage
}
// Invalid SMTP command predicate. Returns true when command is invalid, otherwise returns false
func (server *Server) isInvalidCmd(request string) bool {
return !matchRegex(request, availableCmdsRegexPattern)
}
// Recognizes command implemented commands. Captures the first word divided by spaces,
// converts it to upper case
func (server *Server) recognizeCommand(request string) string {
command := strings.Split(request, " ")[0]
return strings.ToUpper(command)
}
// Addes goroutine to WaitGroup
func (server *Server) addToWaitGroup() {
server.wg.Add(1)
}
// Removes goroutine from WaitGroup
func (server *Server) removeFromWaitGroup() {
server.wg.Done()
}
// Checks ability to end current session
func (server *Server) isAbleToEndSession(message *Message, session sessionInterface) bool {
return message.quitSent || (session.isErrorFound() && server.configuration.isCmdFailFast)
}
//nolint:gocyclo // SMTP client-server session handler
func (server *Server) handleSession(session sessionInterface) {
defer session.finish()
message, configuration := new(Message), server.configuration
defer func() {
server.messages.append(message)
}()
session.writeResponse(configuration.msgGreeting, defaultSessionResponseDelay)
for {
select {
case <-server.quit:
return
default:
session.setTimeout(configuration.sessionTimeout)
request, err := session.readRequest()
if err != nil {
return
}
if server.isInvalidCmd(request) {
session.writeResponse(configuration.msgInvalidCmd, defaultSessionResponseDelay)
continue
}
switch server.recognizeCommand(request) {
case "HELO", "EHLO":
newHandlerHelo(session, message, configuration).run(request)
case "MAIL":
if configuration.multipleMessageReceiving && message.rset && message.IsConsistent() {
message = server.newMessageWithHeloContext(message)
}
newHandlerMailfrom(session, message, configuration).run(request)
case "RCPT":
newHandlerRcptto(session, message, configuration).run(request)
case "DATA":
newHandlerData(session, message, configuration).run(request)
case "RSET":
newHandlerRset(session, message, configuration).run(request)
case "NOOP":
newHandlerNoop(session, message, configuration).run(request)
case "QUIT":
newHandlerQuit(session, message, configuration).run(request)
}
if server.isAbleToEndSession(message, session) {
return
}
}
}
}