8f5132cd6731451fbac8b7143ba0b8730bcddb0c
[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 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.
109 (defvar pop3-read-timeout
110   (if (string-match "windows-nt\\|os/2\\|emx\\|cygwin"
111                     (symbol-name system-type))
112       ;; http://thread.gmane.org/v9655t3pjo.fsf@marauder.physik.uni-ulm.de
113       ;;
114       ;; IIRC, values lower than 1.0 didn't/don't work on Windows/DOS.
115       ;;
116       ;; There should probably be a runtime test to determine the timing
117       ;; resolution, or a primitive to report it.  I don't know off-hand
118       ;; what's possible.  Perhaps better, maybe the Windows/DOS primitive
119       ;; could round up non-zero timeouts to a minimum of 1.0?
120       1.0
121     0.1)
122   "How long pop3 should wait between checking for the end of output.
123 Shorter values mean quicker response, but are more CPU intensive.")
124
125 ;; Borrowed from nnheader-accept-process-output in nnheader.el.
126 (defun pop3-accept-process-output (process)
127   (accept-process-output
128    process
129    (truncate pop3-read-timeout)
130    (truncate (* (- pop3-read-timeout
131                    (truncate pop3-read-timeout))
132                 1000))))
133
134 (defun pop3-movemail (&optional crashbox)
135   "Transfer contents of a maildrop to the specified CRASHBOX."
136   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
137   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
138          (crashbuf (get-buffer-create " *pop3-retr*"))
139          (n 1)
140          message-count
141          (pop3-password pop3-password))
142     ;; for debugging only
143     (if pop3-debug (switch-to-buffer (process-buffer process)))
144     ;; query for password
145     (if (and pop3-password-required (not pop3-password))
146         (setq pop3-password
147               (read-passwd (format "Password for %s: " pop3-maildrop))))
148     (cond ((equal 'apop pop3-authentication-scheme)
149            (pop3-apop process pop3-maildrop))
150           ((equal 'pass pop3-authentication-scheme)
151            (pop3-user process pop3-maildrop)
152            (pop3-pass process))
153           (t (error "Invalid POP3 authentication scheme")))
154     (setq message-count (car (pop3-stat process)))
155     (unwind-protect
156         (while (<= n message-count)
157           (message "Retrieving message %d of %d from %s..."
158                    n message-count pop3-mailhost)
159           (pop3-retr process n crashbuf)
160           (save-excursion
161             (set-buffer crashbuf)
162             (let ((coding-system-for-write 'binary))
163               (write-region (point-min) (point-max) crashbox t 'nomesg))
164             (set-buffer (process-buffer process))
165             (while (> (buffer-size) 5000)
166               (goto-char (point-min))
167               (forward-line 50)
168               (delete-region (point-min) (point))))
169           (unless pop3-leave-mail-on-server
170             (pop3-dele process n))
171           (setq n (+ 1 n))
172           (nnheader-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   "Scan listing of available messages.
458 This function currently does nothing.")
459
460 (defun pop3-retr (process msg crashbuf)
461   "Retrieve message-id MSG to buffer CRASHBUF."
462   (pop3-send-command process (format "RETR %s" msg))
463   (pop3-read-response process)
464   (let ((start pop3-read-point) end)
465     (save-excursion
466       (set-buffer (process-buffer process))
467       (while (not (re-search-forward "^\\.\r\n" nil t))
468         (pop3-accept-process-output process)
469         (goto-char start))
470       (setq pop3-read-point (point-marker))
471       ;; this code does not seem to work for some POP servers...
472       ;; and I cannot figure out why not.
473       ;;      (goto-char (match-beginning 0))
474       ;;      (backward-char 2)
475       ;;      (if (not (looking-at "\r\n"))
476       ;;          (insert "\r\n"))
477       ;;      (re-search-forward "\\.\r\n")
478       (goto-char (match-beginning 0))
479       (setq end (point-marker))
480       (pop3-clean-region start end)
481       (pop3-munge-message-separator start end)
482       (save-excursion
483         (set-buffer crashbuf)
484         (erase-buffer))
485       (copy-to-buffer crashbuf start end)
486       (delete-region start end)
487       )))
488
489 (defun pop3-dele (process msg)
490   "Mark message-id MSG as deleted."
491   (pop3-send-command process (format "DELE %s" msg))
492   (pop3-read-response process))
493
494 (defun pop3-noop (process msg)
495   "No-operation."
496   (pop3-send-command process "NOOP")
497   (pop3-read-response process))
498
499 (defun pop3-last (process)
500   "Return highest accessed message-id number for the session."
501   (pop3-send-command process "LAST")
502   (let ((response (pop3-read-response process t)))
503     (string-to-number (nth 1 (split-string response " ")))
504     ))
505
506 (defun pop3-rset (process)
507   "Remove all delete marks from current maildrop."
508   (pop3-send-command process "RSET")
509   (pop3-read-response process))
510
511 ;; UPDATE
512
513 (defun pop3-quit (process)
514   "Close connection to POP3 server.
515 Tell server to remove all messages marked as deleted, unlock the maildrop,
516 and close the connection."
517   (pop3-send-command process "QUIT")
518   (pop3-read-response process t)
519   (if process
520       (save-excursion
521         (set-buffer (process-buffer process))
522         (goto-char (point-max))
523         (delete-process process))))
524 \f
525 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
526
527 ;;; AUTHORIZATION STATE
528
529 ;; Initial TCP connection
530 ;; Arguments: none
531 ;; Restrictions: none
532 ;; Possible responses:
533 ;;  +OK [POP3 server ready]
534
535 ;; USER name
536 ;; Arguments: a server specific user-id (required)
537 ;; Restrictions: authorization state [after unsuccessful USER or PASS
538 ;; Possible responses:
539 ;;  +OK [valid user-id]
540 ;;  -ERR [invalid user-id]
541
542 ;; PASS string
543 ;; Arguments: a server/user-id specific password (required)
544 ;; Restrictions: authorization state, after successful USER
545 ;; Possible responses:
546 ;;  +OK [maildrop locked and ready]
547 ;;  -ERR [invalid password]
548 ;;  -ERR [unable to lock maildrop]
549
550 ;; STLS      (RFC 2595)
551 ;; Arguments: none
552 ;; Restrictions: Only permitted in AUTHORIZATION state.
553 ;; Possible responses:
554 ;;  +OK
555 ;;  -ERR
556
557 ;;; TRANSACTION STATE
558
559 ;; STAT
560 ;; Arguments: none
561 ;; Restrictions: transaction state
562 ;; Possible responses:
563 ;;  +OK nn mm [# of messages, size of maildrop]
564
565 ;; LIST [msg]
566 ;; Arguments: a message-id (optional)
567 ;; Restrictions: transaction state; msg must not be deleted
568 ;; Possible responses:
569 ;;  +OK [scan listing follows]
570 ;;  -ERR [no such message]
571
572 ;; RETR msg
573 ;; Arguments: a message-id (required)
574 ;; Restrictions: transaction state; msg must not be deleted
575 ;; Possible responses:
576 ;;  +OK [message contents follow]
577 ;;  -ERR [no such message]
578
579 ;; DELE msg
580 ;; Arguments: a message-id (required)
581 ;; Restrictions: transaction state; msg must not be deleted
582 ;; Possible responses:
583 ;;  +OK [message deleted]
584 ;;  -ERR [no such message]
585
586 ;; NOOP
587 ;; Arguments: none
588 ;; Restrictions: transaction state
589 ;; Possible responses:
590 ;;  +OK
591
592 ;; LAST
593 ;; Arguments: none
594 ;; Restrictions: transaction state
595 ;; Possible responses:
596 ;;  +OK nn [highest numbered message accessed]
597
598 ;; RSET
599 ;; Arguments: none
600 ;; Restrictions: transaction state
601 ;; Possible responses:
602 ;;  +OK [all delete marks removed]
603
604 ;;; UPDATE STATE
605
606 ;; QUIT
607 ;; Arguments: none
608 ;; Restrictions: none
609 ;; Possible responses:
610 ;;  +OK [TCP connection closed]
611
612 (provide 'pop3)
613
614 ;; arch-tag: 2facc142-1d74-498e-82af-4659b64cac12
615 ;;; pop3.el ends here