8b9ff6627813bddf30fde48d8621893ccc928b55
[gnus] / lisp / pop3.el
1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;;   2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
5
6 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
7 ;; Maintainer: FSF
8 ;; Keywords: mail
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
28 ;; are implemented.  The LIST command has not been implemented due to lack
29 ;; of actual usefulness.
30 ;; The optional POP3 command TOP has not been implemented.
31
32 ;; This program was inspired by Kyle E. Jones's vm-pop program.
33
34 ;;; Code:
35
36 (require 'mail-utils)
37 (defvar parse-time-months)
38
39 (defgroup pop3 nil
40   "Post Office Protocol."
41   :group 'mail
42   :group 'mail-source)
43
44 (defcustom pop3-maildrop (or (user-login-name)
45                              (getenv "LOGNAME")
46                              (getenv "USER"))
47   "*POP3 maildrop."
48   :version "22.1" ;; Oort Gnus
49   :type 'string
50   :group 'pop3)
51
52 (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
53                              "pop3")
54   "*POP3 mailhost."
55   :version "22.1" ;; Oort Gnus
56   :type 'string
57   :group 'pop3)
58
59 (defcustom pop3-port 110
60   "*POP3 port."
61   :version "22.1" ;; Oort Gnus
62   :type 'number
63   :group 'pop3)
64
65 (defcustom pop3-password-required t
66   "*Non-nil if a password is required when connecting to POP server."
67   :version "22.1" ;; Oort Gnus
68   :type 'boolean
69   :group 'pop3)
70
71 ;; Should this be customizable?
72 (defvar pop3-password nil
73   "*Password to use when connecting to POP server.")
74
75 (defcustom pop3-authentication-scheme 'pass
76   "*POP3 authentication scheme.
77 Defaults to `pass', for the standard USER/PASS authentication.  The other
78 valid value is 'apop'."
79   :type '(choice (const :tag "Normal user/password" pass)
80                  (const :tag "APOP" apop))
81   :version "22.1" ;; Oort Gnus
82   :group 'pop3)
83
84 (defcustom pop3-leave-mail-on-server nil
85   "*Non-nil if the mail is to be left on the POP server after fetching.
86
87 If `pop3-leave-mail-on-server' is non-nil the mail is to be left
88 on the POP server after fetching.  Note that POP servers maintain
89 no state information between sessions, so what the client
90 believes is there and what is actually there may not match up.
91 If they do not, then you may get duplicate mails or the whole
92 thing can fall apart and leave you with a corrupt mailbox."
93   ;; We can't use the UILD support from XEmacs mail-lib or cvs.m17n.org:
94   ;; http://thread.gmane.org/v9lld8fml4.fsf@marauder.physik.uni-ulm.de
95   ;; http://thread.gmane.org/b9yy8hzy9ej.fsf@jpl.org
96   ;; Any volunteer to re-implement this?
97   :version "22.1" ;; Oort Gnus
98   :type 'boolean
99   :group 'pop3)
100
101 (defvar pop3-timestamp nil
102   "Timestamp returned when initially connected to the POP server.
103 Used for APOP authentication.")
104
105 (defvar pop3-read-point nil)
106 (defvar pop3-debug nil)
107
108 ;; Borrowed from nnheader-accept-process-output in nnheader.el.  See the
109 ;; comments there for explanations about the values.
110
111 (eval-and-compile
112   (if (and (fboundp 'nnheader-accept-process-output)
113            (boundp 'nnheader-read-timeout))
114       (defalias 'pop3-accept-process-output 'nnheader-accept-process-output)
115     ;; Borrowed from `nnheader.el':
116     (defvar pop3-read-timeout
117       (if (string-match "windows-nt\\|os/2\\|cygwin"
118                         (symbol-name system-type))
119           1.0
120         0.01)
121       "How long pop3 should wait between checking for the end of output.
122 Shorter values mean quicker response, but are more CPU intensive.")
123     (defun pop3-accept-process-output (process)
124       (accept-process-output
125        process
126        (truncate pop3-read-timeout)
127        (truncate (* (- pop3-read-timeout
128                        (truncate pop3-read-timeout))
129                     1000))))))
130
131 (defun pop3-movemail (&optional crashbox)
132   "Transfer contents of a maildrop to the specified CRASHBOX."
133   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
134   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
135          (crashbuf (get-buffer-create " *pop3-retr*"))
136          (n 1)
137          message-count
138          message-sizes
139          (pop3-password pop3-password))
140     ;; for debugging only
141     (if pop3-debug (switch-to-buffer (process-buffer process)))
142     ;; query for password
143     (if (and pop3-password-required (not pop3-password))
144         (setq pop3-password
145               (read-passwd (format "Password for %s: " pop3-maildrop))))
146     (cond ((equal 'apop pop3-authentication-scheme)
147            (pop3-apop process pop3-maildrop))
148           ((equal 'pass pop3-authentication-scheme)
149            (pop3-user process pop3-maildrop)
150            (pop3-pass process))
151           (t (error "Invalid POP3 authentication scheme")))
152     (setq message-count (car (pop3-stat process)))
153     (when (and pop3-display-message-size-flag
154                (> message-count 0))
155       (setq message-sizes (pop3-list process)))
156     (unwind-protect
157         (while (<= n message-count)
158           (message "Retrieving message %d of %d from %s... (%.1fk)"
159                    n message-count pop3-mailhost
160                    (/ (cdr (assoc n message-sizes))
161                       1024.0))
162           (pop3-retr process n crashbuf)
163           (save-excursion
164             (set-buffer crashbuf)
165             (let ((coding-system-for-write 'binary))
166               (write-region (point-min) (point-max) crashbox t 'nomesg))
167             (set-buffer (process-buffer process))
168             (erase-buffer))
169           (unless pop3-leave-mail-on-server
170             (pop3-dele process n))
171           (setq n (+ 1 n))
172           (pop3-accept-process-output process))
173       (when (and pop3-leave-mail-on-server
174                  (> n 1))
175         (message "pop3.el doesn't support UIDL.  Setting `pop3-leave-mail-on-server'
176 to %s might not give the result you'd expect." pop3-leave-mail-on-server)
177         (sit-for 1))
178       (pop3-quit process))
179     (kill-buffer crashbuf))
180   t)
181
182 (defun pop3-get-message-count ()
183   "Return the number of messages in the maildrop."
184   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
185          message-count
186          (pop3-password pop3-password))
187     ;; for debugging only
188     (if pop3-debug (switch-to-buffer (process-buffer process)))
189     ;; query for password
190     (if (and pop3-password-required (not pop3-password))
191         (setq pop3-password
192               (read-passwd (format "Password for %s: " pop3-maildrop))))
193     (cond ((equal 'apop pop3-authentication-scheme)
194            (pop3-apop process pop3-maildrop))
195           ((equal 'pass pop3-authentication-scheme)
196            (pop3-user process pop3-maildrop)
197            (pop3-pass process))
198           (t (error "Invalid POP3 authentication scheme")))
199     (setq message-count (car (pop3-stat process)))
200     (pop3-quit process)
201     message-count))
202
203 (autoload 'open-tls-stream "tls")
204 (autoload 'starttls-open-stream "starttls")
205 (autoload 'starttls-negotiate "starttls") ; avoid warning
206
207 (defcustom pop3-stream-type nil
208   "*Transport security type for POP3 connexions.
209 This may be either nil (plain connexion), `ssl' (use an
210 SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
211 to turn on TLS security after opening the stream).  However, if
212 this is nil, `ssl' is assumed for connexions to port
213 995 (pop3s)."
214   :version "23.1" ;; No Gnus
215   :group 'pop3
216   :type '(choice (const :tag "Plain" nil)
217                  (const :tag "SSL/TLS" ssl)
218                  (const starttls)))
219
220 (defun pop3-open-server (mailhost port)
221   "Open TCP connection to MAILHOST on PORT.
222 Returns the process associated with the connection."
223   (let ((coding-system-for-read 'binary)
224         (coding-system-for-write 'binary)
225         process)
226     (save-excursion
227       (set-buffer (get-buffer-create (concat " trace of POP session to "
228                                              mailhost)))
229       (erase-buffer)
230       (setq pop3-read-point (point-min))
231       (setq process
232             (cond
233              ((or (eq pop3-stream-type 'ssl)
234                   (and (not pop3-stream-type) (member port '(995 "pop3s"))))
235               ;; gnutls-cli, openssl don't accept service names
236               (if (or (equal port "pop3s")
237                       (null port))
238                   (setq port 995))
239               (let ((process (open-tls-stream "POP" (current-buffer)
240                                               mailhost port)))
241                 (when process
242                   ;; There's a load of info printed that needs deleting.
243                   (let ((again 't))
244                     ;; repeat until
245                     ;; - either we received the +OK line
246                     ;; - or accept-process-output timed out without getting
247                     ;;   anything
248                     (while (and again
249                                 (setq again (memq (process-status process)
250                                                   '(open run))))
251                       (setq again (pop3-accept-process-output process))
252                       (goto-char (point-max))
253                       (forward-line -1)
254                       (cond ((looking-at "\\+OK")
255                              (setq again nil)
256                              (delete-region (point-min) (point)))
257                             ((not again)
258                              (pop3-quit process)
259                              (error "POP SSL connexion failed")))))
260                   process)))
261              ((eq pop3-stream-type 'starttls)
262               ;; gnutls-cli, openssl don't accept service names
263               (if (equal port "pop3")
264                   (setq port 110))
265               (let ((process (starttls-open-stream "POP" (current-buffer)
266                                                    mailhost (or port 110))))
267                 (pop3-send-command process "STLS")
268                 (let ((response (pop3-read-response process t)))
269                   (if (and response (string-match "+OK" response))
270                       (starttls-negotiate process)
271                     (pop3-quit process)
272                     (error "POP server doesn't support starttls")))
273                 process))
274              (t
275               (open-network-stream "POP" (current-buffer) mailhost port))))
276       (let ((response (pop3-read-response process t)))
277         (setq pop3-timestamp
278               (substring response (or (string-match "<" response) 0)
279                          (+ 1 (or (string-match ">" response) -1)))))
280       process)))
281
282 ;; Support functions
283
284 (defun pop3-process-filter (process output)
285   (save-excursion
286     (set-buffer (process-buffer process))
287     (goto-char (point-max))
288     (insert output)))
289
290 (defun pop3-send-command (process command)
291   (set-buffer (process-buffer process))
292   (goto-char (point-max))
293   ;; (if (= (aref command 0) ?P)
294   ;;     (insert "PASS <omitted>\r\n")
295   ;;   (insert command "\r\n"))
296   (setq pop3-read-point (point))
297   (goto-char (point-max))
298   (process-send-string process (concat command "\r\n")))
299
300 (defun pop3-read-response (process &optional return)
301   "Read the response from the server.
302 Return the response string if optional second argument is non-nil."
303   (let ((case-fold-search nil)
304         match-end)
305     (save-excursion
306       (set-buffer (process-buffer process))
307       (goto-char pop3-read-point)
308       (while (and (memq (process-status process) '(open run))
309                   (not (search-forward "\r\n" nil t)))
310         (pop3-accept-process-output process)
311         (goto-char pop3-read-point))
312       (setq match-end (point))
313       (goto-char pop3-read-point)
314       (if (looking-at "-ERR")
315           (error "%s" (buffer-substring (point) (- match-end 2)))
316         (if (not (looking-at "+OK"))
317             (progn (setq pop3-read-point match-end) nil)
318           (setq pop3-read-point match-end)
319           (if return
320               (buffer-substring (point) match-end)
321             t)
322           )))))
323
324 (defun pop3-clean-region (start end)
325   (setq end (set-marker (make-marker) end))
326   (save-excursion
327     (goto-char start)
328     (while (and (< (point) end) (search-forward "\r\n" end t))
329       (replace-match "\n" t t))
330     (goto-char start)
331     (while (and (< (point) end) (re-search-forward "^\\." end t))
332       (replace-match "" t t)
333       (forward-char)))
334   (set-marker end nil))
335
336 ;; Copied from message-make-date.
337 (defun pop3-make-date (&optional now)
338   "Make a valid date header.
339 If NOW, use that time instead."
340   (require 'parse-time)
341   (let* ((now (or now (current-time)))
342          (zone (nth 8 (decode-time now)))
343          (sign "+"))
344     (when (< zone 0)
345       (setq sign "-")
346       (setq zone (- zone)))
347     (concat
348      (format-time-string "%d" now)
349      ;; The month name of the %b spec is locale-specific.  Pfff.
350      (format " %s "
351              (capitalize (car (rassoc (nth 4 (decode-time now))
352                                       parse-time-months))))
353      (format-time-string "%Y %H:%M:%S " now)
354      ;; We do all of this because XEmacs doesn't have the %z spec.
355      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
356
357 (defun pop3-munge-message-separator (start end)
358   "Check to see if a message separator exists.  If not, generate one."
359   (save-excursion
360     (save-restriction
361       (narrow-to-region start end)
362       (goto-char (point-min))
363       (if (not (or (looking-at "From .?") ; Unix mail
364                    (looking-at "\001\001\001\001\n") ; MMDF
365                    (looking-at "BABYL OPTIONS:") ; Babyl
366                    ))
367           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
368                  (tdate (mail-fetch-field "Date"))
369                  (date (split-string (or (and tdate
370                                               (not (string= "" tdate))
371                                               tdate)
372                                          (pop3-make-date))
373                                      " "))
374                  (From_))
375             ;; sample date formats I have seen
376             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
377             ;; Date: 08 Jul 1996 23:22:24 -0400
378             ;; should be
379             ;; Tue Jul 9 09:04:21 1996
380
381             ;; Fixme: This should use timezone on the date field contents.
382             (setq date
383                   (cond ((not date)
384                          "Tue Jan 1 00:00:0 1900")
385                         ((string-match "[A-Z]" (nth 0 date))
386                          (format "%s %s %s %s %s"
387                                  (nth 0 date) (nth 2 date) (nth 1 date)
388                                  (nth 4 date) (nth 3 date)))
389                         (t
390                          ;; this really needs to be better but I don't feel
391                          ;; like writing a date to day converter.
392                          (format "Sun %s %s %s %s"
393                                  (nth 1 date) (nth 0 date)
394                                  (nth 3 date) (nth 2 date)))
395                         ))
396             (setq From_ (format "\nFrom %s  %s\n" from date))
397             (while (string-match "," From_)
398               (setq From_ (concat (substring From_ 0 (match-beginning 0))
399                                   (substring From_ (match-end 0)))))
400             (goto-char (point-min))
401             (insert From_)
402             (if (search-forward "\n\n" nil t)
403                 nil
404               (goto-char (point-max))
405               (insert "\n"))
406             (narrow-to-region (point) (point-max))
407             (let ((size (- (point-max) (point-min))))
408               (goto-char (point-min))
409               (widen)
410               (forward-line -1)
411               (insert (format "Content-Length: %s\n" size)))
412             )))))
413
414 ;; The Command Set
415
416 ;; AUTHORIZATION STATE
417
418 (defun pop3-user (process user)
419   "Send USER information to POP3 server."
420   (pop3-send-command process (format "USER %s" user))
421   (let ((response (pop3-read-response process t)))
422     (if (not (and response (string-match "+OK" response)))
423         (error "USER %s not valid" user))))
424
425 (defun pop3-pass (process)
426   "Send authentication information to the server."
427   (pop3-send-command process (format "PASS %s" pop3-password))
428   (let ((response (pop3-read-response process t)))
429     (if (not (and response (string-match "+OK" response)))
430         (pop3-quit process))))
431
432 (defun pop3-apop (process user)
433   "Send alternate authentication information to the server."
434   (let ((pass pop3-password))
435     (if (and pop3-password-required (not pass))
436         (setq pass
437               (read-passwd (format "Password for %s: " pop3-maildrop))))
438     (if pass
439         (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
440           (pop3-send-command process (format "APOP %s %s" user hash))
441           (let ((response (pop3-read-response process t)))
442             (if (not (and response (string-match "+OK" response)))
443                 (pop3-quit process)))))
444     ))
445
446 ;; TRANSACTION STATE
447
448 (defun pop3-stat (process)
449   "Return the number of messages in the maildrop and the maildrop's size."
450   (pop3-send-command process "STAT")
451   (let ((response (pop3-read-response process t)))
452     (list (string-to-number (nth 1 (split-string response " ")))
453           (string-to-number (nth 2 (split-string response " "))))
454     ))
455
456 (defun pop3-list (process &optional msg)
457   "If MSG is nil, return an alist of (MESSAGE-ID . SIZE) pairs.
458 Otherwise, return the size of the message-id MSG"
459   (pop3-send-command process (if msg
460                                  (format "LIST %d" msg)
461                                "LIST"))
462   (let ((response (pop3-read-response process t)))
463     (if msg
464         (string-to-number (nth 2 (split-string response " ")))
465       (let ((start pop3-read-point) end)
466         (save-excursion
467           (set-buffer (process-buffer process))
468           (while (not (re-search-forward "^\\.\r\n" nil t))
469             (pop3-accept-process-output process)
470             (goto-char start))
471           (setq pop3-read-point (point-marker))
472           (goto-char (match-beginning 0))
473           (setq end (point-marker))
474           (mapcar #'(lambda (s) (let ((split (split-string s " ")))
475                                   (cons (string-to-number (nth 0 split))
476                                         (string-to-number (nth 1 split)))))
477                   (delete "" (split-string (buffer-substring start end)
478                                            "\r\n"))))))))
479
480 (defun pop3-retr (process msg crashbuf)
481   "Retrieve message-id MSG to buffer CRASHBUF."
482   (pop3-send-command process (format "RETR %s" msg))
483   (pop3-read-response process)
484   (let ((start pop3-read-point) end)
485     (save-excursion
486       (set-buffer (process-buffer process))
487       (while (not (re-search-forward "^\\.\r\n" nil t))
488         (pop3-accept-process-output process)
489         (goto-char start))
490       (setq pop3-read-point (point-marker))
491       ;; this code does not seem to work for some POP servers...
492       ;; and I cannot figure out why not.
493       ;;      (goto-char (match-beginning 0))
494       ;;      (backward-char 2)
495       ;;      (if (not (looking-at "\r\n"))
496       ;;          (insert "\r\n"))
497       ;;      (re-search-forward "\\.\r\n")
498       (goto-char (match-beginning 0))
499       (setq end (point-marker))
500       (pop3-clean-region start end)
501       (pop3-munge-message-separator start end)
502       (save-excursion
503         (set-buffer crashbuf)
504         (erase-buffer))
505       (copy-to-buffer crashbuf start end)
506       (delete-region start end)
507       )))
508
509 (defun pop3-dele (process msg)
510   "Mark message-id MSG as deleted."
511   (pop3-send-command process (format "DELE %s" msg))
512   (pop3-read-response process))
513
514 (defun pop3-noop (process msg)
515   "No-operation."
516   (pop3-send-command process "NOOP")
517   (pop3-read-response process))
518
519 (defun pop3-last (process)
520   "Return highest accessed message-id number for the session."
521   (pop3-send-command process "LAST")
522   (let ((response (pop3-read-response process t)))
523     (string-to-number (nth 1 (split-string response " ")))
524     ))
525
526 (defun pop3-rset (process)
527   "Remove all delete marks from current maildrop."
528   (pop3-send-command process "RSET")
529   (pop3-read-response process))
530
531 ;; UPDATE
532
533 (defun pop3-quit (process)
534   "Close connection to POP3 server.
535 Tell server to remove all messages marked as deleted, unlock the maildrop,
536 and close the connection."
537   (pop3-send-command process "QUIT")
538   (pop3-read-response process t)
539   (if process
540       (save-excursion
541         (set-buffer (process-buffer process))
542         (goto-char (point-max))
543         (delete-process process))))
544 \f
545 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
546
547 ;;; AUTHORIZATION STATE
548
549 ;; Initial TCP connection
550 ;; Arguments: none
551 ;; Restrictions: none
552 ;; Possible responses:
553 ;;  +OK [POP3 server ready]
554
555 ;; USER name
556 ;; Arguments: a server specific user-id (required)
557 ;; Restrictions: authorization state [after unsuccessful USER or PASS
558 ;; Possible responses:
559 ;;  +OK [valid user-id]
560 ;;  -ERR [invalid user-id]
561
562 ;; PASS string
563 ;; Arguments: a server/user-id specific password (required)
564 ;; Restrictions: authorization state, after successful USER
565 ;; Possible responses:
566 ;;  +OK [maildrop locked and ready]
567 ;;  -ERR [invalid password]
568 ;;  -ERR [unable to lock maildrop]
569
570 ;; STLS      (RFC 2595)
571 ;; Arguments: none
572 ;; Restrictions: Only permitted in AUTHORIZATION state.
573 ;; Possible responses:
574 ;;  +OK
575 ;;  -ERR
576
577 ;;; TRANSACTION STATE
578
579 ;; STAT
580 ;; Arguments: none
581 ;; Restrictions: transaction state
582 ;; Possible responses:
583 ;;  +OK nn mm [# of messages, size of maildrop]
584
585 ;; LIST [msg]
586 ;; Arguments: a message-id (optional)
587 ;; Restrictions: transaction state; msg must not be deleted
588 ;; Possible responses:
589 ;;  +OK [scan listing follows]
590 ;;  -ERR [no such message]
591
592 ;; RETR msg
593 ;; Arguments: a message-id (required)
594 ;; Restrictions: transaction state; msg must not be deleted
595 ;; Possible responses:
596 ;;  +OK [message contents follow]
597 ;;  -ERR [no such message]
598
599 ;; DELE msg
600 ;; Arguments: a message-id (required)
601 ;; Restrictions: transaction state; msg must not be deleted
602 ;; Possible responses:
603 ;;  +OK [message deleted]
604 ;;  -ERR [no such message]
605
606 ;; NOOP
607 ;; Arguments: none
608 ;; Restrictions: transaction state
609 ;; Possible responses:
610 ;;  +OK
611
612 ;; LAST
613 ;; Arguments: none
614 ;; Restrictions: transaction state
615 ;; Possible responses:
616 ;;  +OK nn [highest numbered message accessed]
617
618 ;; RSET
619 ;; Arguments: none
620 ;; Restrictions: transaction state
621 ;; Possible responses:
622 ;;  +OK [all delete marks removed]
623
624 ;;; UPDATE STATE
625
626 ;; QUIT
627 ;; Arguments: none
628 ;; Restrictions: none
629 ;; Possible responses:
630 ;;  +OK [TCP connection closed]
631
632 (provide 'pop3)
633
634 ;;; pop3.el ends here