(pop3-display-message-size-flag): Removed -- everybody wants message sizes.
[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             (while (> (buffer-size) 5000)
169               (goto-char (point-min))
170               (forward-line 50)
171               (delete-region (point-min) (point))))
172           (unless pop3-leave-mail-on-server
173             (pop3-dele process n))
174           (setq n (+ 1 n))
175           (pop3-accept-process-output process))
176       (when (and pop3-leave-mail-on-server
177                  (> n 1))
178         (message "pop3.el doesn't support UIDL.  Setting `pop3-leave-mail-on-server'
179 to %s might not give the result you'd expect." pop3-leave-mail-on-server)
180         (sit-for 1))
181       (pop3-quit process))
182     (kill-buffer crashbuf))
183   t)
184
185 (defun pop3-get-message-count ()
186   "Return the number of messages in the maildrop."
187   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
188          message-count
189          (pop3-password pop3-password))
190     ;; for debugging only
191     (if pop3-debug (switch-to-buffer (process-buffer process)))
192     ;; query for password
193     (if (and pop3-password-required (not pop3-password))
194         (setq pop3-password
195               (read-passwd (format "Password for %s: " pop3-maildrop))))
196     (cond ((equal 'apop pop3-authentication-scheme)
197            (pop3-apop process pop3-maildrop))
198           ((equal 'pass pop3-authentication-scheme)
199            (pop3-user process pop3-maildrop)
200            (pop3-pass process))
201           (t (error "Invalid POP3 authentication scheme")))
202     (setq message-count (car (pop3-stat process)))
203     (pop3-quit process)
204     message-count))
205
206 (autoload 'open-tls-stream "tls")
207 (autoload 'starttls-open-stream "starttls")
208 (autoload 'starttls-negotiate "starttls") ; avoid warning
209
210 (defcustom pop3-stream-type nil
211   "*Transport security type for POP3 connexions.
212 This may be either nil (plain connexion), `ssl' (use an
213 SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
214 to turn on TLS security after opening the stream).  However, if
215 this is nil, `ssl' is assumed for connexions to port
216 995 (pop3s)."
217   :version "23.1" ;; No Gnus
218   :group 'pop3
219   :type '(choice (const :tag "Plain" nil)
220                  (const :tag "SSL/TLS" ssl)
221                  (const starttls)))
222
223 (defun pop3-open-server (mailhost port)
224   "Open TCP connection to MAILHOST on PORT.
225 Returns the process associated with the connection."
226   (let ((coding-system-for-read 'binary)
227         (coding-system-for-write 'binary)
228         process)
229     (save-excursion
230       (set-buffer (get-buffer-create (concat " trace of POP session to "
231                                              mailhost)))
232       (erase-buffer)
233       (setq pop3-read-point (point-min))
234       (setq process
235             (cond
236              ((or (eq pop3-stream-type 'ssl)
237                   (and (not pop3-stream-type) (member port '(995 "pop3s"))))
238               ;; gnutls-cli, openssl don't accept service names
239               (if (or (equal port "pop3s")
240                       (null port))
241                   (setq port 995))
242               (let ((process (open-tls-stream "POP" (current-buffer)
243                                               mailhost port)))
244                 (when process
245                   ;; There's a load of info printed that needs deleting.
246                   (let ((again 't))
247                     ;; repeat until
248                     ;; - either we received the +OK line
249                     ;; - or accept-process-output timed out without getting
250                     ;;   anything
251                     (while (and again
252                                 (setq again (memq (process-status process)
253                                                   '(open run))))
254                       (setq again (pop3-accept-process-output process))
255                       (goto-char (point-max))
256                       (forward-line -1)
257                       (cond ((looking-at "\\+OK")
258                              (setq again nil)
259                              (delete-region (point-min) (point)))
260                             ((not again)
261                              (pop3-quit process)
262                              (error "POP SSL connexion failed")))))
263                   process)))
264              ((eq pop3-stream-type 'starttls)
265               ;; gnutls-cli, openssl don't accept service names
266               (if (equal port "pop3")
267                   (setq port 110))
268               (let ((process (starttls-open-stream "POP" (current-buffer)
269                                                    mailhost (or port 110))))
270                 (pop3-send-command process "STLS")
271                 (let ((response (pop3-read-response process t)))
272                   (if (and response (string-match "+OK" response))
273                       (starttls-negotiate process)
274                     (pop3-quit process)
275                     (error "POP server doesn't support starttls")))
276                 process))
277              (t
278               (open-network-stream "POP" (current-buffer) mailhost port))))
279       (let ((response (pop3-read-response process t)))
280         (setq pop3-timestamp
281               (substring response (or (string-match "<" response) 0)
282                          (+ 1 (or (string-match ">" response) -1)))))
283       process)))
284
285 ;; Support functions
286
287 (defun pop3-process-filter (process output)
288   (save-excursion
289     (set-buffer (process-buffer process))
290     (goto-char (point-max))
291     (insert output)))
292
293 (defun pop3-send-command (process command)
294   (set-buffer (process-buffer process))
295   (goto-char (point-max))
296   ;; (if (= (aref command 0) ?P)
297   ;;     (insert "PASS <omitted>\r\n")
298   ;;   (insert command "\r\n"))
299   (setq pop3-read-point (point))
300   (goto-char (point-max))
301   (process-send-string process (concat command "\r\n")))
302
303 (defun pop3-read-response (process &optional return)
304   "Read the response from the server.
305 Return the response string if optional second argument is non-nil."
306   (let ((case-fold-search nil)
307         match-end)
308     (save-excursion
309       (set-buffer (process-buffer process))
310       (goto-char pop3-read-point)
311       (while (and (memq (process-status process) '(open run))
312                   (not (search-forward "\r\n" nil t)))
313         (pop3-accept-process-output process)
314         (goto-char pop3-read-point))
315       (setq match-end (point))
316       (goto-char pop3-read-point)
317       (if (looking-at "-ERR")
318           (error "%s" (buffer-substring (point) (- match-end 2)))
319         (if (not (looking-at "+OK"))
320             (progn (setq pop3-read-point match-end) nil)
321           (setq pop3-read-point match-end)
322           (if return
323               (buffer-substring (point) match-end)
324             t)
325           )))))
326
327 (defun pop3-clean-region (start end)
328   (setq end (set-marker (make-marker) end))
329   (save-excursion
330     (goto-char start)
331     (while (and (< (point) end) (search-forward "\r\n" end t))
332       (replace-match "\n" t t))
333     (goto-char start)
334     (while (and (< (point) end) (re-search-forward "^\\." end t))
335       (replace-match "" t t)
336       (forward-char)))
337   (set-marker end nil))
338
339 ;; Copied from message-make-date.
340 (defun pop3-make-date (&optional now)
341   "Make a valid date header.
342 If NOW, use that time instead."
343   (require 'parse-time)
344   (let* ((now (or now (current-time)))
345          (zone (nth 8 (decode-time now)))
346          (sign "+"))
347     (when (< zone 0)
348       (setq sign "-")
349       (setq zone (- zone)))
350     (concat
351      (format-time-string "%d" now)
352      ;; The month name of the %b spec is locale-specific.  Pfff.
353      (format " %s "
354              (capitalize (car (rassoc (nth 4 (decode-time now))
355                                       parse-time-months))))
356      (format-time-string "%Y %H:%M:%S " now)
357      ;; We do all of this because XEmacs doesn't have the %z spec.
358      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
359
360 (defun pop3-munge-message-separator (start end)
361   "Check to see if a message separator exists.  If not, generate one."
362   (save-excursion
363     (save-restriction
364       (narrow-to-region start end)
365       (goto-char (point-min))
366       (if (not (or (looking-at "From .?") ; Unix mail
367                    (looking-at "\001\001\001\001\n") ; MMDF
368                    (looking-at "BABYL OPTIONS:") ; Babyl
369                    ))
370           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
371                  (tdate (mail-fetch-field "Date"))
372                  (date (split-string (or (and tdate
373                                               (not (string= "" tdate))
374                                               tdate)
375                                          (pop3-make-date))
376                                      " "))
377                  (From_))
378             ;; sample date formats I have seen
379             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
380             ;; Date: 08 Jul 1996 23:22:24 -0400
381             ;; should be
382             ;; Tue Jul 9 09:04:21 1996
383
384             ;; Fixme: This should use timezone on the date field contents.
385             (setq date
386                   (cond ((not date)
387                          "Tue Jan 1 00:00:0 1900")
388                         ((string-match "[A-Z]" (nth 0 date))
389                          (format "%s %s %s %s %s"
390                                  (nth 0 date) (nth 2 date) (nth 1 date)
391                                  (nth 4 date) (nth 3 date)))
392                         (t
393                          ;; this really needs to be better but I don't feel
394                          ;; like writing a date to day converter.
395                          (format "Sun %s %s %s %s"
396                                  (nth 1 date) (nth 0 date)
397                                  (nth 3 date) (nth 2 date)))
398                         ))
399             (setq From_ (format "\nFrom %s  %s\n" from date))
400             (while (string-match "," From_)
401               (setq From_ (concat (substring From_ 0 (match-beginning 0))
402                                   (substring From_ (match-end 0)))))
403             (goto-char (point-min))
404             (insert From_)
405             (if (search-forward "\n\n" nil t)
406                 nil
407               (goto-char (point-max))
408               (insert "\n"))
409             (narrow-to-region (point) (point-max))
410             (let ((size (- (point-max) (point-min))))
411               (goto-char (point-min))
412               (widen)
413               (forward-line -1)
414               (insert (format "Content-Length: %s\n" size)))
415             )))))
416
417 ;; The Command Set
418
419 ;; AUTHORIZATION STATE
420
421 (defun pop3-user (process user)
422   "Send USER information to POP3 server."
423   (pop3-send-command process (format "USER %s" user))
424   (let ((response (pop3-read-response process t)))
425     (if (not (and response (string-match "+OK" response)))
426         (error "USER %s not valid" user))))
427
428 (defun pop3-pass (process)
429   "Send authentication information to the server."
430   (pop3-send-command process (format "PASS %s" pop3-password))
431   (let ((response (pop3-read-response process t)))
432     (if (not (and response (string-match "+OK" response)))
433         (pop3-quit process))))
434
435 (defun pop3-apop (process user)
436   "Send alternate authentication information to the server."
437   (let ((pass pop3-password))
438     (if (and pop3-password-required (not pass))
439         (setq pass
440               (read-passwd (format "Password for %s: " pop3-maildrop))))
441     (if pass
442         (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
443           (pop3-send-command process (format "APOP %s %s" user hash))
444           (let ((response (pop3-read-response process t)))
445             (if (not (and response (string-match "+OK" response)))
446                 (pop3-quit process)))))
447     ))
448
449 ;; TRANSACTION STATE
450
451 (defun pop3-stat (process)
452   "Return the number of messages in the maildrop and the maildrop's size."
453   (pop3-send-command process "STAT")
454   (let ((response (pop3-read-response process t)))
455     (list (string-to-number (nth 1 (split-string response " ")))
456           (string-to-number (nth 2 (split-string response " "))))
457     ))
458
459 (defun pop3-list (process &optional msg)
460   "If MSG is nil, return an alist of (MESSAGE-ID . SIZE) pairs.
461 Otherwise, return the size of the message-id MSG"
462   (pop3-send-command process (if msg
463                                  (format "LIST %d" msg)
464                                "LIST"))
465   (let ((response (pop3-read-response process t)))
466     (if msg
467         (string-to-number (nth 2 (split-string response " ")))
468       (let ((start pop3-read-point) end)
469         (save-excursion
470           (set-buffer (process-buffer process))
471           (while (not (re-search-forward "^\\.\r\n" nil t))
472             (pop3-accept-process-output process)
473             (goto-char start))
474           (setq pop3-read-point (point-marker))
475           (goto-char (match-beginning 0))
476           (setq end (point-marker))
477           (mapcar #'(lambda (s) (let ((split (split-string s " ")))
478                                   (cons (string-to-number (nth 0 split))
479                                         (string-to-number (nth 1 split)))))
480                   (delete "" (split-string (buffer-substring start end)
481                                            "\r\n"))))))))
482
483 (defun pop3-retr (process msg crashbuf)
484   "Retrieve message-id MSG to buffer CRASHBUF."
485   (pop3-send-command process (format "RETR %s" msg))
486   (pop3-read-response process)
487   (let ((start pop3-read-point) end)
488     (save-excursion
489       (set-buffer (process-buffer process))
490       (while (not (re-search-forward "^\\.\r\n" nil t))
491         (pop3-accept-process-output process)
492         (goto-char start))
493       (setq pop3-read-point (point-marker))
494       ;; this code does not seem to work for some POP servers...
495       ;; and I cannot figure out why not.
496       ;;      (goto-char (match-beginning 0))
497       ;;      (backward-char 2)
498       ;;      (if (not (looking-at "\r\n"))
499       ;;          (insert "\r\n"))
500       ;;      (re-search-forward "\\.\r\n")
501       (goto-char (match-beginning 0))
502       (setq end (point-marker))
503       (pop3-clean-region start end)
504       (pop3-munge-message-separator start end)
505       (save-excursion
506         (set-buffer crashbuf)
507         (erase-buffer))
508       (copy-to-buffer crashbuf start end)
509       (delete-region start end)
510       )))
511
512 (defun pop3-dele (process msg)
513   "Mark message-id MSG as deleted."
514   (pop3-send-command process (format "DELE %s" msg))
515   (pop3-read-response process))
516
517 (defun pop3-noop (process msg)
518   "No-operation."
519   (pop3-send-command process "NOOP")
520   (pop3-read-response process))
521
522 (defun pop3-last (process)
523   "Return highest accessed message-id number for the session."
524   (pop3-send-command process "LAST")
525   (let ((response (pop3-read-response process t)))
526     (string-to-number (nth 1 (split-string response " ")))
527     ))
528
529 (defun pop3-rset (process)
530   "Remove all delete marks from current maildrop."
531   (pop3-send-command process "RSET")
532   (pop3-read-response process))
533
534 ;; UPDATE
535
536 (defun pop3-quit (process)
537   "Close connection to POP3 server.
538 Tell server to remove all messages marked as deleted, unlock the maildrop,
539 and close the connection."
540   (pop3-send-command process "QUIT")
541   (pop3-read-response process t)
542   (if process
543       (save-excursion
544         (set-buffer (process-buffer process))
545         (goto-char (point-max))
546         (delete-process process))))
547 \f
548 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
549
550 ;;; AUTHORIZATION STATE
551
552 ;; Initial TCP connection
553 ;; Arguments: none
554 ;; Restrictions: none
555 ;; Possible responses:
556 ;;  +OK [POP3 server ready]
557
558 ;; USER name
559 ;; Arguments: a server specific user-id (required)
560 ;; Restrictions: authorization state [after unsuccessful USER or PASS
561 ;; Possible responses:
562 ;;  +OK [valid user-id]
563 ;;  -ERR [invalid user-id]
564
565 ;; PASS string
566 ;; Arguments: a server/user-id specific password (required)
567 ;; Restrictions: authorization state, after successful USER
568 ;; Possible responses:
569 ;;  +OK [maildrop locked and ready]
570 ;;  -ERR [invalid password]
571 ;;  -ERR [unable to lock maildrop]
572
573 ;; STLS      (RFC 2595)
574 ;; Arguments: none
575 ;; Restrictions: Only permitted in AUTHORIZATION state.
576 ;; Possible responses:
577 ;;  +OK
578 ;;  -ERR
579
580 ;;; TRANSACTION STATE
581
582 ;; STAT
583 ;; Arguments: none
584 ;; Restrictions: transaction state
585 ;; Possible responses:
586 ;;  +OK nn mm [# of messages, size of maildrop]
587
588 ;; LIST [msg]
589 ;; Arguments: a message-id (optional)
590 ;; Restrictions: transaction state; msg must not be deleted
591 ;; Possible responses:
592 ;;  +OK [scan listing follows]
593 ;;  -ERR [no such message]
594
595 ;; RETR msg
596 ;; Arguments: a message-id (required)
597 ;; Restrictions: transaction state; msg must not be deleted
598 ;; Possible responses:
599 ;;  +OK [message contents follow]
600 ;;  -ERR [no such message]
601
602 ;; DELE msg
603 ;; Arguments: a message-id (required)
604 ;; Restrictions: transaction state; msg must not be deleted
605 ;; Possible responses:
606 ;;  +OK [message deleted]
607 ;;  -ERR [no such message]
608
609 ;; NOOP
610 ;; Arguments: none
611 ;; Restrictions: transaction state
612 ;; Possible responses:
613 ;;  +OK
614
615 ;; LAST
616 ;; Arguments: none
617 ;; Restrictions: transaction state
618 ;; Possible responses:
619 ;;  +OK nn [highest numbered message accessed]
620
621 ;; RSET
622 ;; Arguments: none
623 ;; Restrictions: transaction state
624 ;; Possible responses:
625 ;;  +OK [all delete marks removed]
626
627 ;;; UPDATE STATE
628
629 ;; QUIT
630 ;; Arguments: none
631 ;; Restrictions: none
632 ;; Possible responses:
633 ;;  +OK [TCP connection closed]
634
635 (provide 'pop3)
636
637 ;;; pop3.el ends here