-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
121 lines (116 loc) · 2.72 KB
/
handler.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
package imap
import (
"bytes"
"crypto/tls"
"errors"
"fmt"
"io"
"regexp"
"strconv"
)
var (
// ErrResultNo means that NO response is received.
ErrResultNo = errors.New("result NO")
// ErrResultBad means that BAD response is received.
ErrResultBad = errors.New("result BAD")
)
var regexOK, _ = regexp.Compile(`^([0-9]+) ([A-Z]{2,3}).*\r\n$`)
var regexBulkStart, _ = regexp.Compile(`^.*{(\d+)}\r\n$`)
func (c *Client) listen() {
var line []byte
var err error
for line, err = c.r.ReadBytes('\n'); err == nil; line, err = c.r.ReadBytes('\n') {
if c.Debug != nil {
fmt.Fprintln(c.Debug, "read: ", string(line))
}
switch c.state {
case justConnected:
if bytes.HasPrefix(line, []byte("* OK")) {
c.state = normal
}
case normal:
if bytes.HasPrefix(line, []byte("* BYE")) {
break
}
if bytes.HasPrefix(line, []byte("* ")) {
if c.selectedMailbox != nil {
updated := false
if ind := bytes.Index(line, []byte(" EXISTS\r\n")); ind != -1 {
c.selectedMailbox.Exists, _ = strconv.Atoi(string(line[2:ind]))
updated = true
}
if ind := bytes.Index(line, []byte(" RECENT\r\n")); ind != -1 {
c.selectedMailbox.Recent, _ = strconv.Atoi(string(line[2:ind]))
updated = true
}
if updated {
if c.Debug != nil {
fmt.Fprintln(c.Debug, "updated: ", *c.selectedMailbox)
}
if c.UpdateCallback != nil {
go c.UpdateCallback()
}
}
}
c.latestRep = append(c.latestRep, line[2:])
if submatch := regexBulkStart.FindSubmatch(line); submatch != nil {
bulkSize, _ := strconv.Atoi(string(submatch[1]))
bulk := make([]byte, bulkSize)
_, err := io.ReadFull(c.r, bulk)
if err != nil {
break
}
_, err = c.r.ReadBytes('\n')
if err != nil {
break
}
c.latestRep = append(c.latestRep, bulk)
}
continue
}
if submatch := regexOK.FindSubmatch(line); submatch != nil {
data := append([][]byte(nil), c.latestRep...)
c.latestRep = nil
if c.rep == nil {
continue
}
if string(submatch[2]) == "NO" {
c.rep <- &repValue{
err: ErrResultNo,
data: nil,
}
continue
}
if string(submatch[2]) == "BAD" {
c.rep <- &repValue{
err: ErrResultBad,
data: nil,
}
continue
}
if c.cmd == "STARTTLS" {
tlsConn := tls.Client(c.conn, &tls.Config{ServerName: c.tlsHostname})
err := tlsConn.Handshake()
if err != nil {
break
}
c.conn = tlsConn
c.r.Reset(c.conn)
}
c.rep <- &repValue{
err: nil,
data: data,
}
continue
}
c.latestRep = append(c.latestRep, line)
}
}
c.conn.Close()
if c.rep != nil {
c.rep <- &repValue{
err: ErrConnDead,
data: nil,
}
}
}