(pop3-get-extended-response): Fix regexp.
[elisp/gnus.git-] / lisp / pop3.el
1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
2
3 ;; Copyright (C) 1996-1999 Free Software Foundation, Inc.
4
5 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
6 ;;      Daiki Ueno  <ueno@ueda.info.waseda.ac.jp>
7 ;; Keywords: mail, pop3
8 ;; Version: 1.3s
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 2, 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., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, 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 (provide 'pop3)
40
41 (defconst pop3-version "1.3s")
42
43 (defvar pop3-maildrop (or (user-login-name) (getenv "LOGNAME") (getenv "USER") nil)
44   "*POP3 maildrop.")
45 (defvar pop3-mailhost (or (getenv "MAILHOST") nil)
46   "*POP3 mailhost.")
47 (defvar pop3-port 110
48   "*POP3 port.")
49 (defvar pop3-connection-type nil
50   "*POP3 connection type.")
51
52 (defvar pop3-password-required t
53   "*Non-nil if a password is required when connecting to POP server.")
54 (defvar pop3-password nil
55   "*Password to use when connecting to POP server.")
56
57 (defvar pop3-authentication-scheme 'pass
58   "*POP3 authentication scheme.
59 Defaults to 'pass, for the standard USER/PASS authentication.  Other valid
60 values are 'apop.")
61
62 (defvar pop3-timestamp nil
63   "Timestamp returned when initially connected to the POP server.
64 Used for APOP authentication.")
65
66 (defvar pop3-leave-mail-on-server nil
67   "Non-nil if mail is to be left on the server and UIDL used for 
68 message retrieval.")
69
70 (defvar pop3-maximum-message-size nil
71   "If non-nil only download messages smaller than this.")
72
73 (defvar pop3-uidl-file-name "~/.uidls"
74   "File in which to store the UIDL of processed messages.")
75
76 (defvar pop3-uidl-support 'dont-know
77   "Whether the server supports UIDL.
78 Nil means no, t means yes, not-nil-or-t means yet to be determined.")
79
80 (defvar pop3-uidl-obarray (make-vector 31 0)
81   "Uidl hash table.")
82
83 (defvar pop3-read-point nil)
84 (defvar pop3-debug nil)
85
86 (eval-and-compile
87   (autoload 'open-ssl-stream "ssl"))
88
89 (defvar pop3-ssl-program-arguments
90   '("-quiet")
91   "Arguments to be passed to the program `pop3-ssl-program-name'.")
92
93 (defun pop3-movemail (&optional crashbox)
94   "Transfer contents of a maildrop to the specified CRASHBOX."
95   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
96   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
97          (crashbuf (get-buffer-create " *pop3-retr*"))
98          (n 1)
99          (msgid 1)
100          (msglen 0)
101          message-count
102          (pop3-password pop3-password)
103          (pop3-uidl-file-name 
104           (concat pop3-uidl-file-name "-" pop3-mailhost))
105          (retrieved-messages nil)
106          messages)
107     ;; for debugging only
108     (if pop3-debug (switch-to-buffer (process-buffer process)))
109     ;; query for password
110     (if (and pop3-password-required (not pop3-password))
111         (setq pop3-password
112               (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
113     (cond ((equal 'apop pop3-authentication-scheme)
114            (pop3-apop process pop3-maildrop))
115           ((equal 'pass pop3-authentication-scheme)
116            (pop3-user process pop3-maildrop)
117            (pop3-pass process))
118           (t (error "Invalid POP3 authentication scheme.")))
119     ;; get messages that are suitable for download
120     (message "Retrieving message list...")
121     (setq messages (pop3-get-message-numbers process)
122           message-count (length messages))
123     (message (format "Retrieving message list...%d unread" message-count))
124     (unwind-protect
125         (progn
126           (while (<= n message-count)
127             (setq msgid (caar messages)
128                   msglen (cdar messages)
129                   messages (cdr messages))
130             ;; only retrieve messages matching our regexp or in the uidl list
131             (unless (or (not msgid)
132                         ;; don't download messages that are too large
133                         (and pop3-maximum-message-size 
134                              (> msglen pop3-maximum-message-size)))
135               (message (format "Retrieving message %d of %d from %s..."
136                                n message-count pop3-mailhost))
137               (pop3-retr process msgid crashbuf)
138               (setq retrieved-messages (cons msgid retrieved-messages)))
139             (setq n (1+ n)))
140           (with-current-buffer crashbuf
141             (write-region-as-binary (point-min) (point-max)
142                                     crashbox 'append 'nomesg)
143             )
144           ;; mark messages as read
145           (when pop3-leave-mail-on-server
146             (pop3-save-uidls))
147           ;; now delete the messages we have retrieved
148           (unless pop3-leave-mail-on-server
149             (dolist (n retrieved-messages)
150               (message (format "Deleting message %d of %d from %s..."
151                                n message-count pop3-mailhost))
152               (pop3-dele process n)))
153           )
154       (pop3-quit process))
155     (kill-buffer crashbuf)
156     t))
157
158 (defun pop3-open-server (mailhost port)
159   "Open TCP connection to MAILHOST.
160 Returns the process associated with the connection."
161   (let ((process-buffer
162          (get-buffer-create (format "trace of POP session to %s" mailhost)))
163         (process))
164     (save-excursion
165       (set-buffer process-buffer)
166       (erase-buffer))
167     (setq
168      process
169      (cond
170       ((eq pop3-connection-type 'ssl)
171        (pop3-open-ssl-stream "POP" process-buffer mailhost port))
172       (t
173        (open-network-stream-as-binary "POP" process-buffer mailhost port))))
174     (setq pop3-read-point (point-min))
175     (let ((response (pop3-read-response process t)))
176       (setq pop3-timestamp
177             (substring response (or (string-match "<" response) 0)
178                        (+ 1 (or (string-match ">" response) -1)))))
179     process))
180
181 (defun pop3-open-ssl-stream-1 (name buffer host service extra-arg)
182   (let* ((ssl-program-arguments 
183           `(,@pop3-ssl-program-arguments ,extra-arg
184             "-connect" ,(format "%s:%d" host service)))
185          (process (open-ssl-stream name buffer host service)))
186     (when process
187       (with-current-buffer buffer
188         (goto-char (point-min))
189         (while (and (memq (process-status process) '(open run))
190                     (goto-char (point-max))
191                     (forward-line -1)
192                     (not (looking-at "+OK")))
193           (accept-process-output process 1)
194           (sit-for 1))
195         (delete-region (point-min) (point)))
196       (and process (memq (process-status process) '(open run))
197            process))))
198
199 (defun pop3-open-ssl-stream (name buffer host service)
200   "Open a SSL connection for a service to a host."
201   (as-binary-process
202    (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
203        (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
204
205 ;; Support functions
206
207 (defun pop3-process-filter (process output)
208   (save-excursion
209     (set-buffer (process-buffer process))
210     (goto-char (point-max))
211     (insert output)))
212
213 (defun pop3-send-command (process command)
214     (set-buffer (process-buffer process))
215     (goto-char (point-max))
216 ;;    (if (= (aref command 0) ?P)
217 ;;      (insert "PASS <omitted>\r\n")
218 ;;      (insert command "\r\n"))
219     (setq pop3-read-point (point))
220     (goto-char (point-max))
221     (process-send-string process (concat command "\r\n"))
222     )
223
224 (defun pop3-read-response (process &optional return)
225   "Read the response from the server.
226 Return the response string if optional second argument is non-nil."
227   (let ((case-fold-search nil)
228         match-end)
229     (save-excursion
230       (set-buffer (process-buffer process))
231       (goto-char pop3-read-point)
232       (while (not (search-forward "\r\n" nil t))
233         (accept-process-output process 3)
234         (goto-char pop3-read-point))
235       (setq match-end (point))
236       (goto-char pop3-read-point)
237       (if (looking-at "-ERR")
238           (signal 'error (list (buffer-substring (point) (- match-end 2))))
239         (if (not (looking-at "+OK"))
240             (progn (setq pop3-read-point match-end) nil)
241           (setq pop3-read-point match-end)
242           (if return
243               (buffer-substring (point) match-end)
244             t)
245           )))))
246
247 (defvar pop3-read-passwd nil)
248 (defun pop3-read-passwd (prompt)
249   (if (not pop3-read-passwd)
250       (if (functionp 'read-passwd)
251           (setq pop3-read-passwd 'read-passwd)
252         (if (load "passwd" t)
253             (setq pop3-read-passwd 'read-passwd)
254           (autoload 'ange-ftp-read-passwd "ange-ftp")
255           (setq pop3-read-passwd 'ange-ftp-read-passwd))))
256   (funcall pop3-read-passwd prompt))
257
258 (defun pop3-clean-region (start end)
259   (setq end (set-marker (make-marker) end))
260   (save-excursion
261     (goto-char start)
262     (while (and (< (point) end) (search-forward "\r\n" end t))
263       (replace-match "\n" t t))
264     (goto-char start)
265     (while (re-search-forward "\n\n\\(From \\)" end t)
266       (replace-match "\n\n>\\1" t nil))
267     (goto-char start)
268     (while (and (< (point) end) (re-search-forward "^\\." end t))
269       (replace-match "" t t)
270       (forward-char)))
271   (set-marker end nil))
272
273 (defun pop3-munge-message-separator (start end)
274   "Check to see if a message separator exists.  If not, generate one."
275   (if (not (fboundp 'parse-time-string))
276       (autoload 'parse-time-string "parse-time"))
277   (save-excursion
278     (save-restriction
279       (narrow-to-region start end)
280       (goto-char (point-min))
281       (if (not (or (looking-at "From .?") ; Unix mail
282                    (looking-at "\001\001\001\001\n") ; MMDF
283                    (looking-at "BABYL OPTIONS:") ; Babyl
284                    ))
285           (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
286                 (date (mail-fetch-field "Date"))
287                 (From_))
288             ;; sample date formats I have seen
289             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
290             ;; Date: 08 Jul 1996 23:22:24 -0400
291             ;; should be
292             ;; Tue Jul 9 09:04:21 1996
293             (setq date (format-time-string
294                         "%a %b %e %T %Y"
295                         (if date
296                             (condition-case nil
297                                 (apply 'encode-time (parse-time-string date))
298                               (error (current-time)))
299                           (current-time))))
300             (setq From_ (format "\nFrom %s  %s\n" from date))
301             (while (string-match "," From_)
302               (setq From_ (concat (substring From_ 0 (match-beginning 0))
303                                   (substring From_ (match-end 0)))))
304             (goto-char (point-min))
305             (insert From_))))))
306
307 ;; UIDL support
308
309 (defun pop3-get-message-numbers (process)
310   "Get the list of message numbers and lengths to retrieve via PROCESS."
311   ;; we use the LIST comand first anyway to get the message lengths.
312   ;; then if we're leaving mail on the server, see if the UIDL command
313   ;; is implemented. if so, we use it to get the message number list.
314   (let ((messages (pop3-list process))
315         (uidl (if pop3-leave-mail-on-server
316                   (pop3-get-uidl process))))
317     (when messages
318       (pop messages)
319       (cond
320        ((eq pop3-uidl-support t)
321         ;; remove elements not in the uidl, this assumes the uidl is short
322         (remove-if-not
323          (lambda (message) (memq (car message) uidl))
324          (reverse messages)))
325        (t messages)))))
326
327 (defun pop3-get-uidl (process)
328   "Use PROCESS to get a list of unread message numbers."
329   (let ((messages (pop3-uidl process)) uidl)
330     (if (or (null messages) (null pop3-uidl-support))
331         (setq pop3-uidl-support nil)
332       (setq pop3-uidl-support t)
333       (save-excursion
334         (with-temp-buffer
335           (when (file-readable-p pop3-uidl-file-name)
336             (insert-file-contents pop3-uidl-file-name))
337           (goto-char (point-min))
338           (while (looking-at "\\([^ \n\t]+\\)")
339             (set (intern (match-string 1) pop3-uidl-obarray)
340                  (cons nil t))
341             (forward-line 1))
342           ))
343       (dolist (message (cdr messages))
344         (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
345             (setcar (symbol-value uidl) (car message))
346           (set (intern (cdr message) pop3-uidl-obarray)
347                (cons (car message) nil))))
348       (pop3-get-unread-message-numbers))
349     ))
350
351 (defun pop3-get-unread-message-numbers ()
352   "Return a sorted list of unread msg numbers to retrieve."
353   (let (nums)
354     (mapatoms (lambda (atom)
355                 (if (not (cdr (symbol-value atom)))
356                     (push (car (symbol-value atom)) nums)))
357               pop3-uidl-obarray)
358     (sort nums '<)))
359
360 (defun pop3-save-uidls ()
361   "Save the updated UIDLs to disk for use next time."
362   (when (and pop3-leave-mail-on-server 
363              pop3-uidl-obarray
364              (catch 'found
365                (dotimes (i (length pop3-uidl-obarray))
366                  (if (symbolp (aref pop3-uidl-obarray i))
367                      (throw 'found t)))))
368     (save-excursion
369       (with-temp-buffer
370         (when (file-readable-p pop3-uidl-file-name)
371           (copy-file pop3-uidl-file-name
372                      (concat pop3-uidl-file-name ".old")
373                      'overwrite 'keeptime))
374         (mapatoms 
375          (lambda (atom)
376            (when (car (symbol-value atom))
377              (insert (format "%s\n" atom))))
378          pop3-uidl-obarray)
379         (write-file pop3-uidl-file-name)))))
380
381 ;; The Command Set
382
383 ;; AUTHORIZATION STATE
384
385 (defun pop3-user (process user)
386   "Send USER information to POP3 server."
387   (pop3-send-command process (format "USER %s" user))
388   (let ((response (pop3-read-response process t)))
389     (if (not (and response (string-match "+OK" response)))
390         (error (format "USER %s not valid." user)))))
391
392 (defun pop3-pass (process)
393   "Send authentication information to the server."
394   (pop3-send-command process (format "PASS %s" pop3-password))
395   (let ((response (pop3-read-response process t)))
396     (if (not (and response (string-match "+OK" response)))
397         (pop3-quit process))))
398
399 (defun pop3-apop (process user)
400   "Send alternate authentication information to the server."
401   (if (not (fboundp 'md5)) (autoload 'md5 "md5"))
402   (let ((hash (md5 (concat pop3-timestamp pop3-password))))
403     (pop3-send-command process (format "APOP %s %s" user hash))
404     (let ((response (pop3-read-response process t)))
405       (if (not (and response (string-match "+OK" response)))
406           (pop3-quit process)))))
407
408 ;; TRANSACTION STATE
409
410 (defun pop3-stat (process)
411   "Return the number of messages in the maildrop and the maildrop's size."
412   (pop3-send-command process "STAT")
413   (let ((response (pop3-read-response process t)))
414     (list (string-to-int (nth 1 (split-string response)))
415           (string-to-int (nth 2 (split-string response))))
416     ))
417
418 (defun pop3-retr (process msg crashbuf)
419   "Retrieve message-id MSG to buffer CRASHBUF."
420   (pop3-send-command process (format "RETR %s" msg))
421   (pop3-read-response process)
422   (save-excursion
423     (save-restriction
424       (apply 'narrow-to-region (pop3-get-extended-response process))
425       (pop3-munge-message-separator (point-min) (point-max))
426       (append-to-buffer crashbuf (point-min) (point-max))
427       (delete-region (point-min) (point-max))
428       )))
429
430 (defun pop3-dele (process msg)
431   "Mark message-id MSG as deleted."
432   (pop3-send-command process (format "DELE %s" msg))
433   (pop3-read-response process))
434
435 (defun pop3-noop (process msg)
436   "No-operation."
437   (pop3-send-command process "NOOP")
438   (pop3-read-response process))
439
440 (defun pop3-last (process)
441   "Return highest accessed message-id number for the session."
442   (pop3-send-command process "LAST")
443   (let ((response (pop3-read-response process t)))
444     (string-to-int (nth 1 (split-string response)))
445     ))
446
447 (defun pop3-rset (process)
448   "Remove all delete marks from current maildrop."
449   (pop3-send-command process "RSET")
450   (pop3-read-response process))
451
452 ;; UPDATE
453
454 (defun pop3-quit (process)
455   "Close connection to POP3 server.
456 Tell server to remove all messages marked as deleted, unlock the maildrop,
457 and close the connection."
458   (pop3-send-command process "QUIT")
459   (pop3-read-response process t)
460   (when process
461     (save-excursion
462       (set-buffer (process-buffer process))
463       (goto-char (point-max))
464       (delete-process process)
465       )))
466
467 (defun pop3-uidl (process &optional msgno)
468   "Return the results of a UIDL command in PROCESS for optional MSGNO.
469 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
470 Otherwise, return a list in the form
471
472    (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
473
474 where
475
476    N is an integer for the number of UIDLs returned (could be 0)
477    UIDL-n is a string."
478
479   (if msgno
480       (pop3-send-command process (format "UIDL %d" msgno))
481     (pop3-send-command process "UIDL"))
482   
483   (if (null (pop3-read-response process t))
484       nil ;; UIDL is not supported on this server
485     (let (pairs uidl)
486       (save-excursion
487         (save-restriction
488           (apply 'narrow-to-region (pop3-get-extended-response process))
489           (goto-char (point-min))
490           (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
491             (setq msgno (string-to-int (match-string 1))
492                   uidl (match-string 2))
493             (push (cons msgno uidl) pairs)
494             (beginning-of-line 2))
495           (cons (length pairs) (nreverse pairs))
496           )))))
497
498 (defun pop3-list (process &optional msgno)
499   "Return the results of a LIST command for PROCESS and optional MSGNO.
500 If (optional) msgno is invalid, return nil.  Otherwise, return a list
501 in the form
502
503    (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
504
505 where
506
507    N is an integer for the number of msg/len pairs (could be 0)
508    LEN-n is an integer."
509   (if msgno
510       (pop3-send-command process (format "LIST %d" msgno))
511     (pop3-send-command process "LIST"))
512
513   (if (null (pop3-read-response process t))
514       nil ;; MSGNO is not valid number
515     (let (pairs len)
516       (save-excursion
517         (save-restriction
518           (apply 'narrow-to-region (pop3-get-extended-response process))
519           (goto-char (point-min))
520           (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
521             (setq msgno (string-to-int (match-string 1))
522                   len (string-to-int (match-string 2)))
523             (push (cons msgno len) pairs)
524             (beginning-of-line 2))
525           (cons (length pairs) (nreverse pairs))
526           )))))
527
528 ;;; Utility code
529
530 (defun pop3-get-extended-response (process)
531   "Get the extended pop3 response in the PROCESS buffer."
532   (let ((start pop3-read-point) end)
533     (set-buffer (process-buffer process))
534     (goto-char start)
535     (while (not (re-search-forward "^\\.\r\n" nil t))
536       (accept-process-output process 3)
537       (goto-char start))
538     (setq pop3-read-point (point-marker))
539     (goto-char (match-beginning 0))
540     (setq end (point-marker))
541     (pop3-clean-region start end)
542     (list start end)))
543
544 \f
545 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
546
547 ;;; AUTHORIZATION STATE
548
549 ;; Initial TCP connection
550 ;; Arguments: none
551 ;; Restrictions: none
552 ;; Possible responses:
553 ;;  +OK [POP3 server ready]
554
555 ;; USER name
556 ;; Arguments: a server specific user-id (required)
557 ;; Restrictions: authorization state [after unsuccessful USER or PASS
558 ;; Possible responses:
559 ;;  +OK [valid user-id]
560 ;;  -ERR [invalid user-id]
561
562 ;; PASS string
563 ;; Arguments: a server/user-id specific password (required)
564 ;; Restrictions: authorization state, after successful USER
565 ;; Possible responses:
566 ;;  +OK [maildrop locked and ready]
567 ;;  -ERR [invalid password]
568 ;;  -ERR [unable to lock maildrop]
569
570 ;;; TRANSACTION STATE
571
572 ;; STAT
573 ;; Arguments: none
574 ;; Restrictions: transaction state
575 ;; Possible responses:
576 ;;  +OK nn mm [# of messages, size of maildrop]
577
578 ;; LIST [msg]
579 ;; Arguments: a message-id (optional)
580 ;; Restrictions: transaction state; msg must not be deleted
581 ;; Possible responses:
582 ;;  +OK [scan listing follows]
583 ;;  -ERR [no such message]
584
585 ;; UIDL [msg]
586 ;; Arguments: a message-id (optional)
587 ;; Restrictions: transaction state; msg must not be deleted
588 ;; Possible responses:
589 ;;  +OK [uidl listing follows]
590 ;;  -ERR [no such message]
591
592 ;; RETR msg
593 ;; Arguments: a message-id (required)
594 ;; Restrictions: transaction state; msg must not be deleted
595 ;; Possible responses:
596 ;;  +OK [message contents follow]
597 ;;  -ERR [no such message]
598
599 ;; DELE msg
600 ;; Arguments: a message-id (required)
601 ;; Restrictions: transaction state; msg must not be deleted
602 ;; Possible responses:
603 ;;  +OK [message deleted]
604 ;;  -ERR [no such message]
605
606 ;; NOOP
607 ;; Arguments: none
608 ;; Restrictions: transaction state
609 ;; Possible responses:
610 ;;  +OK
611
612 ;; LAST
613 ;; Arguments: none
614 ;; Restrictions: transaction state
615 ;; Possible responses:
616 ;;  +OK nn [highest numbered message accessed]
617
618 ;; RSET
619 ;; Arguments: none
620 ;; Restrictions: transaction state
621 ;; Possible responses:
622 ;;  +OK [all delete marks removed]
623
624 ;;; UPDATE STATE
625
626 ;; QUIT
627 ;; Arguments: none
628 ;; Restrictions: none
629 ;; Possible responses:
630 ;;  +OK [TCP connection closed]