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