forked from unkaktus/mm
/
pop3.go
99 lines (81 loc) · 1.57 KB
/
pop3.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
// pop3.go
package main
import (
"fmt"
"io"
"net"
"net/textproto"
"strings"
)
type POP3Conn struct {
conn *textproto.Conn
}
type Dialer interface {
Dial(network, address string) (net.Conn, error)
}
func ParseResponseLine(input string) (ok bool, msg string, err error) {
s := strings.SplitN(input, " ", 2)
switch s[0] {
case "+OK":
ok = true
case "-ERR":
ok = false
default:
return false, "", fmt.Errorf("Status malformed: '%s'", input)
}
if len(s) == 2 {
msg = s[1]
}
return ok, msg, nil
}
func (pc *POP3Conn) Cmd(format string, args ...interface{}) (string, error) {
c := pc.conn
id, err := c.Cmd(format, args...)
if err != nil {
return "", err
}
c.StartResponse(id)
defer c.EndResponse(id)
line, err := c.ReadLine()
if err != nil {
return "", nil
}
ok, rmsg, err := ParseResponseLine(line)
if err != nil {
return "", err
}
if !ok {
return "", fmt.Errorf("%s", rmsg)
}
return rmsg, nil
}
func (pc *POP3Conn) CmdMulti(format string, args ...interface{}) (string, []byte, error) {
c := pc.conn
id, err := c.Cmd(format, args...)
if err != nil {
return "", nil, err
}
c.StartResponse(id)
defer c.EndResponse(id)
line, err := c.ReadLine()
if err != nil {
return "", nil, err
}
ok, rmsg, err := ParseResponseLine(line)
if err != nil {
return "", nil, err
}
if !ok {
return "", nil, fmt.Errorf("%s", rmsg)
}
data, err := c.ReadDotBytes()
if err != nil {
return "", nil, err
}
return rmsg, data, nil
}
func NewPOP3Conn(rwc io.ReadWriteCloser) *POP3Conn {
pc := &POP3Conn{}
pc.conn = textproto.NewConn(rwc)
return pc
}