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