(rfc2231-parse-string): Support non-ascii chars.
[gnus] / lisp / 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 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 2, or (at your option)
15 ;; 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; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26
27 ;;; Commentary:
28
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.
33
34 ;; This program was inspired by Kyle E. Jones's vm-pop program.
35
36 ;;; Code:
37
38 (require 'mail-utils)
39
40 (defgroup pop3 nil
41   "Post Office Protocol."
42   :group 'mail
43   :group 'mail-source)
44
45 (defcustom pop3-maildrop (or (user-login-name)
46                              (getenv "LOGNAME")
47                              (getenv "USER"))
48   "*POP3 maildrop."
49   :version "22.1" ;; Oort Gnus
50   :type 'string
51   :group 'pop3)
52
53 (defcustom pop3-mailhost (or (getenv "MAILHOST") ;; nil -> mismatch
54                              "pop3")
55   "*POP3 mailhost."
56   :version "22.1" ;; Oort Gnus
57   :type 'string
58   :group 'pop3)
59
60 (defcustom pop3-port 110
61   "*POP3 port."
62   :version "22.1" ;; Oort Gnus
63   :type 'number
64   :group 'pop3)
65
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
69   :type 'boolean
70   :group 'pop3)
71
72 ;; Should this be customizable?
73 (defvar pop3-password nil
74   "*Password to use when connecting to POP server.")
75
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
83   :group 'pop3)
84
85 (defcustom pop3-leave-mail-on-server nil
86   "*Non-nil if the mail is to be left on the POP server after fetching.
87
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 the whole thing can fall apart and leave you
93 with a corrupt mailbox."
94   :version "22.1" ;; Oort Gnus
95   :type 'boolean
96   :group 'pop3)
97
98 (defvar pop3-timestamp nil
99   "Timestamp returned when initially connected to the POP server.
100 Used for APOP authentication.")
101
102 (defvar pop3-read-point nil)
103 (defvar pop3-debug nil)
104
105 ;; Borrowed from nnheader-accept-process-output in nnheader.el.
106 (defvar pop3-read-timeout
107   (if (string-match "windows-nt\\|os/2\\|emx\\|cygwin"
108                     (symbol-name system-type))
109       ;; http://thread.gmane.org/v9655t3pjo.fsf@marauder.physik.uni-ulm.de
110       ;;
111       ;; IIRC, values lower than 1.0 didn't/don't work on Windows/DOS.
112       ;;
113       ;; There should probably be a runtime test to determine the timing
114       ;; resolution, or a primitive to report it.  I don't know off-hand
115       ;; what's possible.  Perhaps better, maybe the Windows/DOS primitive
116       ;; could round up non-zero timeouts to a minimum of 1.0?
117       1.0
118     0.1)
119   "How long pop3 should wait between checking for the end of output.
120 Shorter values mean quicker response, but are more CPU intensive.")
121
122 ;; Borrowed from nnheader-accept-process-output in nnheader.el.
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           (if pop3-debug (sit-for 1) (sit-for 0.1))) ; why?
170       (pop3-quit process))
171     (kill-buffer crashbuf))
172   t)
173
174 (defun pop3-get-message-count ()
175   "Return the number of messages in the maildrop."
176   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
177          message-count
178          (pop3-password pop3-password))
179     ;; for debugging only
180     (if pop3-debug (switch-to-buffer (process-buffer process)))
181     ;; query for password
182     (if (and pop3-password-required (not pop3-password))
183         (setq pop3-password
184               (read-passwd (format "Password for %s: " pop3-maildrop))))
185     (cond ((equal 'apop pop3-authentication-scheme)
186            (pop3-apop process pop3-maildrop))
187           ((equal 'pass pop3-authentication-scheme)
188            (pop3-user process pop3-maildrop)
189            (pop3-pass process))
190           (t (error "Invalid POP3 authentication scheme")))
191     (setq message-count (car (pop3-stat process)))
192     (pop3-quit process)
193     message-count))
194
195 (autoload 'open-tls-stream "tls")
196 (autoload 'starttls-open-stream "starttls")
197
198 (defcustom pop3-stream-type nil
199   "*Transport security type for POP3 connexions.
200 This may be either nil (plain connexion), `ssl' (use an
201 SSL/TSL-secured stream) or `starttls' (use the starttls mechanism
202 to turn on TLS security after opening the stream).  However, if
203 this is nil, `ssl' is assumed for connexions to port
204 995 (pop3s)."
205   :version "23.1"                       ; fixme?
206   :group 'pop3
207   :type '(choice (const :tag "Plain" nil)
208                  (const :tag "SSL/TLS" ssl)
209                  (const starttls)))
210
211 (defun pop3-open-server (mailhost port)
212   "Open TCP connection to MAILHOST on PORT.
213 Returns the process associated with the connection."
214   (let ((coding-system-for-read 'binary)
215         (coding-system-for-write 'binary)
216         process)
217     (save-excursion
218       (set-buffer (get-buffer-create (concat " trace of POP session to "
219                                              mailhost)))
220       (erase-buffer)
221       (setq pop3-read-point (point-min))
222       (setq process
223             (cond
224              ((or (eq pop3-stream-type 'ssl)
225                   (and (not pop3-stream-type) (= port 995))) ; pop3s
226               (let ((process (open-tls-stream "POP" (current-buffer)
227                                               mailhost port)))
228                 (when process
229                   ;; There's a load of info printed that needs deleting.
230                   (while (when (memq (process-status process) '(open run))
231                            (pop3-accept-process-output process)
232                            (goto-char (point-max))
233                            (forward-line -1)
234                            (if (looking-at "\\+OK")
235                                (delete-region (point-min) (point))
236                              (pop3-quit process)
237                              (error "POP SSL connexion failed"))))
238                   process)))
239              ((eq pop3-stream-type 'starttls)
240               (let ((process (starttls-open-stream "POP" (current-buffer)
241                                                    mailhost port)))
242                 (pop3-send-command process "STLS")
243                 (let ((response (pop3-read-response process t)))
244                   (if (and response (string-match "+OK" response))
245                       (starttls-negotiate process)
246                     (pop3-quit process)
247                     (error "POP server doesn't support starttls")))
248                 process))
249              (t 
250               (open-network-stream "POP" (current-buffer) mailhost port))))
251       (let ((response (pop3-read-response process t)))
252         (setq pop3-timestamp
253               (substring response (or (string-match "<" response) 0)
254                          (+ 1 (or (string-match ">" response) -1)))))
255       process)))
256
257 ;; Support functions
258
259 (defun pop3-process-filter (process output)
260   (save-excursion
261     (set-buffer (process-buffer process))
262     (goto-char (point-max))
263     (insert output)))
264
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")))
274
275 (defun pop3-read-response (process &optional return)
276   "Read the response from the server.
277 Return the response string if optional second argument is non-nil."
278   (let ((case-fold-search nil)
279         match-end)
280     (save-excursion
281       (set-buffer (process-buffer process))
282       (goto-char pop3-read-point)
283       (while (and (memq (process-status process) '(open run))
284                   (not (search-forward "\r\n" nil t)))
285         (pop3-accept-process-output process)
286         (goto-char pop3-read-point))
287       (setq match-end (point))
288       (goto-char pop3-read-point)
289       (if (looking-at "-ERR")
290           (error (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)
294           (if return
295               (buffer-substring (point) match-end)
296             t)
297           )))))
298
299 (defun pop3-clean-region (start end)
300   (setq end (set-marker (make-marker) end))
301   (save-excursion
302     (goto-char start)
303     (while (and (< (point) end) (search-forward "\r\n" end t))
304       (replace-match "\n" t t))
305     (goto-char start)
306     (while (and (< (point) end) (re-search-forward "^\\." end t))
307       (replace-match "" t t)
308       (forward-char)))
309   (set-marker end nil))
310
311 (eval-when-compile (defvar parse-time-months))
312
313 ;; Copied from message-make-date.
314 (defun pop3-make-date (&optional now)
315   "Make a valid date header.
316 If NOW, use that time instead."
317   (require 'parse-time)
318   (let* ((now (or now (current-time)))
319          (zone (nth 8 (decode-time now)))
320          (sign "+"))
321     (when (< zone 0)
322       (setq sign "-")
323       (setq zone (- zone)))
324     (concat
325      (format-time-string "%d" now)
326      ;; The month name of the %b spec is locale-specific.  Pfff.
327      (format " %s "
328              (capitalize (car (rassoc (nth 4 (decode-time now))
329                                       parse-time-months))))
330      (format-time-string "%Y %H:%M:%S " now)
331      ;; We do all of this because XEmacs doesn't have the %z spec.
332      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
333
334 (defun pop3-munge-message-separator (start end)
335   "Check to see if a message separator exists.  If not, generate one."
336   (save-excursion
337     (save-restriction
338       (narrow-to-region start end)
339       (goto-char (point-min))
340       (if (not (or (looking-at "From .?") ; Unix mail
341                    (looking-at "\001\001\001\001\n") ; MMDF
342                    (looking-at "BABYL OPTIONS:") ; Babyl
343                    ))
344           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
345                  (tdate (mail-fetch-field "Date"))
346                  (date (split-string (or (and tdate
347                                               (not (string= "" tdate))
348                                               tdate)
349                                          (pop3-make-date))
350                                      " "))
351                  (From_))
352             ;; sample date formats I have seen
353             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
354             ;; Date: 08 Jul 1996 23:22:24 -0400
355             ;; should be
356             ;; Tue Jul 9 09:04:21 1996
357
358             ;; Fixme: This should use timezone on the date field contents.
359             (setq date
360                   (cond ((not date)
361                          "Tue Jan 1 00:00:0 1900")
362                         ((string-match "[A-Z]" (nth 0 date))
363                          (format "%s %s %s %s %s"
364                                  (nth 0 date) (nth 2 date) (nth 1 date)
365                                  (nth 4 date) (nth 3 date)))
366                         (t
367                          ;; this really needs to be better but I don't feel
368                          ;; like writing a date to day converter.
369                          (format "Sun %s %s %s %s"
370                                  (nth 1 date) (nth 0 date)
371                                  (nth 3 date) (nth 2 date)))
372                         ))
373             (setq From_ (format "\nFrom %s  %s\n" from date))
374             (while (string-match "," From_)
375               (setq From_ (concat (substring From_ 0 (match-beginning 0))
376                                   (substring From_ (match-end 0)))))
377             (goto-char (point-min))
378             (insert From_)
379             (if (search-forward "\n\n" nil t)
380                 nil
381               (goto-char (point-max))
382               (insert "\n"))
383             (narrow-to-region (point) (point-max))
384             (let ((size (- (point-max) (point-min))))
385               (goto-char (point-min))
386               (widen)
387               (forward-line -1)
388               (insert (format "Content-Length: %s\n" size)))
389             )))))
390
391 ;; The Command Set
392
393 ;; AUTHORIZATION STATE
394
395 (defun pop3-user (process user)
396   "Send USER information to POP3 server."
397   (pop3-send-command process (format "USER %s" user))
398   (let ((response (pop3-read-response process t)))
399     (if (not (and response (string-match "+OK" response)))
400         (error "USER %s not valid" user))))
401
402 (defun pop3-pass (process)
403   "Send authentication information to the server."
404   (pop3-send-command process (format "PASS %s" pop3-password))
405   (let ((response (pop3-read-response process t)))
406     (if (not (and response (string-match "+OK" response)))
407         (pop3-quit process))))
408
409 (defun pop3-apop (process user)
410   "Send alternate authentication information to the server."
411   (let ((pass pop3-password))
412     (if (and pop3-password-required (not pass))
413         (setq pass
414               (read-passwd (format "Password for %s: " pop3-maildrop))))
415     (if pass
416         (let ((hash (md5 (concat pop3-timestamp pass) nil nil 'binary)))
417           (pop3-send-command process (format "APOP %s %s" user hash))
418           (let ((response (pop3-read-response process t)))
419             (if (not (and response (string-match "+OK" response)))
420                 (pop3-quit process)))))
421     ))
422
423 ;; TRANSACTION STATE
424
425 (defun pop3-stat (process)
426   "Return the number of messages in the maildrop and the maildrop's size."
427   (pop3-send-command process "STAT")
428   (let ((response (pop3-read-response process t)))
429     (list (string-to-number (nth 1 (split-string response " ")))
430           (string-to-number (nth 2 (split-string response " "))))
431     ))
432
433 (defun pop3-list (process &optional msg)
434   "Scan listing of available messages.
435 This function currently does nothing.")
436
437 (defun pop3-retr (process msg crashbuf)
438   "Retrieve message-id MSG to buffer CRASHBUF."
439   (pop3-send-command process (format "RETR %s" msg))
440   (pop3-read-response process)
441   (let ((start pop3-read-point) end)
442     (save-excursion
443       (set-buffer (process-buffer process))
444       (while (not (re-search-forward "^\\.\r\n" nil t))
445         (pop3-accept-process-output process)
446         (goto-char start))
447       (setq pop3-read-point (point-marker))
448       ;; this code does not seem to work for some POP servers...
449       ;; and I cannot figure out why not.
450       ;;      (goto-char (match-beginning 0))
451       ;;      (backward-char 2)
452       ;;      (if (not (looking-at "\r\n"))
453       ;;          (insert "\r\n"))
454       ;;      (re-search-forward "\\.\r\n")
455       (goto-char (match-beginning 0))
456       (setq end (point-marker))
457       (pop3-clean-region start end)
458       (pop3-munge-message-separator start end)
459       (save-excursion
460         (set-buffer crashbuf)
461         (erase-buffer))
462       (copy-to-buffer crashbuf start end)
463       (delete-region start end)
464       )))
465
466 (defun pop3-dele (process msg)
467   "Mark message-id MSG as deleted."
468   (pop3-send-command process (format "DELE %s" msg))
469   (pop3-read-response process))
470
471 (defun pop3-noop (process msg)
472   "No-operation."
473   (pop3-send-command process "NOOP")
474   (pop3-read-response process))
475
476 (defun pop3-last (process)
477   "Return highest accessed message-id number for the session."
478   (pop3-send-command process "LAST")
479   (let ((response (pop3-read-response process t)))
480     (string-to-number (nth 1 (split-string response " ")))
481     ))
482
483 (defun pop3-rset (process)
484   "Remove all delete marks from current maildrop."
485   (pop3-send-command process "RSET")
486   (pop3-read-response process))
487
488 ;; UPDATE
489
490 (defun pop3-quit (process)
491   "Close connection to POP3 server.
492 Tell server to remove all messages marked as deleted, unlock the maildrop,
493 and close the connection."
494   (pop3-send-command process "QUIT")
495   (pop3-read-response process t)
496   (if process
497       (save-excursion
498         (set-buffer (process-buffer process))
499         (goto-char (point-max))
500         (delete-process process))))
501 \f
502 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
503
504 ;;; AUTHORIZATION STATE
505
506 ;; Initial TCP connection
507 ;; Arguments: none
508 ;; Restrictions: none
509 ;; Possible responses:
510 ;;  +OK [POP3 server ready]
511
512 ;; USER name
513 ;; Arguments: a server specific user-id (required)
514 ;; Restrictions: authorization state [after unsuccessful USER or PASS
515 ;; Possible responses:
516 ;;  +OK [valid user-id]
517 ;;  -ERR [invalid user-id]
518
519 ;; PASS string
520 ;; Arguments: a server/user-id specific password (required)
521 ;; Restrictions: authorization state, after successful USER
522 ;; Possible responses:
523 ;;  +OK [maildrop locked and ready]
524 ;;  -ERR [invalid password]
525 ;;  -ERR [unable to lock maildrop]
526
527 ;; STLS      (RFC 2595)
528 ;; Arguments: none
529 ;; Restrictions: Only permitted in AUTHORIZATION state.
530 ;; Possible responses:
531 ;;  +OK
532 ;;  -ERR
533
534 ;;; TRANSACTION STATE
535
536 ;; STAT
537 ;; Arguments: none
538 ;; Restrictions: transaction state
539 ;; Possible responses:
540 ;;  +OK nn mm [# of messages, size of maildrop]
541
542 ;; LIST [msg]
543 ;; Arguments: a message-id (optional)
544 ;; Restrictions: transaction state; msg must not be deleted
545 ;; Possible responses:
546 ;;  +OK [scan listing follows]
547 ;;  -ERR [no such message]
548
549 ;; RETR msg
550 ;; Arguments: a message-id (required)
551 ;; Restrictions: transaction state; msg must not be deleted
552 ;; Possible responses:
553 ;;  +OK [message contents follow]
554 ;;  -ERR [no such message]
555
556 ;; DELE msg
557 ;; Arguments: a message-id (required)
558 ;; Restrictions: transaction state; msg must not be deleted
559 ;; Possible responses:
560 ;;  +OK [message deleted]
561 ;;  -ERR [no such message]
562
563 ;; NOOP
564 ;; Arguments: none
565 ;; Restrictions: transaction state
566 ;; Possible responses:
567 ;;  +OK
568
569 ;; LAST
570 ;; Arguments: none
571 ;; Restrictions: transaction state
572 ;; Possible responses:
573 ;;  +OK nn [highest numbered message accessed]
574
575 ;; RSET
576 ;; Arguments: none
577 ;; Restrictions: transaction state
578 ;; Possible responses:
579 ;;  +OK [all delete marks removed]
580
581 ;;; UPDATE STATE
582
583 ;; QUIT
584 ;; Arguments: none
585 ;; Restrictions: none
586 ;; Possible responses:
587 ;;  +OK [TCP connection closed]
588
589 (provide 'pop3)
590
591 ;;; arch-tag: 2facc142-1d74-498e-82af-4659b64cac12
592 ;;; pop3.el ends here