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.
38 (eval-when-compile (require 'cl))
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 message retrieval.")
69 (defvar pop3-maximum-message-size nil
70 "If non-nil only download messages smaller than this.")
72 (defvar pop3-except-header-regexp nil
73 "If non-nil we do not retrieve messages whose headers are matching this regexp.")
75 (defvar pop3-uidl-file-name "~/.uidls"
76 "File in which to store the UIDL of processed messages.")
78 (defvar pop3-uidl-support 'dont-know
79 "Whether the server supports UIDL.
80 Nil means no, t means yes, not-nil-or-t means yet to be determined.")
82 (defvar pop3-uidl-obarray (make-vector 31 0)
85 (defvar pop3-read-point nil)
86 (defvar pop3-debug nil)
89 (autoload 'open-ssl-stream "ssl")
90 (autoload 'starttls-open-stream "starttls")
91 (autoload 'starttls-negotiate "starttls"))
93 (defvar pop3-ssl-program-arguments
94 '("s_client" "-quiet")
95 "Arguments to be passed to the program `pop3-ssl-program-name'.")
97 (defun pop3-progress-message (format percent &rest args)
98 (apply (function message) format args))
100 (defun pop3-movemail (&optional crashbox)
101 "Transfer contents of a maildrop to the specified CRASHBOX."
102 (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
103 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
104 (crashbuf (get-buffer-create " *pop3-retr*"))
106 (pop3-password pop3-password)
108 (convert-standard-filename
109 (concat pop3-uidl-file-name "-" pop3-mailhost)))
110 (retrieved-messages nil)
111 messages message-count)
112 ;; for debugging only
113 (if pop3-debug (switch-to-buffer (process-buffer process)))
114 ;; query for password
115 (if (and pop3-password-required (not pop3-password))
117 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
118 (cond ((equal 'apop pop3-authentication-scheme)
119 (pop3-apop process pop3-maildrop))
120 ((equal 'pass pop3-authentication-scheme)
121 (pop3-user process pop3-maildrop)
123 (t (error "Invalid POP3 authentication scheme")))
124 ;; get messages that are suitable for download
125 (message "Retrieving message list...")
126 (setq messages (pop3-get-message-numbers process)
127 message-count (length (cdr messages)))
128 (message (format "Retrieving message list...%d of %d unread"
129 message-count (pop messages)))
131 (unless (not (stringp crashbox))
133 (pop3-progress-message
134 "Retrieving message %d of %d (%d octets) from %s..."
135 (floor (* (/ (float n) message-count) 100))
136 n message-count (cdar messages) pop3-mailhost)
137 (pop3-retr process (caar messages) crashbuf)
138 (push (caar messages) retrieved-messages)
139 (setq messages (cdr messages)
141 (with-current-buffer crashbuf
142 (write-region-as-binary (point-min) (point-max)
143 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 Argument PORT specifies connecting port."
162 (let ((process-buffer
163 (get-buffer-create (format "trace of POP session to %s" mailhost)))
166 (set-buffer process-buffer)
171 ((eq pop3-connection-type 'ssl)
172 (pop3-open-ssl-stream "POP" process-buffer mailhost port))
173 ((eq pop3-connection-type 'tls)
174 (pop3-open-tls-stream "POP" process-buffer mailhost port))
176 (open-network-stream-as-binary "POP" process-buffer mailhost port))))
177 (setq pop3-read-point (point-min))
178 (let ((response (pop3-read-response process t)))
180 (substring response (or (string-match "<" response) 0)
181 (+ 1 (or (string-match ">" response) -1)))))
184 (defun pop3-open-ssl-stream-1 (name buffer host service extra-arg)
186 (let* ((ssl-program-name
187 (cond ((exec-installed-p "openssl")
191 (ssl-program-arguments
192 `(,@pop3-ssl-program-arguments ,extra-arg
193 "-connect" ,(format "%s:%d" host service)))
194 (process (open-ssl-stream name buffer host service)))
196 (with-current-buffer buffer
197 (goto-char (point-min))
198 (while (and (memq (process-status process) '(open run))
199 (goto-char (point-max))
201 (not (looking-at "+OK")))
202 (accept-process-output process 1)
204 (delete-region (point-min) (point)))
205 (and process (memq (process-status process) '(open run))
208 (defun pop3-open-ssl-stream (name buffer host service)
209 "Open a SSL connection for a service to a host.
210 Returns a subprocess-object to represent the connection.
211 Args are NAME BUFFER HOST SERVICE."
212 (cond ((eq system-type 'windows-nt)
213 (let (selective-display
214 (coding-system-for-write 'binary)
215 (coding-system-for-read 'raw-text-dos))
216 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
217 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
220 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
221 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))))
223 (defun pop3-open-tls-stream (name buffer host service)
224 "Open a TLSv1 connection for a service to a host.
225 Returns a subprocess-object to represent the connection.
226 Args are NAME BUFFER HOST SERVICE."
228 (as-binary-process (starttls-open-stream
229 name buffer host service))))
231 (starttls-negotiate process)
236 (defun pop3-process-filter (process output)
238 (set-buffer (process-buffer process))
239 (goto-char (point-max))
242 (defun pop3-send-command (process command)
243 (set-buffer (process-buffer process))
244 (goto-char (point-max))
245 ;; (if (= (aref command 0) ?P)
246 ;; (insert "PASS <omitted>\r\n")
247 ;; (insert command "\r\n"))
248 (setq pop3-read-point (point))
249 (goto-char (point-max))
250 (process-send-string process (concat command "\r\n"))
253 (defun pop3-read-response (process &optional return)
254 "Read the response from the server PROCESS.
255 Return the response string if optional second argument RETURN is non-nil."
256 (let ((case-fold-search nil)
259 (set-buffer (process-buffer process))
260 (goto-char pop3-read-point)
261 (while (not (search-forward "\r\n" nil t))
262 (accept-process-output process 3)
263 (goto-char pop3-read-point))
264 (setq match-end (point))
265 (goto-char pop3-read-point)
266 (if (looking-at "-ERR")
267 (signal 'error (list (buffer-substring (point) (- match-end 2))))
268 (if (not (looking-at "+OK"))
269 (progn (setq pop3-read-point match-end) nil)
270 (setq pop3-read-point match-end)
272 (buffer-substring (point) match-end)
276 (defvar pop3-read-passwd nil)
277 (defun pop3-read-passwd (prompt)
278 (if (not pop3-read-passwd)
279 (if (functionp 'read-passwd)
280 (setq pop3-read-passwd 'read-passwd)
281 (if (load "passwd" t)
282 (setq pop3-read-passwd 'read-passwd)
283 (autoload 'ange-ftp-read-passwd "ange-ftp")
284 (setq pop3-read-passwd 'ange-ftp-read-passwd))))
285 (funcall pop3-read-passwd prompt))
287 (defun pop3-clean-region (start end)
288 (setq end (set-marker (make-marker) end))
291 (while (and (< (point) end) (search-forward "\r\n" end t))
292 (replace-match "\n" t t))
294 (while (re-search-forward "\n\n\\(From \\)" end t)
295 (replace-match "\n\n>\\1" t nil))
297 (while (and (< (point) end) (re-search-forward "^\\." end t))
298 (replace-match "" t t)
300 (set-marker end nil))
302 (defun pop3-munge-message-separator (start end)
303 "Check to see if a message separator exists. If not, generate one."
304 (if (not (fboundp 'parse-time-string))
305 (autoload 'parse-time-string "parse-time"))
308 (narrow-to-region start end)
309 (goto-char (point-min))
310 (if (not (or (looking-at "From .?") ; Unix mail
311 (looking-at "\001\001\001\001\n") ; MMDF
312 (looking-at "BABYL OPTIONS:") ; Babyl
314 (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
315 (date (mail-fetch-field "Date"))
317 ;; sample date formats I have seen
318 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
319 ;; Date: 08 Jul 1996 23:22:24 -0400
321 ;; Tue Jul 9 09:04:21 1996
322 (setq date (format-time-string
326 (apply 'encode-time (parse-time-string date))
327 (error (current-time)))
329 (setq From_ (format "\nFrom %s %s\n" from date))
330 (while (string-match "," From_)
331 (setq From_ (concat (substring From_ 0 (match-beginning 0))
332 (substring From_ (match-end 0)))))
333 (goto-char (point-min))
338 (defun pop3-get-message-numbers (process)
339 "Get the list of message numbers and lengths to retrieve via PROCESS."
340 ;; we use the LIST comand first anyway to get the message lengths.
341 ;; then if we're leaving mail on the server, see if the UIDL command
342 ;; is implemented. if so, we use it to get the message number list.
343 (let* ((messages (pop3-list process))
344 (total (or (pop messages) 0))
345 (uidl (if pop3-leave-mail-on-server
346 (pop3-get-uidl process)))
349 ;; only retrieve messages matching our regexp or in the uidl list
351 ;; remove elements not in the uidl, this assumes the uidl is short
352 (or (not (eq pop3-uidl-support t))
353 (memq (caar messages) uidl))
355 ;; don't download messages that are too large
356 (not (and pop3-maximum-message-size
357 (> (cdar messages) pop3-maximum-message-size)))
358 (not (and pop3-except-header-regexp
359 (string-match pop3-except-header-regexp
360 (pop3-top process (caar messages) 0)))))
361 (push (car messages) out))
362 (setq messages (cdr messages)))
363 (cons total (reverse out))))
365 (defun pop3-get-uidl (process)
366 "Use PROCESS to get a list of unread message numbers."
367 (let ((messages (pop3-uidl process)) uidl)
368 (if (or (null messages) (null pop3-uidl-support))
369 (setq pop3-uidl-support nil)
370 (setq pop3-uidl-support t)
373 (when (file-readable-p pop3-uidl-file-name)
374 (insert-file-contents pop3-uidl-file-name))
375 (goto-char (point-min))
376 (while (looking-at "\\([^ \n\t]+\\)")
377 (set (intern (match-string 1) pop3-uidl-obarray)
381 (dolist (message (cdr messages))
382 (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
383 (setcar (symbol-value uidl) (car message))
384 (set (intern (cdr message) pop3-uidl-obarray)
385 (cons (car message) nil))))
386 (pop3-get-unread-message-numbers))
389 (defun pop3-get-unread-message-numbers ()
390 "Return a sorted list of unread msg numbers to retrieve."
392 (mapatoms (lambda (atom)
393 (if (not (cdr (symbol-value atom)))
394 (push (car (symbol-value atom)) nums)))
398 (defun pop3-save-uidls ()
399 "Save the updated UIDLs to disk for use next time."
400 (when (and pop3-leave-mail-on-server
401 ;; UIDL hash table is non-empty
402 (let ((len (length pop3-uidl-obarray)))
404 (setq len (if (symbolp (aref pop3-uidl-obarray (1- len)))
407 (when (file-readable-p pop3-uidl-file-name)
408 (copy-file pop3-uidl-file-name
409 (concat pop3-uidl-file-name ".old")
410 'overwrite 'keeptime))
412 (with-temp-file pop3-uidl-file-name
415 (when (car (symbol-value atom))
416 (insert (format "%s\n" atom))))
417 pop3-uidl-obarray)))))
422 ;; AUTHORIZATION STATE
424 (defun pop3-user (process user)
425 "Send USER information to POP3 server."
426 (pop3-send-command process (format "USER %s" user))
427 (let ((response (pop3-read-response process t)))
428 (if (not (and response (string-match "+OK" response)))
429 (error (format "USER %s not valid." user)))))
431 (defun pop3-pass (process)
432 "Send authentication information to the server."
433 (pop3-send-command process (format "PASS %s" pop3-password))
434 (let ((response (pop3-read-response process t)))
435 (if (not (and response (string-match "+OK" response)))
436 (pop3-quit process))))
438 (autoload 'md5 "md5")
440 (defun pop3-apop (process user)
441 "Send alternate authentication information to the server."
442 (let ((hash (md5 (concat pop3-timestamp pop3-password))))
443 (pop3-send-command process (format "APOP %s %s" user hash))
444 (let ((response (pop3-read-response process t)))
445 (if (not (and response (string-match "+OK" response)))
446 (pop3-quit process)))))
448 (defun pop3-stls (process)
449 "Query whether TLS extension is supported"
450 (pop3-send-command process "STLS")
451 (let ((response (pop3-read-response process t)))
452 (if (not (and response (string-match "+OK" response)))
453 (pop3-quit process))))
457 (defun pop3-stat (process)
458 "Return the number of messages in the maildrop and the maildrop's size."
459 (pop3-send-command process "STAT")
460 (let ((response (pop3-read-response process t)))
461 (list (string-to-int (nth 1 (split-string response)))
462 (string-to-int (nth 2 (split-string response))))
465 (defun pop3-retr (process msg crashbuf)
466 "Retrieve message-id MSG to buffer CRASHBUF."
467 (pop3-send-command process (format "RETR %s" msg))
468 (pop3-read-response process)
470 (let ((region (pop3-get-extended-response process)))
471 (pop3-munge-message-separator (car region) (cadr region))
472 (append-to-buffer crashbuf (car region) (cadr region))
473 (delete-region (car region) (cadr region))
476 (defun pop3-dele (process msg)
477 "Mark message-id MSG as deleted."
478 (pop3-send-command process (format "DELE %s" msg))
479 (pop3-read-response process))
481 (defun pop3-noop (process msg)
483 (pop3-send-command process "NOOP")
484 (pop3-read-response process))
486 (defun pop3-last (process)
487 "Return highest accessed message-id number for the session."
488 (pop3-send-command process "LAST")
489 (let ((response (pop3-read-response process t)))
490 (string-to-int (nth 1 (split-string response)))
493 (defun pop3-rset (process)
494 "Remove all delete marks from current maildrop."
495 (pop3-send-command process "RSET")
496 (pop3-read-response process))
500 (defun pop3-quit (process)
501 "Close connection to POP3 server.
502 Tell server to remove all messages marked as deleted, unlock the maildrop,
503 and close the connection."
504 (pop3-send-command process "QUIT")
505 (pop3-read-response process t)
508 (set-buffer (process-buffer process))
509 (goto-char (point-max))
510 (delete-process process)
512 (when pop3-leave-mail-on-server
515 (when (car (symbol-value atom))
516 (unintern atom pop3-uidl-obarray)))
519 (defun pop3-uidl (process &optional msgno)
520 "Return the results of a UIDL command in PROCESS for optional MSGNO.
521 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
522 Otherwise, return a list in the form
524 (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
528 N is an integer for the number of UIDLs returned (could be 0)
532 (pop3-send-command process (format "UIDL %d" msgno))
533 (pop3-send-command process "UIDL"))
535 (if (null (pop3-read-response process t))
536 nil ;; UIDL is not supported on this server
540 (apply 'narrow-to-region (pop3-get-extended-response process))
541 (goto-char (point-min))
542 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
543 (setq msgno (string-to-int (match-string 1))
544 uidl (match-string 2))
545 (push (cons msgno uidl) pairs)
546 (beginning-of-line 2))
547 (cons (length pairs) (nreverse pairs))
550 (defun pop3-list (process &optional msgno)
551 "Return the results of a LIST command for PROCESS and optional MSGNO.
552 If (optional) msgno is invalid, return nil. Otherwise, return a list
555 (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
559 N is an integer for the number of msg/len pairs (could be 0)
560 LEN-n is an integer."
562 (pop3-send-command process (format "LIST %d" msgno))
563 (pop3-send-command process "LIST"))
565 (if (null (pop3-read-response process t))
566 nil ;; MSGNO is not valid number
570 (apply 'narrow-to-region (pop3-get-extended-response process))
571 (goto-char (point-min))
572 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
573 (setq msgno (string-to-int (match-string 1))
574 len (string-to-int (match-string 2)))
575 (push (cons msgno len) pairs)
576 (beginning-of-line 2))
577 (cons (length pairs) (nreverse pairs))
580 (defun pop3-top (process msgno &optional lines)
581 "Return the top LINES of messages for PROCESS and MSGNO.
582 If msgno is invalid, return nil. Otherwise, return a string."
583 (pop3-send-command process (format "TOP %d %d" msgno (or lines 1)))
584 (if (pop3-read-response process t)
585 nil ;; MSGNO is not valid number
587 (apply 'buffer-substring (pop3-get-extended-response process)))
592 (defun pop3-get-extended-response (process)
593 "Get the extended pop3 response in the PROCESS buffer."
594 (let ((start pop3-read-point) end)
595 (set-buffer (process-buffer process))
597 (while (not (re-search-forward "^\\.\r\n" nil t))
598 (accept-process-output process 3)
600 (setq pop3-read-point (point-marker))
601 (goto-char (match-beginning 0))
602 (setq end (point-marker))
603 (pop3-clean-region start end)
607 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
609 ;;; AUTHORIZATION STATE
611 ;; Initial TCP connection
613 ;; Restrictions: none
614 ;; Possible responses:
615 ;; +OK [POP3 server ready]
618 ;; Arguments: a server specific user-id (required)
619 ;; Restrictions: authorization state [after unsuccessful USER or PASS
620 ;; Possible responses:
621 ;; +OK [valid user-id]
622 ;; -ERR [invalid user-id]
625 ;; Arguments: a server/user-id specific password (required)
626 ;; Restrictions: authorization state, after successful USER
627 ;; Possible responses:
628 ;; +OK [maildrop locked and ready]
629 ;; -ERR [invalid password]
630 ;; -ERR [unable to lock maildrop]
634 ;; Restrictions: authorization state
635 ;; Possible responses:
636 ;; +OK [negotiation is ready]
637 ;; -ERR [security layer is already active]
639 ;;; TRANSACTION STATE
643 ;; Restrictions: transaction state
644 ;; Possible responses:
645 ;; +OK nn mm [# of messages, size of maildrop]
648 ;; Arguments: a message-id (optional)
649 ;; Restrictions: transaction state; msg must not be deleted
650 ;; Possible responses:
651 ;; +OK [scan listing follows]
652 ;; -ERR [no such message]
655 ;; Arguments: a message-id (required), number of lines (optional)
656 ;; Restrictions: transaction state; msg must not be deleted
657 ;; Possible responses:
658 ;; +OK [partial message listing follows]
659 ;; -ERR [no such message]
662 ;; Arguments: a message-id (optional)
663 ;; Restrictions: transaction state; msg must not be deleted
664 ;; Possible responses:
665 ;; +OK [uidl listing follows]
666 ;; -ERR [no such message]
669 ;; Arguments: a message-id (required)
670 ;; Restrictions: transaction state; msg must not be deleted
671 ;; Possible responses:
672 ;; +OK [message contents follow]
673 ;; -ERR [no such message]
676 ;; Arguments: a message-id (required)
677 ;; Restrictions: transaction state; msg must not be deleted
678 ;; Possible responses:
679 ;; +OK [message deleted]
680 ;; -ERR [no such message]
684 ;; Restrictions: transaction state
685 ;; Possible responses:
690 ;; Restrictions: transaction state
691 ;; Possible responses:
692 ;; +OK nn [highest numbered message accessed]
696 ;; Restrictions: transaction state
697 ;; Possible responses:
698 ;; +OK [all delete marks removed]
704 ;; Restrictions: none
705 ;; Possible responses:
706 ;; +OK [TCP connection closed]
710 ;;; pop3.el ends here