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>
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software; you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs; see the file COPYING. If not, write to the
25 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
31 ;; are implemented. The LIST command has not been implemented due to lack
32 ;; of actual usefulness.
33 ;; The optional POP3 command TOP has not been implemented.
35 ;; This program was inspired by Kyle E. Jones's vm-pop program.
39 (eval-when-compile (require 'cl))
40 (eval-when-compile (require 'static))
44 (defvar pop3-maildrop (or (user-login-name) (getenv "LOGNAME") (getenv "USER") nil)
46 (defvar pop3-mailhost (or (getenv "MAILHOST") nil)
50 (defvar pop3-connection-type nil
51 "*POP3 connection type.")
53 (defvar pop3-password-required t
54 "*Non-nil if a password is required when connecting to POP server.")
55 (defvar pop3-password nil
56 "*Password to use when connecting to POP server.")
58 (defvar pop3-authentication-scheme 'pass
59 "*POP3 authentication scheme.
60 Defaults to 'pass, for the standard USER/PASS authentication. Other valid
63 (defvar pop3-timestamp nil
64 "Timestamp returned when initially connected to the POP server.
65 Used for APOP authentication.")
67 (defvar pop3-leave-mail-on-server nil
68 "Non-nil if mail is to be left on the server and UIDL used for message retrieval.")
70 (defvar pop3-maximum-message-size nil
71 "If non-nil only download messages smaller than this.")
73 (defvar pop3-except-header-regexp nil
74 "If non-nil we do not retrieve messages whose headers are matching this regexp.")
76 (defvar pop3-uidl-file-name "~/.uidls"
77 "File in which to store the UIDL of processed messages.")
79 (defvar pop3-uidl-support 'dont-know
80 "Whether the server supports UIDL.
81 Nil means no, t means yes, not-nil-or-t means yet to be determined.")
83 (defvar pop3-uidl-obarray (make-vector 31 0)
86 (defvar pop3-read-point nil)
87 (defvar pop3-debug nil)
90 (autoload 'open-ssl-stream "ssl")
91 (autoload 'starttls-open-stream "starttls")
92 (autoload 'starttls-negotiate "starttls"))
94 (defvar pop3-ssl-program-name
95 (if (exec-installed-p "openssl")
98 "The program to run in a subprocess to open an SSL connection.")
100 (defvar pop3-ssl-program-arguments
101 '("s_client" "-quiet")
102 "Arguments to be passed to the program `pop3-ssl-program-name'.")
104 (defun pop3-progress-message (format percent &rest args)
105 (apply (function message) format args))
107 (defun pop3-movemail (&optional crashbox)
108 "Transfer contents of a maildrop to the specified CRASHBOX."
109 (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
110 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
111 (crashbuf (get-buffer-create " *pop3-retr*"))
114 (pop3-password pop3-password)
115 (pop3-uidl-file-name (convert-standard-filename
116 (concat pop3-uidl-file-name "-"
118 retrieved-messages messages)
119 ;; for debugging only
120 (if pop3-debug (switch-to-buffer (process-buffer process)))
121 ;; query for password
122 (if (and pop3-password-required (not pop3-password))
124 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
125 (cond ((equal 'apop pop3-authentication-scheme)
126 (pop3-apop process pop3-maildrop))
127 ((equal 'pass pop3-authentication-scheme)
128 (pop3-user process pop3-maildrop)
130 (t (error "Invalid POP3 authentication scheme")))
131 ;; get messages that are suitable for download
132 (message "Retrieving message list...")
133 (setq messages (pop3-get-message-numbers process)
134 message-count (length (cdr messages)))
135 (message "Retrieving message list...%d of %d unread"
136 message-count (pop messages))
138 (unless (not (stringp crashbox))
140 (pop3-progress-message
141 "Retrieving message %d of %d (%d octets) from %s..."
142 (floor (* (/ (float n) message-count) 100))
143 n message-count (cdar messages) pop3-mailhost)
144 (pop3-retr process (caar messages) crashbuf)
145 (push (caar messages) retrieved-messages)
146 (setq messages (cdr messages)
148 (with-current-buffer crashbuf
149 (write-region-as-binary (point-min) (point-max)
150 crashbox 'append 'nomesg))
151 ;; mark messages as read
152 (when pop3-leave-mail-on-server
154 ;; now delete the messages we have retrieved
155 (unless pop3-leave-mail-on-server
156 (dolist (n retrieved-messages)
157 (message "Deleting message %d of %d from %s..."
158 n message-count pop3-mailhost)
159 (pop3-dele process n)))
162 (kill-buffer crashbuf)
165 (defun pop3-open-server (mailhost port)
166 "Open TCP connection to MAILHOST on PORT.
167 Returns the process associated with the connection.
168 Argument PORT specifies connecting port."
171 (set-buffer (get-buffer-create (concat " trace of POP session to "
174 (setq pop3-read-point (point-min))
178 ((eq pop3-connection-type 'ssl)
179 (pop3-open-ssl-stream "POP" (current-buffer) mailhost port))
180 ((eq pop3-connection-type 'tls)
181 (pop3-open-tls-stream "POP" (current-buffer) mailhost port))
183 (open-network-stream-as-binary "POP" (current-buffer)
185 (let ((response (pop3-read-response process t)))
187 (substring response (or (string-match "<" response) 0)
188 (+ 1 (or (string-match ">" response) -1)))))
191 (defun pop3-open-ssl-stream-1 (name buffer host service extra-arg)
193 (let* ((ssl-program-name
194 pop3-ssl-program-name)
195 (ssl-program-arguments
196 `(,@pop3-ssl-program-arguments ,extra-arg
197 "-connect" ,(format "%s:%d" host service)))
198 (process (open-ssl-stream name buffer host service)))
200 (with-current-buffer buffer
201 (goto-char (point-min))
202 (while (and (memq (process-status process) '(open run))
203 (goto-char (point-max))
205 (not (looking-at "+OK")))
206 (accept-process-output process 1)
208 (delete-region (point-min) (point)))
209 (and process (memq (process-status process) '(open run))
212 (defun pop3-open-ssl-stream (name buffer host service)
213 "Open a SSL connection for a service to a host.
214 Returns a subprocess-object to represent the connection.
215 Args are NAME BUFFER HOST SERVICE."
216 (cond ((eq system-type 'windows-nt)
217 (let (selective-display
218 (coding-system-for-write 'binary)
219 (coding-system-for-read 'raw-text-dos))
220 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
221 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
224 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
225 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))))
227 (defun pop3-open-tls-stream (name buffer host service)
228 "Open a TLSv1 connection for a service to a host.
229 Returns a subprocess-object to represent the connection.
230 Args are NAME BUFFER HOST SERVICE."
232 (as-binary-process (starttls-open-stream
233 name buffer host service))))
235 (starttls-negotiate process)
240 (defun pop3-process-filter (process output)
242 (set-buffer (process-buffer process))
243 (goto-char (point-max))
246 (defun pop3-send-command (process command)
247 (set-buffer (process-buffer process))
248 (goto-char (point-max))
249 ;; (if (= (aref command 0) ?P)
250 ;; (insert "PASS <omitted>\r\n")
251 ;; (insert command "\r\n"))
252 (setq pop3-read-point (point))
253 (goto-char (point-max))
254 (process-send-string process (concat command "\r\n"))
257 (defun pop3-read-response (process &optional return)
258 "Read the response from the server.
259 Return the response string if optional second argument is non-nil."
260 (let ((case-fold-search nil)
263 (set-buffer (process-buffer process))
264 (goto-char pop3-read-point)
265 (while (not (search-forward "\r\n" nil t))
266 (accept-process-output process 3)
267 (goto-char pop3-read-point))
268 (setq match-end (point))
269 (goto-char pop3-read-point)
270 (if (looking-at "-ERR")
271 (error (buffer-substring (point) (- match-end 2)))
272 (if (not (looking-at "+OK"))
273 (progn (setq pop3-read-point match-end) nil)
274 (setq pop3-read-point match-end)
276 (buffer-substring (point) match-end)
280 (defvar pop3-read-passwd nil)
281 (defun pop3-read-passwd (prompt)
282 (if (not pop3-read-passwd)
283 (if (fboundp 'read-passwd)
284 (setq pop3-read-passwd 'read-passwd)
285 (if (load "passwd" t)
286 (setq pop3-read-passwd 'read-passwd)
287 (autoload 'ange-ftp-read-passwd "ange-ftp")
288 (setq pop3-read-passwd 'ange-ftp-read-passwd))))
289 (funcall pop3-read-passwd prompt))
291 (defun pop3-clean-region (start end)
292 (setq end (set-marker (make-marker) end))
295 (while (and (< (point) end) (search-forward "\r\n" end t))
296 (replace-match "\n" t t))
298 (while (re-search-forward "\n\n\\(From \\)" end t)
299 (replace-match "\n\n>\\1" t nil))
301 (while (and (< (point) end) (re-search-forward "^\\." end t))
302 (replace-match "" t t)
304 (set-marker end nil))
306 (defun pop3-munge-message-separator (start end)
307 "Check to see if a message separator exists. If not, generate one."
308 (if (not (fboundp 'parse-time-string))
309 (autoload 'parse-time-string "parse-time"))
312 (narrow-to-region start end)
313 (goto-char (point-min))
314 (if (not (or (looking-at "From .?") ; Unix mail
315 (looking-at "\001\001\001\001\n") ; MMDF
316 (looking-at "BABYL OPTIONS:") ; Babyl
318 (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
319 (date (mail-fetch-field "Date"))
321 ;; sample date formats I have seen
322 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
323 ;; Date: 08 Jul 1996 23:22:24 -0400
325 ;; Tue Jul 9 09:04:21 1996
326 (setq date (format-time-string
330 (apply 'encode-time (parse-time-string date))
331 (error (current-time)))
333 (setq From_ (format "\nFrom %s %s\n" from date))
334 (while (string-match "," From_)
335 (setq From_ (concat (substring From_ 0 (match-beginning 0))
336 (substring From_ (match-end 0)))))
337 (goto-char (point-min))
342 (defun pop3-get-message-numbers (process)
343 "Get the list of message numbers and lengths to retrieve via PROCESS."
344 ;; we use the LIST comand first anyway to get the message lengths.
345 ;; then if we're leaving mail on the server, see if the UIDL command
346 ;; is implemented. if so, we use it to get the message number list.
347 (let* ((messages (pop3-list process))
348 (total (or (pop messages) 0))
349 (uidl (if pop3-leave-mail-on-server
350 (pop3-get-uidl process)))
353 ;; only retrieve messages matching our regexp or in the uidl list
355 ;; remove elements not in the uidl, this assumes the uidl is short
356 (or (not (eq pop3-uidl-support t))
357 (memq (caar messages) uidl))
359 ;; don't download messages that are too large
360 (not (and pop3-maximum-message-size
361 (> (cdar messages) pop3-maximum-message-size)))
362 (not (and pop3-except-header-regexp
363 (string-match pop3-except-header-regexp
364 (pop3-top process (caar messages) 0)))))
365 (push (car messages) out))
366 (setq messages (cdr messages)))
367 (cons total (reverse out))))
369 (defun pop3-get-uidl (process)
370 "Use PROCESS to get a list of unread message numbers."
371 (let ((messages (pop3-uidl process)) uidl)
372 (if (or (null messages) (null pop3-uidl-support))
373 (setq pop3-uidl-support nil)
374 (setq pop3-uidl-support t)
377 (when (file-readable-p pop3-uidl-file-name)
378 (insert-file-contents pop3-uidl-file-name))
379 (goto-char (point-min))
380 (while (looking-at "\\([^ \n\t]+\\)")
381 (set (intern (match-string 1) pop3-uidl-obarray)
385 (dolist (message (cdr messages))
386 (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
387 (setcar (symbol-value uidl) (car message))
388 (set (intern (cdr message) pop3-uidl-obarray)
389 (cons (car message) nil))))
390 (pop3-get-unread-message-numbers))
393 (defun pop3-get-unread-message-numbers ()
394 "Return a sorted list of unread msg numbers to retrieve."
396 (mapatoms (lambda (atom)
397 (if (not (cdr (symbol-value atom)))
398 (push (car (symbol-value atom)) nums)))
402 (defun pop3-save-uidls ()
403 "Save the updated UIDLs to disk for use next time."
404 (when (and pop3-leave-mail-on-server
405 ;; UIDL hash table is non-empty
406 (let ((len (length pop3-uidl-obarray)))
408 (setq len (if (symbolp (aref pop3-uidl-obarray (1- len)))
411 (when (file-readable-p pop3-uidl-file-name)
412 (copy-file pop3-uidl-file-name
413 (concat pop3-uidl-file-name ".old")
414 'overwrite 'keeptime))
416 (with-temp-file pop3-uidl-file-name
419 (when (car (symbol-value atom))
420 (insert (format "%s\n" atom))))
422 (fillarray pop3-uidl-obarray 0)))
427 ;; AUTHORIZATION STATE
429 (defun pop3-user (process user)
430 "Send USER information to POP3 server."
431 (pop3-send-command process (format "USER %s" user))
432 (let ((response (pop3-read-response process t)))
433 (if (not (and response (string-match "+OK" response)))
434 (error (format "USER %s not valid." user)))))
436 (defun pop3-pass (process)
437 "Send authentication information to the server."
438 (pop3-send-command process (format "PASS %s" pop3-password))
439 (let ((response (pop3-read-response process t)))
440 (if (not (and response (string-match "+OK" response)))
441 (pop3-quit process))))
443 (static-unless (and (fboundp 'md5) (subrp (symbol-function 'md5)))
446 (if (module-installed-p 'md5)
448 (autoload 'md5 "md5")
449 (fset 'pop3-md5 'md5))
451 (defvar pop3-md5-program "md5"
452 "*Program to encode its input in MD5.")
454 (defun pop3-md5 (string)
457 (call-process-region (point-min) (point-max)
458 (or shell-file-name "/bin/sh")
459 t (current-buffer) nil
460 "-c" pop3-md5-program)
461 ;; The meaningful output is the first 32 characters.
462 ;; Don't return the newline that follows them!
463 (buffer-substring (point-min) (+ (point-min) 32))))
466 (defun pop3-apop (process user)
467 "Send alternate authentication information to the server."
468 (let ((pass pop3-password))
469 (if (and pop3-password-required (not pass))
471 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
473 (let ((hash (static-if (and (fboundp 'md5)
474 (subrp (symbol-function 'md5)))
475 (md5 (concat pop3-timestamp pass))
476 (pop3-md5 (concat pop3-timestamp pass)))))
477 (pop3-send-command process (format "APOP %s %s" user hash))
478 (let ((response (pop3-read-response process t)))
479 (if (not (and response (string-match "+OK" response)))
480 (pop3-quit process)))))
483 (defun pop3-stls (process)
484 "Query whether TLS extension is supported"
485 (pop3-send-command process "STLS")
486 (let ((response (pop3-read-response process t)))
487 (if (not (and response (string-match "+OK" response)))
488 (pop3-quit process))))
492 (defun pop3-stat (process)
493 "Return the number of messages in the maildrop and the maildrop's size."
494 (pop3-send-command process "STAT")
495 (let ((response (pop3-read-response process t)))
496 (list (string-to-int (nth 1 (split-string response " ")))
497 (string-to-int (nth 2 (split-string response " "))))
500 (defun pop3-retr (process msg crashbuf)
501 "Retrieve message-id MSG to buffer CRASHBUF."
502 (pop3-send-command process (format "RETR %s" msg))
503 (pop3-read-response process)
505 (let ((region (pop3-get-extended-response process)))
506 (pop3-munge-message-separator (car region) (cadr region))
507 (append-to-buffer crashbuf (car region) (cadr region))
508 (delete-region (car region) (cadr region))
511 (defun pop3-dele (process msg)
512 "Mark message-id MSG as deleted."
513 (pop3-send-command process (format "DELE %s" msg))
514 (pop3-read-response process))
516 (defun pop3-noop (process msg)
518 (pop3-send-command process "NOOP")
519 (pop3-read-response process))
521 (defun pop3-last (process)
522 "Return highest accessed message-id number for the session."
523 (pop3-send-command process "LAST")
524 (let ((response (pop3-read-response process t)))
525 (string-to-int (nth 1 (split-string response " ")))
528 (defun pop3-rset (process)
529 "Remove all delete marks from current maildrop."
530 (pop3-send-command process "RSET")
531 (pop3-read-response process))
535 (defun pop3-quit (process)
536 "Close connection to POP3 server.
537 Tell server to remove all messages marked as deleted, unlock the maildrop,
538 and close the connection."
539 (pop3-send-command process "QUIT")
540 (pop3-read-response process t)
543 (set-buffer (process-buffer process))
544 (goto-char (point-max))
545 (delete-process process))))
547 (defun pop3-uidl (process &optional msgno)
548 "Return the results of a UIDL command in PROCESS for optional MSGNO.
549 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
550 Otherwise, return a list in the form
552 (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
556 N is an integer for the number of UIDLs returned (could be 0)
560 (pop3-send-command process (format "UIDL %d" msgno))
561 (pop3-send-command process "UIDL"))
563 (if (null (pop3-read-response process t))
564 nil ;; UIDL is not supported on this server
568 (apply 'narrow-to-region (pop3-get-extended-response process))
569 (goto-char (point-min))
570 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
571 (setq msgno (string-to-int (match-string 1))
572 uidl (match-string 2))
573 (push (cons msgno uidl) pairs)
574 (beginning-of-line 2))
575 (cons (length pairs) (nreverse pairs))
578 (defun pop3-list (process &optional msgno)
579 "Return the results of a LIST command for PROCESS and optional MSGNO.
580 If (optional) msgno is invalid, return nil. Otherwise, return a list
583 (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
587 N is an integer for the number of msg/len pairs (could be 0)
588 LEN-n is an integer."
590 (pop3-send-command process (format "LIST %d" msgno))
591 (pop3-send-command process "LIST"))
593 (if (null (pop3-read-response process t))
594 nil ;; MSGNO is not valid number
598 (apply 'narrow-to-region (pop3-get-extended-response process))
599 (goto-char (point-min))
600 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
601 (setq msgno (string-to-int (match-string 1))
602 len (string-to-int (match-string 2)))
603 (push (cons msgno len) pairs)
604 (beginning-of-line 2))
605 (cons (length pairs) (nreverse pairs))
608 (defun pop3-top (process msgno &optional lines)
609 "Return the top LINES of messages for PROCESS and MSGNO.
610 If msgno is invalid, return nil. Otherwise, return a string."
611 (pop3-send-command process (format "TOP %d %d" msgno (or lines 1)))
612 (if (pop3-read-response process t)
613 nil ;; MSGNO is not valid number
615 (apply 'buffer-substring (pop3-get-extended-response process)))
620 (defun pop3-get-extended-response (process)
621 "Get the extended pop3 response in the PROCESS buffer."
622 (let ((start pop3-read-point) end)
623 (set-buffer (process-buffer process))
625 (while (not (re-search-forward "^\\.\r\n" nil t))
626 (accept-process-output process 3)
628 (setq pop3-read-point (point-marker))
629 (goto-char (match-beginning 0))
630 (setq end (point-marker))
631 (pop3-clean-region start end)
635 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
637 ;;; AUTHORIZATION STATE
639 ;; Initial TCP connection
641 ;; Restrictions: none
642 ;; Possible responses:
643 ;; +OK [POP3 server ready]
646 ;; Arguments: a server specific user-id (required)
647 ;; Restrictions: authorization state [after unsuccessful USER or PASS
648 ;; Possible responses:
649 ;; +OK [valid user-id]
650 ;; -ERR [invalid user-id]
653 ;; Arguments: a server/user-id specific password (required)
654 ;; Restrictions: authorization state, after successful USER
655 ;; Possible responses:
656 ;; +OK [maildrop locked and ready]
657 ;; -ERR [invalid password]
658 ;; -ERR [unable to lock maildrop]
662 ;; Restrictions: authorization state
663 ;; Possible responses:
664 ;; +OK [negotiation is ready]
665 ;; -ERR [security layer is already active]
667 ;;; TRANSACTION STATE
671 ;; Restrictions: transaction state
672 ;; Possible responses:
673 ;; +OK nn mm [# of messages, size of maildrop]
676 ;; Arguments: a message-id (optional)
677 ;; Restrictions: transaction state; msg must not be deleted
678 ;; Possible responses:
679 ;; +OK [scan listing follows]
680 ;; -ERR [no such message]
683 ;; Arguments: a message-id (required), number of lines (optional)
684 ;; Restrictions: transaction state; msg must not be deleted
685 ;; Possible responses:
686 ;; +OK [partial message listing follows]
687 ;; -ERR [no such message]
690 ;; Arguments: a message-id (optional)
691 ;; Restrictions: transaction state; msg must not be deleted
692 ;; Possible responses:
693 ;; +OK [uidl listing follows]
694 ;; -ERR [no such message]
697 ;; Arguments: a message-id (required)
698 ;; Restrictions: transaction state; msg must not be deleted
699 ;; Possible responses:
700 ;; +OK [message contents follow]
701 ;; -ERR [no such message]
704 ;; Arguments: a message-id (required)
705 ;; Restrictions: transaction state; msg must not be deleted
706 ;; Possible responses:
707 ;; +OK [message deleted]
708 ;; -ERR [no such message]
712 ;; Restrictions: transaction state
713 ;; Possible responses:
718 ;; Restrictions: transaction state
719 ;; Possible responses:
720 ;; +OK nn [highest numbered message accessed]
724 ;; Restrictions: transaction state
725 ;; Possible responses:
726 ;; +OK [all delete marks removed]
732 ;; Restrictions: none
733 ;; Possible responses:
734 ;; +OK [TCP connection closed]
738 ;;; pop3.el ends here