forked from inbucket/inbucket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
listener.go
96 lines (88 loc) · 2.42 KB
/
listener.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
package pop3d
import (
"fmt"
"github.com/jhillyerd/inbucket/config"
"github.com/jhillyerd/inbucket/log"
"github.com/jhillyerd/inbucket/smtpd"
"net"
"sync"
"time"
)
// Real server code starts here
type Server struct {
domain string
maxIdleSeconds int
dataStore smtpd.DataStore
listener net.Listener
shutdown bool
waitgroup *sync.WaitGroup
}
// Init a new Server object
func New() *Server {
// TODO is two filestores better/worse than sharing w/ smtpd?
ds := smtpd.DefaultFileDataStore()
cfg := config.GetPop3Config()
return &Server{domain: cfg.Domain, dataStore: ds, maxIdleSeconds: cfg.MaxIdleSeconds,
waitgroup: new(sync.WaitGroup)}
}
// Main listener loop
func (s *Server) Start() {
cfg := config.GetPop3Config()
addr, err := net.ResolveTCPAddr("tcp4", fmt.Sprintf("%v:%v",
cfg.Ip4address, cfg.Ip4port))
if err != nil {
log.LogError("POP3 Failed to build tcp4 address: %v", err)
// TODO More graceful early-shutdown procedure
panic(err)
}
log.LogInfo("POP3 listening on TCP4 %v", addr)
s.listener, err = net.ListenTCP("tcp4", addr)
if err != nil {
log.LogError("POP3 failed to start tcp4 listener: %v", err)
// TODO More graceful early-shutdown procedure
panic(err)
}
// Handle incoming connections
var tempDelay time.Duration
for sid := 1; ; sid++ {
if conn, err := s.listener.Accept(); err != nil {
if nerr, ok := err.(net.Error); ok && nerr.Temporary() {
// Temporary error, sleep for a bit and try again
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
log.LogError("POP3 accept error: %v; retrying in %v", err, tempDelay)
time.Sleep(tempDelay)
continue
} else {
if s.shutdown {
log.LogTrace("POP3 listener shutting down on request")
return
}
// TODO Implement a max error counter before shutdown?
// or maybe attempt to restart POP3
panic(err)
}
} else {
tempDelay = 0
s.waitgroup.Add(1)
go s.startSession(sid, conn)
}
}
}
// Stop requests the POP3 server closes it's listener
func (s *Server) Stop() {
log.LogTrace("POP3 shutdown requested, connections will be drained")
s.shutdown = true
s.listener.Close()
}
// Drain causes the caller to block until all active POP3 sessions have finished
func (s *Server) Drain() {
s.waitgroup.Wait()
log.LogTrace("POP3 connections drained")
}