1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
3 ;; Copyright (C) 1996-1999 Free Software Foundation, Inc.
5 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
6 ;; Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
7 ;; Keywords: mail, pop3
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
29 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
30 ;; are implemented. The LIST command has not been implemented due to lack
31 ;; of actual usefulness.
32 ;; The optional POP3 command TOP has not been implemented.
34 ;; This program was inspired by Kyle E. Jones's vm-pop program.
41 (defconst pop3-version "1.3s")
43 (defvar pop3-maildrop (or (user-login-name) (getenv "LOGNAME") (getenv "USER") nil)
45 (defvar pop3-mailhost (or (getenv "MAILHOST") nil)
49 (defvar pop3-connection-type nil
50 "*POP3 connection type.")
52 (defvar pop3-password-required t
53 "*Non-nil if a password is required when connecting to POP server.")
54 (defvar pop3-password nil
55 "*Password to use when connecting to POP server.")
57 (defvar pop3-authentication-scheme 'pass
58 "*POP3 authentication scheme.
59 Defaults to 'pass, for the standard USER/PASS authentication. Other valid
62 (defvar pop3-timestamp nil
63 "Timestamp returned when initially connected to the POP server.
64 Used for APOP authentication.")
66 (defvar pop3-leave-mail-on-server nil
67 "Non-nil if mail is to be left on the server and UIDL used for
70 (defvar pop3-maximum-message-size nil
71 "If non-nil only download messages smaller than this.")
73 (defvar pop3-uidl-file-name "~/.uidls"
74 "File in which to store the UIDL of processed messages.")
76 (defvar pop3-uidl-support 'dont-know
77 "Whether the server supports UIDL.
78 Nil means no, t means yes, not-nil-or-t means yet to be determined.")
80 (defvar pop3-uidl-obarray (make-vector 31 0)
83 (defvar pop3-read-point nil)
84 (defvar pop3-debug nil)
87 (autoload 'open-ssl-stream "ssl"))
89 (defvar pop3-ssl-program-arguments
91 "Arguments to be passed to the program `pop3-ssl-program-name'.")
93 (defun pop3-movemail (&optional crashbox)
94 "Transfer contents of a maildrop to the specified CRASHBOX."
95 (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
96 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
97 (crashbuf (get-buffer-create " *pop3-retr*"))
102 (pop3-password pop3-password)
104 (concat pop3-uidl-file-name "-" pop3-mailhost))
105 (retrieved-messages nil)
107 ;; for debugging only
108 (if pop3-debug (switch-to-buffer (process-buffer process)))
109 ;; query for password
110 (if (and pop3-password-required (not pop3-password))
112 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
113 (cond ((equal 'apop pop3-authentication-scheme)
114 (pop3-apop process pop3-maildrop))
115 ((equal 'pass pop3-authentication-scheme)
116 (pop3-user process pop3-maildrop)
118 (t (error "Invalid POP3 authentication scheme.")))
119 ;; get messages that are suitable for download
120 (message "Retrieving message list...")
121 (setq messages (pop3-get-message-numbers process)
122 message-count (length messages))
123 (message (format "Retrieving message list...%d unread" message-count))
126 (while (<= n message-count)
127 (setq msgid (caar messages)
128 msglen (cdar messages)
129 messages (cdr messages))
130 ;; only retrieve messages matching our regexp or in the uidl list
131 (unless (or (not msgid)
132 ;; don't download messages that are too large
133 (and pop3-maximum-message-size
134 (> msglen pop3-maximum-message-size)))
135 (message (format "Retrieving message %d of %d from %s..."
136 n message-count pop3-mailhost))
137 (pop3-retr process msgid crashbuf)
138 (setq retrieved-messages (cons msgid retrieved-messages)))
140 (with-current-buffer crashbuf
141 (write-region-as-binary (point-min) (point-max)
142 crashbox 'append 'nomesg)
144 ;; mark messages as read
145 (when pop3-leave-mail-on-server
147 ;; now delete the messages we have retrieved
148 (unless pop3-leave-mail-on-server
149 (dolist (n retrieved-messages)
150 (message (format "Deleting message %d of %d from %s..."
151 n message-count pop3-mailhost))
152 (pop3-dele process n)))
155 (kill-buffer crashbuf)
158 (defun pop3-open-server (mailhost port)
159 "Open TCP connection to MAILHOST.
160 Returns the process associated with the connection."
161 (let ((process-buffer
162 (get-buffer-create (format "trace of POP session to %s" mailhost)))
165 (set-buffer process-buffer)
170 ((eq pop3-connection-type 'ssl)
171 (pop3-open-ssl-stream "POP" process-buffer mailhost port))
173 (open-network-stream-as-binary "POP" process-buffer mailhost port))))
174 (setq pop3-read-point (point-min))
175 (let ((response (pop3-read-response process t)))
177 (substring response (or (string-match "<" response) 0)
178 (+ 1 (or (string-match ">" response) -1)))))
181 (defun pop3-open-ssl-stream-1 (name buffer host service extra-arg)
182 (let* ((ssl-program-arguments
183 `(,@pop3-ssl-program-arguments ,extra-arg
184 "-connect" ,(format "%s:%d" host service)))
185 (process (open-ssl-stream name buffer host service)))
187 (with-current-buffer buffer
188 (goto-char (point-min))
189 (while (and (memq (process-status process) '(open run))
190 (goto-char (point-max))
192 (not (looking-at "+OK")))
193 (accept-process-output process 1)
195 (delete-region (point-min) (point)))
196 (and process (memq (process-status process) '(open run))
199 (defun pop3-open-ssl-stream (name buffer host service)
200 "Open a SSL connection for a service to a host."
202 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
203 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
207 (defun pop3-process-filter (process output)
209 (set-buffer (process-buffer process))
210 (goto-char (point-max))
213 (defun pop3-send-command (process command)
214 (set-buffer (process-buffer process))
215 (goto-char (point-max))
216 ;; (if (= (aref command 0) ?P)
217 ;; (insert "PASS <omitted>\r\n")
218 ;; (insert command "\r\n"))
219 (setq pop3-read-point (point))
220 (goto-char (point-max))
221 (process-send-string process (concat command "\r\n"))
224 (defun pop3-read-response (process &optional return)
225 "Read the response from the server.
226 Return the response string if optional second argument is non-nil."
227 (let ((case-fold-search nil)
230 (set-buffer (process-buffer process))
231 (goto-char pop3-read-point)
232 (while (not (search-forward "\r\n" nil t))
233 (accept-process-output process 3)
234 (goto-char pop3-read-point))
235 (setq match-end (point))
236 (goto-char pop3-read-point)
237 (if (looking-at "-ERR")
238 (signal 'error (list (buffer-substring (point) (- match-end 2))))
239 (if (not (looking-at "+OK"))
240 (progn (setq pop3-read-point match-end) nil)
241 (setq pop3-read-point match-end)
243 (buffer-substring (point) match-end)
247 (defvar pop3-read-passwd nil)
248 (defun pop3-read-passwd (prompt)
249 (if (not pop3-read-passwd)
250 (if (functionp 'read-passwd)
251 (setq pop3-read-passwd 'read-passwd)
252 (if (load "passwd" t)
253 (setq pop3-read-passwd 'read-passwd)
254 (autoload 'ange-ftp-read-passwd "ange-ftp")
255 (setq pop3-read-passwd 'ange-ftp-read-passwd))))
256 (funcall pop3-read-passwd prompt))
258 (defun pop3-clean-region (start end)
259 (setq end (set-marker (make-marker) end))
262 (while (and (< (point) end) (search-forward "\r\n" end t))
263 (replace-match "\n" t t))
265 (while (re-search-forward "\n\n\\(From \\)" end t)
266 (replace-match "\n\n>\\1" t nil))
268 (while (and (< (point) end) (re-search-forward "^\\." end t))
269 (replace-match "" t t)
271 (set-marker end nil))
273 (defun pop3-munge-message-separator (start end)
274 "Check to see if a message separator exists. If not, generate one."
275 (if (not (fboundp 'parse-time-string))
276 (autoload 'parse-time-string "parse-time"))
279 (narrow-to-region start end)
280 (goto-char (point-min))
281 (if (not (or (looking-at "From .?") ; Unix mail
282 (looking-at "\001\001\001\001\n") ; MMDF
283 (looking-at "BABYL OPTIONS:") ; Babyl
285 (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
286 (date (mail-fetch-field "Date"))
288 ;; sample date formats I have seen
289 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
290 ;; Date: 08 Jul 1996 23:22:24 -0400
292 ;; Tue Jul 9 09:04:21 1996
293 (setq date (format-time-string
297 (apply 'encode-time (parse-time-string date))
298 (error (current-time)))
300 (setq From_ (format "\nFrom %s %s\n" from date))
301 (while (string-match "," From_)
302 (setq From_ (concat (substring From_ 0 (match-beginning 0))
303 (substring From_ (match-end 0)))))
304 (goto-char (point-min))
309 (defun pop3-get-message-numbers (process)
310 "Get the list of message numbers and lengths to retrieve via PROCESS."
311 ;; we use the LIST comand first anyway to get the message lengths.
312 ;; then if we're leaving mail on the server, see if the UIDL command
313 ;; is implemented. if so, we use it to get the message number list.
314 (let ((messages (pop3-list process))
315 (uidl (if pop3-leave-mail-on-server
316 (pop3-get-uidl process))))
320 ((eq pop3-uidl-support t)
321 ;; remove elements not in the uidl, this assumes the uidl is short
323 (lambda (message) (memq (car message) uidl))
327 (defun pop3-get-uidl (process)
328 "Use PROCESS to get a list of unread message numbers."
329 (let ((messages (pop3-uidl process)) uidl)
330 (if (or (null messages) (null pop3-uidl-support))
331 (setq pop3-uidl-support nil)
332 (setq pop3-uidl-support t)
335 (when (file-readable-p pop3-uidl-file-name)
336 (insert-file-contents pop3-uidl-file-name))
337 (goto-char (point-min))
338 (while (looking-at "\\([^ \n\t]+\\)")
339 (set (intern (match-string 1) pop3-uidl-obarray)
343 (dolist (message (cdr messages))
344 (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
345 (setcar (symbol-value uidl) (car message))
346 (set (intern (cdr message) pop3-uidl-obarray)
347 (cons (car message) nil))))
348 (pop3-get-unread-message-numbers))
351 (defun pop3-get-unread-message-numbers ()
352 "Return a sorted list of unread msg numbers to retrieve."
354 (mapatoms (lambda (atom)
355 (if (not (cdr (symbol-value atom)))
356 (push (car (symbol-value atom)) nums)))
360 (defun pop3-save-uidls ()
361 "Save the updated UIDLs to disk for use next time."
362 (when (and pop3-leave-mail-on-server
365 (dotimes (i (length pop3-uidl-obarray))
366 (if (symbolp (aref pop3-uidl-obarray i))
370 (when (file-readable-p pop3-uidl-file-name)
371 (copy-file pop3-uidl-file-name
372 (concat pop3-uidl-file-name ".old")
373 'overwrite 'keeptime))
376 (when (car (symbol-value atom))
377 (insert (format "%s\n" atom))))
379 (write-file pop3-uidl-file-name)))))
383 ;; AUTHORIZATION STATE
385 (defun pop3-user (process user)
386 "Send USER information to POP3 server."
387 (pop3-send-command process (format "USER %s" user))
388 (let ((response (pop3-read-response process t)))
389 (if (not (and response (string-match "+OK" response)))
390 (error (format "USER %s not valid." user)))))
392 (defun pop3-pass (process)
393 "Send authentication information to the server."
394 (pop3-send-command process (format "PASS %s" pop3-password))
395 (let ((response (pop3-read-response process t)))
396 (if (not (and response (string-match "+OK" response)))
397 (pop3-quit process))))
399 (defun pop3-apop (process user)
400 "Send alternate authentication information to the server."
401 (if (not (fboundp 'md5)) (autoload 'md5 "md5"))
402 (let ((hash (md5 (concat pop3-timestamp pop3-password))))
403 (pop3-send-command process (format "APOP %s %s" user hash))
404 (let ((response (pop3-read-response process t)))
405 (if (not (and response (string-match "+OK" response)))
406 (pop3-quit process)))))
410 (defun pop3-stat (process)
411 "Return the number of messages in the maildrop and the maildrop's size."
412 (pop3-send-command process "STAT")
413 (let ((response (pop3-read-response process t)))
414 (list (string-to-int (nth 1 (split-string response)))
415 (string-to-int (nth 2 (split-string response))))
418 (defun pop3-retr (process msg crashbuf)
419 "Retrieve message-id MSG to buffer CRASHBUF."
420 (pop3-send-command process (format "RETR %s" msg))
421 (pop3-read-response process)
424 (apply 'narrow-to-region (pop3-get-extended-response process))
425 (pop3-munge-message-separator (point-min) (point-max))
426 (append-to-buffer crashbuf (point-min) (point-max))
427 (delete-region (point-min) (point-max))
430 (defun pop3-dele (process msg)
431 "Mark message-id MSG as deleted."
432 (pop3-send-command process (format "DELE %s" msg))
433 (pop3-read-response process))
435 (defun pop3-noop (process msg)
437 (pop3-send-command process "NOOP")
438 (pop3-read-response process))
440 (defun pop3-last (process)
441 "Return highest accessed message-id number for the session."
442 (pop3-send-command process "LAST")
443 (let ((response (pop3-read-response process t)))
444 (string-to-int (nth 1 (split-string response)))
447 (defun pop3-rset (process)
448 "Remove all delete marks from current maildrop."
449 (pop3-send-command process "RSET")
450 (pop3-read-response process))
454 (defun pop3-quit (process)
455 "Close connection to POP3 server.
456 Tell server to remove all messages marked as deleted, unlock the maildrop,
457 and close the connection."
458 (pop3-send-command process "QUIT")
459 (pop3-read-response process t)
462 (set-buffer (process-buffer process))
463 (goto-char (point-max))
464 (delete-process process)
467 (defun pop3-uidl (process &optional msgno)
468 "Return the results of a UIDL command in PROCESS for optional MSGNO.
469 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
470 Otherwise, return a list in the form
472 (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
476 N is an integer for the number of UIDLs returned (could be 0)
480 (pop3-send-command process (format "UIDL %d" msgno))
481 (pop3-send-command process "UIDL"))
483 (if (null (pop3-read-response process t))
484 nil ;; UIDL is not supported on this server
488 (apply 'narrow-to-region (pop3-get-extended-response process))
489 (goto-char (point-min))
490 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
491 (setq msgno (string-to-int (match-string 1))
492 uidl (match-string 2))
493 (push (cons msgno uidl) pairs)
494 (beginning-of-line 2))
495 (cons (length pairs) (nreverse pairs))
498 (defun pop3-list (process &optional msgno)
499 "Return the results of a LIST command for PROCESS and optional MSGNO.
500 If (optional) msgno is invalid, return nil. Otherwise, return a list
503 (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
507 N is an integer for the number of msg/len pairs (could be 0)
508 LEN-n is an integer."
510 (pop3-send-command process (format "LIST %d" msgno))
511 (pop3-send-command process "LIST"))
513 (if (null (pop3-read-response process t))
514 nil ;; MSGNO is not valid number
518 (apply 'narrow-to-region (pop3-get-extended-response process))
519 (goto-char (point-min))
520 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
521 (setq msgno (string-to-int (match-string 1))
522 len (string-to-int (match-string 2)))
523 (push (cons msgno len) pairs)
524 (beginning-of-line 2))
525 (cons (length pairs) (nreverse pairs))
530 (defun pop3-get-extended-response (process)
531 "Get the extended pop3 response in the PROCESS buffer."
532 (let ((start pop3-read-point) end)
533 (set-buffer (process-buffer process))
535 (while (not (re-search-forward "^\\.\r\n" nil t))
536 (accept-process-output process 3)
538 (setq pop3-read-point (point-marker))
539 (goto-char (match-beginning 0))
540 (setq end (point-marker))
541 (pop3-clean-region start end)
545 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
547 ;;; AUTHORIZATION STATE
549 ;; Initial TCP connection
551 ;; Restrictions: none
552 ;; Possible responses:
553 ;; +OK [POP3 server ready]
556 ;; Arguments: a server specific user-id (required)
557 ;; Restrictions: authorization state [after unsuccessful USER or PASS
558 ;; Possible responses:
559 ;; +OK [valid user-id]
560 ;; -ERR [invalid user-id]
563 ;; Arguments: a server/user-id specific password (required)
564 ;; Restrictions: authorization state, after successful USER
565 ;; Possible responses:
566 ;; +OK [maildrop locked and ready]
567 ;; -ERR [invalid password]
568 ;; -ERR [unable to lock maildrop]
570 ;;; TRANSACTION STATE
574 ;; Restrictions: transaction state
575 ;; Possible responses:
576 ;; +OK nn mm [# of messages, size of maildrop]
579 ;; Arguments: a message-id (optional)
580 ;; Restrictions: transaction state; msg must not be deleted
581 ;; Possible responses:
582 ;; +OK [scan listing follows]
583 ;; -ERR [no such message]
586 ;; Arguments: a message-id (optional)
587 ;; Restrictions: transaction state; msg must not be deleted
588 ;; Possible responses:
589 ;; +OK [uidl listing follows]
590 ;; -ERR [no such message]
593 ;; Arguments: a message-id (required)
594 ;; Restrictions: transaction state; msg must not be deleted
595 ;; Possible responses:
596 ;; +OK [message contents follow]
597 ;; -ERR [no such message]
600 ;; Arguments: a message-id (required)
601 ;; Restrictions: transaction state; msg must not be deleted
602 ;; Possible responses:
603 ;; +OK [message deleted]
604 ;; -ERR [no such message]
608 ;; Restrictions: transaction state
609 ;; Possible responses:
614 ;; Restrictions: transaction state
615 ;; Possible responses:
616 ;; +OK nn [highest numbered message accessed]
620 ;; Restrictions: transaction state
621 ;; Possible responses:
622 ;; +OK [all delete marks removed]
628 ;; Restrictions: none
629 ;; Possible responses:
630 ;; +OK [TCP connection closed]