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