* pop3.el (pop3-md5): Treat a given string as binary.
[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
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 ;;; Code:
39
40 (eval-when-compile (require 'cl))
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
219             ,extra-arg
220             "-connect" ,(format "%s:%d" host service)))
221          (process (open-ssl-stream name buffer host service)))
222     (when process
223       (with-current-buffer buffer
224         (goto-char (point-min))
225         (while (and (memq (process-status process) '(open run))
226                     (goto-char (point-max))
227                     (forward-line -1)
228                     (not (looking-at "+OK")))
229           (accept-process-output process 1)
230           (sit-for 1))
231         (delete-region (point-min) (point)))
232       (and process (memq (process-status process) '(open run))
233            process))))
234
235 (defun pop3-open-ssl-stream (name buffer host service)
236   "Open a SSL connection for a service to a host.
237 Returns a subprocess-object to represent the connection.
238 Args are NAME BUFFER HOST SERVICE."
239   (cond ((eq system-type 'windows-nt)
240          (let (selective-display
241                (coding-system-for-write 'binary)
242                (coding-system-for-read 'raw-text-dos))
243            (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
244                (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
245         (t
246          (as-binary-process
247           (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
248               (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))))
249
250 (defun pop3-open-tls-stream (name buffer host service)
251   "Open a TLSv1 connection for a service to a host.
252 Returns a subprocess-object to represent the connection.
253 Args are NAME BUFFER HOST SERVICE."
254   (let ((process
255          (as-binary-process (starttls-open-stream
256                              name buffer host service))))
257     (pop3-stls process)
258     (starttls-negotiate process)
259     process))
260
261 ;; Support functions
262
263 (defun pop3-process-filter (process output)
264   (save-excursion
265     (set-buffer (process-buffer process))
266     (goto-char (point-max))
267     (insert output)))
268
269 (defun pop3-send-command (process command)
270   (set-buffer (process-buffer process))
271   (goto-char (point-max))
272 ;;  (if (= (aref command 0) ?P)
273 ;;      (insert "PASS <omitted>\r\n")
274 ;;    (insert command "\r\n"))
275   (setq pop3-read-point (point))
276   (goto-char (point-max))
277   (process-send-string process (concat command "\r\n"))
278   )
279
280 (defun pop3-read-response (process &optional return)
281   "Read the response from the server PROCESS.
282 Return the response string if optional second argument RETURN is non-nil."
283   (let ((case-fold-search nil)
284         match-end)
285     (save-excursion
286       (set-buffer (process-buffer process))
287       (goto-char pop3-read-point)
288       (while (not (search-forward "\r\n" nil t))
289         (accept-process-output process 3)
290         (goto-char pop3-read-point))
291       (setq match-end (point))
292       (goto-char pop3-read-point)
293       (if (looking-at "-ERR")
294           (error (buffer-substring (point) (- match-end 2)))
295         (if (not (looking-at "+OK"))
296             (progn (setq pop3-read-point match-end) nil)
297           (setq pop3-read-point match-end)
298           (if return
299               (buffer-substring (point) match-end)
300             t)
301           )))))
302
303 (defvar pop3-read-passwd nil)
304 (defun pop3-read-passwd (prompt)
305   (if (not pop3-read-passwd)
306       (if (fboundp 'read-passwd)
307           (setq pop3-read-passwd 'read-passwd)
308         (if (load "passwd" t)
309             (setq pop3-read-passwd 'read-passwd)
310           (autoload 'ange-ftp-read-passwd "ange-ftp")
311           (setq pop3-read-passwd 'ange-ftp-read-passwd))))
312   (funcall pop3-read-passwd prompt))
313
314 (defun pop3-clean-region (start end)
315   (setq end (set-marker (make-marker) end))
316   (save-excursion
317     (goto-char start)
318     (while (and (< (point) end) (search-forward "\r\n" end t))
319       (replace-match "\n" t t))
320     (goto-char start)
321     (while (re-search-forward "\n\n\\(From \\)" end t)
322       (replace-match "\n\n>\\1" t nil))
323     (goto-char start)
324     (while (and (< (point) end) (re-search-forward "^\\." end t))
325       (replace-match "" t t)
326       (forward-char)))
327   (set-marker end nil))
328
329 (eval-when-compile (defvar parse-time-months))
330
331 ;; Copied from message-make-date.
332 (defun pop3-make-date (&optional now)
333   "Make a valid date header.
334 If NOW, use that time instead."
335   (require 'parse-time)
336   (let* ((now (or now (current-time)))
337          (zone (nth 8 (decode-time now)))
338          (sign "+"))
339     (when (< zone 0)
340       (setq sign "-")
341       (setq zone (- zone)))
342     (concat
343      (format-time-string "%d" now)
344      ;; The month name of the %b spec is locale-specific.  Pfff.
345      (format " %s "
346              (capitalize (car (rassoc (nth 4 (decode-time now))
347                                       parse-time-months))))
348      (format-time-string "%Y %H:%M:%S " now)
349      ;; We do all of this because XEmacs doesn't have the %z spec.
350      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
351
352 (defun pop3-munge-message-separator (start end)
353   "Check to see if a message separator exists.  If not, generate one."
354   (save-excursion
355     (save-restriction
356       (narrow-to-region start end)
357       (goto-char (point-min))
358       (if (not (or (looking-at "From .?") ; Unix mail
359                    (looking-at "\001\001\001\001\n") ; MMDF
360                    (looking-at "BABYL OPTIONS:") ; Babyl
361                    ))
362           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
363                  (tdate (mail-fetch-field "Date"))
364                  (date (split-string (or (and tdate
365                                               (not (string= "" tdate))
366                                               tdate)
367                                          (pop3-make-date))
368                                      " "))
369                  (From_))
370             ;; sample date formats I have seen
371             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
372             ;; Date: 08 Jul 1996 23:22:24 -0400
373             ;; should be
374             ;; Tue Jul 9 09:04:21 1996
375             (setq date
376                   (cond ((not date)
377                          "Tue Jan 1 00:00:0 1900")
378                         ((string-match "[A-Z]" (nth 0 date))
379                          (format "%s %s %s %s %s"
380                                  (nth 0 date) (nth 2 date) (nth 1 date)
381                                  (nth 4 date) (nth 3 date)))
382                         (t
383                          ;; this really needs to be better but I don't feel
384                          ;; like writing a date to day converter.
385                          (format "Sun %s %s %s %s"
386                                  (nth 1 date) (nth 0 date)
387                                  (nth 3 date) (nth 2 date)))
388                         ))
389             (setq From_ (format "\nFrom %s  %s\n" from date))
390             (while (string-match "," From_)
391               (setq From_ (concat (substring From_ 0 (match-beginning 0))
392                                   (substring From_ (match-end 0)))))
393             (goto-char (point-min))
394             (insert From_)
395             (if (search-forward "\n\n" nil t)
396                 nil
397               (goto-char (point-max))
398               (insert "\n"))
399             (narrow-to-region (point) (point-max))
400             (let ((size (- (point-max) (point-min))))
401               (goto-char (point-min))
402               (widen)
403               (forward-line -1)
404               (insert (format "Content-Length: %s\n" size)))
405             )))))
406
407 ;; UIDL support
408
409 (defun pop3-get-message-numbers (process)
410   "Get the list of message numbers and lengths to retrieve via PROCESS."
411   ;; we use the LIST comand first anyway to get the message lengths.
412   ;; then if we're leaving mail on the server, see if the UIDL command
413   ;; is implemented. if so, we use it to get the message number list.
414   (let* ((messages (pop3-list process))
415          (total (or (pop messages) 0))
416          (uidl (if pop3-leave-mail-on-server
417                    (pop3-get-uidl process)))
418          out)
419     (while messages
420       ;; only retrieve messages matching our regexp or in the uidl list
421       (when (and
422              ;; remove elements not in the uidl, this assumes the uidl is short
423              (or (not (eq pop3-uidl-support t))
424                  (memq (caar messages) uidl))
425              (caar messages)
426              ;; don't download messages that are too large
427              (not (and pop3-maximum-message-size
428                        (> (cdar messages) pop3-maximum-message-size)))
429              (not (and pop3-except-header-regexp
430                        (string-match pop3-except-header-regexp
431                                      (pop3-top process (caar messages) 0)))))
432         (push (car messages) out))
433       (setq messages (cdr messages)))
434     (cons total (reverse out))))
435
436 (defun pop3-get-uidl (process)
437   "Use PROCESS to get a list of unread message numbers."
438   (let ((messages (pop3-uidl process)) uidl)
439     (if (or (null messages) (null pop3-uidl-support))
440         (setq pop3-uidl-support nil)
441       (setq pop3-uidl-support t)
442       (save-excursion
443         (with-temp-buffer
444           (when (file-readable-p pop3-uidl-file-name)
445             (insert-file-contents pop3-uidl-file-name))
446           (goto-char (point-min))
447           (while (looking-at "\\([^ \n\t]+\\)")
448             (set (intern (match-string 1) pop3-uidl-obarray)
449                  (cons nil t))
450             (forward-line 1))
451           ))
452       (dolist (message (cdr messages))
453         (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
454             (setcar (symbol-value uidl) (car message))
455           (set (intern (cdr message) pop3-uidl-obarray)
456                (cons (car message) nil))))
457       (pop3-get-unread-message-numbers))
458     ))
459
460 (defun pop3-get-unread-message-numbers ()
461   "Return a sorted list of unread msg numbers to retrieve."
462   (let (nums)
463     (mapatoms (lambda (atom)
464                 (if (not (cdr (symbol-value atom)))
465                     (push (car (symbol-value atom)) nums)))
466               pop3-uidl-obarray)
467     (sort nums '<)))
468
469 (defun pop3-save-uidls ()
470   "Save the updated UIDLs to disk for use next time."
471   (when (and pop3-leave-mail-on-server
472              ;; UIDL hash table is non-empty
473              (let ((len (length pop3-uidl-obarray)))
474                (while (< 0 len)
475                  (setq len (if (symbolp (aref pop3-uidl-obarray (1- len)))
476                                -1 (1- len))))
477                (minusp len)))
478     (when (file-readable-p pop3-uidl-file-name)
479       (copy-file pop3-uidl-file-name
480                  (concat pop3-uidl-file-name ".old")
481                  'overwrite 'keeptime))
482     (save-excursion
483       (with-temp-file pop3-uidl-file-name
484         (mapatoms
485          (lambda (atom)
486            (when (car (symbol-value atom))
487              (insert (format "%s\n" atom))))
488          pop3-uidl-obarray)))
489     (fillarray pop3-uidl-obarray 0)))
490
491
492 ;; The Command Set
493
494 ;; AUTHORIZATION STATE
495
496 (defun pop3-user (process user)
497   "Send USER information to POP3 server."
498   (pop3-send-command process (format "USER %s" user))
499   (let ((response (pop3-read-response process t)))
500     (if (not (and response (string-match "+OK" response)))
501         (error (format "USER %s not valid" user)))))
502
503 (defun pop3-pass (process)
504   "Send authentication information to the server."
505   (pop3-send-command process (format "PASS %s" pop3-password))
506   (let ((response (pop3-read-response process t)))
507     (if (not (and response (string-match "+OK" response)))
508         (pop3-quit process))))
509
510 ;; Note that `pop3-md5' won't encode a given string to use for the
511 ;; apop authentication.
512 (eval-and-compile
513   (if (and (fboundp 'md5)
514            (subrp (symbol-function 'md5)))
515       (if (condition-case nil
516               (md5 "Check whether the 3rd argument CODING is allowed"
517                    nil nil 'binary)
518             (error nil))
519           ;; XEmacs 20
520           (defalias 'pop3-md5 'md5)
521         ;; Emacs 21 or XEmacs 21
522         (defun pop3-md5 (string)
523           (md5 string nil nil 'binary)))
524     ;; The lisp function provided by FLIM
525     (autoload 'md5 "md5")
526     (defalias 'pop3-md5 'md5)))
527
528 (defun pop3-apop (process user)
529   "Send alternate authentication information to the server."
530   (let ((pass pop3-password))
531     (if (and pop3-password-required (not pass))
532         (setq pass
533               (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
534     (if pass
535         (let ((hash (pop3-md5 (concat pop3-timestamp pass))))
536           (pop3-send-command process (format "APOP %s %s" user hash))
537           (let ((response (pop3-read-response process t)))
538             (if (not (and response (string-match "+OK" response)))
539                 (pop3-quit process)))))
540     ))
541
542 (defun pop3-stls (process)
543   "Query whether TLS extension is supported"
544   (pop3-send-command process "STLS")
545   (let ((response (pop3-read-response process t)))
546     (if (not (and response (string-match "+OK" response)))
547         (pop3-quit process))))
548
549 ;; TRANSACTION STATE
550
551 (defun pop3-stat (process)
552   "Return the number of messages in the maildrop and the maildrop's size."
553   (pop3-send-command process "STAT")
554   (let ((response (pop3-read-response process t)))
555     (list (string-to-int (nth 1 (split-string response " ")))
556           (string-to-int (nth 2 (split-string response " "))))
557     ))
558
559 (defun pop3-retr (process msg crashbuf)
560   "Retrieve message-id MSG to buffer CRASHBUF."
561   (pop3-send-command process (format "RETR %s" msg))
562   (pop3-read-response process)
563   (save-excursion
564     (let ((region (pop3-get-extended-response process)))
565       (pop3-munge-message-separator (car region) (cadr region))
566       (append-to-buffer crashbuf (car region) (cadr region))
567       (delete-region (car region) (cadr region))
568       )))
569
570 (defun pop3-dele (process msg)
571   "Mark message-id MSG as deleted."
572   (pop3-send-command process (format "DELE %s" msg))
573   (pop3-read-response process))
574
575 (defun pop3-noop (process msg)
576   "No-operation."
577   (pop3-send-command process "NOOP")
578   (pop3-read-response process))
579
580 (defun pop3-last (process)
581   "Return highest accessed message-id number for the session."
582   (pop3-send-command process "LAST")
583   (let ((response (pop3-read-response process t)))
584     (string-to-int (nth 1 (split-string response " ")))
585     ))
586
587 (defun pop3-rset (process)
588   "Remove all delete marks from current maildrop."
589   (pop3-send-command process "RSET")
590   (pop3-read-response process))
591
592 ;; UPDATE
593
594 (defun pop3-quit (process)
595   "Close connection to POP3 server.
596 Tell server to remove all messages marked as deleted, unlock the maildrop,
597 and close the connection."
598   (pop3-send-command process "QUIT")
599   (pop3-read-response process t)
600   (when process
601     (save-excursion
602       (set-buffer (process-buffer process))
603       (goto-char (point-max))
604       (delete-process process))))
605
606 (defun pop3-uidl (process &optional msgno)
607   "Return the results of a UIDL command in PROCESS for optional MSGNO.
608 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
609 Otherwise, return a list in the form
610
611    (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
612
613 where
614
615    N is an integer for the number of UIDLs returned (could be 0)
616    UIDL-n is a string."
617
618   (if msgno
619       (pop3-send-command process (format "UIDL %d" msgno))
620     (pop3-send-command process "UIDL"))
621
622   (if (null (pop3-read-response process t))
623       nil ;; UIDL is not supported on this server
624     (let (pairs uidl)
625       (save-excursion
626         (save-restriction
627           (apply 'narrow-to-region (pop3-get-extended-response process))
628           (goto-char (point-min))
629           (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
630             (setq msgno (string-to-int (match-string 1))
631                   uidl (match-string 2))
632             (push (cons msgno uidl) pairs)
633             (beginning-of-line 2))
634           (cons (length pairs) (nreverse pairs))
635           )))))
636
637 (defun pop3-list (process &optional msgno)
638   "Return the results of a LIST command for PROCESS and optional MSGNO.
639 If (optional) msgno is invalid, return nil.  Otherwise, return a list
640 in the form
641
642    (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
643
644 where
645
646    N is an integer for the number of msg/len pairs (could be 0)
647    LEN-n is an integer."
648   (if msgno
649       (pop3-send-command process (format "LIST %d" msgno))
650     (pop3-send-command process "LIST"))
651
652   (if (null (pop3-read-response process t))
653       nil ;; MSGNO is not valid number
654     (let (pairs len)
655       (save-excursion
656         (save-restriction
657           (apply 'narrow-to-region (pop3-get-extended-response process))
658           (goto-char (point-min))
659           (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
660             (setq msgno (string-to-int (match-string 1))
661                   len (string-to-int (match-string 2)))
662             (push (cons msgno len) pairs)
663             (beginning-of-line 2))
664           (cons (length pairs) (nreverse pairs))
665           )))))
666
667 (defun pop3-top (process msgno &optional lines)
668   "Return the top LINES of messages for PROCESS and MSGNO.
669 If msgno is invalid, return nil.  Otherwise, return a string."
670   (pop3-send-command process (format "TOP %d %d" msgno (or lines 1)))
671   (if (pop3-read-response process t)
672       nil ;; MSGNO is not valid number
673     (save-excursion
674       (apply 'buffer-substring (pop3-get-extended-response process)))
675     ))
676
677 ;;; Utility code
678
679 (defun pop3-get-extended-response (process)
680   "Get the extended pop3 response in the PROCESS buffer."
681   (let ((start pop3-read-point) end)
682     (set-buffer (process-buffer process))
683     (goto-char start)
684     (while (not (re-search-forward "^\\.\r\n" nil t))
685       (accept-process-output process 3)
686       (goto-char start))
687     (setq pop3-read-point (point-marker))
688     (goto-char (match-beginning 0))
689     (setq end (point-marker))
690     (pop3-clean-region start end)
691     (list start end)))
692
693 \f
694 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
695
696 ;;; AUTHORIZATION STATE
697
698 ;; Initial TCP connection
699 ;; Arguments: none
700 ;; Restrictions: none
701 ;; Possible responses:
702 ;;  +OK [POP3 server ready]
703
704 ;; USER name
705 ;; Arguments: a server specific user-id (required)
706 ;; Restrictions: authorization state [after unsuccessful USER or PASS
707 ;; Possible responses:
708 ;;  +OK [valid user-id]
709 ;;  -ERR [invalid user-id]
710
711 ;; PASS string
712 ;; Arguments: a server/user-id specific password (required)
713 ;; Restrictions: authorization state, after successful USER
714 ;; Possible responses:
715 ;;  +OK [maildrop locked and ready]
716 ;;  -ERR [invalid password]
717 ;;  -ERR [unable to lock maildrop]
718
719 ;; STLS
720 ;; Arguments: none
721 ;; Restrictions: authorization state
722 ;; Possible responses:
723 ;;  +OK [negotiation is ready]
724 ;;  -ERR [security layer is already active]
725
726 ;;; TRANSACTION STATE
727
728 ;; STAT
729 ;; Arguments: none
730 ;; Restrictions: transaction state
731 ;; Possible responses:
732 ;;  +OK nn mm [# of messages, size of maildrop]
733
734 ;; LIST [msg]
735 ;; Arguments: a message-id (optional)
736 ;; Restrictions: transaction state; msg must not be deleted
737 ;; Possible responses:
738 ;;  +OK [scan listing follows]
739 ;;  -ERR [no such message]
740
741 ;; TOP msg [lines]
742 ;; Arguments: a message-id (required), number of lines (optional)
743 ;; Restrictions: transaction state; msg must not be deleted
744 ;; Possible responses:
745 ;;  +OK [partial message listing follows]
746 ;;  -ERR [no such message]
747
748 ;; UIDL [msg]
749 ;; Arguments: a message-id (optional)
750 ;; Restrictions: transaction state; msg must not be deleted
751 ;; Possible responses:
752 ;;  +OK [uidl listing follows]
753 ;;  -ERR [no such message]
754
755 ;; RETR msg
756 ;; Arguments: a message-id (required)
757 ;; Restrictions: transaction state; msg must not be deleted
758 ;; Possible responses:
759 ;;  +OK [message contents follow]
760 ;;  -ERR [no such message]
761
762 ;; DELE msg
763 ;; Arguments: a message-id (required)
764 ;; Restrictions: transaction state; msg must not be deleted
765 ;; Possible responses:
766 ;;  +OK [message deleted]
767 ;;  -ERR [no such message]
768
769 ;; NOOP
770 ;; Arguments: none
771 ;; Restrictions: transaction state
772 ;; Possible responses:
773 ;;  +OK
774
775 ;; LAST
776 ;; Arguments: none
777 ;; Restrictions: transaction state
778 ;; Possible responses:
779 ;;  +OK nn [highest numbered message accessed]
780
781 ;; RSET
782 ;; Arguments: none
783 ;; Restrictions: transaction state
784 ;; Possible responses:
785 ;;  +OK [all delete marks removed]
786
787 ;;; UPDATE STATE
788
789 ;; QUIT
790 ;; Arguments: none
791 ;; Restrictions: none
792 ;; Possible responses:
793 ;;  +OK [TCP connection closed]
794
795 (provide 'pop3)
796
797 ;;; pop3.el ends here