Add 2011 to FSF/AIST copyright years.
[bpt/emacs.git] / lisp / gnus / pop3.el
1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003,
4 ;; 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
5
6 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
7 ;; Maintainer: FSF
8 ;; Keywords: mail
9
10 ;; This file is part of GNU Emacs.
11
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.
16
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.
21
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/>.
24
25 ;;; Commentary:
26
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.
31
32 ;; This program was inspired by Kyle E. Jones's vm-pop program.
33
34 ;;; Code:
35
36 (require 'mail-utils)
37 (defvar parse-time-months)
38
39 (defgroup pop3 nil
40 "Post Office Protocol."
41 :group 'mail
42 :group 'mail-source)
43
44 (defcustom pop3-maildrop (or (user-login-name)
45 (getenv "LOGNAME")
46 (getenv "USER"))
47 "*POP3 maildrop."
48 :version "22.1" ;; Oort Gnus
49 :type 'string
50 :group 'pop3)
51
52 (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
53 "pop3")
54 "*POP3 mailhost."
55 :version "22.1" ;; Oort Gnus
56 :type 'string
57 :group 'pop3)
58
59 (defcustom pop3-port 110
60 "*POP3 port."
61 :version "22.1" ;; Oort Gnus
62 :type 'number
63 :group 'pop3)
64
65 (defcustom pop3-password-required t
66 "*Non-nil if a password is required when connecting to POP server."
67 :version "22.1" ;; Oort Gnus
68 :type 'boolean
69 :group 'pop3)
70
71 ;; Should this be customizable?
72 (defvar pop3-password nil
73 "*Password to use when connecting to POP server.")
74
75 (defcustom pop3-authentication-scheme 'pass
76 "*POP3 authentication scheme.
77 Defaults to `pass', for the standard USER/PASS authentication. The other
78 valid value is 'apop'."
79 :type '(choice (const :tag "Normal user/password" pass)
80 (const :tag "APOP" apop))
81 :version "22.1" ;; Oort Gnus
82 :group 'pop3)
83
84 (defcustom pop3-leave-mail-on-server nil
85 "*Non-nil if the mail is to be left on the POP server after fetching.
86
87 If `pop3-leave-mail-on-server' is non-nil the mail is to be left
88 on the POP server after fetching. Note that POP servers maintain
89 no state information between sessions, so what the client
90 believes is there and what is actually there may not match up.
91 If they do not, then you may get duplicate mails or the whole
92 thing can fall apart and leave you with a corrupt mailbox."
93 ;; We can't use the UILD support from XEmacs mail-lib or cvs.m17n.org:
94 ;; http://thread.gmane.org/v9lld8fml4.fsf@marauder.physik.uni-ulm.de
95 ;; http://thread.gmane.org/b9yy8hzy9ej.fsf@jpl.org
96 ;; Any volunteer to re-implement this?
97 :version "22.1" ;; Oort Gnus
98 :type 'boolean
99 :group 'pop3)
100
101 (defvar pop3-timestamp nil
102 "Timestamp returned when initially connected to the POP server.
103 Used for APOP authentication.")
104
105 (defvar pop3-read-point nil)
106 (defvar pop3-debug nil)
107
108 ;; Borrowed from nnheader-accept-process-output in nnheader.el. See the
109 ;; comments there for explanations about the values.
110
111 (eval-and-compile
112 (if (and (fboundp 'nnheader-accept-process-output)
113 (boundp 'nnheader-read-timeout))
114 (defalias 'pop3-accept-process-output 'nnheader-accept-process-output)
115 ;; Borrowed from `nnheader.el':
116 (defvar pop3-read-timeout
117 (if (string-match "windows-nt\\|os/2\\|emx\\|cygwin"
118 (symbol-name system-type))
119 1.0
120 0.01)
121 "How long pop3 should wait between checking for the end of output.
122 Shorter values mean quicker response, but are more CPU intensive.")
123 (defun pop3-accept-process-output (process)
124 (accept-process-output
125 process
126 (truncate pop3-read-timeout)
127 (truncate (* (- pop3-read-timeout
128 (truncate pop3-read-timeout))
129 1000))))))
130
131 (defun pop3-movemail (&optional crashbox)
132 "Transfer contents of a maildrop to the specified CRASHBOX."
133 (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
134 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
135 (crashbuf (get-buffer-create " *pop3-retr*"))
136 (n 1)
137 message-count
138 (pop3-password pop3-password))
139 ;; for debugging only
140 (if pop3-debug (switch-to-buffer (process-buffer process)))
141 ;; query for password
142 (if (and pop3-password-required (not pop3-password))
143 (setq pop3-password
144 (read-passwd (format "Password for %s: " pop3-maildrop))))
145 (cond ((equal 'apop pop3-authentication-scheme)
146 (pop3-apop process pop3-maildrop))
147 ((equal 'pass pop3-authentication-scheme)
148 (pop3-user process pop3-maildrop)
149 (pop3-pass process))
150 (t (error "Invalid POP3 authentication scheme")))
151 (setq message-count (car (pop3-stat process)))
152 (unwind-protect
153 (while (<= n message-count)
154 (message "Retrieving message %d of %d from %s..."
155 n message-count pop3-mailhost)
156 (pop3-retr process n crashbuf)
157 (save-excursion
158 (set-buffer crashbuf)
159 (let ((coding-system-for-write 'binary))
160 (write-region (point-min) (point-max) crashbox t 'nomesg))
161 (set-buffer (process-buffer process))
162 (while (> (buffer-size) 5000)
163 (goto-char (point-min))
164 (forward-line 50)
165 (delete-region (point-min) (point))))
166 (unless pop3-leave-mail-on-server
167 (pop3-dele process n))
168 (setq n (+ 1 n))
169 (pop3-accept-process-output process))
170 (when (and pop3-leave-mail-on-server
171 (> n 1))
172 (message "pop3.el doesn't support UIDL. Setting `pop3-leave-mail-on-server'
173 to %s might not give the result you'd expect." pop3-leave-mail-on-server)
174 (sit-for 1))
175 (pop3-quit process))
176 (kill-buffer crashbuf))
177 t)
178
179 (defun pop3-get-message-count ()
180 "Return the number of messages in the maildrop."
181 (let* ((process (pop3-open-server pop3-mailhost pop3-port))
182 message-count
183 (pop3-password pop3-password))
184 ;; for debugging only
185 (if pop3-debug (switch-to-buffer (process-buffer process)))
186 ;; query for password
187 (if (and pop3-password-required (not pop3-password))
188 (setq pop3-password
189 (read-passwd (format "Password for %s: " pop3-maildrop))))
190 (cond ((equal 'apop pop3-authentication-scheme)
191 (pop3-apop process pop3-maildrop))
192 ((equal 'pass pop3-authentication-scheme)
193 (pop3-user process pop3-maildrop)
194 (pop3-pass process))
195 (t (error "Invalid POP3 authentication scheme")))
196 (setq message-count (car (pop3-stat process)))
197 (pop3-quit process)
198 message-count))
199
200 (autoload 'open-tls-stream "tls")
201 (autoload 'starttls-open-stream "starttls")
202 (autoload 'starttls-negotiate "starttls") ; avoid warning
203
204 (defcustom pop3-stream-type nil
205 "*Transport security type for POP3 connexions.
206 This may be either nil (plain connexion), `ssl' (use an
207 SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
208 to turn on TLS security after opening the stream). However, if
209 this is nil, `ssl' is assumed for connexions to port
210 995 (pop3s)."
211 :version "23.1" ;; No Gnus
212 :group 'pop3
213 :type '(choice (const :tag "Plain" nil)
214 (const :tag "SSL/TLS" ssl)
215 (const starttls)))
216
217 (defun pop3-open-server (mailhost port)
218 "Open TCP connection to MAILHOST on PORT.
219 Returns the process associated with the connection."
220 (let ((coding-system-for-read 'binary)
221 (coding-system-for-write 'binary)
222 process)
223 (save-excursion
224 (set-buffer (get-buffer-create (concat " trace of POP session to "
225 mailhost)))
226 (erase-buffer)
227 (setq pop3-read-point (point-min))
228 (setq process
229 (cond
230 ((or (eq pop3-stream-type 'ssl)
231 (and (not pop3-stream-type) (member port '(995 "pop3s"))))
232 ;; gnutls-cli, openssl don't accept service names
233 (if (or (equal port "pop3s")
234 (null port))
235 (setq port 995))
236 (let ((process (open-tls-stream "POP" (current-buffer)
237 mailhost port)))
238 (when process
239 ;; There's a load of info printed that needs deleting.
240 (let ((again 't))
241 ;; repeat until
242 ;; - either we received the +OK line
243 ;; - or accept-process-output timed out without getting
244 ;; anything
245 (while (and again
246 (setq again (memq (process-status process)
247 '(open run))))
248 (setq again (pop3-accept-process-output process))
249 (goto-char (point-max))
250 (forward-line -1)
251 (cond ((looking-at "\\+OK")
252 (setq again nil)
253 (delete-region (point-min) (point)))
254 ((not again)
255 (pop3-quit process)
256 (error "POP SSL connexion failed")))))
257 process)))
258 ((eq pop3-stream-type 'starttls)
259 ;; gnutls-cli, openssl don't accept service names
260 (if (equal port "pop3")
261 (setq port 110))
262 ;; Delay STLS until server greeting is read (Bug#7438).
263 (starttls-open-stream "POP" (current-buffer)
264 mailhost (or port 110)))
265 (t
266 (open-network-stream "POP" (current-buffer) mailhost port))))
267 (let ((response (pop3-read-response process t)))
268 (setq pop3-timestamp
269 (substring response (or (string-match "<" response) 0)
270 (+ 1 (or (string-match ">" response) -1)))))
271 (when (eq pop3-stream-type 'starttls)
272 (pop3-send-command process "STLS")
273 (let ((response (pop3-read-response process t)))
274 (if (and response (string-match "+OK" response))
275 (starttls-negotiate process)
276 (pop3-quit process)
277 (error "POP server doesn't support starttls"))))
278 process)))
279
280 ;; Support functions
281
282 (defun pop3-process-filter (process output)
283 (save-excursion
284 (set-buffer (process-buffer process))
285 (goto-char (point-max))
286 (insert output)))
287
288 (defun pop3-send-command (process command)
289 (set-buffer (process-buffer process))
290 (goto-char (point-max))
291 ;; (if (= (aref command 0) ?P)
292 ;; (insert "PASS <omitted>\r\n")
293 ;; (insert command "\r\n"))
294 (setq pop3-read-point (point))
295 (goto-char (point-max))
296 (process-send-string process (concat command "\r\n")))
297
298 (defun pop3-read-response (process &optional return)
299 "Read the response from the server.
300 Return the response string if optional second argument is non-nil."
301 (let ((case-fold-search nil)
302 match-end)
303 (save-excursion
304 (set-buffer (process-buffer process))
305 (goto-char pop3-read-point)
306 (while (and (memq (process-status process) '(open run))
307 (not (search-forward "\r\n" nil t)))
308 (pop3-accept-process-output process)
309 (goto-char pop3-read-point))
310 (setq match-end (point))
311 (goto-char pop3-read-point)
312 (if (looking-at "-ERR")
313 (error "%s" (buffer-substring (point) (- match-end 2)))
314 (if (not (looking-at "+OK"))
315 (progn (setq pop3-read-point match-end) nil)
316 (setq pop3-read-point match-end)
317 (if return
318 (buffer-substring (point) match-end)
319 t)
320 )))))
321
322 (defun pop3-clean-region (start end)
323 (setq end (set-marker (make-marker) end))
324 (save-excursion
325 (goto-char start)
326 (while (and (< (point) end) (search-forward "\r\n" end t))
327 (replace-match "\n" t t))
328 (goto-char start)
329 (while (and (< (point) end) (re-search-forward "^\\." end t))
330 (replace-match "" t t)
331 (forward-char)))
332 (set-marker end nil))
333
334 ;; Copied from message-make-date.
335 (defun pop3-make-date (&optional now)
336 "Make a valid date header.
337 If NOW, use that time instead."
338 (require 'parse-time)
339 (let* ((now (or now (current-time)))
340 (zone (nth 8 (decode-time now)))
341 (sign "+"))
342 (when (< zone 0)
343 (setq sign "-")
344 (setq zone (- zone)))
345 (concat
346 (format-time-string "%d" now)
347 ;; The month name of the %b spec is locale-specific. Pfff.
348 (format " %s "
349 (capitalize (car (rassoc (nth 4 (decode-time now))
350 parse-time-months))))
351 (format-time-string "%Y %H:%M:%S " now)
352 ;; We do all of this because XEmacs doesn't have the %z spec.
353 (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
354
355 (defun pop3-munge-message-separator (start end)
356 "Check to see if a message separator exists. If not, generate one."
357 (save-excursion
358 (save-restriction
359 (narrow-to-region start end)
360 (goto-char (point-min))
361 (if (not (or (looking-at "From .?") ; Unix mail
362 (looking-at "\001\001\001\001\n") ; MMDF
363 (looking-at "BABYL OPTIONS:") ; Babyl
364 ))
365 (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
366 (tdate (mail-fetch-field "Date"))
367 (date (split-string (or (and tdate
368 (not (string= "" tdate))
369 tdate)
370 (pop3-make-date))
371 " "))
372 (From_))
373 ;; sample date formats I have seen
374 ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
375 ;; Date: 08 Jul 1996 23:22:24 -0400
376 ;; should be
377 ;; Tue Jul 9 09:04:21 1996
378
379 ;; Fixme: This should use timezone on the date field contents.
380 (setq date
381 (cond ((not date)
382 "Tue Jan 1 00:00:0 1900")
383 ((string-match "[A-Z]" (nth 0 date))
384 (format "%s %s %s %s %s"
385 (nth 0 date) (nth 2 date) (nth 1 date)
386 (nth 4 date) (nth 3 date)))
387 (t
388 ;; this really needs to be better but I don't feel
389 ;; like writing a date to day converter.
390 (format "Sun %s %s %s %s"
391 (nth 1 date) (nth 0 date)
392 (nth 3 date) (nth 2 date)))
393 ))
394 (setq From_ (format "\nFrom %s %s\n" from date))
395 (while (string-match "," From_)
396 (setq From_ (concat (substring From_ 0 (match-beginning 0))
397 (substring From_ (match-end 0)))))
398 (goto-char (point-min))
399 (insert From_)
400 (if (search-forward "\n\n" nil t)
401 nil
402 (goto-char (point-max))
403 (insert "\n"))
404 (narrow-to-region (point) (point-max))
405 (let ((size (- (point-max) (point-min))))
406 (goto-char (point-min))
407 (widen)
408 (forward-line -1)
409 (insert (format "Content-Length: %s\n" size)))
410 )))))
411
412 ;; The Command Set
413
414 ;; AUTHORIZATION STATE
415
416 (defun pop3-user (process user)
417 "Send USER information to POP3 server."
418 (pop3-send-command process (format "USER %s" user))
419 (let ((response (pop3-read-response process t)))
420 (if (not (and response (string-match "+OK" response)))
421 (error "USER %s not valid" user))))
422
423 (defun pop3-pass (process)
424 "Send authentication information to the server."
425 (pop3-send-command process (format "PASS %s" pop3-password))
426 (let ((response (pop3-read-response process t)))
427 (if (not (and response (string-match "+OK" response)))
428 (pop3-quit process))))
429
430 (defun pop3-apop (process user)
431 "Send alternate authentication information to the server."
432 (let ((pass pop3-password))
433 (if (and pop3-password-required (not pass))
434 (setq pass
435 (read-passwd (format "Password for %s: " pop3-maildrop))))
436 (if pass
437 (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
438 (pop3-send-command process (format "APOP %s %s" user hash))
439 (let ((response (pop3-read-response process t)))
440 (if (not (and response (string-match "+OK" response)))
441 (pop3-quit process)))))
442 ))
443
444 ;; TRANSACTION STATE
445
446 (defun pop3-stat (process)
447 "Return the number of messages in the maildrop and the maildrop's size."
448 (pop3-send-command process "STAT")
449 (let ((response (pop3-read-response process t)))
450 (list (string-to-number (nth 1 (split-string response " ")))
451 (string-to-number (nth 2 (split-string response " "))))
452 ))
453
454 (defun pop3-list (process &optional msg)
455 "Scan listing of available messages.
456 This function currently does nothing.")
457
458 (defun pop3-retr (process msg crashbuf)
459 "Retrieve message-id MSG to buffer CRASHBUF."
460 (pop3-send-command process (format "RETR %s" msg))
461 (pop3-read-response process)
462 (let ((start pop3-read-point) end)
463 (save-excursion
464 (set-buffer (process-buffer process))
465 (while (not (re-search-forward "^\\.\r\n" nil t))
466 (pop3-accept-process-output process)
467 (goto-char start))
468 (setq pop3-read-point (point-marker))
469 ;; this code does not seem to work for some POP servers...
470 ;; and I cannot figure out why not.
471 ;; (goto-char (match-beginning 0))
472 ;; (backward-char 2)
473 ;; (if (not (looking-at "\r\n"))
474 ;; (insert "\r\n"))
475 ;; (re-search-forward "\\.\r\n")
476 (goto-char (match-beginning 0))
477 (setq end (point-marker))
478 (pop3-clean-region start end)
479 (pop3-munge-message-separator start end)
480 (save-excursion
481 (set-buffer crashbuf)
482 (erase-buffer))
483 (copy-to-buffer crashbuf start end)
484 (delete-region start end)
485 )))
486
487 (defun pop3-dele (process msg)
488 "Mark message-id MSG as deleted."
489 (pop3-send-command process (format "DELE %s" msg))
490 (pop3-read-response process))
491
492 (defun pop3-noop (process msg)
493 "No-operation."
494 (pop3-send-command process "NOOP")
495 (pop3-read-response process))
496
497 (defun pop3-last (process)
498 "Return highest accessed message-id number for the session."
499 (pop3-send-command process "LAST")
500 (let ((response (pop3-read-response process t)))
501 (string-to-number (nth 1 (split-string response " ")))
502 ))
503
504 (defun pop3-rset (process)
505 "Remove all delete marks from current maildrop."
506 (pop3-send-command process "RSET")
507 (pop3-read-response process))
508
509 ;; UPDATE
510
511 (defun pop3-quit (process)
512 "Close connection to POP3 server.
513 Tell server to remove all messages marked as deleted, unlock the maildrop,
514 and close the connection."
515 (pop3-send-command process "QUIT")
516 (pop3-read-response process t)
517 (if process
518 (save-excursion
519 (set-buffer (process-buffer process))
520 (goto-char (point-max))
521 (delete-process process))))
522 \f
523 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
524
525 ;;; AUTHORIZATION STATE
526
527 ;; Initial TCP connection
528 ;; Arguments: none
529 ;; Restrictions: none
530 ;; Possible responses:
531 ;; +OK [POP3 server ready]
532
533 ;; USER name
534 ;; Arguments: a server specific user-id (required)
535 ;; Restrictions: authorization state [after unsuccessful USER or PASS
536 ;; Possible responses:
537 ;; +OK [valid user-id]
538 ;; -ERR [invalid user-id]
539
540 ;; PASS string
541 ;; Arguments: a server/user-id specific password (required)
542 ;; Restrictions: authorization state, after successful USER
543 ;; Possible responses:
544 ;; +OK [maildrop locked and ready]
545 ;; -ERR [invalid password]
546 ;; -ERR [unable to lock maildrop]
547
548 ;; STLS (RFC 2595)
549 ;; Arguments: none
550 ;; Restrictions: Only permitted in AUTHORIZATION state.
551 ;; Possible responses:
552 ;; +OK
553 ;; -ERR
554
555 ;;; TRANSACTION STATE
556
557 ;; STAT
558 ;; Arguments: none
559 ;; Restrictions: transaction state
560 ;; Possible responses:
561 ;; +OK nn mm [# of messages, size of maildrop]
562
563 ;; LIST [msg]
564 ;; Arguments: a message-id (optional)
565 ;; Restrictions: transaction state; msg must not be deleted
566 ;; Possible responses:
567 ;; +OK [scan listing follows]
568 ;; -ERR [no such message]
569
570 ;; RETR msg
571 ;; Arguments: a message-id (required)
572 ;; Restrictions: transaction state; msg must not be deleted
573 ;; Possible responses:
574 ;; +OK [message contents follow]
575 ;; -ERR [no such message]
576
577 ;; DELE msg
578 ;; Arguments: a message-id (required)
579 ;; Restrictions: transaction state; msg must not be deleted
580 ;; Possible responses:
581 ;; +OK [message deleted]
582 ;; -ERR [no such message]
583
584 ;; NOOP
585 ;; Arguments: none
586 ;; Restrictions: transaction state
587 ;; Possible responses:
588 ;; +OK
589
590 ;; LAST
591 ;; Arguments: none
592 ;; Restrictions: transaction state
593 ;; Possible responses:
594 ;; +OK nn [highest numbered message accessed]
595
596 ;; RSET
597 ;; Arguments: none
598 ;; Restrictions: transaction state
599 ;; Possible responses:
600 ;; +OK [all delete marks removed]
601
602 ;;; UPDATE STATE
603
604 ;; QUIT
605 ;; Arguments: none
606 ;; Restrictions: none
607 ;; Possible responses:
608 ;; +OK [TCP connection closed]
609
610 (provide 'pop3)
611
612 ;; arch-tag: 2facc142-1d74-498e-82af-4659b64cac12
613 ;;; pop3.el ends here