Synch to No Gnus 200410120226.
[elisp/gnus.git-] / lisp / pop3.el
1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004
4 ;;        Free Software Foundation, Inc.
5
6 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
7 ;;      Daiki Ueno  <ueno@ueda.info.waseda.ac.jp>
8 ;;      Katsumi Yamaoka <yamaoka@jpl.org>
9 ;; Maintainer: Volunteers
10 ;; Keywords: mail
11
12 ;; This file is part of T-gnus.
13
14 ;; GNU Emacs is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; any later version.
18
19 ;; GNU Emacs is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
27 ;; Boston, MA 02111-1307, USA.
28
29 ;;; Commentary:
30
31 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
32 ;; are implemented.  The LIST command has not been implemented due to lack
33 ;; of actual usefulness.
34 ;; The optional POP3 command TOP has not been implemented.
35
36 ;; This program was inspired by Kyle E. Jones's vm-pop program.
37
38 ;;; Gnus:
39
40 ;; You can use this program for Gnus, without needing any modification.
41 ;; There are two ways to do that; one is to replace Gnus' pop3.el with
42 ;; it when installing Gnus; the other is to replace Gnus' pop3.el which
43 ;; has been installed with this module and byte-compile it.
44
45 ;; Note: you should not modify the value for the `pop' section of the
46 ;; `mail-source-keyword-map' variable.
47
48 ;; This program provides the following features in addition to Gnus:
49
50 ;; 1. You can use SSL or STARTTLS stream to connect to mail servers.
51 ;;    For example, specify the `:connection' keyword and the value pair
52 ;;    in a mail-source as follows:
53 ;;
54 ;;(setq mail-sources '((pop :server "pop3.mail.server" :port 995
55 ;;                        :connection ssl :authentication apop)))
56 ;;
57 ;;    For STARTTLS stream, use `tls' isntead of `ssl'.  The default
58 ;;    connection type is defined by `pop3-connection-type' which
59 ;;    defaults to nil.
60
61 ;; 2. You can fetch mails without deleting them in mail servers.  To do
62 ;;    that, specify the `:leave' keyword with the value t as follows:
63 ;;
64 ;;(setq mail-sources '((pop :server "pop3.mail.server" :leave t)))
65 ;;
66 ;;    Already read mails are registered into the ~/.uidls-SERVER file
67 ;;    (which is the default, see `pop3-uidl-file-name'), and you will
68 ;;    never need to fetch them twice.  The default value for the
69 ;;    `:leave' keyword is specified by the `pop3-leave-mail-on-server'
70 ;;    variable.  You have no need to modify that value normally.
71
72 ;; 3. See the source code for some other miscellaneous extended features.
73
74 ;;; Code:
75
76 (eval-when-compile
77   (require 'cl))
78
79 (require 'mail-utils)
80 (require 'nnheader)
81
82 (defgroup pop3 nil
83   "Post Office Protocol"
84   :group 'mail
85   :group 'mail-source)
86
87 (defcustom pop3-maildrop (or (user-login-name)
88                              (getenv "LOGNAME")
89                              (getenv "USER"))
90   "*POP3 maildrop."
91   :version "21.4" ;; Oort Gnus
92   :type 'string
93   :group 'pop3)
94
95 (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
96                              "pop3")
97   "*POP3 mailhost."
98   :version "21.4" ;; Oort Gnus
99   :type 'string
100   :group 'pop3)
101
102 (defcustom pop3-port 110
103   "*POP3 port."
104   :version "21.4" ;; Oort Gnus
105   :type 'number
106   :group 'pop3)
107
108 (defcustom pop3-connection-type nil
109   "*POP3 connection type."
110   :type 'boolean
111   :group 'pop3)
112
113 (defcustom pop3-password-required t
114   "*Non-nil if a password is required when connecting to POP server."
115   :version "21.4" ;; Oort Gnus
116   :type 'boolean
117   :group 'pop3)
118
119 ;; Should this be customizable?
120 (defvar pop3-password nil
121   "*Password to use when connecting to POP server.")
122
123 (defcustom pop3-authentication-scheme 'pass
124   "*POP3 authentication scheme.
125 Defaults to 'pass, for the standard USER/PASS authentication.  Other valid
126 values are 'apop."
127   :version "21.4" ;; Oort Gnus
128   :type '(choice (const :tag "USER/PASS" pass)
129                  (const :tag "APOP" apop))
130   :group 'pop3)
131
132 (defcustom pop3-leave-mail-on-server nil
133   "*Non-nil if the mail is to be left on the POP server after fetching."
134   :version "21.4" ;; Oort Gnus
135   :type 'boolean
136   :group 'pop3)
137
138 (defvar pop3-timestamp nil
139   "Timestamp returned when initially connected to the POP server.
140 Used for APOP authentication.")
141
142 (defcustom pop3-maximum-message-size nil
143   "If non-nil only download messages smaller than this."
144   :type '(choice (const :tag "Unlimited" nil)
145                  (integer :tag "Maximum size" :format "%t: %v\n" :size 0))
146   :group 'pop3)
147
148 (defcustom pop3-except-header-regexp nil
149   "If non-nil we do not retrieve messages whose headers are matching this regexp."
150   :type '(choice (const :tag "Retrieve any messages" nil)
151                  (regexp :format "%t: %v\n" :size 0))
152   :group 'pop3)
153
154 (defcustom pop3-uidl-file-name "~/.uidls"
155   "File in which to store the UIDL of processed messages."
156   :type '(file :format "%t: %v\n" :size 0)
157   :group 'pop3)
158
159 (defcustom pop3-uidl-support nil
160   "Alist of servers and flags of whether they support UIDLs.
161 Users don't have to set this value."
162   :type 'boolean
163   :group 'pop3)
164
165 (defvar pop3-uidl-obarray (make-vector 31 0)
166   "Uidl hash table.")
167
168 (defvar pop3-read-point nil)
169 (defvar pop3-debug nil)
170
171 (eval-and-compile
172   (autoload 'starttls-open-stream "starttls")
173   (autoload 'starttls-negotiate "starttls"))
174
175 (defcustom pop3-ssl-program-name
176   (if (executable-find "openssl")
177       "openssl"
178     "ssleay")
179   "The program to run in a subprocess to open an SSL connection."
180   :type '(string :format "%t: %v\n" :size 0)
181   :group 'pop3)
182
183 (defcustom pop3-ssl-program-arguments
184   '("s_client" "-quiet")
185   "Arguments to be passed to the program `pop3-ssl-program-name'."
186   :type '(repeat (string :format "%v\n" :size 0))
187   :group 'pop3)
188
189 (defun pop3-progress-message (format percent &rest args)
190   (apply (function message) format args))
191
192 (defun pop3-movemail (&optional crashbox)
193   "Transfer contents of a maildrop to the specified CRASHBOX."
194   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
195   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
196          (crashbuf (get-buffer-create " *pop3-retr*"))
197          (n 1)
198          message-count
199          (pop3-password pop3-password)
200          (pop3-uidl-file-name (convert-standard-filename
201                                (concat pop3-uidl-file-name "-"
202                                        pop3-mailhost)))
203          retrieved-messages messages)
204     ;; for debugging only
205     (if pop3-debug (switch-to-buffer (process-buffer process)))
206     ;; query for password
207     (if (and pop3-password-required (not pop3-password))
208         (setq pop3-password
209               (read-passwd (format "Password for %s: " pop3-maildrop))))
210     (cond ((equal 'apop pop3-authentication-scheme)
211            (pop3-apop process pop3-maildrop))
212           ((equal 'pass pop3-authentication-scheme)
213            (pop3-user process pop3-maildrop)
214            (pop3-pass process))
215           (t (error "Invalid POP3 authentication scheme")))
216     ;; get messages that are suitable for download
217     (message "Retrieving message list...")
218     (setq messages (pop3-get-message-numbers process)
219           message-count (length (cdr messages)))
220     (message "Retrieving message list...%d of %d unread"
221              message-count (pop messages))
222     (unwind-protect
223         (unless (not (stringp crashbox))
224           (while messages
225             (pop3-progress-message
226              "Retrieving message %d of %d (%d octets) from %s..."
227              (floor (* (/ (float n) message-count) 100))
228              n message-count (cdar messages) pop3-mailhost)
229             (pop3-retr process (caar messages) crashbuf)
230             (push (caar messages) retrieved-messages)
231             (setq messages (cdr messages)
232                   n (1+ n)))
233           (with-current-buffer crashbuf
234             (let ((coding-system-for-write 'binary)
235                   jka-compr-compression-info-list jam-zcat-filename-list)
236               (write-region (point-min) (point-max)
237                             crashbox 'append 'nomesg)))
238           ;; mark messages as read
239           (when pop3-leave-mail-on-server
240             (pop3-save-uidls))
241           ;; now delete the messages we have retrieved
242           (unless pop3-leave-mail-on-server
243             (dolist (n retrieved-messages)
244               (message "Deleting message %d of %d from %s..."
245                        n message-count pop3-mailhost)
246               (pop3-dele process n))))
247       (pop3-quit process))
248     (kill-buffer crashbuf)
249     message-count))
250
251 (defun pop3-get-message-count ()
252   "Return the number of messages in the maildrop."
253   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
254          message-count
255          (pop3-password pop3-password))
256     ;; for debugging only
257     (if pop3-debug (switch-to-buffer (process-buffer process)))
258     ;; query for password
259     (if (and pop3-password-required (not pop3-password))
260         (setq pop3-password
261               (read-passwd (format "Password for %s: " pop3-maildrop))))
262     (cond ((equal 'apop pop3-authentication-scheme)
263            (pop3-apop process pop3-maildrop))
264           ((equal 'pass pop3-authentication-scheme)
265            (pop3-user process pop3-maildrop)
266            (pop3-pass process))
267           (t (error "Invalid POP3 authentication scheme")))
268     (setq message-count (car (pop3-stat process)))
269     (pop3-quit process)
270     message-count))
271
272 (defun pop3-open-server (mailhost port)
273   "Open TCP connection to MAILHOST on PORT.
274 Returns the process associated with the connection.
275 Argument PORT specifies connecting port."
276   (let (process)
277     (save-excursion
278       (set-buffer (get-buffer-create (concat " trace of POP session to "
279                                              mailhost)))
280       (erase-buffer)
281       (setq pop3-read-point (point-min))
282       (setq
283        process
284        (cond
285         ((eq pop3-connection-type 'ssl)
286          (pop3-open-ssl-stream "POP" (current-buffer) mailhost port))
287         ((eq pop3-connection-type 'tls)
288          (pop3-open-tls-stream "POP" (current-buffer) mailhost port))
289         (t
290          (let ((coding-system-for-read 'binary)
291                (coding-system-for-write 'binary))
292            (open-network-stream "POP" (current-buffer) mailhost port)))))
293       (let ((response (pop3-read-response process t)))
294         (setq pop3-timestamp
295               (substring response (or (string-match "<" response) 0)
296                          (+ 1 (or (string-match ">" response) -1)))))
297       process)))
298
299 (eval-when-compile
300   (autoload 'open-ssl-stream "ssl"))
301
302 (defun pop3-open-ssl-stream-1 (name buffer host service extra-arg)
303   (require 'ssl)
304   (let* ((ssl-program-name
305           pop3-ssl-program-name)
306          (ssl-program-arguments
307           `(,@pop3-ssl-program-arguments
308             ,extra-arg
309             "-connect" ,(format "%s:%d" host service)))
310          (process (open-ssl-stream name buffer host service)))
311     (when process
312       (with-current-buffer buffer
313         (goto-char (point-min))
314         (while (and (memq (process-status process) '(open run))
315                     (goto-char (point-max))
316                     (forward-line -1)
317                     (not (looking-at "+OK")))
318           (nnheader-accept-process-output process)
319           (sit-for 1))
320         (delete-region (point-min) (point)))
321       (and process (memq (process-status process) '(open run))
322            process))))
323
324 (defun pop3-open-ssl-stream (name buffer host service)
325   "Open a SSL connection for a service to a host.
326 Returns a subprocess-object to represent the connection.
327 Args are NAME BUFFER HOST SERVICE."
328   (let (selective-display ;; Disable ^M to nl translation.
329         (coding-system-for-read 'binary)
330         (coding-system-for-write 'binary))
331     (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
332         (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
333
334 (defun pop3-open-tls-stream (name buffer host service)
335   "Open a TLSv1 connection for a service to a host.
336 Returns a subprocess-object to represent the connection.
337 Args are NAME BUFFER HOST SERVICE."
338   (let* (selective-display ;; Disable ^M to nl translation.
339          (coding-system-for-read 'binary)
340          (coding-system-for-write 'binary)
341          (process (starttls-open-stream name buffer host service)))
342     (pop3-stls process)
343     (starttls-negotiate process)
344     process))
345
346 ;; Support functions
347
348 (defun pop3-process-filter (process output)
349   (save-excursion
350     (set-buffer (process-buffer process))
351     (goto-char (point-max))
352     (insert output)))
353
354 (defun pop3-send-command (process command)
355   (set-buffer (process-buffer process))
356   (goto-char (point-max))
357   ;; (if (= (aref command 0) ?P)
358   ;;     (insert "PASS <omitted>\r\n")
359   ;;   (insert command "\r\n"))
360   (setq pop3-read-point (point))
361   (goto-char (point-max))
362   (process-send-string process (concat command "\r\n")))
363
364 (defun pop3-read-response (process &optional return)
365   "Read the response from the server PROCESS.
366 Return the response string if optional second argument RETURN is non-nil."
367   (let ((case-fold-search nil)
368         match-end)
369     (save-excursion
370       (set-buffer (process-buffer process))
371       (goto-char pop3-read-point)
372       (while (and (memq (process-status process) '(open run))
373                   (not (search-forward "\r\n" nil t)))
374         (nnheader-accept-process-output process)
375         (goto-char pop3-read-point))
376       (setq match-end (point))
377       (goto-char pop3-read-point)
378       (if (looking-at "-ERR")
379           (error (buffer-substring (point) (- match-end 2)))
380         (if (not (looking-at "+OK"))
381             (progn (setq pop3-read-point match-end) nil)
382           (setq pop3-read-point match-end)
383           (if return
384               (buffer-substring (point) match-end)
385             t))))))
386
387 (defun pop3-clean-region (start end)
388   (setq end (set-marker (make-marker) end))
389   (save-excursion
390     (goto-char start)
391     (while (and (< (point) end) (search-forward "\r\n" end t))
392       (replace-match "\n" t t))
393     (goto-char start)
394     (while (re-search-forward "\n\n\\(From \\)" end t)
395       (replace-match "\n\n>\\1" t nil))
396     (goto-char start)
397     (while (and (< (point) end) (re-search-forward "^\\." end t))
398       (replace-match "" t t)
399       (forward-char)))
400   (set-marker end nil))
401
402 (eval-when-compile (defvar parse-time-months))
403
404 ;; Copied from message-make-date.
405 (defun pop3-make-date (&optional now)
406   "Make a valid date header.
407 If NOW, use that time instead."
408   (require 'parse-time)
409   (let* ((now (or now (current-time)))
410          (zone (nth 8 (decode-time now)))
411          (sign "+"))
412     (when (< zone 0)
413       (setq sign "-")
414       (setq zone (- zone)))
415     (concat
416      (format-time-string "%d" now)
417      ;; The month name of the %b spec is locale-specific.  Pfff.
418      (format " %s "
419              (capitalize (car (rassoc (nth 4 (decode-time now))
420                                       parse-time-months))))
421      (format-time-string "%Y %H:%M:%S " now)
422      ;; We do all of this because XEmacs doesn't have the %z spec.
423      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
424
425 (defun pop3-munge-message-separator (start end)
426   "Check to see if a message separator exists.  If not, generate one."
427   (save-excursion
428     (save-restriction
429       (narrow-to-region start end)
430       (goto-char (point-min))
431       (if (not (or (looking-at "From .?") ; Unix mail
432                    (looking-at "\001\001\001\001\n") ; MMDF
433                    (looking-at "BABYL OPTIONS:"))) ; Babyl
434           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
435                  (tdate (mail-fetch-field "Date"))
436                  (date (split-string (or (and tdate
437                                               (not (string= "" tdate))
438                                               tdate)
439                                          (pop3-make-date))
440                                      " "))
441                  (From_))
442             ;; sample date formats I have seen
443             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
444             ;; Date: 08 Jul 1996 23:22:24 -0400
445             ;; should be
446             ;; Tue Jul 9 09:04:21 1996
447             (setq date
448                   (cond ((not date)
449                          "Tue Jan 1 00:00:0 1900")
450                         ((string-match "[A-Z]" (nth 0 date))
451                          (format "%s %s %s %s %s"
452                                  (nth 0 date) (nth 2 date) (nth 1 date)
453                                  (nth 4 date) (nth 3 date)))
454                         (t
455                          ;; this really needs to be better but I don't feel
456                          ;; like writing a date to day converter.
457                          (format "Sun %s %s %s %s"
458                                  (nth 1 date) (nth 0 date)
459                                  (nth 3 date) (nth 2 date)))))
460             (setq From_ (format "\nFrom %s  %s\n" from date))
461             (while (string-match "," From_)
462               (setq From_ (concat (substring From_ 0 (match-beginning 0))
463                                   (substring From_ (match-end 0)))))
464             (goto-char (point-min))
465             (insert From_)
466             (if (search-forward "\n\n" nil t)
467                 nil
468               (goto-char (point-max))
469               (insert "\n"))
470             (narrow-to-region (point) (point-max))
471             (let ((size (- (point-max) (point-min))))
472               (goto-char (point-min))
473               (widen)
474               (forward-line -1)
475               (insert (format "Content-Length: %s\n" size))))))))
476
477 ;; UIDL support
478
479 (defun pop3-get-message-numbers (process)
480   "Get the list of message numbers and lengths to retrieve via PROCESS."
481   ;; we use the LIST comand first anyway to get the message lengths.
482   ;; then if we're leaving mail on the server, see if the UIDL command
483   ;; is implemented. if so, we use it to get the message number list.
484   (let* ((messages (pop3-list process))
485          (total (or (pop messages) 0))
486          (uidl (if pop3-leave-mail-on-server
487                    (pop3-get-uidl process)))
488          out)
489     (while messages
490       ;; only retrieve messages matching our regexp or in the uidl list
491       (when (and
492              ;; remove elements not in the uidl, this assumes the uidl is short
493              (or (not (and pop3-leave-mail-on-server
494                            (cdr (assoc pop3-mailhost pop3-uidl-support))))
495                  (memq (caar messages) uidl))
496              (caar messages)
497              ;; don't download messages that are too large
498              (not (and pop3-maximum-message-size
499                        (> (cdar messages) pop3-maximum-message-size)))
500              (not (and pop3-except-header-regexp
501                        (string-match pop3-except-header-regexp
502                                      (pop3-top process (caar messages) 0)))))
503         (push (car messages) out))
504       (setq messages (cdr messages)))
505     (cons total (nreverse out))))
506
507 (defun pop3-get-uidl (process)
508   "Use PROCESS to get a list of unread message numbers."
509   (let ((messages (pop3-uidl process))
510         (support (assoc pop3-mailhost pop3-uidl-support))
511         uidl)
512     (if support
513         (setcdr support (and messages t))
514       (push (cons pop3-mailhost (and messages t))
515             pop3-uidl-support))
516     (when messages
517       (save-excursion
518         (with-temp-buffer
519           (when (file-readable-p pop3-uidl-file-name)
520             (insert-file-contents pop3-uidl-file-name))
521           (goto-char (point-min))
522           (while (looking-at "\\([^ \n\t]+\\)")
523             (set (intern (match-string 1) pop3-uidl-obarray)
524                  (cons nil t))
525             (forward-line 1))))
526       (dolist (message (cdr messages))
527         (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
528             (setcar (symbol-value uidl) (car message))
529           (set (intern (cdr message) pop3-uidl-obarray)
530                (cons (car message) nil))))
531       (pop3-get-unread-message-numbers))))
532
533 (defun pop3-get-unread-message-numbers ()
534   "Return a sorted list of unread msg numbers to retrieve."
535   (let (nums)
536     (mapatoms (lambda (atom)
537                 (if (not (cdr (symbol-value atom)))
538                     (push (car (symbol-value atom)) nums)))
539               pop3-uidl-obarray)
540     (sort nums '<)))
541
542 (defun pop3-save-uidls ()
543   "Save the updated UIDLs to disk for use next time."
544   (when (and pop3-leave-mail-on-server
545              ;; UIDL hash table is non-empty
546              (let ((len (length pop3-uidl-obarray)))
547                (while (< 0 len)
548                  (setq len (if (symbolp (aref pop3-uidl-obarray (1- len)))
549                                -1 (1- len))))
550                (minusp len)))
551     (when (file-readable-p pop3-uidl-file-name)
552       (copy-file pop3-uidl-file-name
553                  (concat pop3-uidl-file-name ".old")
554                  'overwrite 'keeptime))
555     (save-excursion
556       (with-temp-file pop3-uidl-file-name
557         (mapatoms
558          (lambda (atom)
559            (when (car (symbol-value atom))
560              (insert (format "%s\n" atom))))
561          pop3-uidl-obarray)))
562     (fillarray pop3-uidl-obarray 0)))
563
564
565 ;; The Command Set
566
567 ;; AUTHORIZATION STATE
568
569 (defun pop3-user (process user)
570   "Send USER information to POP3 server."
571   (pop3-send-command process (format "USER %s" user))
572   (let ((response (pop3-read-response process t)))
573     (if (not (and response (string-match "+OK" response)))
574         (error (format "USER %s not valid" user)))))
575
576 (defun pop3-pass (process)
577   "Send authentication information to the server."
578   (pop3-send-command process (format "PASS %s" pop3-password))
579   (let ((response (pop3-read-response process t)))
580     (if (not (and response (string-match "+OK" response)))
581         (pop3-quit process))))
582
583 (defun pop3-apop (process user)
584   "Send alternate authentication information to the server."
585   (let ((pass pop3-password))
586     (if (and pop3-password-required (not pass))
587         (setq pass
588               (read-passwd (format "Password for %s: " pop3-maildrop))))
589     (if pass
590         ;; Note that `md5' should never encode a given string to use for
591         ;; the apop authentication, so we should specify `binary'.
592         (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
593           (pop3-send-command process (format "APOP %s %s" user hash))
594           (let ((response (pop3-read-response process t)))
595             (if (not (and response (string-match "+OK" response)))
596                 (pop3-quit process)))))))
597
598 (defun pop3-stls (process)
599   "Query whether TLS extension is supported"
600   (pop3-send-command process "STLS")
601   (let ((response (pop3-read-response process t)))
602     (if (not (and response (string-match "+OK" response)))
603         (pop3-quit process))))
604
605 ;; TRANSACTION STATE
606
607 (defun pop3-stat (process)
608   "Return the number of messages in the maildrop and the maildrop's size."
609   (pop3-send-command process "STAT")
610   (let ((response (pop3-read-response process t)))
611     (list (string-to-int (nth 1 (split-string response " ")))
612           (string-to-int (nth 2 (split-string response " "))))))
613
614 (defun pop3-retr (process msg crashbuf)
615   "Retrieve message-id MSG to buffer CRASHBUF."
616   (pop3-send-command process (format "RETR %s" msg))
617   (pop3-read-response process)
618   (save-excursion
619     (let ((region (pop3-get-extended-response process)))
620       (pop3-munge-message-separator (car region) (cadr region))
621       (append-to-buffer crashbuf (car region) (cadr region))
622       (delete-region (car region) (cadr region)))))
623
624 (defun pop3-dele (process msg)
625   "Mark message-id MSG as deleted."
626   (pop3-send-command process (format "DELE %s" msg))
627   (pop3-read-response process))
628
629 (defun pop3-noop (process msg)
630   "No-operation."
631   (pop3-send-command process "NOOP")
632   (pop3-read-response process))
633
634 (defun pop3-last (process)
635   "Return highest accessed message-id number for the session."
636   (pop3-send-command process "LAST")
637   (let ((response (pop3-read-response process t)))
638     (string-to-int (nth 1 (split-string response " ")))))
639
640 (defun pop3-rset (process)
641   "Remove all delete marks from current maildrop."
642   (pop3-send-command process "RSET")
643   (pop3-read-response process))
644
645 ;; UPDATE
646
647 (defun pop3-quit (process)
648   "Close connection to POP3 server.
649 Tell server to remove all messages marked as deleted, unlock the maildrop,
650 and close the connection."
651   (pop3-send-command process "QUIT")
652   (pop3-read-response process t)
653   (when process
654     (save-excursion
655       (set-buffer (process-buffer process))
656       (goto-char (point-max))
657       (delete-process process))))
658
659 (defun pop3-uidl (process &optional msgno)
660   "Return the results of a UIDL command in PROCESS for optional MSGNO.
661 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
662 Otherwise, return a list in the form
663
664    (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
665
666 where
667
668    N is an integer for the number of UIDLs returned (could be 0)
669    UIDL-n is a string."
670
671   (if msgno
672       (pop3-send-command process (format "UIDL %d" msgno))
673     (pop3-send-command process "UIDL"))
674
675   (if (null (pop3-read-response process t))
676       nil ;; UIDL is not supported on this server
677     (let (pairs uidl)
678       (save-excursion
679         (save-restriction
680           (apply 'narrow-to-region (pop3-get-extended-response process))
681           (goto-char (point-min))
682           (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
683             (setq msgno (string-to-int (match-string 1))
684                   uidl (match-string 2))
685             (push (cons msgno uidl) pairs)
686             (beginning-of-line 2))
687           (cons (length pairs) (nreverse pairs)))))))
688
689 (defun pop3-list (process &optional msgno)
690   "Return the results of a LIST command for PROCESS and optional MSGNO.
691 If (optional) msgno is invalid, return nil.  Otherwise, return a list
692 in the form
693
694    (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
695
696 where
697
698    N is an integer for the number of msg/len pairs (could be 0)
699    LEN-n is an integer."
700   (if msgno
701       (pop3-send-command process (format "LIST %d" msgno))
702     (pop3-send-command process "LIST"))
703
704   (if (null (pop3-read-response process t))
705       nil ;; MSGNO is not valid number
706     (let (pairs len)
707       (save-excursion
708         (save-restriction
709           (apply 'narrow-to-region (pop3-get-extended-response process))
710           (goto-char (point-min))
711           (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
712             (setq msgno (string-to-int (match-string 1))
713                   len (string-to-int (match-string 2)))
714             (push (cons msgno len) pairs)
715             (beginning-of-line 2))
716           (cons (length pairs) (nreverse pairs)))))))
717
718 (defun pop3-top (process msgno &optional lines)
719   "Return the top LINES of messages for PROCESS and MSGNO.
720 If msgno is invalid, return nil.  Otherwise, return a string."
721   (pop3-send-command process (format "TOP %d %d" msgno (or lines 1)))
722   (if (pop3-read-response process t)
723       nil ;; MSGNO is not valid number
724     (save-excursion
725       (apply 'buffer-substring (pop3-get-extended-response process)))))
726
727 ;;; Utility code
728
729 (defun pop3-get-extended-response (process)
730   "Get the extended pop3 response in the PROCESS buffer."
731   (let ((start pop3-read-point) end)
732     (set-buffer (process-buffer process))
733     (goto-char start)
734     (while (not (re-search-forward "^\\.\r\n" nil t))
735       ;; Fixme: Shouldn't depend on nnheader.
736       (nnheader-accept-process-output process)
737       (goto-char start))
738     (setq pop3-read-point (point-marker))
739     (goto-char (match-beginning 0))
740     (setq end (point-marker))
741     (pop3-clean-region start end)
742     (list start end)))
743
744 ;;; Advise the mail-source function in order to use this module in Gnus.
745
746 (eval-after-load "mail-source"
747   '(if (member '(:connection)
748                (assq 'pop (symbol-value 'mail-source-keyword-map)))
749        nil ;; T-gnus is running.
750      (defadvice mail-source-fetch-pop (around bind-t-gnus-keywords activate)
751        "Bind `pop3-connection-type' and `pop3-leave-mail-on-server' according
752 to `mail-sources' while fetching mails with Gnus."
753        (let ((pop3-connection-type (or (plist-get (cdr (ad-get-arg 0))
754                                                   :connection)
755                                        pop3-connection-type))
756              (pop3-leave-mail-on-server (or (plist-get (cdr (ad-get-arg 0))
757                                                        :leave)
758                                             pop3-leave-mail-on-server)))
759          ad-do-it))))
760
761 \f
762 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
763
764 ;;; AUTHORIZATION STATE
765
766 ;; Initial TCP connection
767 ;; Arguments: none
768 ;; Restrictions: none
769 ;; Possible responses:
770 ;;  +OK [POP3 server ready]
771
772 ;; USER name
773 ;; Arguments: a server specific user-id (required)
774 ;; Restrictions: authorization state [after unsuccessful USER or PASS
775 ;; Possible responses:
776 ;;  +OK [valid user-id]
777 ;;  -ERR [invalid user-id]
778
779 ;; PASS string
780 ;; Arguments: a server/user-id specific password (required)
781 ;; Restrictions: authorization state, after successful USER
782 ;; Possible responses:
783 ;;  +OK [maildrop locked and ready]
784 ;;  -ERR [invalid password]
785 ;;  -ERR [unable to lock maildrop]
786
787 ;; STLS
788 ;; Arguments: none
789 ;; Restrictions: authorization state
790 ;; Possible responses:
791 ;;  +OK [negotiation is ready]
792 ;;  -ERR [security layer is already active]
793
794 ;;; TRANSACTION STATE
795
796 ;; STAT
797 ;; Arguments: none
798 ;; Restrictions: transaction state
799 ;; Possible responses:
800 ;;  +OK nn mm [# of messages, size of maildrop]
801
802 ;; LIST [msg]
803 ;; Arguments: a message-id (optional)
804 ;; Restrictions: transaction state; msg must not be deleted
805 ;; Possible responses:
806 ;;  +OK [scan listing follows]
807 ;;  -ERR [no such message]
808
809 ;; TOP msg [lines]
810 ;; Arguments: a message-id (required), number of lines (optional)
811 ;; Restrictions: transaction state; msg must not be deleted
812 ;; Possible responses:
813 ;;  +OK [partial message listing follows]
814 ;;  -ERR [no such message]
815
816 ;; UIDL [msg]
817 ;; Arguments: a message-id (optional)
818 ;; Restrictions: transaction state; msg must not be deleted
819 ;; Possible responses:
820 ;;  +OK [uidl listing follows]
821 ;;  -ERR [no such message]
822
823 ;; RETR msg
824 ;; Arguments: a message-id (required)
825 ;; Restrictions: transaction state; msg must not be deleted
826 ;; Possible responses:
827 ;;  +OK [message contents follow]
828 ;;  -ERR [no such message]
829
830 ;; DELE msg
831 ;; Arguments: a message-id (required)
832 ;; Restrictions: transaction state; msg must not be deleted
833 ;; Possible responses:
834 ;;  +OK [message deleted]
835 ;;  -ERR [no such message]
836
837 ;; NOOP
838 ;; Arguments: none
839 ;; Restrictions: transaction state
840 ;; Possible responses:
841 ;;  +OK
842
843 ;; LAST
844 ;; Arguments: none
845 ;; Restrictions: transaction state
846 ;; Possible responses:
847 ;;  +OK nn [highest numbered message accessed]
848
849 ;; RSET
850 ;; Arguments: none
851 ;; Restrictions: transaction state
852 ;; Possible responses:
853 ;;  +OK [all delete marks removed]
854
855 ;;; UPDATE STATE
856
857 ;; QUIT
858 ;; Arguments: none
859 ;; Restrictions: none
860 ;; Possible responses:
861 ;;  +OK [TCP connection closed]
862
863 (provide 'pop3)
864
865 ;;; pop3.el ends here