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
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)
185 (let* ((ssl-program-arguments
186 `(,@pop3-ssl-program-arguments ,extra-arg
187 "-connect" ,(format "%s:%d" host service)))
188 (process (open-ssl-stream name buffer host service)))
190 (with-current-buffer buffer
191 (goto-char (point-min))
192 (while (and (memq (process-status process) '(open run))
193 (goto-char (point-max))
195 (not (looking-at "+OK")))
196 (accept-process-output process 1)
198 (delete-region (point-min) (point)))
199 (and process (memq (process-status process) '(open run))
202 (defun pop3-open-ssl-stream (name buffer host service)
203 "Open a SSL connection for a service to a host.
204 Returns a subprocess-object to represent the connection.
205 Args are NAME BUFFER HOST SERVICE."
207 (or (pop3-open-ssl-stream-1 name buffer host service "-ssl3")
208 (pop3-open-ssl-stream-1 name buffer host service "-ssl2"))))
210 (defun pop3-open-tls-stream (name buffer host service)
211 "Open a TLSv1 connection for a service to a host.
212 Returns a subprocess-object to represent the connection.
213 Args are NAME BUFFER HOST SERVICE."
215 (as-binary-process (starttls-open-stream
216 name buffer host service))))
218 (starttls-negotiate process)
223 (defun pop3-process-filter (process output)
225 (set-buffer (process-buffer process))
226 (goto-char (point-max))
229 (defun pop3-send-command (process command)
230 (set-buffer (process-buffer process))
231 (goto-char (point-max))
232 ;; (if (= (aref command 0) ?P)
233 ;; (insert "PASS <omitted>\r\n")
234 ;; (insert command "\r\n"))
235 (setq pop3-read-point (point))
236 (goto-char (point-max))
237 (process-send-string process (concat command "\r\n"))
240 (defun pop3-read-response (process &optional return)
241 "Read the response from the server PROCESS.
242 Return the response string if optional second argument RETURN is non-nil."
243 (let ((case-fold-search nil)
246 (set-buffer (process-buffer process))
247 (goto-char pop3-read-point)
248 (while (not (search-forward "\r\n" nil t))
249 (accept-process-output process 3)
250 (goto-char pop3-read-point))
251 (setq match-end (point))
252 (goto-char pop3-read-point)
253 (if (looking-at "-ERR")
254 (signal 'error (list (buffer-substring (point) (- match-end 2))))
255 (if (not (looking-at "+OK"))
256 (progn (setq pop3-read-point match-end) nil)
257 (setq pop3-read-point match-end)
259 (buffer-substring (point) match-end)
263 (defvar pop3-read-passwd nil)
264 (defun pop3-read-passwd (prompt)
265 (if (not pop3-read-passwd)
266 (if (functionp 'read-passwd)
267 (setq pop3-read-passwd 'read-passwd)
268 (if (load "passwd" t)
269 (setq pop3-read-passwd 'read-passwd)
270 (autoload 'ange-ftp-read-passwd "ange-ftp")
271 (setq pop3-read-passwd 'ange-ftp-read-passwd))))
272 (funcall pop3-read-passwd prompt))
274 (defun pop3-clean-region (start end)
275 (setq end (set-marker (make-marker) end))
278 (while (and (< (point) end) (search-forward "\r\n" end t))
279 (replace-match "\n" t t))
281 (while (re-search-forward "\n\n\\(From \\)" end t)
282 (replace-match "\n\n>\\1" t nil))
284 (while (and (< (point) end) (re-search-forward "^\\." end t))
285 (replace-match "" t t)
287 (set-marker end nil))
289 (defun pop3-munge-message-separator (start end)
290 "Check to see if a message separator exists. If not, generate one."
291 (if (not (fboundp 'parse-time-string))
292 (autoload 'parse-time-string "parse-time"))
295 (narrow-to-region start end)
296 (goto-char (point-min))
297 (if (not (or (looking-at "From .?") ; Unix mail
298 (looking-at "\001\001\001\001\n") ; MMDF
299 (looking-at "BABYL OPTIONS:") ; Babyl
301 (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
302 (date (mail-fetch-field "Date"))
304 ;; sample date formats I have seen
305 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
306 ;; Date: 08 Jul 1996 23:22:24 -0400
308 ;; Tue Jul 9 09:04:21 1996
309 (setq date (format-time-string
313 (apply 'encode-time (parse-time-string date))
314 (error (current-time)))
316 (setq From_ (format "\nFrom %s %s\n" from date))
317 (while (string-match "," From_)
318 (setq From_ (concat (substring From_ 0 (match-beginning 0))
319 (substring From_ (match-end 0)))))
320 (goto-char (point-min))
325 (defun pop3-get-message-numbers (process)
326 "Get the list of message numbers and lengths to retrieve via PROCESS."
327 ;; we use the LIST comand first anyway to get the message lengths.
328 ;; then if we're leaving mail on the server, see if the UIDL command
329 ;; is implemented. if so, we use it to get the message number list.
330 (let* ((messages (pop3-list process))
331 (total (or (pop messages) 0))
332 (uidl (if pop3-leave-mail-on-server
333 (pop3-get-uidl process)))
336 ;; only retrieve messages matching our regexp or in the uidl list
338 ;; remove elements not in the uidl, this assumes the uidl is short
339 (or (not (eq pop3-uidl-support t))
340 (memq (caar messages) uidl))
342 ;; don't download messages that are too large
343 (not (and pop3-maximum-message-size
344 (> (cdar messages) pop3-maximum-message-size)))
345 (not (and pop3-except-header-regexp
346 (string-match pop3-except-header-regexp
347 (pop3-top process (caar messages) 0)))))
348 (push (car messages) out))
349 (setq messages (cdr messages)))
350 (cons total (reverse out))))
352 (defun pop3-get-uidl (process)
353 "Use PROCESS to get a list of unread message numbers."
354 (let ((messages (pop3-uidl process)) uidl)
355 (if (or (null messages) (null pop3-uidl-support))
356 (setq pop3-uidl-support nil)
357 (setq pop3-uidl-support t)
360 (when (file-readable-p pop3-uidl-file-name)
361 (insert-file-contents pop3-uidl-file-name))
362 (goto-char (point-min))
363 (while (looking-at "\\([^ \n\t]+\\)")
364 (set (intern (match-string 1) pop3-uidl-obarray)
368 (dolist (message (cdr messages))
369 (if (setq uidl (intern-soft (cdr message) pop3-uidl-obarray))
370 (setcar (symbol-value uidl) (car message))
371 (set (intern (cdr message) pop3-uidl-obarray)
372 (cons (car message) nil))))
373 (pop3-get-unread-message-numbers))
376 (defun pop3-get-unread-message-numbers ()
377 "Return a sorted list of unread msg numbers to retrieve."
379 (mapatoms (lambda (atom)
380 (if (not (cdr (symbol-value atom)))
381 (push (car (symbol-value atom)) nums)))
385 (defun pop3-save-uidls ()
386 "Save the updated UIDLs to disk for use next time."
387 (when (and pop3-leave-mail-on-server
388 ;; UIDL hash table is non-empty
389 (let ((len (length pop3-uidl-obarray)))
391 (setq len (if (symbolp (aref pop3-uidl-obarray (1- len)))
394 (when (file-readable-p pop3-uidl-file-name)
395 (copy-file pop3-uidl-file-name
396 (concat pop3-uidl-file-name ".old")
397 'overwrite 'keeptime))
399 (with-temp-file pop3-uidl-file-name
402 (when (car (symbol-value atom))
403 (insert (format "%s\n" atom))))
404 pop3-uidl-obarray)))))
409 ;; AUTHORIZATION STATE
411 (defun pop3-user (process user)
412 "Send USER information to POP3 server."
413 (pop3-send-command process (format "USER %s" user))
414 (let ((response (pop3-read-response process t)))
415 (if (not (and response (string-match "+OK" response)))
416 (error (format "USER %s not valid." user)))))
418 (defun pop3-pass (process)
419 "Send authentication information to the server."
420 (pop3-send-command process (format "PASS %s" pop3-password))
421 (let ((response (pop3-read-response process t)))
422 (if (not (and response (string-match "+OK" response)))
423 (pop3-quit process))))
425 (autoload 'md5 "md5")
427 (defun pop3-apop (process user)
428 "Send alternate authentication information to the server."
429 (let ((hash (md5 (concat pop3-timestamp pop3-password))))
430 (pop3-send-command process (format "APOP %s %s" user hash))
431 (let ((response (pop3-read-response process t)))
432 (if (not (and response (string-match "+OK" response)))
433 (pop3-quit process)))))
435 (defun pop3-stls (process)
436 "Query whether TLS extension is supported"
437 (pop3-send-command process "STLS")
438 (let ((response (pop3-read-response process t)))
439 (if (not (and response (string-match "+OK" response)))
440 (pop3-quit process))))
444 (defun pop3-stat (process)
445 "Return the number of messages in the maildrop and the maildrop's size."
446 (pop3-send-command process "STAT")
447 (let ((response (pop3-read-response process t)))
448 (list (string-to-int (nth 1 (split-string response)))
449 (string-to-int (nth 2 (split-string response))))
452 (defun pop3-retr (process msg crashbuf)
453 "Retrieve message-id MSG to buffer CRASHBUF."
454 (pop3-send-command process (format "RETR %s" msg))
455 (pop3-read-response process)
457 (let ((region (pop3-get-extended-response process)))
458 (pop3-munge-message-separator (car region) (cadr region))
459 (append-to-buffer crashbuf (car region) (cadr region))
460 (delete-region (car region) (cadr region))
463 (defun pop3-dele (process msg)
464 "Mark message-id MSG as deleted."
465 (pop3-send-command process (format "DELE %s" msg))
466 (pop3-read-response process))
468 (defun pop3-noop (process msg)
470 (pop3-send-command process "NOOP")
471 (pop3-read-response process))
473 (defun pop3-last (process)
474 "Return highest accessed message-id number for the session."
475 (pop3-send-command process "LAST")
476 (let ((response (pop3-read-response process t)))
477 (string-to-int (nth 1 (split-string response)))
480 (defun pop3-rset (process)
481 "Remove all delete marks from current maildrop."
482 (pop3-send-command process "RSET")
483 (pop3-read-response process))
487 (defun pop3-quit (process)
488 "Close connection to POP3 server.
489 Tell server to remove all messages marked as deleted, unlock the maildrop,
490 and close the connection."
491 (pop3-send-command process "QUIT")
492 (pop3-read-response process t)
495 (set-buffer (process-buffer process))
496 (goto-char (point-max))
497 (delete-process process)
499 (when pop3-leave-mail-on-server
502 (when (car (symbol-value atom))
503 (unintern atom pop3-uidl-obarray)))
506 (defun pop3-uidl (process &optional msgno)
507 "Return the results of a UIDL command in PROCESS for optional MSGNO.
508 If UIDL is unsupported on this mail server or if msgno is invalid, return nil.
509 Otherwise, return a list in the form
511 (N (1 UIDL-1) (2 UIDL-2) ... (N UIDL-N))
515 N is an integer for the number of UIDLs returned (could be 0)
519 (pop3-send-command process (format "UIDL %d" msgno))
520 (pop3-send-command process "UIDL"))
522 (if (null (pop3-read-response process t))
523 nil ;; UIDL is not supported on this server
527 (apply 'narrow-to-region (pop3-get-extended-response process))
528 (goto-char (point-min))
529 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
530 (setq msgno (string-to-int (match-string 1))
531 uidl (match-string 2))
532 (push (cons msgno uidl) pairs)
533 (beginning-of-line 2))
534 (cons (length pairs) (nreverse pairs))
537 (defun pop3-list (process &optional msgno)
538 "Return the results of a LIST command for PROCESS and optional MSGNO.
539 If (optional) msgno is invalid, return nil. Otherwise, return a list
542 (N (1 LEN-1) (2 LEN-2) ... (N LEN-N))
546 N is an integer for the number of msg/len pairs (could be 0)
547 LEN-n is an integer."
549 (pop3-send-command process (format "LIST %d" msgno))
550 (pop3-send-command process "LIST"))
552 (if (null (pop3-read-response process t))
553 nil ;; MSGNO is not valid number
557 (apply 'narrow-to-region (pop3-get-extended-response process))
558 (goto-char (point-min))
559 (while (looking-at "\\([^ \n\t]*\\) \\([^ \n\t]*\\)")
560 (setq msgno (string-to-int (match-string 1))
561 len (string-to-int (match-string 2)))
562 (push (cons msgno len) pairs)
563 (beginning-of-line 2))
564 (cons (length pairs) (nreverse pairs))
567 (defun pop3-top (process msgno &optional lines)
568 "Return the top LINES of messages for PROCESS and MSGNO.
569 If msgno is invalid, return nil. Otherwise, return a string."
570 (pop3-send-command process (format "TOP %d %d" msgno (or lines 1)))
571 (if (pop3-read-response process t)
572 nil ;; MSGNO is not valid number
574 (apply 'buffer-substring (pop3-get-extended-response process)))
579 (defun pop3-get-extended-response (process)
580 "Get the extended pop3 response in the PROCESS buffer."
581 (let ((start pop3-read-point) end)
582 (set-buffer (process-buffer process))
584 (while (not (re-search-forward "^\\.\r\n" nil t))
585 (accept-process-output process 3)
587 (setq pop3-read-point (point-marker))
588 (goto-char (match-beginning 0))
589 (setq end (point-marker))
590 (pop3-clean-region start end)
594 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
596 ;;; AUTHORIZATION STATE
598 ;; Initial TCP connection
600 ;; Restrictions: none
601 ;; Possible responses:
602 ;; +OK [POP3 server ready]
605 ;; Arguments: a server specific user-id (required)
606 ;; Restrictions: authorization state [after unsuccessful USER or PASS
607 ;; Possible responses:
608 ;; +OK [valid user-id]
609 ;; -ERR [invalid user-id]
612 ;; Arguments: a server/user-id specific password (required)
613 ;; Restrictions: authorization state, after successful USER
614 ;; Possible responses:
615 ;; +OK [maildrop locked and ready]
616 ;; -ERR [invalid password]
617 ;; -ERR [unable to lock maildrop]
621 ;; Restrictions: authorization state
622 ;; Possible responses:
623 ;; +OK [negotiation is ready]
624 ;; -ERR [security layer is already active]
626 ;;; TRANSACTION STATE
630 ;; Restrictions: transaction state
631 ;; Possible responses:
632 ;; +OK nn mm [# of messages, size of maildrop]
635 ;; Arguments: a message-id (optional)
636 ;; Restrictions: transaction state; msg must not be deleted
637 ;; Possible responses:
638 ;; +OK [scan listing follows]
639 ;; -ERR [no such message]
642 ;; Arguments: a message-id (required), number of lines (optional)
643 ;; Restrictions: transaction state; msg must not be deleted
644 ;; Possible responses:
645 ;; +OK [partial message listing follows]
646 ;; -ERR [no such message]
649 ;; Arguments: a message-id (optional)
650 ;; Restrictions: transaction state; msg must not be deleted
651 ;; Possible responses:
652 ;; +OK [uidl listing follows]
653 ;; -ERR [no such message]
656 ;; Arguments: a message-id (required)
657 ;; Restrictions: transaction state; msg must not be deleted
658 ;; Possible responses:
659 ;; +OK [message contents follow]
660 ;; -ERR [no such message]
663 ;; Arguments: a message-id (required)
664 ;; Restrictions: transaction state; msg must not be deleted
665 ;; Possible responses:
666 ;; +OK [message deleted]
667 ;; -ERR [no such message]
671 ;; Restrictions: transaction state
672 ;; Possible responses:
677 ;; Restrictions: transaction state
678 ;; Possible responses:
679 ;; +OK nn [highest numbered message accessed]
683 ;; Restrictions: transaction state
684 ;; Possible responses:
685 ;; +OK [all delete marks removed]
691 ;; Restrictions: none
692 ;; Possible responses:
693 ;; +OK [TCP connection closed]
697 ;;; pop3.el ends here