1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
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 3 of the License, or
15 ;; (at your option) any later version.
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. If not, see <http://www.gnu.org/licenses/>.
27 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
28 ;; are implemented. The LIST command has not been implemented due to lack
29 ;; of actual usefulness.
30 ;; The optional POP3 command TOP has not been implemented.
32 ;; This program was inspired by Kyle E. Jones's vm-pop program.
36 (eval-when-compile (require 'cl))
38 (defvar parse-time-months)
41 "Post Office Protocol."
45 (defcustom pop3-maildrop (or (user-login-name)
49 :version "22.1" ;; Oort Gnus
53 (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
56 :version "22.1" ;; Oort Gnus
60 (defcustom pop3-port 110
62 :version "22.1" ;; Oort Gnus
66 (defcustom pop3-password-required t
67 "*Non-nil if a password is required when connecting to POP server."
68 :version "22.1" ;; Oort Gnus
72 ;; Should this be customizable?
73 (defvar pop3-password nil
74 "*Password to use when connecting to POP server.")
76 (defcustom pop3-authentication-scheme 'pass
77 "*POP3 authentication scheme.
78 Defaults to `pass', for the standard USER/PASS authentication. The other
79 valid value is 'apop'."
80 :type '(choice (const :tag "Normal user/password" pass)
81 (const :tag "APOP" apop))
82 :version "22.1" ;; Oort Gnus
85 (defcustom pop3-leave-mail-on-server nil
86 "*Non-nil if the mail is to be left on the POP server after fetching.
88 If `pop3-leave-mail-on-server' is non-nil the mail is to be left
89 on the POP server after fetching. Note that POP servers maintain
90 no state information between sessions, so what the client
91 believes is there and what is actually there may not match up.
92 If they do not, then you may get duplicate mails or the whole
93 thing can fall apart and leave you with a corrupt mailbox."
94 ;; We can't use the UILD support from XEmacs mail-lib or cvs.m17n.org:
95 ;; http://thread.gmane.org/v9lld8fml4.fsf@marauder.physik.uni-ulm.de
96 ;; http://thread.gmane.org/b9yy8hzy9ej.fsf@jpl.org
97 ;; Any volunteer to re-implement this?
98 :version "22.1" ;; Oort Gnus
102 (defvar pop3-timestamp nil
103 "Timestamp returned when initially connected to the POP server.
104 Used for APOP authentication.")
106 (defvar pop3-read-point nil)
107 (defvar pop3-debug nil)
109 ;; Borrowed from nnheader-accept-process-output in nnheader.el. See the
110 ;; comments there for explanations about the values.
113 (if (and (fboundp 'nnheader-accept-process-output)
114 (boundp 'nnheader-read-timeout))
115 (defalias 'pop3-accept-process-output 'nnheader-accept-process-output)
116 ;; Borrowed from `nnheader.el':
117 (defvar pop3-read-timeout
118 (if (string-match "windows-nt\\|os/2\\|cygwin"
119 (symbol-name system-type))
122 "How long pop3 should wait between checking for the end of output.
123 Shorter values mean quicker response, but are more CPU intensive.")
124 (defun pop3-accept-process-output (process)
125 (accept-process-output
127 (truncate pop3-read-timeout)
128 (truncate (* (- pop3-read-timeout
129 (truncate pop3-read-timeout))
133 (defun pop3-movemail (file)
134 "Transfer contents of a maildrop to the specified FILE.
135 Use streaming commands."
136 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
137 message-count message-total-size)
139 (with-current-buffer (process-buffer process)
140 (let ((size (pop3-stat process)))
141 (setq message-count (car size)
142 message-total-size (cadr size)))
143 (when (plusp message-count)
144 (pop3-send-streaming-command
145 process "RETR" message-count message-total-size)
146 (pop3-write-to-file file)
147 (unless pop3-leave-mail-on-server
148 (pop3-send-streaming-command
149 process "DELE" message-count nil))))
153 (defun pop3-send-streaming-command (process command count total-size)
157 (process-send-string process (format "%s %d\r\n" command i))
158 ;; Only do 100 messages at a time to avoid pipe stalls.
159 (when (zerop (% i 100))
160 (pop3-wait-for-messages process i total-size))
162 (pop3-wait-for-messages process count total-size))
164 (defun pop3-wait-for-messages (process count total-size)
165 (while (< (pop3-number-of-responses total-size) count)
167 (message "pop3 retrieved %dKB (%d%%)"
168 (truncate (/ (buffer-size) 1000))
169 (truncate (* (/ (* (buffer-size) 1.0)
171 (pop3-accept-process-output process)))
173 (defun pop3-write-to-file (file)
174 (let ((pop-buffer (current-buffer))
179 (setq temp-buffer (current-buffer))
180 (with-current-buffer pop-buffer
181 (goto-char (point-min))
182 (while (re-search-forward "^\\+OK" nil t)
185 (when (re-search-forward "^\\.\r?\n" nil t)
189 (with-current-buffer temp-buffer
190 (goto-char (point-max))
191 (let ((hstart (point)))
192 (insert-buffer-substring pop-buffer beg end)
193 (pop3-clean-region hstart (point))
194 (goto-char (point-max))
195 (pop3-munge-message-separator hstart (point))
196 (goto-char (point-max))))))
197 (let ((coding-system-for-write 'binary))
198 (goto-char (point-min))
199 ;; Check whether something inserted a newline at the start and
203 (write-region (point-min) (point-max) file nil 'nomesg)))))
205 (defun pop3-number-of-responses (endp)
208 (goto-char (point-min))
209 (while (or (and (re-search-forward "^\\+OK" nil t)
211 (re-search-forward "^\\.\r?\n" nil t)))
212 (re-search-forward "^-ERR " nil t))
216 (defun pop3-logon (process)
217 (let ((pop3-password pop3-password))
218 ;; for debugging only
219 (if pop3-debug (switch-to-buffer (process-buffer process)))
220 ;; query for password
221 (if (and pop3-password-required (not pop3-password))
223 (read-passwd (format "Password for %s: " pop3-maildrop))))
224 (cond ((equal 'apop pop3-authentication-scheme)
225 (pop3-apop process pop3-maildrop))
226 ((equal 'pass pop3-authentication-scheme)
227 (pop3-user process pop3-maildrop)
229 (t (error "Invalid POP3 authentication scheme")))))
231 (defun pop3-get-message-count ()
232 "Return the number of messages in the maildrop."
233 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
235 (pop3-password pop3-password))
236 ;; for debugging only
237 (if pop3-debug (switch-to-buffer (process-buffer process)))
238 ;; query for password
239 (if (and pop3-password-required (not pop3-password))
241 (read-passwd (format "Password for %s: " pop3-maildrop))))
242 (cond ((equal 'apop pop3-authentication-scheme)
243 (pop3-apop process pop3-maildrop))
244 ((equal 'pass pop3-authentication-scheme)
245 (pop3-user process pop3-maildrop)
247 (t (error "Invalid POP3 authentication scheme")))
248 (setq message-count (car (pop3-stat process)))
252 (autoload 'open-tls-stream "tls")
253 (autoload 'starttls-open-stream "starttls")
254 (autoload 'starttls-negotiate "starttls") ; avoid warning
256 (defcustom pop3-stream-type nil
257 "*Transport security type for POP3 connexions.
258 This may be either nil (plain connexion), `ssl' (use an
259 SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
260 to turn on TLS security after opening the stream). However, if
261 this is nil, `ssl' is assumed for connexions to port
263 :version "23.1" ;; No Gnus
265 :type '(choice (const :tag "Plain" nil)
266 (const :tag "SSL/TLS" ssl)
270 (if (fboundp 'set-process-query-on-exit-flag)
271 (defalias 'pop3-set-process-query-on-exit-flag
272 'set-process-query-on-exit-flag)
273 (defalias 'pop3-set-process-query-on-exit-flag
274 'process-kill-without-query)))
276 (defun pop3-open-server (mailhost port)
277 "Open TCP connection to MAILHOST on PORT.
278 Returns the process associated with the connection."
279 (let ((coding-system-for-read 'binary)
280 (coding-system-for-write 'binary)
283 (get-buffer-create (concat " trace of POP session to "
286 (setq pop3-read-point (point-min))
289 ((or (eq pop3-stream-type 'ssl)
290 (and (not pop3-stream-type) (member port '(995 "pop3s"))))
291 ;; gnutls-cli, openssl don't accept service names
292 (if (or (equal port "pop3s")
295 (let ((process (open-tls-stream "POP" (current-buffer)
298 ;; There's a load of info printed that needs deleting.
301 ;; - either we received the +OK line
302 ;; - or accept-process-output timed out without getting
305 (setq again (memq (process-status process)
307 (setq again (pop3-accept-process-output process))
308 (goto-char (point-max))
310 (cond ((looking-at "\\+OK")
312 (delete-region (point-min) (point)))
315 (error "POP SSL connexion failed")))))
317 ((eq pop3-stream-type 'starttls)
318 ;; gnutls-cli, openssl don't accept service names
319 (if (equal port "pop3")
321 (let ((process (starttls-open-stream "POP" (current-buffer)
322 mailhost (or port 110))))
323 (pop3-send-command process "STLS")
324 (let ((response (pop3-read-response process t)))
325 (if (and response (string-match "+OK" response))
326 (starttls-negotiate process)
328 (error "POP server doesn't support starttls")))
331 (open-network-stream "POP" (current-buffer) mailhost port))))
332 (let ((response (pop3-read-response process t)))
334 (substring response (or (string-match "<" response) 0)
335 (+ 1 (or (string-match ">" response) -1)))))
336 (pop3-set-process-query-on-exit-flag process nil)
341 (defun pop3-send-command (process command)
342 (set-buffer (process-buffer process))
343 (goto-char (point-max))
344 ;; (if (= (aref command 0) ?P)
345 ;; (insert "PASS <omitted>\r\n")
346 ;; (insert command "\r\n"))
347 (setq pop3-read-point (point))
348 (goto-char (point-max))
349 (process-send-string process (concat command "\r\n")))
351 (defun pop3-read-response (process &optional return)
352 "Read the response from the server.
353 Return the response string if optional second argument is non-nil."
354 (let ((case-fold-search nil)
356 (with-current-buffer (process-buffer process)
357 (goto-char pop3-read-point)
358 (while (and (memq (process-status process) '(open run))
359 (not (search-forward "\r\n" nil t)))
360 (pop3-accept-process-output process)
361 (goto-char pop3-read-point))
362 (setq match-end (point))
363 (goto-char pop3-read-point)
364 (if (looking-at "-ERR")
365 (error "%s" (buffer-substring (point) (- match-end 2)))
366 (if (not (looking-at "+OK"))
367 (progn (setq pop3-read-point match-end) nil)
368 (setq pop3-read-point match-end)
370 (buffer-substring (point) match-end)
374 (defun pop3-clean-region (start end)
375 (setq end (set-marker (make-marker) end))
378 (while (and (< (point) end) (search-forward "\r\n" end t))
379 (replace-match "\n" t t))
381 (while (and (< (point) end) (re-search-forward "^\\." end t))
382 (replace-match "" t t)
384 (set-marker end nil))
386 ;; Copied from message-make-date.
387 (defun pop3-make-date (&optional now)
388 "Make a valid date header.
389 If NOW, use that time instead."
390 (require 'parse-time)
391 (let* ((now (or now (current-time)))
392 (zone (nth 8 (decode-time now)))
396 (setq zone (- zone)))
398 (format-time-string "%d" now)
399 ;; The month name of the %b spec is locale-specific. Pfff.
401 (capitalize (car (rassoc (nth 4 (decode-time now))
402 parse-time-months))))
403 (format-time-string "%Y %H:%M:%S " now)
404 ;; We do all of this because XEmacs doesn't have the %z spec.
405 (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
407 (defun pop3-munge-message-separator (start end)
408 "Check to see if a message separator exists. If not, generate one."
411 (narrow-to-region start end)
412 (goto-char (point-min))
413 (if (not (or (looking-at "From .?") ; Unix mail
414 (looking-at "\001\001\001\001\n") ; MMDF
415 (looking-at "BABYL OPTIONS:") ; Babyl
417 (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
418 (tdate (mail-fetch-field "Date"))
419 (date (split-string (or (and tdate
420 (not (string= "" tdate))
425 ;; sample date formats I have seen
426 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
427 ;; Date: 08 Jul 1996 23:22:24 -0400
429 ;; Tue Jul 9 09:04:21 1996
431 ;; Fixme: This should use timezone on the date field contents.
434 "Tue Jan 1 00:00:0 1900")
435 ((string-match "[A-Z]" (nth 0 date))
436 (format "%s %s %s %s %s"
437 (nth 0 date) (nth 2 date) (nth 1 date)
438 (nth 4 date) (nth 3 date)))
440 ;; this really needs to be better but I don't feel
441 ;; like writing a date to day converter.
442 (format "Sun %s %s %s %s"
443 (nth 1 date) (nth 0 date)
444 (nth 3 date) (nth 2 date)))
446 (setq From_ (format "\nFrom %s %s\n" from date))
447 (while (string-match "," From_)
448 (setq From_ (concat (substring From_ 0 (match-beginning 0))
449 (substring From_ (match-end 0)))))
450 (goto-char (point-min))
452 (if (search-forward "\n\n" nil t)
454 (goto-char (point-max))
456 (let ((size (- (point-max) (point))))
458 (insert (format "Content-Length: %s\n" size)))
463 ;; AUTHORIZATION STATE
465 (defun pop3-user (process user)
466 "Send USER information to POP3 server."
467 (pop3-send-command process (format "USER %s" user))
468 (let ((response (pop3-read-response process t)))
469 (if (not (and response (string-match "+OK" response)))
470 (error "USER %s not valid" user))))
472 (defun pop3-pass (process)
473 "Send authentication information to the server."
474 (pop3-send-command process (format "PASS %s" pop3-password))
475 (let ((response (pop3-read-response process t)))
476 (if (not (and response (string-match "+OK" response)))
477 (pop3-quit process))))
479 (defun pop3-apop (process user)
480 "Send alternate authentication information to the server."
481 (let ((pass pop3-password))
482 (if (and pop3-password-required (not pass))
484 (read-passwd (format "Password for %s: " pop3-maildrop))))
486 (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
487 (pop3-send-command process (format "APOP %s %s" user hash))
488 (let ((response (pop3-read-response process t)))
489 (if (not (and response (string-match "+OK" response)))
490 (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-number (nth 1 (split-string response " ")))
500 (string-to-number (nth 2 (split-string response " "))))
503 (defun pop3-list (process &optional msg)
504 "If MSG is nil, return an alist of (MESSAGE-ID . SIZE) pairs.
505 Otherwise, return the size of the message-id MSG"
506 (pop3-send-command process (if msg
507 (format "LIST %d" msg)
509 (let ((response (pop3-read-response process t)))
511 (string-to-number (nth 2 (split-string response " ")))
512 (let ((start pop3-read-point) end)
513 (with-current-buffer (process-buffer process)
514 (while (not (re-search-forward "^\\.\r\n" nil t))
515 (pop3-accept-process-output process)
517 (setq pop3-read-point (point-marker))
518 (goto-char (match-beginning 0))
519 (setq end (point-marker))
520 (mapcar #'(lambda (s) (let ((split (split-string s " ")))
521 (cons (string-to-number (nth 0 split))
522 (string-to-number (nth 1 split)))))
523 (split-string (buffer-substring start end) "\r\n" t)))))))
525 (defun pop3-retr (process msg crashbuf)
526 "Retrieve message-id MSG to buffer CRASHBUF."
527 (pop3-send-command process (format "RETR %s" msg))
528 (pop3-read-response process)
529 (let ((start pop3-read-point) end)
530 (with-current-buffer (process-buffer process)
531 (while (not (re-search-forward "^\\.\r\n" nil t))
532 (pop3-accept-process-output process)
534 (setq pop3-read-point (point-marker))
535 ;; this code does not seem to work for some POP servers...
536 ;; and I cannot figure out why not.
537 ;; (goto-char (match-beginning 0))
539 ;; (if (not (looking-at "\r\n"))
541 ;; (re-search-forward "\\.\r\n")
542 (goto-char (match-beginning 0))
543 (setq end (point-marker))
544 (pop3-clean-region start end)
545 (pop3-munge-message-separator start end)
546 (with-current-buffer crashbuf
548 (copy-to-buffer crashbuf start end)
549 (delete-region start end)
552 (defun pop3-dele (process msg)
553 "Mark message-id MSG as deleted."
554 (pop3-send-command process (format "DELE %s" msg))
555 (pop3-read-response process))
557 (defun pop3-noop (process msg)
559 (pop3-send-command process "NOOP")
560 (pop3-read-response process))
562 (defun pop3-last (process)
563 "Return highest accessed message-id number for the session."
564 (pop3-send-command process "LAST")
565 (let ((response (pop3-read-response process t)))
566 (string-to-number (nth 1 (split-string response " ")))
569 (defun pop3-rset (process)
570 "Remove all delete marks from current maildrop."
571 (pop3-send-command process "RSET")
572 (pop3-read-response process))
576 (defun pop3-quit (process)
577 "Close connection to POP3 server.
578 Tell server to remove all messages marked as deleted, unlock the maildrop,
579 and close the connection."
580 (pop3-send-command process "QUIT")
581 (pop3-read-response process t)
583 (with-current-buffer (process-buffer process)
584 (goto-char (point-max))
585 (delete-process process))))
587 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
589 ;;; AUTHORIZATION STATE
591 ;; Initial TCP connection
593 ;; Restrictions: none
594 ;; Possible responses:
595 ;; +OK [POP3 server ready]
598 ;; Arguments: a server specific user-id (required)
599 ;; Restrictions: authorization state [after unsuccessful USER or PASS
600 ;; Possible responses:
601 ;; +OK [valid user-id]
602 ;; -ERR [invalid user-id]
605 ;; Arguments: a server/user-id specific password (required)
606 ;; Restrictions: authorization state, after successful USER
607 ;; Possible responses:
608 ;; +OK [maildrop locked and ready]
609 ;; -ERR [invalid password]
610 ;; -ERR [unable to lock maildrop]
614 ;; Restrictions: Only permitted in AUTHORIZATION state.
615 ;; Possible responses:
619 ;;; TRANSACTION STATE
623 ;; Restrictions: transaction state
624 ;; Possible responses:
625 ;; +OK nn mm [# of messages, size of maildrop]
628 ;; Arguments: a message-id (optional)
629 ;; Restrictions: transaction state; msg must not be deleted
630 ;; Possible responses:
631 ;; +OK [scan listing follows]
632 ;; -ERR [no such message]
635 ;; Arguments: a message-id (required)
636 ;; Restrictions: transaction state; msg must not be deleted
637 ;; Possible responses:
638 ;; +OK [message contents follow]
639 ;; -ERR [no such message]
642 ;; Arguments: a message-id (required)
643 ;; Restrictions: transaction state; msg must not be deleted
644 ;; Possible responses:
645 ;; +OK [message deleted]
646 ;; -ERR [no such message]
650 ;; Restrictions: transaction state
651 ;; Possible responses:
656 ;; Restrictions: transaction state
657 ;; Possible responses:
658 ;; +OK nn [highest numbered message accessed]
662 ;; Restrictions: transaction state
663 ;; Possible responses:
664 ;; +OK [all delete marks removed]
670 ;; Restrictions: none
671 ;; Possible responses:
672 ;; +OK [TCP connection closed]
676 ;;; pop3.el ends here