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