1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
4 ;; Free Software Foundation, Inc.
6 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
7 ;; Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
12 ;; This file is part of GNU Emacs.
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)
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.
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.
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.
36 ;; This program was inspired by Kyle E. Jones's vm-pop program.
40 (eval-when-compile (require 'cl))
41 (eval-when-compile (require 'static))
45 (defconst pop3-version "1.3s")
47 (defvar pop3-maildrop (or (user-login-name) (getenv "LOGNAME") (getenv "USER") nil)
49 (defvar pop3-mailhost (or (getenv "MAILHOST") nil)
53 (defvar pop3-connection-type nil
54 "*POP3 connection type.")
56 (defvar pop3-password-required t
57 "*Non-nil if a password is required when connecting to POP server.")
58 (defvar pop3-password nil
59 "*Password to use when connecting to POP server.")
61 (defvar pop3-authentication-scheme 'pass
62 "*POP3 authentication scheme.
63 Defaults to 'pass, for the standard USER/PASS authentication. Other valid
66 (defvar pop3-timestamp nil
67 "Timestamp returned when initially connected to the POP server.
68 Used for APOP authentication.")
70 (defvar pop3-leave-mail-on-server nil
71 "Non-nil if mail is to be left on the server and UIDL used for message retrieval.")
73 (defvar pop3-maximum-message-size nil
74 "If non-nil only download messages smaller than this.")
76 (defvar pop3-except-header-regexp nil
77 "If non-nil we do not retrieve messages whose headers are matching this regexp.")
79 (defvar pop3-uidl-file-name "~/.uidls"
80 "File in which to store the UIDL of processed messages.")
82 (defvar pop3-uidl-support 'dont-know
83 "Whether the server supports UIDL.
84 Nil means no, t means yes, not-nil-or-t means yet to be determined.")
86 (defvar pop3-uidl-obarray (make-vector 31 0)
89 (defvar pop3-read-point nil)
90 (defvar pop3-debug nil)
93 (autoload 'open-ssl-stream "ssl")
94 (autoload 'starttls-open-stream "starttls")
95 (autoload 'starttls-negotiate "starttls"))
97 (defvar pop3-ssl-program-name
98 (if (exec-installed-p "openssl")
101 "The program to run in a subprocess to open an SSL connection.")
103 (defvar pop3-ssl-program-arguments
104 '("s_client" "-quiet")
105 "Arguments to be passed to the program `pop3-ssl-program-name'.")
107 (defun pop3-progress-message (format percent &rest args)
108 (apply (function message) format args))
110 (defun pop3-movemail (&optional crashbox)
111 "Transfer contents of a maildrop to the specified CRASHBOX."
112 (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
113 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
114 (crashbuf (get-buffer-create " *pop3-retr*"))
117 (pop3-password pop3-password)
118 (pop3-uidl-file-name (convert-standard-filename
119 (concat pop3-uidl-file-name "-"
121 retrieved-messages messages)
122 ;; for debugging only
123 (if pop3-debug (switch-to-buffer (process-buffer process)))
124 ;; query for password
125 (if (and pop3-password-required (not pop3-password))
127 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
128 (cond ((equal 'apop pop3-authentication-scheme)
129 (pop3-apop process pop3-maildrop))
130 ((equal 'pass pop3-authentication-scheme)
131 (pop3-user process pop3-maildrop)
133 (t (error "Invalid POP3 authentication scheme")))
134 ;; get messages that are suitable for download
135 (message "Retrieving message list...")
136 (setq messages (pop3-get-message-numbers process)
137 message-count (length (cdr messages)))
138 (message "Retrieving message list...%d of %d unread"
139 message-count (pop messages))
141 (unless (not (stringp crashbox))
143 (pop3-progress-message
144 "Retrieving message %d of %d (%d octets) from %s..."
145 (floor (* (/ (float n) message-count) 100))
146 n message-count (cdar messages) pop3-mailhost)
147 (pop3-retr process (caar messages) crashbuf)
148 (push (caar messages) retrieved-messages)
149 (setq messages (cdr messages)
151 (with-current-buffer crashbuf
152 (write-region-as-binary (point-min) (point-max)
153 crashbox 'append 'nomesg))
154 ;; mark messages as read
155 (when pop3-leave-mail-on-server
157 ;; now delete the messages we have retrieved
158 (unless pop3-leave-mail-on-server
159 (dolist (n retrieved-messages)
160 (message "Deleting message %d of %d from %s..."
161 n message-count pop3-mailhost)
162 (pop3-dele process n)))
165 (kill-buffer crashbuf)
168 (defun pop3-open-server (mailhost port)
169 "Open TCP connection to MAILHOST on PORT.
170 Returns the process associated with the connection.
171 Argument PORT specifies connecting port."
174 (set-buffer (get-buffer-create (concat " trace of POP session to "
177 (setq pop3-read-point (point-min))
181 ((eq pop3-connection-type 'ssl)
182 (pop3-open-ssl-stream "POP" (current-buffer) mailhost port))
183 ((eq pop3-connection-type 'tls)
184 (pop3-open-tls-stream "POP" (current-buffer) mailhost port))
186 (open-network-stream-as-binary "POP" (current-buffer)
188 (let ((response (pop3-read-response process t)))
190 (substring response (or (string-match "<" response) 0)
191 (+ 1 (or (string-match ">" response) -1)))))
194 (defun pop3-open-ssl-stream-1 (name buffer host service extra-arg)
196 (let* ((ssl-program-name
197 pop3-ssl-program-name)
198 (ssl-program-arguments
199 `(,@pop3-ssl-program-arguments ,extra-arg
200 "-connect" ,(format "%s:%d" host service)))
201 (process (open-ssl-stream name buffer host service)))
203 (with-current-buffer buffer
204 (goto-char (point-min))
205 (while (and (memq (process-status process) '(open run))
206 (goto-char (point-max))
208 (not (looking-at "+OK")))
209 (accept-process-output process 1)
211 (delete-region (point-min) (point)))
212 (and process (memq (process-status process) '(open run))
215 (defun pop3-open-ssl-stream (name buffer host service)
216 "Open a SSL connection for a service to a host.
217 Returns a subprocess-object to represent the connection.
218 Args are NAME BUFFER HOST SERVICE."
219 (cond ((eq system-type 'windows-nt)
220 (let (selective-display
221 (coding-system-for-write 'binary)
222 (coding-system-for-read 'raw-text-dos))
223 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
224 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
227 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
228 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))))
230 (defun pop3-open-tls-stream (name buffer host service)
231 "Open a TLSv1 connection for a service to a host.
232 Returns a subprocess-object to represent the connection.
233 Args are NAME BUFFER HOST SERVICE."
235 (as-binary-process (starttls-open-stream
236 name buffer host service))))
238 (starttls-negotiate process)
243 (defun pop3-process-filter (process output)
245 (set-buffer (process-buffer process))
246 (goto-char (point-max))
249 (defun pop3-send-command (process command)
250 (set-buffer (process-buffer process))
251 (goto-char (point-max))
252 ;; (if (= (aref command 0) ?P)
253 ;; (insert "PASS <omitted>\r\n")
254 ;; (insert command "\r\n"))
255 (setq pop3-read-point (point))
256 (goto-char (point-max))
257 (process-send-string process (concat command "\r\n"))
260 (defun pop3-read-response (process &optional return)
261 "Read the response from the server PROCESS.
262 Return the response string if optional second argument RETURN is non-nil."
263 (let ((case-fold-search nil)
266 (set-buffer (process-buffer process))
267 (goto-char pop3-read-point)
268 (while (not (search-forward "\r\n" nil t))
269 (accept-process-output process 3)
270 (goto-char pop3-read-point))
271 (setq match-end (point))
272 (goto-char pop3-read-point)
273 (if (looking-at "-ERR")
274 (error (buffer-substring (point) (- match-end 2)))
275 (if (not (looking-at "+OK"))
276 (progn (setq pop3-read-point match-end) nil)
277 (setq pop3-read-point match-end)
279 (buffer-substring (point) match-end)
283 (defvar pop3-read-passwd nil)
284 (defun pop3-read-passwd (prompt)
285 (if (not pop3-read-passwd)
286 (if (fboundp 'read-passwd)
287 (setq pop3-read-passwd 'read-passwd)
288 (if (load "passwd" t)
289 (setq pop3-read-passwd 'read-passwd)
290 (autoload 'ange-ftp-read-passwd "ange-ftp")
291 (setq pop3-read-passwd 'ange-ftp-read-passwd))))
292 (funcall pop3-read-passwd prompt))
294 (defun pop3-clean-region (start end)
295 (setq end (set-marker (make-marker) end))
298 (while (and (< (point) end) (search-forward "\r\n" end t))
299 (replace-match "\n" t t))
301 (while (re-search-forward "\n\n\\(From \\)" end t)
302 (replace-match "\n\n>\\1" t nil))
304 (while (and (< (point) end) (re-search-forward "^\\." end t))
305 (replace-match "" t t)
307 (set-marker end nil))
309 (defun pop3-munge-message-separator (start end)
310 "Check to see if a message separator exists. If not, generate one."
311 (if (not (fboundp 'parse-time-string))
312 (autoload 'parse-time-string "parse-time"))
315 (narrow-to-region start end)
316 (goto-char (point-min))
317 (if (not (or (looking-at "From .?") ; Unix mail
318 (looking-at "\001\001\001\001\n") ; MMDF
319 (looking-at "BABYL OPTIONS:") ; Babyl
321 (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
322 (date (mail-fetch-field "Date"))
324 ;; sample date formats I have seen
325 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
326 ;; Date: 08 Jul 1996 23:22:24 -0400
328 ;; Tue Jul 9 09:04:21 1996
329 (setq date (format-time-string
333 (apply 'encode-time (parse-time-string date))
334 (error (current-time)))
336 (setq From_ (format "\nFrom %s %s\n" from date))
337 (while (string-match "," From_)
338 (setq From_ (concat (substring From_ 0 (match-beginning 0))
339 (substring From_ (match-end 0)))))
340 (goto-char (point-min))
345 (defun pop3-get-message-numbers (process)
346 "Get the list of message numbers and lengths to retrieve via PROCESS."
347 ;; we use the LIST comand first anyway to get the message lengths.
348 ;; then if we're leaving mail on the server, see if the UIDL command
349 ;; is implemented. if so, we use it to get the message number list.
350 (let* ((messages (pop3-list process))
351 (total (or (pop messages) 0))
352 (uidl (if pop3-leave-mail-on-server
353 (pop3-get-uidl process)))
356 ;; only retrieve messages matching our regexp or in the uidl list
358 ;; remove elements not in the uidl, this assumes the uidl is short
359 (or (not (eq pop3-uidl-support t))
360 (memq (caar messages) uidl))
362 ;; don't download messages that are too large
363 (not (and pop3-maximum-message-size
364 (> (cdar messages) pop3-maximum-message-size)))
365 (not (and pop3-except-header-regexp
366 (string-match pop3-except-header-regexp
367 (pop3-top process (caar messages) 0)))))
368 (push (car messages) out))
369 (setq messages (cdr messages)))
370 (cons total (reverse out))))
372 (defun pop3-get-uidl (process)
373 "Use PROCESS to get a list of unread message numbers."
374 (let ((messages (pop3-uidl process)) uidl)
375 (if (or (null messages) (null pop3-uidl-support))
376 (setq pop3-uidl-support nil)
377 (setq pop3-uidl-support t)
380 (when (file-readable-p pop3-uidl-file-name)
381 (insert-file-contents pop3-uidl-file-name))
382 (goto-char (point-min))
383 (while (looking-at "\\([^ \n\t]+\\)")
384 (set (intern (match-string 1) pop3-uidl-obarray)
388 (dolist (message (cdr messages))
389 (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
390 (setcar (symbol-value uidl) (car message))
391 (set (intern (cdr message) pop3-uidl-obarray)
392 (cons (car message) nil))))
393 (pop3-get-unread-message-numbers))
396 (defun pop3-get-unread-message-numbers ()
397 "Return a sorted list of unread msg numbers to retrieve."
399 (mapatoms (lambda (atom)
400 (if (not (cdr (symbol-value atom)))
401 (push (car (symbol-value atom)) nums)))
405 (defun pop3-save-uidls ()
406 "Save the updated UIDLs to disk for use next time."
407 (when (and pop3-leave-mail-on-server
408 ;; UIDL hash table is non-empty
409 (let ((len (length pop3-uidl-obarray)))
411 (setq len (if (symbolp (aref pop3-uidl-obarray (1- len)))
414 (when (file-readable-p pop3-uidl-file-name)
415 (copy-file pop3-uidl-file-name
416 (concat pop3-uidl-file-name ".old")
417 'overwrite 'keeptime))
419 (with-temp-file pop3-uidl-file-name
422 (when (car (symbol-value atom))
423 (insert (format "%s\n" atom))))
425 (fillarray pop3-uidl-obarray 0)))
430 ;; AUTHORIZATION STATE
432 (defun pop3-user (process user)
433 "Send USER information to POP3 server."
434 (pop3-send-command process (format "USER %s" user))
435 (let ((response (pop3-read-response process t)))
436 (if (not (and response (string-match "+OK" response)))
437 (error (format "USER %s not valid." user)))))
439 (defun pop3-pass (process)
440 "Send authentication information to the server."
441 (pop3-send-command process (format "PASS %s" pop3-password))
442 (let ((response (pop3-read-response process t)))
443 (if (not (and response (string-match "+OK" response)))
444 (pop3-quit process))))
446 (static-unless (and (fboundp 'md5) (subrp (symbol-function 'md5)))
449 (if (module-installed-p 'md5)
451 (autoload 'md5 "md5")
452 (fset 'pop3-md5 'md5))
454 (defvar pop3-md5-program "md5"
455 "*Program to encode its input in MD5.")
457 (defun pop3-md5 (string)
460 (call-process-region (point-min) (point-max)
461 (or shell-file-name "/bin/sh")
462 t (current-buffer) nil
463 "-c" pop3-md5-program)
464 ;; The meaningful output is the first 32 characters.
465 ;; Don't return the newline that follows them!
466 (buffer-substring (point-min) (+ (point-min) 32))))
469 (defun pop3-apop (process user)
470 "Send alternate authentication information to the server."
471 (let ((pass pop3-password))
472 (if (and pop3-password-required (not pass))
474 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
476 (let ((hash (static-if (and (fboundp 'md5)
477 (subrp (symbol-function 'md5)))
478 (md5 (concat pop3-timestamp pass))
479 (pop3-md5 (concat pop3-timestamp pass)))))
480 (pop3-send-command process (format "APOP %s %s" user hash))
481 (let ((response (pop3-read-response process t)))
482 (if (not (and response (string-match "+OK" response)))
483 (pop3-quit process)))))
486 (defun pop3-stls (process)
487 "Query whether TLS extension is supported"
488 (pop3-send-command process "STLS")
489 (let ((response (pop3-read-response process t)))
490 (if (not (and response (string-match "+OK" response)))
491 (pop3-quit process))))
495 (defun pop3-stat (process)
496 "Return the number of messages in the maildrop and the maildrop's size."
497 (pop3-send-command process "STAT")
498 (let ((response (pop3-read-response process t)))
499 (list (string-to-int (nth 1 (split-string response " ")))
500 (string-to-int (nth 2 (split-string response " "))))
503 (defun pop3-retr (process msg crashbuf)
504 "Retrieve message-id MSG to buffer CRASHBUF."
505 (pop3-send-command process (format "RETR %s" msg))
506 (pop3-read-response process)
508 (let ((region (pop3-get-extended-response process)))
509 (pop3-munge-message-separator (car region) (cadr region))
510 (append-to-buffer crashbuf (car region) (cadr region))
511 (delete-region (car region) (cadr region))
514 (defun pop3-dele (process msg)
515 "Mark message-id MSG as deleted."
516 (pop3-send-command process (format "DELE %s" msg))
517 (pop3-read-response process))
519 (defun pop3-noop (process msg)
521 (pop3-send-command process "NOOP")
522 (pop3-read-response process))
524 (defun pop3-last (process)
525 "Return highest accessed message-id number for the session."
526 (pop3-send-command process "LAST")
527 (let ((response (pop3-read-response process t)))
528 (string-to-int (nth 1 (split-string response " ")))
531 (defun pop3-rset (process)
532 "Remove all delete marks from current maildrop."
533 (pop3-send-command process "RSET")
534 (pop3-read-response process))
538 (defun pop3-quit (process)
539 "Close connection to POP3 server.
540 Tell server to remove all messages marked as deleted, unlock the maildrop,
541 and close the connection."
542 (pop3-send-command process "QUIT")
543 (pop3-read-response process t)
546 (set-buffer (process-buffer process))
547 (goto-char (point-max))
548 (delete-process process))))
550 (defun pop3-uidl (process &optional msgno)
551 "Return the results of a UIDL command in PROCESS for optional MSGNO.
552 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
553 Otherwise, return a list in the form
555 (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
559 N is an integer for the number of UIDLs returned (could be 0)
563 (pop3-send-command process (format "UIDL %d" msgno))
564 (pop3-send-command process "UIDL"))
566 (if (null (pop3-read-response process t))
567 nil ;; UIDL is not supported on this server
571 (apply 'narrow-to-region (pop3-get-extended-response process))
572 (goto-char (point-min))
573 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
574 (setq msgno (string-to-int (match-string 1))
575 uidl (match-string 2))
576 (push (cons msgno uidl) pairs)
577 (beginning-of-line 2))
578 (cons (length pairs) (nreverse pairs))
581 (defun pop3-list (process &optional msgno)
582 "Return the results of a LIST command for PROCESS and optional MSGNO.
583 If (optional) msgno is invalid, return nil. Otherwise, return a list
586 (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
590 N is an integer for the number of msg/len pairs (could be 0)
591 LEN-n is an integer."
593 (pop3-send-command process (format "LIST %d" msgno))
594 (pop3-send-command process "LIST"))
596 (if (null (pop3-read-response process t))
597 nil ;; MSGNO is not valid number
601 (apply 'narrow-to-region (pop3-get-extended-response process))
602 (goto-char (point-min))
603 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
604 (setq msgno (string-to-int (match-string 1))
605 len (string-to-int (match-string 2)))
606 (push (cons msgno len) pairs)
607 (beginning-of-line 2))
608 (cons (length pairs) (nreverse pairs))
611 (defun pop3-top (process msgno &optional lines)
612 "Return the top LINES of messages for PROCESS and MSGNO.
613 If msgno is invalid, return nil. Otherwise, return a string."
614 (pop3-send-command process (format "TOP %d %d" msgno (or lines 1)))
615 (if (pop3-read-response process t)
616 nil ;; MSGNO is not valid number
618 (apply 'buffer-substring (pop3-get-extended-response process)))
623 (defun pop3-get-extended-response (process)
624 "Get the extended pop3 response in the PROCESS buffer."
625 (let ((start pop3-read-point) end)
626 (set-buffer (process-buffer process))
628 (while (not (re-search-forward "^\\.\r\n" nil t))
629 (accept-process-output process 3)
631 (setq pop3-read-point (point-marker))
632 (goto-char (match-beginning 0))
633 (setq end (point-marker))
634 (pop3-clean-region start end)
638 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
640 ;;; AUTHORIZATION STATE
642 ;; Initial TCP connection
644 ;; Restrictions: none
645 ;; Possible responses:
646 ;; +OK [POP3 server ready]
649 ;; Arguments: a server specific user-id (required)
650 ;; Restrictions: authorization state [after unsuccessful USER or PASS
651 ;; Possible responses:
652 ;; +OK [valid user-id]
653 ;; -ERR [invalid user-id]
656 ;; Arguments: a server/user-id specific password (required)
657 ;; Restrictions: authorization state, after successful USER
658 ;; Possible responses:
659 ;; +OK [maildrop locked and ready]
660 ;; -ERR [invalid password]
661 ;; -ERR [unable to lock maildrop]
665 ;; Restrictions: authorization state
666 ;; Possible responses:
667 ;; +OK [negotiation is ready]
668 ;; -ERR [security layer is already active]
670 ;;; TRANSACTION STATE
674 ;; Restrictions: transaction state
675 ;; Possible responses:
676 ;; +OK nn mm [# of messages, size of maildrop]
679 ;; Arguments: a message-id (optional)
680 ;; Restrictions: transaction state; msg must not be deleted
681 ;; Possible responses:
682 ;; +OK [scan listing follows]
683 ;; -ERR [no such message]
686 ;; Arguments: a message-id (required), number of lines (optional)
687 ;; Restrictions: transaction state; msg must not be deleted
688 ;; Possible responses:
689 ;; +OK [partial message listing follows]
690 ;; -ERR [no such message]
693 ;; Arguments: a message-id (optional)
694 ;; Restrictions: transaction state; msg must not be deleted
695 ;; Possible responses:
696 ;; +OK [uidl listing follows]
697 ;; -ERR [no such message]
700 ;; Arguments: a message-id (required)
701 ;; Restrictions: transaction state; msg must not be deleted
702 ;; Possible responses:
703 ;; +OK [message contents follow]
704 ;; -ERR [no such message]
707 ;; Arguments: a message-id (required)
708 ;; Restrictions: transaction state; msg must not be deleted
709 ;; Possible responses:
710 ;; +OK [message deleted]
711 ;; -ERR [no such message]
715 ;; Restrictions: transaction state
716 ;; Possible responses:
721 ;; Restrictions: transaction state
722 ;; Possible responses:
723 ;; +OK nn [highest numbered message accessed]
727 ;; Restrictions: transaction state
728 ;; Possible responses:
729 ;; +OK [all delete marks removed]
735 ;; Restrictions: none
736 ;; Possible responses:
737 ;; +OK [TCP connection closed]
741 ;;; pop3.el ends here