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