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