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