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