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