Debian Codegraph @

pop3.go

raw
1 // Package pop3 is a simple POP3 e-mail client library.
2 package pop3
3
4 import (
5 "bufio"
6 "bytes"
7 "crypto/tls"
8 "errors"
9 "fmt"
10 "net"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/emersion/go-message"
16 )
17
18 // Client implements a Client e-mail client.
19 type Client struct {
20 opt Opt
21 dialer Dialer
22 }
23
24 // Conn is a stateful connection with the POP3 server/
25 type Conn struct {
26 conn net.Conn
27 r *bufio.Reader
28 w *bufio.Writer
29 }
30
31 // Opt represents the client configuration.
32 type Opt struct {
33 Host string `json:"host"`
34 Port int `json:"port"`
35
36 // Default is 3 seconds.
37 DialTimeout time.Duration `json:"dial_timeout"`
38 Dialer Dialer `json:"-"`
39
40 TLSEnabled bool `json:"tls_enabled"`
41 TLSSkipVerify bool `json:"tls_skip_verify"`
42 }
43
44 type Dialer interface {
45 Dial(network, address string) (net.Conn, error)
46 }
47
48 // MessageID contains the ID and size of an individual message.
49 type MessageID struct {
50 // ID is the numerical index (non-unique) of the message.
51 ID int
52 Size int
53
54 // UID is only present if the response is to the UIDL command.
55 UID string
56 }
57
58 var (
59 lineBreak = []byte("\r\n")
60 utf8BOM = []byte{0xEF, 0xBB, 0xBF}
61
62 respOK = []byte("+OK") // `+OK` without additional info
63 respOKInfo = []byte("+OK ") // `+OK <info>`
64 respErr = []byte("-ERR") // `-ERR` without additional info
65 respErrInfo = []byte("-ERR ") // `-ERR <info>`
66 )
67
68 // New returns a new client object using an existing connection.
69 func New(opt Opt) *Client {
70 if opt.DialTimeout < time.Millisecond {
71 opt.DialTimeout = time.Second * 3
72 }
73
74 c := &Client{
75 opt: opt,
76 dialer: opt.Dialer,
77 }
78
79 if c.dialer == nil {
80 c.dialer = &net.Dialer{Timeout: opt.DialTimeout}
81 }
82
83 return c
84 }
85
86 // NewConn creates and returns live POP3 server connection.
87 func (c *Client) NewConn() (*Conn, error) {
88 var (
89 addr = fmt.Sprintf("%s:%d", c.opt.Host, c.opt.Port)
90 )
91
92 conn, err := c.dialer.Dial("tcp", addr)
93 if err != nil {
94 return nil, err
95 }
96
97 // No TLS.
98 if c.opt.TLSEnabled {
99 // Skip TLS host verification.
100 tlsCfg := tls.Config{}
101 if c.opt.TLSSkipVerify {
102 tlsCfg.InsecureSkipVerify = c.opt.TLSSkipVerify
103 } else {
104 tlsCfg.ServerName = c.opt.Host
105 }
106
107 conn = tls.Client(conn, &tlsCfg)
108 }
109
110 pCon := &Conn{
111 conn: conn,
112 r: bufio.NewReader(conn),
113 w: bufio.NewWriter(conn),
114 }
115
116 // Verify the connection by reading the welcome +OK greeting.
117 if _, err := pCon.ReadOne(); err != nil {
118 return nil, err
119 }
120
121 return pCon, nil
122 }
123
124 // Send sends a POP3 command to the server. The given comand is suffixed with "\r\n".
125 func (c *Conn) Send(b string) error {
126 if _, err := c.w.WriteString(b + "\r\n"); err != nil {
127 return err
128 }
129 return c.w.Flush()
130 }
131
132 // Cmd sends a command to the server. POP3 responses are either single line or multi-line.
133 // The first line always with -ERR in case of an error or +OK in case of a successful operation.
134 // OK+ is always followed by a response on the same line which is either the actual response data
135 // in case of single line responses, or a help message followed by multiple lines of actual response
136 // data in case of multiline responses.
137 // See https://www.shellhacks.com/retrieve-email-pop3-server-command-line/ for examples.
138 func (c *Conn) Cmd(cmd string, isMulti bool, args ...interface{}) (*bytes.Buffer, error) {
139 var cmdLine string
140
141 // Repeat a %v to format each arg.
142 if len(args) > 0 {
143 format := " " + strings.TrimRight(strings.Repeat("%v ", len(args)), " ")
144
145 // CMD arg1 argn ...\r\n
146 cmdLine = cmd + fmt.Sprintf(format, args...)
147 } else {
148 cmdLine = cmd
149 }
150
151 if err := c.Send(cmdLine); err != nil {
152 return nil, err
153 }
154
155 // Read the first line of response to get the +OK/-ERR status.
156 b, err := c.ReadOne()
157 if err != nil {
158 return nil, err
159 }
160
161 // Single line response.
162 if !isMulti {
163 return bytes.NewBuffer(b), err
164 }
165
166 buf, err := c.ReadAll()
167 return buf, err
168 }
169
170 // ReadOne reads a single line response from the conn.
171 func (c *Conn) ReadOne() ([]byte, error) {
172 b, err := c.r.ReadBytes('\n')
173 if err != nil {
174 return nil, err
175 }
176
177 b = bytes.TrimSuffix(b, []byte("\r\n"))
178 b = bytes.TrimSuffix(b, []byte("\n"))
179
180 r, err := parseResp(b)
181 return r, err
182 }
183
184 // ReadAll reads all lines from the connection until the POP3 multiline terminator "." is encountered
185 // and returns a bytes.Buffer of all the read lines.
186 func (c *Conn) ReadAll() (*bytes.Buffer, error) {
187 buf := &bytes.Buffer{}
188
189 for {
190 line, err := c.r.ReadBytes('\n')
191 if err != nil {
192 return nil, err
193 }
194
195 // Strip the trailing protocol line break.
196 line = bytes.TrimSuffix(line, []byte("\r\n"))
197 line = bytes.TrimSuffix(line, []byte("\n"))
198
199 // "." indicates the end of a multi-line response.
200 if bytes.Equal(line, []byte(".")) {
201 break
202 }
203
204 // Remove the leading dot from lines starting with ".".
205 // Spec "byte-stuffs" lines starting with "." by prefixing them with an additional dot
206 // to prevent mis-interpretation of the line as the end of the multi-line response.
207 // So, remove the leading dot.
208 if bytes.HasPrefix(line, []byte(".")) {
209 line = line[1:]
210 }
211
212 if _, err := buf.Write(line); err != nil {
213 return nil, err
214 }
215 if _, err := buf.Write(lineBreak); err != nil {
216 return nil, err
217 }
218 }
219
220 return buf, nil
221 }
222
223 // Auth authenticates the given credentials with the server.
224 func (c *Conn) Auth(user, password string) error {
225 if err := c.User(user); err != nil {
226 return err
227 }
228
229 if err := c.Pass(password); err != nil {
230 return err
231 }
232
233 // Issue a NOOP to force the server to respond to the auth.
234 // Couresy: github.com/TheCreeper/go-pop3
235 return c.Noop()
236 }
237
238 // User sends the username to the server.
239 func (c *Conn) User(s string) error {
240 _, err := c.Cmd("USER", false, s)
241 return err
242 }
243
244 // Pass sends the password to the server.
245 func (c *Conn) Pass(s string) error {
246 _, err := c.Cmd("PASS", false, s)
247 return err
248 }
249
250 // Stat returns the number of messages and their total size in bytes in the inbox.
251 func (c *Conn) Stat() (int, int, error) {
252 b, err := c.Cmd("STAT", false)
253 if err != nil {
254 return 0, 0, err
255 }
256
257 // count size
258 f := bytes.Fields(b.Bytes())
259 if len(f) < 2 {
260 return 0, 0, fmt.Errorf("malformed STAT response")
261 }
262
263 // Total number of messages.
264 count, err := strconv.Atoi(string(f[0]))
265 if err != nil {
266 return 0, 0, err
267 }
268 if count == 0 {
269 return 0, 0, nil
270 }
271
272 // Total size of all messages in bytes.
273 size, err := strconv.Atoi(string(f[1]))
274 if err != nil {
275 return 0, 0, err
276 }
277
278 return count, size, nil
279 }
280
281 // List returns a list of (message ID, message Size) pairs.
282 // If the optional msgID > 0, then only that particular message is listed.
283 // The message IDs are sequential, 1 to N.
284 func (c *Conn) List(msgID int) ([]MessageID, error) {
285 var (
286 buf *bytes.Buffer
287 err error
288 )
289
290 if msgID <= 0 {
291 // Multiline response listing all messages.
292 buf, err = c.Cmd("LIST", true)
293 } else {
294 // Single line response listing one message.
295 buf, err = c.Cmd("LIST", false, msgID)
296 }
297 if err != nil {
298 return nil, err
299 }
300
301 var (
302 out []MessageID
303 lines = bytes.Split(buf.Bytes(), lineBreak)
304 )
305
306 for _, l := range lines {
307 // id size
308 f := bytes.Fields(l)
309 if len(f) < 2 {
310 break
311 }
312
313 id, err := strconv.Atoi(string(f[0]))
314 if err != nil {
315 return nil, err
316 }
317
318 size, err := strconv.Atoi(string(f[1]))
319 if err != nil {
320 return nil, err
321 }
322
323 out = append(out, MessageID{ID: id, Size: size})
324 }
325
326 return out, nil
327 }
328
329 // Uidl returns a list of (message ID, message UID) pairs. If the optional msgID
330 // is > 0, then only that particular message is listed. It works like Top() but only works on
331 // servers that support the UIDL command. Messages size field is not available in the UIDL response.
332 func (c *Conn) Uidl(msgID int) ([]MessageID, error) {
333 var (
334 buf *bytes.Buffer
335 err error
336 )
337
338 if msgID <= 0 {
339 // Multiline response listing all messages.
340 buf, err = c.Cmd("UIDL", true)
341 } else {
342 // Single line response listing one message.
343 buf, err = c.Cmd("UIDL", false, msgID)
344 }
345 if err != nil {
346 return nil, err
347 }
348
349 var (
350 out []MessageID
351 lines = bytes.Split(buf.Bytes(), lineBreak)
352 )
353
354 for _, l := range lines {
355 // id size
356 f := bytes.Fields(l)
357 if len(f) < 2 {
358 break
359 }
360
361 id, err := strconv.Atoi(string(f[0]))
362 if err != nil {
363 return nil, err
364 }
365
366 out = append(out, MessageID{ID: id, UID: string(f[1])})
367 }
368
369 return out, nil
370 }
371
372 // Retr downloads a message by the given msgID, parses it and returns it as a
373 // emersion/go-message.message.Entity object.
374 func (c *Conn) Retr(msgID int) (*message.Entity, error) {
375 b, err := c.Cmd("RETR", true, msgID)
376 if err != nil {
377 return nil, err
378 }
379
380 // Strip UTF-8 BOM if present. Some mail servers/proxies like Office 365 prepend this.
381 raw := bytes.TrimPrefix(b.Bytes(), utf8BOM)
382 m, err := message.Read(bytes.NewReader(raw))
383 if err != nil {
384 if !message.IsUnknownCharset(err) {
385 return nil, err
386 }
387 }
388
389 return m, nil
390 }
391
392 // RetrRaw downloads a message by the given msgID and returns the raw []byte
393 // of the entire message.
394 func (c *Conn) RetrRaw(msgID int) (*bytes.Buffer, error) {
395 b, err := c.Cmd("RETR", true, msgID)
396 return b, err
397 }
398
399 // Top retrieves a message by its ID with full headers and numLines lines of the body.
400 func (c *Conn) Top(msgID int, numLines int) (*message.Entity, error) {
401 b, err := c.Cmd("TOP", true, msgID, numLines)
402 if err != nil {
403 return nil, err
404 }
405
406 // Strip UTF-8 BOM if present. Some mail servers/proxies like Office 365 prepend this.
407 raw := bytes.TrimPrefix(b.Bytes(), utf8BOM)
408 m, err := message.Read(bytes.NewReader(raw))
409 if err != nil {
410 return nil, err
411 }
412
413 return m, nil
414 }
415
416 // Dele deletes one or more messages. The server only executes the
417 // deletions after a successful Quit().
418 func (c *Conn) Dele(msgID ...int) error {
419 for _, id := range msgID {
420 _, err := c.Cmd("DELE", false, id)
421 if err != nil {
422 return err
423 }
424 }
425 return nil
426 }
427
428 // Rset clears the messages marked for deletion in the current session.
429 func (c *Conn) Rset() error {
430 _, err := c.Cmd("RSET", false)
431 return err
432 }
433
434 // Noop issues a do-nothing NOOP command to the server. This is useful for
435 // prolonging open connections.
436 func (c *Conn) Noop() error {
437 _, err := c.Cmd("NOOP", false)
438 return err
439 }
440
441 // Quit sends the QUIT command to server and gracefully closes the connection.
442 // Message deletions (DELE command) are only excuted by the server on a graceful
443 // quit and close.
444 func (c *Conn) Quit() error {
445 defer c.conn.Close()
446
447 if _, err := c.Cmd("QUIT", false); err != nil {
448 return err
449 }
450
451 return nil
452 }
453
454 // parseResp checks if the response is an error that starts with `-ERR`
455 // and returns an error with the message that succeeds the error indicator.
456 // For success `+OK` messages, it returns the remaining response bytes.
457 func parseResp(b []byte) ([]byte, error) {
458 if len(b) == 0 {
459 return nil, nil
460 }
461
462 if bytes.Equal(b, respOK) {
463 return nil, nil
464 } else if bytes.HasPrefix(b, respOKInfo) {
465 return bytes.TrimPrefix(b, respOKInfo), nil
466 } else if bytes.Equal(b, respErr) {
467 return nil, errors.New("unknown error (no info specified in response)")
468 } else if bytes.HasPrefix(b, respErrInfo) {
469 return nil, errors.New(string(bytes.TrimPrefix(b, respErrInfo)))
470 } else {
471 return nil, fmt.Errorf("unknown response: %s. Neither -ERR, nor +OK", string(b))
472 }
473 }