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.
42 (defconst pop3-version "1.3s")
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 "~/Mail/.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-arguments
95 '("s_client" "-quiet")
96 "Arguments to be passed to the program `pop3-ssl-program-name'.")
98 (defun pop3-progress-message (format percent &rest args)
99 (apply (function message) format args))
101 (defun pop3-movemail (&optional crashbox)
102 "Transfer contents of a maildrop to the specified CRASHBOX."
103 (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
104 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
105 (crashbuf (get-buffer-create " *pop3-retr*"))
107 (pop3-password pop3-password)
109 (convert-standard-filename
110 (concat pop3-uidl-file-name "-" pop3-mailhost)))
111 (retrieved-messages nil)
112 messages message-count)
113 ;; for debugging only
114 (if pop3-debug (switch-to-buffer (process-buffer process)))
115 ;; query for password
116 (if (and pop3-password-required (not pop3-password))
118 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
119 (cond ((equal 'apop pop3-authentication-scheme)
120 (pop3-apop process pop3-maildrop))
121 ((equal 'pass pop3-authentication-scheme)
122 (pop3-user process pop3-maildrop)
124 (t (error "Invalid POP3 authentication scheme")))
125 ;; get messages that are suitable for download
126 (message "Retrieving message list...")
127 (setq messages (pop3-get-message-numbers process)
128 message-count (length (cdr messages)))
129 (message "Retrieving message list...%d of %d unread"
130 message-count (pop messages))
132 (unless (not (stringp crashbox))
134 (pop3-progress-message
135 "Retrieving message %d of %d (%d octets) from %s..."
136 (floor (* (/ (float n) message-count) 100))
137 n message-count (cdar messages) pop3-mailhost)
138 (pop3-retr process (caar messages) crashbuf)
139 (push (caar messages) retrieved-messages)
140 (setq messages (cdr messages)
142 (with-current-buffer crashbuf
143 (write-region-as-binary (point-min) (point-max)
144 crashbox 'append 'nomesg))
145 ;; mark messages as read
146 (when pop3-leave-mail-on-server
148 ;; now delete the messages we have retrieved
149 (unless pop3-leave-mail-on-server
150 (dolist (n retrieved-messages)
151 (message "Deleting message %d of %d from %s..."
152 n message-count pop3-mailhost)
153 (pop3-dele process n)))
156 (kill-buffer crashbuf)
159 (defun pop3-get-message-count ()
160 "Return the number of messages in the maildrop."
161 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
163 (pop3-password pop3-password)
165 ;; for debugging only
166 (if pop3-debug (switch-to-buffer (process-buffer process)))
167 ;; query for password
168 (if (and pop3-password-required (not pop3-password))
170 (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
171 (cond ((equal 'apop pop3-authentication-scheme)
172 (pop3-apop process pop3-maildrop))
173 ((equal 'pass pop3-authentication-scheme)
174 (pop3-user process pop3-maildrop)
176 (t (error "Invalid POP3 authentication scheme.")))
177 (setq message-count (car (pop3-stat process)))
181 (defun pop3-open-server (mailhost port)
182 "Open TCP connection to MAILHOST.
183 Returns the process associated with the connection.
184 Argument PORT specifies connecting port."
185 (let ((process-buffer
186 (get-buffer-create (format "trace of POP session to %s" mailhost)))
189 (set-buffer process-buffer)
194 ((eq pop3-connection-type 'ssl)
195 (pop3-open-ssl-stream "POP" process-buffer mailhost port))
196 ((eq pop3-connection-type 'tls)
197 (pop3-open-tls-stream "POP" process-buffer mailhost port))
199 (open-network-stream-as-binary "POP" process-buffer mailhost port))))
200 (setq pop3-read-point (point-min))
201 (let ((response (pop3-read-response process t)))
203 (substring response (or (string-match "<" response) 0)
204 (+ 1 (or (string-match ">" response) -1)))))
207 (defun pop3-open-ssl-stream-1 (name buffer host service extra-arg)
209 (let* ((ssl-program-name
210 (cond ((exec-installed-p "openssl")
214 (ssl-program-arguments
215 `(,@pop3-ssl-program-arguments ,extra-arg
216 "-connect" ,(format "%s:%d" host service)))
217 (process (open-ssl-stream name buffer host service)))
219 (with-current-buffer buffer
220 (goto-char (point-min))
221 (while (and (memq (process-status process) '(open run))
222 (goto-char (point-max))
224 (not (looking-at "+OK")))
225 (accept-process-output process 1)
227 (delete-region (point-min) (point)))
228 (and process (memq (process-status process) '(open run))
231 (defun pop3-open-ssl-stream (name buffer host service)
232 "Open a SSL connection for a service to a host.
233 Returns a subprocess-object to represent the connection.
234 Args are NAME BUFFER HOST SERVICE."
235 (cond ((eq system-type 'windows-nt)
236 (let (selective-display
237 (coding-system-for-write 'binary)
238 (coding-system-for-read 'raw-text-dos))
239 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
240 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
243 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
244 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))))
246 (defun pop3-open-tls-stream (name buffer host service)
247 "Open a TLSv1 connection for a service to a host.
248 Returns a subprocess-object to represent the connection.
249 Args are NAME BUFFER HOST SERVICE."
251 (as-binary-process (starttls-open-stream
252 name buffer host service))))
254 (starttls-negotiate process)
259 (defun pop3-process-filter (process output)
261 (set-buffer (process-buffer process))
262 (goto-char (point-max))
265 (defun pop3-send-command (process command)
266 (set-buffer (process-buffer process))
267 (goto-char (point-max))
268 ;; (if (= (aref command 0) ?P)
269 ;; (insert "PASS <omitted>\r\n")
270 ;; (insert command "\r\n"))
271 (setq pop3-read-point (point))
272 (goto-char (point-max))
273 (process-send-string process (concat command "\r\n"))
276 (defun pop3-read-response (process &optional return)
277 "Read the response from the server PROCESS.
278 Return the response string if optional second argument RETURN is non-nil."
279 (let ((case-fold-search nil)
282 (set-buffer (process-buffer process))
283 (goto-char pop3-read-point)
284 (while (not (search-forward "\r\n" nil t))
285 (accept-process-output process 3)
286 (goto-char pop3-read-point))
287 (setq match-end (point))
288 (goto-char pop3-read-point)
289 (if (looking-at "-ERR")
290 (signal 'error (list (buffer-substring (point) (- match-end 2))))
291 (if (not (looking-at "+OK"))
292 (progn (setq pop3-read-point match-end) nil)
293 (setq pop3-read-point match-end)
295 (buffer-substring (point) match-end)
299 (defvar pop3-read-passwd nil)
300 (defun pop3-read-passwd (prompt)
301 (if (not pop3-read-passwd)
302 (if (or (fboundp 'read-passwd) (load "passwd" t))
303 (setq pop3-read-passwd 'read-passwd)
304 (autoload 'ange-ftp-read-passwd "ange-ftp")
305 (setq pop3-read-passwd 'ange-ftp-read-passwd)))
306 (funcall pop3-read-passwd prompt))
308 (defun pop3-clean-region (start end)
309 (setq end (set-marker (make-marker) end))
312 (while (and (< (point) end) (search-forward "\r\n" end t))
313 (replace-match "\n" t t))
315 (while (re-search-forward "\n\n\\(From \\)" end t)
316 (replace-match "\n\n>\\1" t nil))
318 (while (and (< (point) end) (re-search-forward "^\\." end t))
319 (replace-match "" t t)
321 (set-marker end nil))
323 (defun pop3-munge-message-separator (start end)
324 "Check to see if a message separator exists. If not, generate one."
325 (if (not (fboundp 'parse-time-string))
326 (autoload 'parse-time-string "parse-time"))
329 (narrow-to-region start end)
330 (goto-char (point-min))
331 (if (not (or (looking-at "From .?") ; Unix mail
332 (looking-at "\001\001\001\001\n") ; MMDF
333 (looking-at "BABYL OPTIONS:") ; Babyl
335 (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
336 (date (mail-fetch-field "Date"))
338 ;; sample date formats I have seen
339 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
340 ;; Date: 08 Jul 1996 23:22:24 -0400
342 ;; Tue Jul 9 09:04:21 1996
343 (setq date (format-time-string
347 (apply 'encode-time (parse-time-string date))
348 (error (current-time)))
350 (setq From_ (format "\nFrom %s %s\n" from date))
351 (while (string-match "," From_)
352 (setq From_ (concat (substring From_ 0 (match-beginning 0))
353 (substring From_ (match-end 0)))))
354 (goto-char (point-min))
359 (defun pop3-get-message-numbers (process)
360 "Get the list of message numbers and lengths to retrieve via PROCESS."
361 ;; we use the LIST comand first anyway to get the message lengths.
362 ;; then if we're leaving mail on the server, see if the UIDL command
363 ;; is implemented. if so, we use it to get the message number list.
364 (let* ((messages (pop3-list process))
365 (total (or (pop messages) 0))
366 (uidl (if pop3-leave-mail-on-server
367 (pop3-get-uidl process)))
370 ;; only retrieve messages matching our regexp or in the uidl list
372 ;; remove elements not in the uidl, this assumes the uidl is short
373 (or (not (eq pop3-uidl-support t))
374 (memq (caar messages) uidl))
376 ;; don't download messages that are too large
377 (not (and pop3-maximum-message-size
378 (> (cdar messages) pop3-maximum-message-size)))
379 (not (and pop3-except-header-regexp
380 (string-match pop3-except-header-regexp
381 (pop3-top process (caar messages) 0)))))
382 (push (car messages) out))
383 (setq messages (cdr messages)))
384 (cons total (reverse out))))
386 (defun pop3-get-uidl (process)
387 "Use PROCESS to get a list of unread message numbers."
388 (let ((messages (pop3-uidl process)) uidl)
389 (if (or (null messages) (null pop3-uidl-support))
390 (setq pop3-uidl-support nil)
391 (setq pop3-uidl-support t)
394 (when (file-readable-p pop3-uidl-file-name)
395 (insert-file-contents pop3-uidl-file-name))
396 (goto-char (point-min))
397 (while (looking-at "\\([^ \n\t]+\\)")
398 (set (intern (match-string 1) pop3-uidl-obarray)
402 (dolist (message (cdr messages))
403 (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
404 (setcar (symbol-value uidl) (car message))
405 (set (intern (cdr message) pop3-uidl-obarray)
406 (cons (car message) nil))))
407 (pop3-get-unread-message-numbers))
410 (defun pop3-get-unread-message-numbers ()
411 "Return a sorted list of unread msg numbers to retrieve."
413 (mapatoms (lambda (atom)
414 (if (not (cdr (symbol-value atom)))
415 (push (car (symbol-value atom)) nums)))
419 (defun pop3-save-uidls ()
420 "Save the updated UIDLs to disk for use next time."
421 (when (and pop3-leave-mail-on-server
422 ;; UIDL hash table is non-empty
423 (let ((len (length pop3-uidl-obarray)))
425 (setq len (if (symbolp (aref pop3-uidl-obarray (1- len)))
428 (when (file-readable-p pop3-uidl-file-name)
429 (copy-file pop3-uidl-file-name
430 (concat pop3-uidl-file-name ".old")
431 'overwrite 'keeptime))
433 (with-temp-file pop3-uidl-file-name
436 (when (car (symbol-value atom))
437 (insert (format "%s\n" atom))))
438 pop3-uidl-obarray)))))
443 ;; AUTHORIZATION STATE
445 (defun pop3-user (process user)
446 "Send USER information to POP3 server."
447 (pop3-send-command process (format "USER %s" user))
448 (let ((response (pop3-read-response process t)))
449 (if (not (and response (string-match "+OK" response)))
450 (error (format "USER %s not valid." user)))))
452 (defun pop3-pass (process)
453 "Send authentication information to the server."
454 (pop3-send-command process (format "PASS %s" pop3-password))
455 (let ((response (pop3-read-response process t)))
456 (if (not (and response (string-match "+OK" response)))
457 (pop3-quit process))))
459 (autoload 'md5 "md5")
461 (defun pop3-apop (process user)
462 "Send alternate authentication information to the server."
463 (let ((hash (md5 (concat pop3-timestamp pop3-password))))
464 (pop3-send-command process (format "APOP %s %s" user hash))
465 (let ((response (pop3-read-response process t)))
466 (if (not (and response (string-match "+OK" response)))
467 (pop3-quit process)))))
469 (defun pop3-stls (process)
470 "Query whether TLS extension is supported"
471 (pop3-send-command process "STLS")
472 (let ((response (pop3-read-response process t)))
473 (if (not (and response (string-match "+OK" response)))
474 (pop3-quit process))))
478 (defun pop3-stat (process)
479 "Return the number of messages in the maildrop and the maildrop's size."
480 (pop3-send-command process "STAT")
481 (let ((response (pop3-read-response process t)))
482 (list (string-to-int (nth 1 (split-string response)))
483 (string-to-int (nth 2 (split-string response))))
486 (defun pop3-retr (process msg crashbuf)
487 "Retrieve message-id MSG to buffer CRASHBUF."
488 (pop3-send-command process (format "RETR %s" msg))
489 (pop3-read-response process)
491 (let ((region (pop3-get-extended-response process)))
492 (pop3-munge-message-separator (car region) (cadr region))
493 (append-to-buffer crashbuf (car region) (cadr region))
494 (delete-region (car region) (cadr region))
497 (defun pop3-dele (process msg)
498 "Mark message-id MSG as deleted."
499 (pop3-send-command process (format "DELE %s" msg))
500 (pop3-read-response process))
502 (defun pop3-noop (process msg)
504 (pop3-send-command process "NOOP")
505 (pop3-read-response process))
507 (defun pop3-last (process)
508 "Return highest accessed message-id number for the session."
509 (pop3-send-command process "LAST")
510 (let ((response (pop3-read-response process t)))
511 (string-to-int (nth 1 (split-string response)))
514 (defun pop3-rset (process)
515 "Remove all delete marks from current maildrop."
516 (pop3-send-command process "RSET")
517 (pop3-read-response process))
521 (defun pop3-quit (process)
522 "Close connection to POP3 server.
523 Tell server to remove all messages marked as deleted, unlock the maildrop,
524 and close the connection."
525 (pop3-send-command process "QUIT")
526 (pop3-read-response process t)
529 (set-buffer (process-buffer process))
530 (goto-char (point-max))
531 (delete-process process)
533 (when pop3-leave-mail-on-server
536 (when (car (symbol-value atom))
537 (unintern atom pop3-uidl-obarray)))
540 (defun pop3-uidl (process &optional msgno)
541 "Return the results of a UIDL command in PROCESS for optional MSGNO.
542 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
543 Otherwise, return a list in the form
545 (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
549 N is an integer for the number of UIDLs returned (could be 0)
553 (pop3-send-command process (format "UIDL %d" msgno))
554 (pop3-send-command process "UIDL"))
556 (if (null (pop3-read-response process t))
557 nil ;; UIDL is not supported on this server
561 (apply 'narrow-to-region (pop3-get-extended-response process))
562 (goto-char (point-min))
563 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
564 (setq msgno (string-to-int (match-string 1))
565 uidl (match-string 2))
566 (push (cons msgno uidl) pairs)
567 (beginning-of-line 2))
568 (cons (length pairs) (nreverse pairs))
571 (defun pop3-list (process &optional msgno)
572 "Return the results of a LIST command for PROCESS and optional MSGNO.
573 If (optional) msgno is invalid, return nil. Otherwise, return a list
576 (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
580 N is an integer for the number of msg/len pairs (could be 0)
581 LEN-n is an integer."
583 (pop3-send-command process (format "LIST %d" msgno))
584 (pop3-send-command process "LIST"))
586 (if (null (pop3-read-response process t))
587 nil ;; MSGNO is not valid number
591 (apply 'narrow-to-region (pop3-get-extended-response process))
592 (goto-char (point-min))
593 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
594 (setq msgno (string-to-int (match-string 1))
595 len (string-to-int (match-string 2)))
596 (push (cons msgno len) pairs)
597 (beginning-of-line 2))
598 (cons (length pairs) (nreverse pairs))
601 (defun pop3-top (process msgno &optional lines)
602 "Return the top LINES of messages for PROCESS and MSGNO.
603 If msgno is invalid, return nil. Otherwise, return a string."
604 (pop3-send-command process (format "TOP %d %d" msgno (or lines 1)))
605 (if (pop3-read-response process t)
606 nil ;; MSGNO is not valid number
608 (apply 'buffer-substring (pop3-get-extended-response process)))
613 (defun pop3-get-extended-response (process)
614 "Get the extended pop3 response in the PROCESS buffer."
615 (let ((start pop3-read-point) end)
616 (set-buffer (process-buffer process))
618 (while (not (re-search-forward "^\\.\r\n" nil t))
619 (accept-process-output process 3)
621 (setq pop3-read-point (point-marker))
622 (goto-char (match-beginning 0))
623 (setq end (point-marker))
624 (pop3-clean-region start end)
628 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
630 ;;; AUTHORIZATION STATE
632 ;; Initial TCP connection
634 ;; Restrictions: none
635 ;; Possible responses:
636 ;; +OK [POP3 server ready]
639 ;; Arguments: a server specific user-id (required)
640 ;; Restrictions: authorization state [after unsuccessful USER or PASS
641 ;; Possible responses:
642 ;; +OK [valid user-id]
643 ;; -ERR [invalid user-id]
646 ;; Arguments: a server/user-id specific password (required)
647 ;; Restrictions: authorization state, after successful USER
648 ;; Possible responses:
649 ;; +OK [maildrop locked and ready]
650 ;; -ERR [invalid password]
651 ;; -ERR [unable to lock maildrop]
655 ;; Restrictions: authorization state
656 ;; Possible responses:
657 ;; +OK [negotiation is ready]
658 ;; -ERR [security layer is already active]
660 ;;; TRANSACTION STATE
664 ;; Restrictions: transaction state
665 ;; Possible responses:
666 ;; +OK nn mm [# of messages, size of maildrop]
669 ;; Arguments: a message-id (optional)
670 ;; Restrictions: transaction state; msg must not be deleted
671 ;; Possible responses:
672 ;; +OK [scan listing follows]
673 ;; -ERR [no such message]
676 ;; Arguments: a message-id (required), number of lines (optional)
677 ;; Restrictions: transaction state; msg must not be deleted
678 ;; Possible responses:
679 ;; +OK [partial message listing follows]
680 ;; -ERR [no such message]
683 ;; Arguments: a message-id (optional)
684 ;; Restrictions: transaction state; msg must not be deleted
685 ;; Possible responses:
686 ;; +OK [uidl listing follows]
687 ;; -ERR [no such message]
690 ;; Arguments: a message-id (required)
691 ;; Restrictions: transaction state; msg must not be deleted
692 ;; Possible responses:
693 ;; +OK [message contents follow]
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 deleted]
701 ;; -ERR [no such message]
705 ;; Restrictions: transaction state
706 ;; Possible responses:
711 ;; Restrictions: transaction state
712 ;; Possible responses:
713 ;; +OK nn [highest numbered message accessed]
717 ;; Restrictions: transaction state
718 ;; Possible responses:
719 ;; +OK [all delete marks removed]
725 ;; Restrictions: none
726 ;; Possible responses:
727 ;; +OK [TCP connection closed]
731 ;;; pop3.el ends here