-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsmtpd.go
239 lines (186 loc) · 4.43 KB
/
smtpd.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
package smtpd
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/mail"
"sync"
logging "github.com/op/go-logging"
)
var log = logging.MustGetLogger("smtpd")
var receiveChan chan mail.Message
type Handler interface {
Serve(msg Message) error
}
type HandlerFunc func(msg Message) error
type ServeMux struct {
m []HandlerFunc
mu sync.RWMutex
}
func (mux *ServeMux) HandleFunc(handler func(msg Message) error) {
mux.mu.Lock()
defer mux.mu.Unlock()
mux.m = append(mux.m, handler)
}
func HandleFunc(handler func(msg Message) error) *ServeMux {
DefaultServeMux.HandleFunc(handler)
return DefaultServeMux
}
var DefaultServeMux = NewServeMux()
func NewServeMux() *ServeMux { return &ServeMux{m: make([]HandlerFunc, 0)} }
type Server struct {
*Config
}
type smtpServer struct {
ID string
Banner func() string
TLSConfig *tls.Config
Handler Handler
starttls bool
}
var ErrServerClosed = errors.New("SMTPd Closed.")
//ListenAndServe starts serving smtp on the configured listeners.
//Always returns an error.
func (s *Server) ListenAndServe(ctx context.Context) error {
//lctx, cancel := context.WithCancel(ctx)
//defer cancel()
wg := &sync.WaitGroup{}
log.Debugf("Starting %d listeners.", len(s.Listeners))
//keep track of listeners to close them.
listeners := make([]*onceCloseListener, 0, 2)
for _, ln := range s.Listeners {
server := &smtpServer{
ID: ln.ID,
Banner: ln.Banner,
TLSConfig: ln.TLSConfig,
Handler: ln.Handler,
}
var (
listen net.Listener
err error
)
switch ln.Mode {
case "plain":
//STARTTLS is optional.
listen, err = net.Listen("tcp", ln.Address+":"+ln.Port)
if err != nil {
return fmt.Errorf("Listener: %+v, error: %w", ln, err)
}
server.starttls = true
if server.TLSConfig == nil {
server.starttls = false
}
case "starttls":
//TODO (jerry 2020-03-30): Force STARTTLS.
if server.TLSConfig == nil {
return fmt.Errorf("Mode: tls, need a tls.Config")
}
listen, err = net.Listen("tcp", ln.Address+":"+ln.Port)
if err != nil {
return fmt.Errorf("Listener: %+v, error: %w", ln, err)
}
server.starttls = true
case "tls":
if server.TLSConfig == nil {
return fmt.Errorf("Mode: tls, need a tls.Config")
}
listen, err = tls.Listen("tcp", ln.Address+":"+ln.Port, server.TLSConfig)
if err != nil {
return fmt.Errorf("Listener: %+v, error: %w", ln, err)
}
server.starttls = false
}
l := &onceCloseListener{Listener: listen}
wg.Add(1)
go server.serve(l, wg)
listeners = append(listeners, l)
log.Infof("Server: '%s' start serving on port %s in %s mode.", ln.ID, ln.Port, ln.Mode)
}
if len(listeners) == 0 {
return fmt.Errorf("No Listeners started; %w", ErrServerClosed)
}
//wait for cancelation for a clean shutdown.
<-ctx.Done()
log.Info("SMTPd shutting down...")
for _, l := range listeners {
l.Close()
}
wg.Wait()
return ErrServerClosed
}
func (s *smtpServer) serve(ln net.Listener, wg *sync.WaitGroup) {
defer ln.Close()
defer wg.Done()
for {
conn, err := ln.Accept()
if err != nil {
if ne, ok := err.(net.Error); ok && ne.Temporary() {
log.Debugf("Accept error: %v; retrying", err)
continue
}
log.Errorf("Error accept (Listener: %s): %v; closing", s.ID, err)
return
}
c, err := s.newConn(conn)
if err != nil {
continue
}
go c.serve()
}
}
func New(options ...func(*Config) error) (*Server, error) {
cfg := &Config{
Listeners: make([]Listener, 0, 2),
}
for _, optionFn := range options {
if err := optionFn(cfg); err != nil {
return nil, err
}
}
server := &Server{
Config: cfg,
}
return server, nil
}
func (s *ServeMux) Serve(msg Message) error {
for _, h := range s.m {
if err := h(msg); err != nil {
return err
}
}
return nil
}
func (s *smtpServer) newConn(rwc net.Conn) (c *conn, err error) {
c = &conn{
server: s,
rwc: rwc,
i: 0,
}
c.msg = c.newMessage()
return c, nil
}
type serverHandler struct {
srv *smtpServer
}
func (sh serverHandler) Serve(msg Message) {
handler := sh.srv.Handler
if handler == nil {
handler = DefaultServeMux
}
handler.Serve(msg)
}
//onceCloseListener wraps a net.Listener. Protecting it from multiple Close calls.
type onceCloseListener struct {
net.Listener
once sync.Once
closeErr error
}
func (oc *onceCloseListener) Close() error {
oc.once.Do(oc.close)
return oc.closeErr
}
func (oc *onceCloseListener) close() {
oc.closeErr = oc.Listener.Close()
}