* gnus-art.el (gnus-use-idna)
[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
40 (defgroup pop3 nil
41   "Post Office Protocol."
42   :group 'mail
43   :group 'mail-source)
44
45 (defcustom pop3-maildrop (or (user-login-name)
46                              (getenv "LOGNAME")
47                              (getenv "USER"))
48   "*POP3 maildrop."
49   :version "22.1" ;; Oort Gnus
50   :type 'string
51   :group 'pop3)
52
53 (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
54                              "pop3")
55   "*POP3 mailhost."
56   :version "22.1" ;; Oort Gnus
57   :type 'string
58   :group 'pop3)
59
60 (defcustom pop3-port 110
61   "*POP3 port."
62   :version "22.1" ;; Oort Gnus
63   :type 'number
64   :group 'pop3)
65
66 (defcustom pop3-password-required t
67   "*Non-nil if a password is required when connecting to POP server."
68   :version "22.1" ;; Oort Gnus
69   :type 'boolean
70   :group 'pop3)
71
72 ;; Should this be customizable?
73 (defvar pop3-password nil
74   "*Password to use when connecting to POP server.")
75
76 (defcustom pop3-authentication-scheme 'pass
77   "*POP3 authentication scheme.
78 Defaults to `pass', for the standard USER/PASS authentication.  The other
79 valid value is 'apop'."
80   :type '(choice (const :tag "Normal user/password" pass)
81                  (const :tag "APOP" apop))
82   :version "22.1" ;; Oort Gnus
83   :group 'pop3)
84
85 (defcustom pop3-leave-mail-on-server nil
86   "*Non-nil if the mail is to be left on the POP server after fetching.
87
88 If `pop3-leave-mail-on-server' is non-nil the mail is to be left
89 on the POP server after fetching.  Note that POP servers maintain
90 no state information between sessions, so what the client
91 believes is there and what is actually there may not match up.
92 If they do not, then you may get duplicate mails or the whole
93 thing can fall apart and leave you with a corrupt mailbox."
94   ;; We can't use the UILD support from XEmacs mail-lib or cvs.m17n.org:
95   ;; http://thread.gmane.org/v9lld8fml4.fsf@marauder.physik.uni-ulm.de
96   ;; http://thread.gmane.org/b9yy8hzy9ej.fsf@jpl.org
97   ;; Any volunteer to re-implement this?
98   :version "22.1" ;; Oort Gnus
99   :type 'boolean
100   :group 'pop3)
101
102 (defvar pop3-timestamp nil
103   "Timestamp returned when initially connected to the POP server.
104 Used for APOP authentication.")
105
106 (defvar pop3-read-point nil)
107 (defvar pop3-debug nil)
108
109 ;; Borrowed from nnheader-accept-process-output in nnheader.el.
110 (defvar pop3-read-timeout
111   (if (string-match "windows-nt\\|os/2\\|emx\\|cygwin"
112                     (symbol-name system-type))
113       ;; http://thread.gmane.org/v9655t3pjo.fsf@marauder.physik.uni-ulm.de
114       ;;
115       ;; IIRC, values lower than 1.0 didn't/don't work on Windows/DOS.
116       ;;
117       ;; There should probably be a runtime test to determine the timing
118       ;; resolution, or a primitive to report it.  I don't know off-hand
119       ;; what's possible.  Perhaps better, maybe the Windows/DOS primitive
120       ;; could round up non-zero timeouts to a minimum of 1.0?
121       1.0
122     0.1)
123   "How long pop3 should wait between checking for the end of output.
124 Shorter values mean quicker response, but are more CPU intensive.")
125
126 ;; Borrowed from nnheader-accept-process-output in nnheader.el.
127 (defun pop3-accept-process-output (process)
128   (accept-process-output
129    process
130    (truncate pop3-read-timeout)
131    (truncate (* (- pop3-read-timeout
132                    (truncate pop3-read-timeout))
133                 1000))))
134
135 (defun pop3-movemail (&optional crashbox)
136   "Transfer contents of a maildrop to the specified CRASHBOX."
137   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
138   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
139          (crashbuf (get-buffer-create " *pop3-retr*"))
140          (n 1)
141          message-count
142          (pop3-password pop3-password))
143     ;; for debugging only
144     (if pop3-debug (switch-to-buffer (process-buffer process)))
145     ;; query for password
146     (if (and pop3-password-required (not pop3-password))
147         (setq pop3-password
148               (read-passwd (format "Password for %s: " pop3-maildrop))))
149     (cond ((equal 'apop pop3-authentication-scheme)
150            (pop3-apop process pop3-maildrop))
151           ((equal 'pass pop3-authentication-scheme)
152            (pop3-user process pop3-maildrop)
153            (pop3-pass process))
154           (t (error "Invalid POP3 authentication scheme")))
155     (setq message-count (car (pop3-stat process)))
156     (unwind-protect
157         (while (<= n message-count)
158           (message "Retrieving message %d of %d from %s..."
159                    n message-count pop3-mailhost)
160           (pop3-retr process n crashbuf)
161           (save-excursion
162             (set-buffer crashbuf)
163             (let ((coding-system-for-write 'binary))
164               (write-region (point-min) (point-max) crashbox t 'nomesg))
165             (set-buffer (process-buffer process))
166             (while (> (buffer-size) 5000)
167               (goto-char (point-min))
168               (forward-line 50)
169               (delete-region (point-min) (point))))
170           (unless pop3-leave-mail-on-server
171             (pop3-dele process n))
172           (setq n (+ 1 n))
173           (if pop3-debug (sit-for 1) (sit-for 0.1))) ; why?
174       (when (and pop3-leave-mail-on-server
175                  (> n 1))
176         (message "pop3.el doesn't support UIDL.  Setting `pop3-leave-mail-on-server'
177 to %s might not give the result you'd expect." pop3-leave-mail-on-server)
178         (sit-for 1))
179       (pop3-quit process))
180     (kill-buffer crashbuf))
181   t)
182
183 (defun pop3-get-message-count ()
184   "Return the number of messages in the maildrop."
185   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
186          message-count
187          (pop3-password pop3-password))
188     ;; for debugging only
189     (if pop3-debug (switch-to-buffer (process-buffer process)))
190     ;; query for password
191     (if (and pop3-password-required (not pop3-password))
192         (setq pop3-password
193               (read-passwd (format "Password for %s: " pop3-maildrop))))
194     (cond ((equal 'apop pop3-authentication-scheme)
195            (pop3-apop process pop3-maildrop))
196           ((equal 'pass pop3-authentication-scheme)
197            (pop3-user process pop3-maildrop)
198            (pop3-pass process))
199           (t (error "Invalid POP3 authentication scheme")))
200     (setq message-count (car (pop3-stat process)))
201     (pop3-quit process)
202     message-count))
203
204 (autoload 'open-tls-stream "tls")
205 (autoload 'starttls-open-stream "starttls")
206 (autoload 'starttls-negotiate "starttls") ; avoid warning
207
208 (defcustom pop3-stream-type nil
209   "*Transport security type for POP3 connexions.
210 This may be either nil (plain connexion), `ssl' (use an
211 SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
212 to turn on TLS security after opening the stream).  However, if
213 this is nil, `ssl' is assumed for connexions to port
214 995 (pop3s)."
215   :version "23.0" ;; No Gnus
216   :group 'pop3
217   :type '(choice (const :tag "Plain" nil)
218                  (const :tag "SSL/TLS" ssl)
219                  (const starttls)))
220
221 (defun pop3-open-server (mailhost port)
222   "Open TCP connection to MAILHOST on PORT.
223 Returns the process associated with the connection."
224   (let ((coding-system-for-read 'binary)
225         (coding-system-for-write 'binary)
226         process)
227     (save-excursion
228       (set-buffer (get-buffer-create (concat " trace of POP session to "
229                                              mailhost)))
230       (erase-buffer)
231       (setq pop3-read-point (point-min))
232       (setq process
233             (cond
234              ((or (eq pop3-stream-type 'ssl)
235                   (and (not pop3-stream-type) (member port '(995 "pop3s"))))
236               ;; gnutls-cli, openssl don't accept service names
237               (if (or (equal port "pop3s")
238                       (null port))
239                   (setq port 995))
240               (let ((process (open-tls-stream "POP" (current-buffer)
241                                               mailhost port)))
242                 (when process
243                   ;; There's a load of info printed that needs deleting.
244                   (let ((again 't))
245                     ;; repeat until
246                     ;; - either we received the +OK line
247                     ;; - or accept-process-output timed out without getting
248                     ;;   anything
249                     (while (and again
250                                 (setq again (memq (process-status process)
251                                                   '(open run))))
252                       (setq again (pop3-accept-process-output process))
253                       (goto-char (point-max))
254                       (forward-line -1)
255                       (cond ((looking-at "\\+OK")
256                              (setq again nil)
257                              (delete-region (point-min) (point)))
258                             ((not again)
259                              (pop3-quit process)
260                              (error "POP SSL connexion failed")))))
261                   process)))
262              ((eq pop3-stream-type 'starttls)
263               ;; gnutls-cli, openssl don't accept service names
264               (if (equal port "pop3")
265                   (setq port 110))
266               (let ((process (starttls-open-stream "POP" (current-buffer)
267                                                    mailhost (or port 110))))
268                 (pop3-send-command process "STLS")
269                 (let ((response (pop3-read-response process t)))
270                   (if (and response (string-match "+OK" response))
271                       (starttls-negotiate process)
272                     (pop3-quit process)
273                     (error "POP server doesn't support starttls")))
274                 process))
275              (t 
276               (open-network-stream "POP" (current-buffer) mailhost port))))
277       (let ((response (pop3-read-response process t)))
278         (setq pop3-timestamp
279               (substring response (or (string-match "<" response) 0)
280                          (+ 1 (or (string-match ">" response) -1)))))
281       process)))
282
283 ;; Support functions
284
285 (defun pop3-process-filter (process output)
286   (save-excursion
287     (set-buffer (process-buffer process))
288     (goto-char (point-max))
289     (insert output)))
290
291 (defun pop3-send-command (process command)
292   (set-buffer (process-buffer process))
293   (goto-char (point-max))
294   ;; (if (= (aref command 0) ?P)
295   ;;     (insert "PASS <omitted>\r\n")
296   ;;   (insert command "\r\n"))
297   (setq pop3-read-point (point))
298   (goto-char (point-max))
299   (process-send-string process (concat command "\r\n")))
300
301 (defun pop3-read-response (process &optional return)
302   "Read the response from the server.
303 Return the response string if optional second argument is non-nil."
304   (let ((case-fold-search nil)
305         match-end)
306     (save-excursion
307       (set-buffer (process-buffer process))
308       (goto-char pop3-read-point)
309       (while (and (memq (process-status process) '(open run))
310                   (not (search-forward "\r\n" nil t)))
311         (pop3-accept-process-output process)
312         (goto-char pop3-read-point))
313       (setq match-end (point))
314       (goto-char pop3-read-point)
315       (if (looking-at "-ERR")
316           (error (buffer-substring (point) (- match-end 2)))
317         (if (not (looking-at "+OK"))
318             (progn (setq pop3-read-point match-end) nil)
319           (setq pop3-read-point match-end)
320           (if return
321               (buffer-substring (point) match-end)
322             t)
323           )))))
324
325 (defun pop3-clean-region (start end)
326   (setq end (set-marker (make-marker) end))
327   (save-excursion
328     (goto-char start)
329     (while (and (< (point) end) (search-forward "\r\n" end t))
330       (replace-match "\n" t t))
331     (goto-char start)
332     (while (and (< (point) end) (re-search-forward "^\\." end t))
333       (replace-match "" t t)
334       (forward-char)))
335   (set-marker end nil))
336
337 (eval-when-compile (defvar parse-time-months))
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   "Scan listing of available messages.
461 This function currently does nothing.")
462
463 (defun pop3-retr (process msg crashbuf)
464   "Retrieve message-id MSG to buffer CRASHBUF."
465   (pop3-send-command process (format "RETR %s" msg))
466   (pop3-read-response process)
467   (let ((start pop3-read-point) end)
468     (save-excursion
469       (set-buffer (process-buffer process))
470       (while (not (re-search-forward "^\\.\r\n" nil t))
471         (pop3-accept-process-output process)
472         (goto-char start))
473       (setq pop3-read-point (point-marker))
474       ;; this code does not seem to work for some POP servers...
475       ;; and I cannot figure out why not.
476       ;;      (goto-char (match-beginning 0))
477       ;;      (backward-char 2)
478       ;;      (if (not (looking-at "\r\n"))
479       ;;          (insert "\r\n"))
480       ;;      (re-search-forward "\\.\r\n")
481       (goto-char (match-beginning 0))
482       (setq end (point-marker))
483       (pop3-clean-region start end)
484       (pop3-munge-message-separator start end)
485       (save-excursion
486         (set-buffer crashbuf)
487         (erase-buffer))
488       (copy-to-buffer crashbuf start end)
489       (delete-region start end)
490       )))
491
492 (defun pop3-dele (process msg)
493   "Mark message-id MSG as deleted."
494   (pop3-send-command process (format "DELE %s" msg))
495   (pop3-read-response process))
496
497 (defun pop3-noop (process msg)
498   "No-operation."
499   (pop3-send-command process "NOOP")
500   (pop3-read-response process))
501
502 (defun pop3-last (process)
503   "Return highest accessed message-id number for the session."
504   (pop3-send-command process "LAST")
505   (let ((response (pop3-read-response process t)))
506     (string-to-number (nth 1 (split-string response " ")))
507     ))
508
509 (defun pop3-rset (process)
510   "Remove all delete marks from current maildrop."
511   (pop3-send-command process "RSET")
512   (pop3-read-response process))
513
514 ;; UPDATE
515
516 (defun pop3-quit (process)
517   "Close connection to POP3 server.
518 Tell server to remove all messages marked as deleted, unlock the maildrop,
519 and close the connection."
520   (pop3-send-command process "QUIT")
521   (pop3-read-response process t)
522   (if process
523       (save-excursion
524         (set-buffer (process-buffer process))
525         (goto-char (point-max))
526         (delete-process process))))
527 \f
528 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
529
530 ;;; AUTHORIZATION STATE
531
532 ;; Initial TCP connection
533 ;; Arguments: none
534 ;; Restrictions: none
535 ;; Possible responses:
536 ;;  +OK [POP3 server ready]
537
538 ;; USER name
539 ;; Arguments: a server specific user-id (required)
540 ;; Restrictions: authorization state [after unsuccessful USER or PASS
541 ;; Possible responses:
542 ;;  +OK [valid user-id]
543 ;;  -ERR [invalid user-id]
544
545 ;; PASS string
546 ;; Arguments: a server/user-id specific password (required)
547 ;; Restrictions: authorization state, after successful USER
548 ;; Possible responses:
549 ;;  +OK [maildrop locked and ready]
550 ;;  -ERR [invalid password]
551 ;;  -ERR [unable to lock maildrop]
552
553 ;; STLS      (RFC 2595)
554 ;; Arguments: none
555 ;; Restrictions: Only permitted in AUTHORIZATION state.
556 ;; Possible responses:
557 ;;  +OK
558 ;;  -ERR
559
560 ;;; TRANSACTION STATE
561
562 ;; STAT
563 ;; Arguments: none
564 ;; Restrictions: transaction state
565 ;; Possible responses:
566 ;;  +OK nn mm [# of messages, size of maildrop]
567
568 ;; LIST [msg]
569 ;; Arguments: a message-id (optional)
570 ;; Restrictions: transaction state; msg must not be deleted
571 ;; Possible responses:
572 ;;  +OK [scan listing follows]
573 ;;  -ERR [no such message]
574
575 ;; RETR msg
576 ;; Arguments: a message-id (required)
577 ;; Restrictions: transaction state; msg must not be deleted
578 ;; Possible responses:
579 ;;  +OK [message contents follow]
580 ;;  -ERR [no such message]
581
582 ;; DELE msg
583 ;; Arguments: a message-id (required)
584 ;; Restrictions: transaction state; msg must not be deleted
585 ;; Possible responses:
586 ;;  +OK [message deleted]
587 ;;  -ERR [no such message]
588
589 ;; NOOP
590 ;; Arguments: none
591 ;; Restrictions: transaction state
592 ;; Possible responses:
593 ;;  +OK
594
595 ;; LAST
596 ;; Arguments: none
597 ;; Restrictions: transaction state
598 ;; Possible responses:
599 ;;  +OK nn [highest numbered message accessed]
600
601 ;; RSET
602 ;; Arguments: none
603 ;; Restrictions: transaction state
604 ;; Possible responses:
605 ;;  +OK [all delete marks removed]
606
607 ;;; UPDATE STATE
608
609 ;; QUIT
610 ;; Arguments: none
611 ;; Restrictions: none
612 ;; Possible responses:
613 ;;  +OK [TCP connection closed]
614
615 (provide 'pop3)
616
617 ;;; arch-tag: 2facc142-1d74-498e-82af-4659b64cac12
618 ;;; pop3.el ends here