gnus-registry.el: Correct function argument order.
[gnus] / lisp / pop3.el
1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
2
3 ;; Copyright (C) 1996-2015 Free Software Foundation, Inc.
4
5 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Keywords: mail
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
27 ;; are implemented.  The LIST command has not been implemented due to lack
28 ;; of actual usefulness.
29 ;; The optional POP3 command TOP has not been implemented.
30
31 ;; This program was inspired by Kyle E. Jones's vm-pop program.
32
33 ;;; Code:
34
35 (eval-when-compile (require 'cl))
36
37 (eval-and-compile
38   ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
39   ;; `make-network-stream'.
40   (unless (fboundp 'open-protocol-stream)
41     (require 'proto-stream)))
42
43 (require 'mail-utils)
44 (defvar parse-time-months)
45
46 (defgroup pop3 nil
47   "Post Office Protocol."
48   :group 'mail
49   :group 'mail-source)
50
51 (defcustom pop3-maildrop (or (user-login-name)
52                              (getenv "LOGNAME")
53                              (getenv "USER"))
54   "*POP3 maildrop."
55   :version "22.1" ;; Oort Gnus
56   :type 'string
57   :group 'pop3)
58
59 (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
60                              "pop3")
61   "*POP3 mailhost."
62   :version "22.1" ;; Oort Gnus
63   :type 'string
64   :group 'pop3)
65
66 (defcustom pop3-port 110
67   "*POP3 port."
68   :version "22.1" ;; Oort Gnus
69   :type 'number
70   :group 'pop3)
71
72 (defcustom pop3-password-required t
73   "*Non-nil if a password is required when connecting to POP server."
74   :version "22.1" ;; Oort Gnus
75   :type 'boolean
76   :group 'pop3)
77
78 ;; Should this be customizable?
79 (defvar pop3-password nil
80   "*Password to use when connecting to POP server.")
81
82 (defcustom pop3-authentication-scheme 'pass
83   "*POP3 authentication scheme.
84 Defaults to `pass', for the standard USER/PASS authentication.  The other
85 valid value is 'apop'."
86   :type '(choice (const :tag "Normal user/password" pass)
87                  (const :tag "APOP" apop))
88   :version "22.1" ;; Oort Gnus
89   :group 'pop3)
90
91 (defcustom pop3-stream-length 100
92   "How many messages should be requested at one time.
93 The lower the number, the more latency-sensitive the fetching
94 will be.  If your pop3 server doesn't support streaming at all,
95 set this to 1."
96   :type 'number
97   :version "24.1"
98   :group 'pop3)
99
100 (defcustom pop3-leave-mail-on-server nil
101   "Non-nil if the mail is to be left on the POP server after fetching.
102 Mails once fetched will never be fetched again by the UIDL control.
103
104 If this is neither nil nor a number, all mails will be left on the
105 server.  If this is a number, leave mails on the server for this many
106 days since you first checked new mails.  If this is nil, mails will be
107 deleted on the server right after fetching.
108
109 Gnus users should use the `:leave' keyword in a mail source to direct
110 the behavior per server, rather than directly modifying this value.
111
112 Note that POP servers maintain no state information between sessions,
113 so what the client believes is there and what is actually there may
114 not match up.  If they do not, then you may get duplicate mails or
115 the whole thing can fall apart and leave you with a corrupt mailbox."
116   :version "24.4"
117   :type '(choice (const :tag "Don't leave mails" nil)
118                  (const :tag "Leave all mails" t)
119                  (number :tag "Leave mails for this many days" :value 14))
120   :group 'pop3)
121
122 (defcustom pop3-uidl-file "~/.pop3-uidl"
123   "File used to save UIDL."
124   :version "24.4"
125   :type 'file
126   :group 'pop3)
127
128 (defcustom pop3-uidl-file-backup '(0 9)
129   "How to backup the UIDL file `pop3-uidl-file' when updating.
130 If it is a list of numbers, the first one binds `kept-old-versions' and
131 the other binds `kept-new-versions' to keep number of oldest and newest
132 versions.  Otherwise, the value binds `version-control' (which see).
133
134 Note: Backup will take place whenever you check new mails on a server.
135 So, you may lose the backup files having been saved before a trouble
136 if you set it so as to make too few backups whereas you have access to
137 many servers."
138   :version "24.4"
139   :type '(choice (group :tag "Keep versions" :format "\n%v" :indent 3
140                         (number :tag "oldest")
141                         (number :tag "newest"))
142                  (sexp :format "%v"
143                        :match (lambda (widget value)
144                                 (condition-case nil
145                                     (not (and (numberp (car value))
146                                               (numberp (car (cdr value)))))
147                                   (error t)))))
148   :group 'pop3)
149
150 (defvar pop3-timestamp nil
151   "Timestamp returned when initially connected to the POP server.
152 Used for APOP authentication.")
153
154 (defvar pop3-read-point nil)
155 (defvar pop3-debug nil)
156
157 ;; Borrowed from nnheader-accept-process-output in nnheader.el.  See the
158 ;; comments there for explanations about the values.
159
160 (eval-and-compile
161   (if (and (fboundp 'nnheader-accept-process-output)
162            (boundp 'nnheader-read-timeout))
163       (defalias 'pop3-accept-process-output 'nnheader-accept-process-output)
164     ;; Borrowed from `nnheader.el':
165     (defvar pop3-read-timeout
166       (if (string-match "windows-nt\\|os/2\\|cygwin"
167                         (symbol-name system-type))
168           1.0
169         0.01)
170       "How long pop3 should wait between checking for the end of output.
171 Shorter values mean quicker response, but are more CPU intensive.")
172     (defun pop3-accept-process-output (process)
173       (accept-process-output
174        process
175        (truncate pop3-read-timeout)
176        (truncate (* (- pop3-read-timeout
177                        (truncate pop3-read-timeout))
178                     1000))))))
179
180 (defvar pop3-uidl)
181 ;; List of UIDLs of existing messages at present in the server:
182 ;; ("UIDL1" "UIDL2" "UIDL3"...)
183
184 (defvar pop3-uidl-saved)
185 ;; Locally saved UIDL data; an alist of the server, the user, and the UIDL
186 ;; and timestamp pairs:
187 ;; (("SERVER_A" ("USER_A1" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
188 ;;              ("USER_A2" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
189 ;;              ...)
190 ;;  ("SERVER_B" ("USER_B1" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
191 ;;              ("USER_B2" "UIDL1" TIMESTAMP1 "UIDL2" TIMESTAMP2...)
192 ;;              ...))
193 ;; Where TIMESTAMP is the most significant two digits of an Emacs time,
194 ;; i.e. the return value of `current-time'.
195
196 ;;;###autoload
197 (defun pop3-movemail (file)
198   "Transfer contents of a maildrop to the specified FILE.
199 Use streaming commands."
200   (let ((process (pop3-open-server pop3-mailhost pop3-port))
201         messages total-size
202         pop3-uidl
203         pop3-uidl-saved)
204     (pop3-logon process)
205     (if pop3-leave-mail-on-server
206         (setq messages (pop3-uidl-stat process)
207               total-size (cadr messages)
208               messages (car messages))
209       (let ((size (pop3-stat process)))
210         (dotimes (i (car size)) (push (1+ i) messages))
211         (setq messages (nreverse messages)
212               total-size (cadr size))))
213     (when messages
214       (with-current-buffer (process-buffer process)
215         (pop3-send-streaming-command process "RETR" messages total-size)
216         (pop3-write-to-file file messages)
217         (unless pop3-leave-mail-on-server
218           (pop3-send-streaming-command process "DELE" messages nil))))
219     (if pop3-leave-mail-on-server
220         (when (prog1 (pop3-uidl-dele process) (pop3-quit process))
221           (pop3-uidl-save))
222       (pop3-quit process)
223       ;; Remove UIDL data for the account that got not to leave mails.
224       (setq pop3-uidl-saved (pop3-uidl-load))
225       (let ((elt (assoc pop3-maildrop
226                         (cdr (assoc pop3-mailhost pop3-uidl-saved)))))
227         (when elt
228           (setcdr elt nil)
229           (pop3-uidl-save))))
230     t))
231
232 (defun pop3-send-streaming-command (process command messages total-size)
233   (erase-buffer)
234   (let ((count (length messages))
235         (i 1)
236         (start-point (point-min))
237         (waited-for 0))
238     (while messages
239       (process-send-string process (format "%s %d\r\n" command (pop messages)))
240       ;; Only do 100 messages at a time to avoid pipe stalls.
241       (when (zerop (% i pop3-stream-length))
242         (setq start-point
243               (pop3-wait-for-messages process pop3-stream-length
244                                       total-size start-point))
245         (incf waited-for pop3-stream-length))
246       (incf i))
247     (pop3-wait-for-messages process (- count waited-for)
248                             total-size start-point)))
249
250 (defun pop3-wait-for-messages (process count total-size start-point)
251   (while (> count 0)
252     (goto-char start-point)
253     (while (or (and (re-search-forward "^\\+OK" nil t)
254                     (or (not total-size)
255                         (re-search-forward "^\\.\r?\n" nil t)))
256                (re-search-forward "^-ERR " nil t))
257       (decf count)
258       (setq start-point (point)))
259     (unless (memq (process-status process) '(open run))
260       (error "pop3 process died"))
261     (when total-size
262       (let ((size 0))
263         (goto-char (point-min))
264         (while (re-search-forward "^\\+OK.*\n" nil t)
265           (setq size (+ size (- (point))
266                         (if (re-search-forward "^\\.\r?\n" nil 'move)
267                             (match-beginning 0)
268                           (point)))))
269         (message "pop3 retrieved %dKB (%d%%)"
270                  (truncate (/ size 1000))
271                  (truncate (* (/ (* size 1.0) total-size) 100)))))
272     (pop3-accept-process-output process))
273   start-point)
274
275 (defun pop3-write-to-file (file messages)
276   (let ((pop-buffer (current-buffer))
277         (start (point-min))
278         beg end
279         temp-buffer)
280     (with-temp-buffer
281       (setq temp-buffer (current-buffer))
282       (with-current-buffer pop-buffer
283         (goto-char (point-min))
284         (while (re-search-forward "^\\+OK" nil t)
285           (forward-line 1)
286           (setq beg (point))
287           (when (re-search-forward "^\\.\r?\n" nil t)
288             (setq start (point))
289             (forward-line -1)
290             (setq end (point)))
291           (with-current-buffer temp-buffer
292             (goto-char (point-max))
293             (let ((hstart (point)))
294               (insert-buffer-substring pop-buffer beg end)
295               (pop3-clean-region hstart (point))
296               (goto-char (point-max))
297               (pop3-munge-message-separator hstart (point))
298               (when pop3-leave-mail-on-server
299                 (pop3-uidl-add-xheader hstart (pop messages)))
300               (goto-char (point-max))))))
301       (let ((coding-system-for-write 'binary))
302         (goto-char (point-min))
303         ;; Check whether something inserted a newline at the start and
304         ;; delete it.
305         (when (eolp)
306           (delete-char 1))
307         (write-region (point-min) (point-max) file nil 'nomesg)))))
308
309 (defun pop3-logon (process)
310   (let ((pop3-password pop3-password))
311     ;; for debugging only
312     (if pop3-debug (switch-to-buffer (process-buffer process)))
313     ;; query for password
314     (if (and pop3-password-required (not pop3-password))
315         (setq pop3-password
316               (read-passwd (format "Password for %s: " pop3-maildrop))))
317     (cond ((equal 'apop pop3-authentication-scheme)
318            (pop3-apop process pop3-maildrop))
319           ((equal 'pass pop3-authentication-scheme)
320            (pop3-user process pop3-maildrop)
321            (pop3-pass process))
322           (t (error "Invalid POP3 authentication scheme")))))
323
324 (defun pop3-get-message-count ()
325   "Return the number of messages in the maildrop."
326   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
327          message-count
328          (pop3-password pop3-password))
329     ;; for debugging only
330     (if pop3-debug (switch-to-buffer (process-buffer process)))
331     ;; query for password
332     (if (and pop3-password-required (not pop3-password))
333         (setq pop3-password
334               (read-passwd (format "Password for %s: " pop3-maildrop))))
335     (cond ((equal 'apop pop3-authentication-scheme)
336            (pop3-apop process pop3-maildrop))
337           ((equal 'pass pop3-authentication-scheme)
338            (pop3-user process pop3-maildrop)
339            (pop3-pass process))
340           (t (error "Invalid POP3 authentication scheme")))
341     (setq message-count (car (pop3-stat process)))
342     (pop3-quit process)
343     message-count))
344
345 (defun pop3-uidl-stat (process)
346   "Return a list of unread message numbers and total size."
347   (pop3-send-command process "UIDL")
348   (let (err messages size)
349     (if (condition-case code
350             (progn
351               (pop3-read-response process)
352               t)
353           (error (setq err (error-message-string code))
354                  nil))
355         (let ((start pop3-read-point)
356               saved list)
357           (with-current-buffer (process-buffer process)
358             (while (not (re-search-forward "^\\.\r\n" nil t))
359               (unless (memq (process-status process) '(open run))
360                 (error "pop3 server closed the connection"))
361               (pop3-accept-process-output process)
362               (goto-char start))
363             (setq pop3-read-point (point-marker)
364                   pop3-uidl nil)
365             (while (progn (forward-line -1) (>= (point) start))
366               (when (looking-at "[0-9]+ \\([^\n\r ]+\\)")
367                 (push (match-string 1) pop3-uidl)))
368             (when pop3-uidl
369               (setq pop3-uidl-saved (pop3-uidl-load)
370                     saved (cdr (assoc pop3-maildrop
371                                       (cdr (assoc pop3-mailhost
372                                                   pop3-uidl-saved)))))
373               (let ((i (length pop3-uidl)))
374                 (while (> i 0)
375                   (unless (member (nth (1- i) pop3-uidl) saved)
376                     (push i messages))
377                   (decf i)))
378               (when messages
379                 (setq list (pop3-list process)
380                       size 0)
381                 (dolist (msg messages)
382                   (setq size (+ size (cdr (assq msg list)))))
383                 (list messages size)))))
384       (message "%s doesn't support UIDL (%s), so we try a regressive way..."
385                pop3-mailhost err)
386       (sit-for 1)
387       (setq size (pop3-stat process))
388       (dotimes (i (car size)) (push (1+ i) messages))
389       (setcar size (nreverse messages))
390       size)))
391
392 (defun pop3-uidl-dele (process)
393   "Delete messages according to `pop3-leave-mail-on-server'.
394 Return non-nil if it is necessary to update the local UIDL file."
395   (let* ((ctime (current-time))
396          (srvr (assoc pop3-mailhost pop3-uidl-saved))
397          (saved (assoc pop3-maildrop (cdr srvr)))
398          i uidl mod new tstamp dele)
399     (setcdr (cdr ctime) nil)
400     ;; Add new messages to the data to be saved.
401     (cond ((and pop3-uidl saved)
402            (setq i (1- (length pop3-uidl)))
403            (while (>= i 0)
404              (unless (member (setq uidl (nth i pop3-uidl)) (cdr saved))
405                (push ctime new)
406                (push uidl new))
407              (decf i)))
408           (pop3-uidl
409            (setq new (apply 'nconc (mapcar (lambda (elt) (list elt ctime))
410                                            pop3-uidl)))))
411     (when new (setq mod t))
412     ;; List expirable messages and delete them from the data to be saved.
413     (setq ctime (when (numberp pop3-leave-mail-on-server)
414                   (/ (+ (* (car ctime) 65536.0) (cadr ctime)) 86400))
415           i (1- (length saved)))
416     (while (> i 0)
417       (if (member (setq uidl (nth (1- i) saved)) pop3-uidl)
418           (progn
419             (setq tstamp (nth i saved))
420             (if (and ctime
421                      (> (- ctime (/ (+ (* (car tstamp) 65536.0) (cadr tstamp))
422                                     86400))
423                         pop3-leave-mail-on-server))
424                 ;; Mails to delete.
425                 (progn
426                   (setq mod t)
427                   (push uidl dele))
428               ;; Mails to keep.
429               (push tstamp new)
430               (push uidl new)))
431         ;; Mails having been deleted in the server.
432         (setq mod t))
433       (decf i 2))
434     (cond (saved
435            (setcdr saved new))
436           (srvr
437            (setcdr (last srvr) (list (cons pop3-maildrop new))))
438           (t
439            (add-to-list 'pop3-uidl-saved
440                         (list pop3-mailhost (cons pop3-maildrop new))
441                         t)))
442     ;; Actually delete the messages in the server.
443     (when dele
444       (setq uidl nil
445             i (length pop3-uidl))
446       (while (> i 0)
447         (when (member (nth (1- i) pop3-uidl) dele)
448           (push i uidl))
449         (decf i))
450       (when uidl
451         (pop3-send-streaming-command process "DELE" uidl nil)))
452     mod))
453
454 (defun pop3-uidl-load ()
455   "Load saved UIDL."
456   (when (file-exists-p pop3-uidl-file)
457     (with-temp-buffer
458       (condition-case code
459           (progn
460             (insert-file-contents pop3-uidl-file)
461             (goto-char (point-min))
462             (read (current-buffer)))
463         (error
464          (message "Error while loading %s (%s)"
465                   pop3-uidl-file (error-message-string code))
466          (sit-for 1)
467          nil)))))
468
469 (defun pop3-uidl-save ()
470   "Save UIDL."
471   (with-temp-buffer
472     (if pop3-uidl-saved
473         (progn
474           (insert "(")
475           (dolist (srvr pop3-uidl-saved)
476             (when (cdr srvr)
477               (insert "(\"" (pop srvr) "\"\n  ")
478               (dolist (elt srvr)
479                 (when (cdr elt)
480                   (insert "(\"" (pop elt) "\"\n   ")
481                   (while elt
482                     (insert (format "\"%s\" %s\n   " (pop elt) (pop elt))))
483                   (delete-char -4)
484                   (insert ")\n  ")))
485               (delete-char -3)
486               (if (eq (char-before) ?\))
487                   (insert ")\n ")
488                 (goto-char (1+ (point-at-bol)))
489                 (delete-region (point) (point-max)))))
490           (when (eq (char-before) ? )
491             (delete-char -2))
492           (insert ")\n"))
493       (insert "()\n"))
494     (let ((buffer-file-name pop3-uidl-file)
495           (delete-old-versions t)
496           (kept-new-versions kept-new-versions)
497           (kept-old-versions kept-old-versions)
498           (version-control version-control))
499       (if (consp pop3-uidl-file-backup)
500           (setq kept-new-versions (cadr pop3-uidl-file-backup)
501                 kept-old-versions (car pop3-uidl-file-backup)
502                 version-control t)
503         (setq version-control pop3-uidl-file-backup))
504       (save-buffer))))
505
506 (defun pop3-uidl-add-xheader (start msgno)
507   "Add X-UIDL header."
508   (let ((case-fold-search t))
509     (save-restriction
510       (narrow-to-region start (progn
511                                 (goto-char start)
512                                 (search-forward "\n\n" nil 'move)
513                                 (1- (point))))
514       (goto-char start)
515       (while (re-search-forward "^x-uidl:" nil t)
516         (while (progn
517                  (forward-line 1)
518                  (memq (char-after) '(?\t ? ))))
519         (delete-region (match-beginning 0) (point)))
520       (goto-char (point-max))
521       (insert "X-UIDL: " (nth (1- msgno) pop3-uidl) "\n"))))
522
523 (defcustom pop3-stream-type nil
524   "*Transport security type for POP3 connections.
525 This may be either nil (plain connection), `ssl' (use an
526 SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
527 to turn on TLS security after opening the stream).  However, if
528 this is nil, `ssl' is assumed for connections to port
529 995 (pop3s)."
530   :version "23.1" ;; No Gnus
531   :group 'pop3
532   :type '(choice (const :tag "Plain" nil)
533                  (const :tag "SSL/TLS" ssl)
534                  (const starttls)))
535
536 (eval-and-compile
537   (if (fboundp 'set-process-query-on-exit-flag)
538       (defalias 'pop3-set-process-query-on-exit-flag
539         'set-process-query-on-exit-flag)
540     (defalias 'pop3-set-process-query-on-exit-flag
541       'process-kill-without-query)))
542
543 (defun pop3-open-server (mailhost port)
544   "Open TCP connection to MAILHOST on PORT.
545 Returns the process associated with the connection."
546   (let ((coding-system-for-read 'binary)
547         (coding-system-for-write 'binary)
548         result)
549     (with-current-buffer
550         (get-buffer-create (concat " trace of POP session to "
551                                    mailhost))
552       (erase-buffer)
553       (setq pop3-read-point (point-min))
554       (setq result
555             (open-protocol-stream
556              "POP" (current-buffer) mailhost port
557              :type (cond
558                     ((or (eq pop3-stream-type 'ssl)
559                          (and (not pop3-stream-type)
560                               (member port '(995 "pop3s"))))
561                      'tls)
562                     (t
563                      (or pop3-stream-type 'network)))
564              :warn-unless-encrypted t
565              :capability-command "CAPA\r\n"
566              :end-of-command "^\\(-ERR\\|+OK\\).*\n"
567              :end-of-capability "^\\.\r?\n\\|^-ERR"
568              :success "^\\+OK.*\n"
569              :return-list t
570              :starttls-function
571              (lambda (capabilities)
572                (and (string-match "\\bSTLS\\b" capabilities)
573                     "STLS\r\n"))))
574       (when result
575         (let ((response (plist-get (cdr result) :greeting)))
576           (setq pop3-timestamp
577                 (substring response (or (string-match "<" response) 0)
578                            (+ 1 (or (string-match ">" response) -1)))))
579         (pop3-set-process-query-on-exit-flag (car result) nil)
580         (erase-buffer)
581         (car result)))))
582
583 ;; Support functions
584
585 (defun pop3-send-command (process command)
586   (set-buffer (process-buffer process))
587   (goto-char (point-max))
588   ;; (if (= (aref command 0) ?P)
589   ;;     (insert "PASS <omitted>\r\n")
590   ;;   (insert command "\r\n"))
591   (setq pop3-read-point (point))
592   (goto-char (point-max))
593   (process-send-string process (concat command "\r\n")))
594
595 (defun pop3-read-response (process &optional return)
596   "Read the response from the server.
597 Return the response string if optional second argument is non-nil."
598   (let ((case-fold-search nil)
599         match-end)
600     (with-current-buffer (process-buffer process)
601       (goto-char pop3-read-point)
602       (while (and (memq (process-status process) '(open run))
603                   (not (search-forward "\r\n" nil t)))
604         (pop3-accept-process-output process)
605         (goto-char pop3-read-point))
606       (setq match-end (point))
607       (goto-char pop3-read-point)
608       (if (looking-at "-ERR")
609           (error "%s" (buffer-substring (point) (- match-end 2)))
610         (if (not (looking-at "+OK"))
611             (progn (setq pop3-read-point match-end) nil)
612           (setq pop3-read-point match-end)
613           (if return
614               (buffer-substring (point) match-end)
615             t)
616           )))))
617
618 (defun pop3-clean-region (start end)
619   (setq end (set-marker (make-marker) end))
620   (save-excursion
621     (goto-char start)
622     (while (and (< (point) end) (search-forward "\r\n" end t))
623       (replace-match "\n" t t))
624     (goto-char start)
625     (while (and (< (point) end) (re-search-forward "^\\." end t))
626       (replace-match "" t t)
627       (forward-char)))
628   (set-marker end nil))
629
630 ;; Copied from message-make-date.
631 (defun pop3-make-date (&optional now)
632   "Make a valid date header.
633 If NOW, use that time instead."
634   (require 'parse-time)
635   (let* ((now (or now (current-time)))
636          (zone (nth 8 (decode-time now)))
637          (sign "+"))
638     (when (< zone 0)
639       (setq sign "-")
640       (setq zone (- zone)))
641     (concat
642      (format-time-string "%d" now)
643      ;; The month name of the %b spec is locale-specific.  Pfff.
644      (format " %s "
645              (capitalize (car (rassoc (nth 4 (decode-time now))
646                                       parse-time-months))))
647      (format-time-string "%Y %H:%M:%S " now)
648      ;; We do all of this because XEmacs doesn't have the %z spec.
649      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
650
651 (defun pop3-munge-message-separator (start end)
652   "Check to see if a message separator exists.  If not, generate one."
653   (save-excursion
654     (save-restriction
655       (narrow-to-region start end)
656       (goto-char (point-min))
657       (if (not (or (looking-at "From .?") ; Unix mail
658                    (looking-at "\001\001\001\001\n") ; MMDF
659                    (looking-at "BABYL OPTIONS:") ; Babyl
660                    ))
661           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
662                  (tdate (mail-fetch-field "Date"))
663                  (date (split-string (or (and tdate
664                                               (not (string= "" tdate))
665                                               tdate)
666                                          (pop3-make-date))
667                                      " "))
668                  (From_))
669             ;; sample date formats I have seen
670             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
671             ;; Date: 08 Jul 1996 23:22:24 -0400
672             ;; should be
673             ;; Tue Jul 9 09:04:21 1996
674
675             ;; Fixme: This should use timezone on the date field contents.
676             (setq date
677                   (cond ((not date)
678                          "Tue Jan 1 00:00:0 1900")
679                         ((string-match "[A-Z]" (nth 0 date))
680                          (format "%s %s %s %s %s"
681                                  (nth 0 date) (nth 2 date) (nth 1 date)
682                                  (nth 4 date) (nth 3 date)))
683                         (t
684                          ;; this really needs to be better but I don't feel
685                          ;; like writing a date to day converter.
686                          (format "Sun %s %s %s %s"
687                                  (nth 1 date) (nth 0 date)
688                                  (nth 3 date) (nth 2 date)))
689                         ))
690             (setq From_ (format "\nFrom %s  %s\n" from date))
691             (while (string-match "," From_)
692               (setq From_ (concat (substring From_ 0 (match-beginning 0))
693                                   (substring From_ (match-end 0)))))
694             (goto-char (point-min))
695             (insert From_)
696             (if (search-forward "\n\n" nil t)
697                 nil
698               (goto-char (point-max))
699               (insert "\n"))
700             (let ((size (- (point-max) (point))))
701               (forward-line -1)
702               (insert (format "Content-Length: %s\n" size)))
703             )))))
704
705 ;; The Command Set
706
707 ;; AUTHORIZATION STATE
708
709 (defun pop3-user (process user)
710   "Send USER information to POP3 server."
711   (pop3-send-command process (format "USER %s" user))
712   (let ((response (pop3-read-response process t)))
713     (if (not (and response (string-match "+OK" response)))
714         (error "USER %s not valid" user))))
715
716 (defun pop3-pass (process)
717   "Send authentication information to the server."
718   (pop3-send-command process (format "PASS %s" pop3-password))
719   (let ((response (pop3-read-response process t)))
720     (if (not (and response (string-match "+OK" response)))
721         (pop3-quit process))))
722
723 (defun pop3-apop (process user)
724   "Send alternate authentication information to the server."
725   (let ((pass pop3-password))
726     (if (and pop3-password-required (not pass))
727         (setq pass
728               (read-passwd (format "Password for %s: " pop3-maildrop))))
729     (if pass
730         (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
731           (pop3-send-command process (format "APOP %s %s" user hash))
732           (let ((response (pop3-read-response process t)))
733             (if (not (and response (string-match "+OK" response)))
734                 (pop3-quit process)))))
735     ))
736
737 ;; TRANSACTION STATE
738
739 (defun pop3-stat (process)
740   "Return the number of messages in the maildrop and the maildrop's size."
741   (pop3-send-command process "STAT")
742   (let ((response (pop3-read-response process t)))
743     (list (string-to-number (nth 1 (split-string response " ")))
744           (string-to-number (nth 2 (split-string response " "))))
745     ))
746
747 (defun pop3-list (process &optional msg)
748   "If MSG is nil, return an alist of (MESSAGE-ID . SIZE) pairs.
749 Otherwise, return the size of the message-id MSG"
750   (pop3-send-command process (if msg
751                                  (format "LIST %d" msg)
752                                "LIST"))
753   (let ((response (pop3-read-response process t)))
754     (if msg
755         (string-to-number (nth 2 (split-string response " ")))
756       (let ((start pop3-read-point) end)
757         (with-current-buffer (process-buffer process)
758           (while (not (re-search-forward "^\\.\r\n" nil t))
759             (pop3-accept-process-output process)
760             (goto-char start))
761           (setq pop3-read-point (point-marker))
762           (goto-char (match-beginning 0))
763           (setq end (point-marker))
764           (mapcar #'(lambda (s) (let ((split (split-string s " ")))
765                                   (cons (string-to-number (nth 0 split))
766                                         (string-to-number (nth 1 split)))))
767                   (split-string (buffer-substring start end) "\r\n" t)))))))
768
769 (defun pop3-retr (process msg crashbuf)
770   "Retrieve message-id MSG to buffer CRASHBUF."
771   (pop3-send-command process (format "RETR %s" msg))
772   (pop3-read-response process)
773   (let ((start pop3-read-point) end)
774     (with-current-buffer (process-buffer process)
775       (while (not (re-search-forward "^\\.\r\n" nil t))
776         (unless (memq (process-status process) '(open run))
777           (error "pop3 server closed the connection"))
778         (pop3-accept-process-output process)
779         (goto-char start))
780       (setq pop3-read-point (point-marker))
781       ;; this code does not seem to work for some POP servers...
782       ;; and I cannot figure out why not.
783       ;;      (goto-char (match-beginning 0))
784       ;;      (backward-char 2)
785       ;;      (if (not (looking-at "\r\n"))
786       ;;          (insert "\r\n"))
787       ;;      (re-search-forward "\\.\r\n")
788       (goto-char (match-beginning 0))
789       (setq end (point-marker))
790       (pop3-clean-region start end)
791       (pop3-munge-message-separator start end)
792       (with-current-buffer crashbuf
793         (erase-buffer))
794       (copy-to-buffer crashbuf start end)
795       (delete-region start end)
796       )))
797
798 (defun pop3-dele (process msg)
799   "Mark message-id MSG as deleted."
800   (pop3-send-command process (format "DELE %s" msg))
801   (pop3-read-response process))
802
803 (defun pop3-noop (process msg)
804   "No-operation."
805   (pop3-send-command process "NOOP")
806   (pop3-read-response process))
807
808 (defun pop3-last (process)
809   "Return highest accessed message-id number for the session."
810   (pop3-send-command process "LAST")
811   (let ((response (pop3-read-response process t)))
812     (string-to-number (nth 1 (split-string response " ")))
813     ))
814
815 (defun pop3-rset (process)
816   "Remove all delete marks from current maildrop."
817   (pop3-send-command process "RSET")
818   (pop3-read-response process))
819
820 ;; UPDATE
821
822 (defun pop3-quit (process)
823   "Close connection to POP3 server.
824 Tell server to remove all messages marked as deleted, unlock the maildrop,
825 and close the connection."
826   (pop3-send-command process "QUIT")
827   (pop3-read-response process t)
828   (if process
829       (with-current-buffer (process-buffer process)
830         (goto-char (point-max))
831         (delete-process process))))
832 \f
833 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
834
835 ;;; AUTHORIZATION STATE
836
837 ;; Initial TCP connection
838 ;; Arguments: none
839 ;; Restrictions: none
840 ;; Possible responses:
841 ;;  +OK [POP3 server ready]
842
843 ;; USER name
844 ;; Arguments: a server specific user-id (required)
845 ;; Restrictions: authorization state [after unsuccessful USER or PASS
846 ;; Possible responses:
847 ;;  +OK [valid user-id]
848 ;;  -ERR [invalid user-id]
849
850 ;; PASS string
851 ;; Arguments: a server/user-id specific password (required)
852 ;; Restrictions: authorization state, after successful USER
853 ;; Possible responses:
854 ;;  +OK [maildrop locked and ready]
855 ;;  -ERR [invalid password]
856 ;;  -ERR [unable to lock maildrop]
857
858 ;; STLS      (RFC 2595)
859 ;; Arguments: none
860 ;; Restrictions: Only permitted in AUTHORIZATION state.
861 ;; Possible responses:
862 ;;  +OK
863 ;;  -ERR
864
865 ;;; TRANSACTION STATE
866
867 ;; STAT
868 ;; Arguments: none
869 ;; Restrictions: transaction state
870 ;; Possible responses:
871 ;;  +OK nn mm [# of messages, size of maildrop]
872
873 ;; LIST [msg]
874 ;; Arguments: a message-id (optional)
875 ;; Restrictions: transaction state; msg must not be deleted
876 ;; Possible responses:
877 ;;  +OK [scan listing follows]
878 ;;  -ERR [no such message]
879
880 ;; RETR msg
881 ;; Arguments: a message-id (required)
882 ;; Restrictions: transaction state; msg must not be deleted
883 ;; Possible responses:
884 ;;  +OK [message contents follow]
885 ;;  -ERR [no such message]
886
887 ;; DELE msg
888 ;; Arguments: a message-id (required)
889 ;; Restrictions: transaction state; msg must not be deleted
890 ;; Possible responses:
891 ;;  +OK [message deleted]
892 ;;  -ERR [no such message]
893
894 ;; NOOP
895 ;; Arguments: none
896 ;; Restrictions: transaction state
897 ;; Possible responses:
898 ;;  +OK
899
900 ;; LAST
901 ;; Arguments: none
902 ;; Restrictions: transaction state
903 ;; Possible responses:
904 ;;  +OK nn [highest numbered message accessed]
905
906 ;; RSET
907 ;; Arguments: none
908 ;; Restrictions: transaction state
909 ;; Possible responses:
910 ;;  +OK [all delete marks removed]
911
912 ;; UIDL [msg]
913 ;; Arguments: a message-id (optional)
914 ;; Restrictions: transaction state; msg must not be deleted
915 ;; Possible responses:
916 ;;  +OK [uidl listing follows]
917 ;;  -ERR [no such message]
918
919 ;;; UPDATE STATE
920
921 ;; QUIT
922 ;; Arguments: none
923 ;; Restrictions: none
924 ;; Possible responses:
925 ;;  +OK [TCP connection closed]
926
927 (provide 'pop3)
928
929 ;;; pop3.el ends here