f69c1d555f6bd06cf411ecfe11912cb09f8fc412
[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, 2004
4 ;;        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., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, 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 "21.4" ;; 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 "21.4" ;; Oort Gnus
57   :type 'string
58   :group 'pop3)
59
60 (defcustom pop3-port 110
61   "*POP3 port."
62   :version "21.4" ;; 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 "21.4" ;; 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.  Other valid
79 values are 'apop."
80   :version "21.4" ;; Oort Gnus
81   :type '(choice (const :tag "USER/PASS" pass)
82                  (const :tag "APOP" apop))
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   :version "21.4" ;; Oort Gnus
88   :type 'boolean
89   :group 'pop3)
90
91 (defvar pop3-timestamp nil
92   "Timestamp returned when initially connected to the POP server.
93 Used for APOP authentication.")
94
95 (defvar pop3-read-point nil)
96 (defvar pop3-debug nil)
97
98 ;; Borrowed from nnheader-accept-process-output in nnheader.el.
99 (defvar pop3-read-timeout
100   (if (string-match "windows-nt\\|os/2\\|emx\\|cygwin"
101                     (symbol-name system-type))
102       ;; http://thread.gmane.org/v9655t3pjo.fsf@marauder.physik.uni-ulm.de
103       ;;
104       ;; IIRC, values lower than 1.0 didn't/don't work on Windows/DOS.
105       ;;
106       ;; There should probably be a runtime test to determine the timing
107       ;; resolution, or a primitive to report it.  I don't know off-hand
108       ;; what's possible.  Perhaps better, maybe the Windows/DOS primitive
109       ;; could round up non-zero timeouts to a minimum of 1.0?
110       1.0
111     0.1)
112   "How long pop3 should wait between checking for the end of output.
113 Shorter values mean quicker response, but are more CPU intensive.")
114
115 ;; Borrowed from nnheader-accept-process-output in nnheader.el.
116 (defun pop3-accept-process-output (process)
117   (accept-process-output
118    process
119    (truncate pop3-read-timeout)
120    (truncate (* (- pop3-read-timeout
121                    (truncate pop3-read-timeout))
122                 1000))))
123
124 (defun pop3-movemail (&optional crashbox)
125   "Transfer contents of a maildrop to the specified CRASHBOX."
126   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
127   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
128          (crashbuf (get-buffer-create " *pop3-retr*"))
129          (n 1)
130          message-count
131          (pop3-password pop3-password))
132     ;; for debugging only
133     (if pop3-debug (switch-to-buffer (process-buffer process)))
134     ;; query for password
135     (if (and pop3-password-required (not pop3-password))
136         (setq pop3-password
137               (read-passwd (format "Password for %s: " pop3-maildrop))))
138     (cond ((equal 'apop pop3-authentication-scheme)
139            (pop3-apop process pop3-maildrop))
140           ((equal 'pass pop3-authentication-scheme)
141            (pop3-user process pop3-maildrop)
142            (pop3-pass process))
143           (t (error "Invalid POP3 authentication scheme")))
144     (setq message-count (car (pop3-stat process)))
145     (unwind-protect
146         (while (<= n message-count)
147           (message "Retrieving message %d of %d from %s..."
148                    n message-count pop3-mailhost)
149           (pop3-retr process n crashbuf)
150           (save-excursion
151             (set-buffer crashbuf)
152             (let ((coding-system-for-write 'binary))
153               (write-region (point-min) (point-max) crashbox t 'nomesg))
154             (set-buffer (process-buffer process))
155             (while (> (buffer-size) 5000)
156               (goto-char (point-min))
157               (forward-line 50)
158               (delete-region (point-min) (point))))
159           (unless pop3-leave-mail-on-server
160             (pop3-dele process n))
161           (setq n (+ 1 n))
162           (if pop3-debug (sit-for 1) (sit-for 0.1))
163           )
164       (pop3-quit process))
165     (kill-buffer crashbuf)
166     )
167   t)
168
169 (defun pop3-get-message-count ()
170   "Return the number of messages in the maildrop."
171   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
172          message-count
173          (pop3-password pop3-password))
174     ;; for debugging only
175     (if pop3-debug (switch-to-buffer (process-buffer process)))
176     ;; query for password
177     (if (and pop3-password-required (not pop3-password))
178         (setq pop3-password
179               (read-passwd (format "Password for %s: " pop3-maildrop))))
180     (cond ((equal 'apop pop3-authentication-scheme)
181            (pop3-apop process pop3-maildrop))
182           ((equal 'pass pop3-authentication-scheme)
183            (pop3-user process pop3-maildrop)
184            (pop3-pass process))
185           (t (error "Invalid POP3 authentication scheme")))
186     (setq message-count (car (pop3-stat process)))
187     (pop3-quit process)
188     message-count))
189
190 (defun pop3-open-server (mailhost port)
191   "Open TCP connection to MAILHOST on PORT.
192 Returns the process associated with the connection."
193   (let ((coding-system-for-read 'binary)
194         (coding-system-for-write 'binary)
195         process)
196     (save-excursion
197       (set-buffer (get-buffer-create (concat " trace of POP session to "
198                                              mailhost)))
199       (erase-buffer)
200       (setq pop3-read-point (point-min))
201       (setq process (open-network-stream "POP" (current-buffer) mailhost port))
202       (let ((response (pop3-read-response process t)))
203         (setq pop3-timestamp
204               (substring response (or (string-match "<" response) 0)
205                          (+ 1 (or (string-match ">" response) -1)))))
206       process)))
207
208 ;; Support functions
209
210 (defun pop3-process-filter (process output)
211   (save-excursion
212     (set-buffer (process-buffer process))
213     (goto-char (point-max))
214     (insert output)))
215
216 (defun pop3-send-command (process command)
217   (set-buffer (process-buffer process))
218   (goto-char (point-max))
219   ;; (if (= (aref command 0) ?P)
220   ;;     (insert "PASS <omitted>\r\n")
221   ;;   (insert command "\r\n"))
222   (setq pop3-read-point (point))
223   (goto-char (point-max))
224   (process-send-string process (concat command "\r\n")))
225
226 (defun pop3-read-response (process &optional return)
227   "Read the response from the server.
228 Return the response string if optional second argument is non-nil."
229   (let ((case-fold-search nil)
230         match-end)
231     (save-excursion
232       (set-buffer (process-buffer process))
233       (goto-char pop3-read-point)
234       (while (and (memq (process-status process) '(open run))
235                   (not (search-forward "\r\n" nil t)))
236         (pop3-accept-process-output process)
237         (goto-char pop3-read-point))
238       (setq match-end (point))
239       (goto-char pop3-read-point)
240       (if (looking-at "-ERR")
241           (error (buffer-substring (point) (- match-end 2)))
242         (if (not (looking-at "+OK"))
243             (progn (setq pop3-read-point match-end) nil)
244           (setq pop3-read-point match-end)
245           (if return
246               (buffer-substring (point) match-end)
247             t)
248           )))))
249
250 (defun pop3-clean-region (start end)
251   (setq end (set-marker (make-marker) end))
252   (save-excursion
253     (goto-char start)
254     (while (and (< (point) end) (search-forward "\r\n" end t))
255       (replace-match "\n" t t))
256     (goto-char start)
257     (while (and (< (point) end) (re-search-forward "^\\." end t))
258       (replace-match "" t t)
259       (forward-char)))
260   (set-marker end nil))
261
262 (eval-when-compile (defvar parse-time-months))
263
264 ;; Copied from message-make-date.
265 (defun pop3-make-date (&optional now)
266   "Make a valid date header.
267 If NOW, use that time instead."
268   (require 'parse-time)
269   (let* ((now (or now (current-time)))
270          (zone (nth 8 (decode-time now)))
271          (sign "+"))
272     (when (< zone 0)
273       (setq sign "-")
274       (setq zone (- zone)))
275     (concat
276      (format-time-string "%d" now)
277      ;; The month name of the %b spec is locale-specific.  Pfff.
278      (format " %s "
279              (capitalize (car (rassoc (nth 4 (decode-time now))
280                                       parse-time-months))))
281      (format-time-string "%Y %H:%M:%S " now)
282      ;; We do all of this because XEmacs doesn't have the %z spec.
283      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
284
285 (defun pop3-munge-message-separator (start end)
286   "Check to see if a message separator exists.  If not, generate one."
287   (save-excursion
288     (save-restriction
289       (narrow-to-region start end)
290       (goto-char (point-min))
291       (if (not (or (looking-at "From .?") ; Unix mail
292                    (looking-at "\001\001\001\001\n") ; MMDF
293                    (looking-at "BABYL OPTIONS:") ; Babyl
294                    ))
295           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
296                  (tdate (mail-fetch-field "Date"))
297                  (date (split-string (or (and tdate
298                                               (not (string= "" tdate))
299                                               tdate)
300                                          (pop3-make-date))
301                                      " "))
302                  (From_))
303             ;; sample date formats I have seen
304             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
305             ;; Date: 08 Jul 1996 23:22:24 -0400
306             ;; should be
307             ;; Tue Jul 9 09:04:21 1996
308             (setq date
309                   (cond ((not date)
310                          "Tue Jan 1 00:00:0 1900")
311                         ((string-match "[A-Z]" (nth 0 date))
312                          (format "%s %s %s %s %s"
313                                  (nth 0 date) (nth 2 date) (nth 1 date)
314                                  (nth 4 date) (nth 3 date)))
315                         (t
316                          ;; this really needs to be better but I don't feel
317                          ;; like writing a date to day converter.
318                          (format "Sun %s %s %s %s"
319                                  (nth 1 date) (nth 0 date)
320                                  (nth 3 date) (nth 2 date)))
321                         ))
322             (setq From_ (format "\nFrom %s  %s\n" from date))
323             (while (string-match "," From_)
324               (setq From_ (concat (substring From_ 0 (match-beginning 0))
325                                   (substring From_ (match-end 0)))))
326             (goto-char (point-min))
327             (insert From_)
328             (if (search-forward "\n\n" nil t)
329                 nil
330               (goto-char (point-max))
331               (insert "\n"))
332             (narrow-to-region (point) (point-max))
333             (let ((size (- (point-max) (point-min))))
334               (goto-char (point-min))
335               (widen)
336               (forward-line -1)
337               (insert (format "Content-Length: %s\n" size)))
338             )))))
339
340 ;; The Command Set
341
342 ;; AUTHORIZATION STATE
343
344 (defun pop3-user (process user)
345   "Send USER information to POP3 server."
346   (pop3-send-command process (format "USER %s" user))
347   (let ((response (pop3-read-response process t)))
348     (if (not (and response (string-match "+OK" response)))
349         (error (format "USER %s not valid" user)))))
350
351 (defun pop3-pass (process)
352   "Send authentication information to the server."
353   (pop3-send-command process (format "PASS %s" pop3-password))
354   (let ((response (pop3-read-response process t)))
355     (if (not (and response (string-match "+OK" response)))
356         (pop3-quit process))))
357
358 (defun pop3-apop (process user)
359   "Send alternate authentication information to the server."
360   (let ((pass pop3-password))
361     (if (and pop3-password-required (not pass))
362         (setq pass
363               (read-passwd (format "Password for %s: " pop3-maildrop))))
364     (if pass
365         (let ((hash (md5 (concat pop3-timestamp pass))))
366           (pop3-send-command process (format "APOP %s %s" user hash))
367           (let ((response (pop3-read-response process t)))
368             (if (not (and response (string-match "+OK" response)))
369                 (pop3-quit process)))))
370     ))
371
372 ;; TRANSACTION STATE
373
374 (defun pop3-stat (process)
375   "Return the number of messages in the maildrop and the maildrop's size."
376   (pop3-send-command process "STAT")
377   (let ((response (pop3-read-response process t)))
378     (list (string-to-int (nth 1 (split-string response " ")))
379           (string-to-int (nth 2 (split-string response " "))))
380     ))
381
382 (defun pop3-list (process &optional msg)
383   "Scan listing of available messages.
384 This function currently does nothing.")
385
386 (defun pop3-retr (process msg crashbuf)
387   "Retrieve message-id MSG to buffer CRASHBUF."
388   (pop3-send-command process (format "RETR %s" msg))
389   (pop3-read-response process)
390   (let ((start pop3-read-point) end)
391     (save-excursion
392       (set-buffer (process-buffer process))
393       (while (not (re-search-forward "^\\.\r\n" nil t))
394         (pop3-accept-process-output process)
395         (goto-char start))
396       (setq pop3-read-point (point-marker))
397       ;; this code does not seem to work for some POP servers...
398       ;; and I cannot figure out why not.
399       ;;      (goto-char (match-beginning 0))
400       ;;      (backward-char 2)
401       ;;      (if (not (looking-at "\r\n"))
402       ;;          (insert "\r\n"))
403       ;;      (re-search-forward "\\.\r\n")
404       (goto-char (match-beginning 0))
405       (setq end (point-marker))
406       (pop3-clean-region start end)
407       (pop3-munge-message-separator start end)
408       (save-excursion
409         (set-buffer crashbuf)
410         (erase-buffer))
411       (copy-to-buffer crashbuf start end)
412       (delete-region start end)
413       )))
414
415 (defun pop3-dele (process msg)
416   "Mark message-id MSG as deleted."
417   (pop3-send-command process (format "DELE %s" msg))
418   (pop3-read-response process))
419
420 (defun pop3-noop (process msg)
421   "No-operation."
422   (pop3-send-command process "NOOP")
423   (pop3-read-response process))
424
425 (defun pop3-last (process)
426   "Return highest accessed message-id number for the session."
427   (pop3-send-command process "LAST")
428   (let ((response (pop3-read-response process t)))
429     (string-to-int (nth 1 (split-string response " ")))
430     ))
431
432 (defun pop3-rset (process)
433   "Remove all delete marks from current maildrop."
434   (pop3-send-command process "RSET")
435   (pop3-read-response process))
436
437 ;; UPDATE
438
439 (defun pop3-quit (process)
440   "Close connection to POP3 server.
441 Tell server to remove all messages marked as deleted, unlock the maildrop,
442 and close the connection."
443   (pop3-send-command process "QUIT")
444   (pop3-read-response process t)
445   (if process
446       (save-excursion
447         (set-buffer (process-buffer process))
448         (goto-char (point-max))
449         (delete-process process))))
450 \f
451 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
452
453 ;;; AUTHORIZATION STATE
454
455 ;; Initial TCP connection
456 ;; Arguments: none
457 ;; Restrictions: none
458 ;; Possible responses:
459 ;;  +OK [POP3 server ready]
460
461 ;; USER name
462 ;; Arguments: a server specific user-id (required)
463 ;; Restrictions: authorization state [after unsuccessful USER or PASS
464 ;; Possible responses:
465 ;;  +OK [valid user-id]
466 ;;  -ERR [invalid user-id]
467
468 ;; PASS string
469 ;; Arguments: a server/user-id specific password (required)
470 ;; Restrictions: authorization state, after successful USER
471 ;; Possible responses:
472 ;;  +OK [maildrop locked and ready]
473 ;;  -ERR [invalid password]
474 ;;  -ERR [unable to lock maildrop]
475
476 ;;; TRANSACTION STATE
477
478 ;; STAT
479 ;; Arguments: none
480 ;; Restrictions: transaction state
481 ;; Possible responses:
482 ;;  +OK nn mm [# of messages, size of maildrop]
483
484 ;; LIST [msg]
485 ;; Arguments: a message-id (optional)
486 ;; Restrictions: transaction state; msg must not be deleted
487 ;; Possible responses:
488 ;;  +OK [scan listing follows]
489 ;;  -ERR [no such message]
490
491 ;; RETR msg
492 ;; Arguments: a message-id (required)
493 ;; Restrictions: transaction state; msg must not be deleted
494 ;; Possible responses:
495 ;;  +OK [message contents follow]
496 ;;  -ERR [no such message]
497
498 ;; DELE msg
499 ;; Arguments: a message-id (required)
500 ;; Restrictions: transaction state; msg must not be deleted
501 ;; Possible responses:
502 ;;  +OK [message deleted]
503 ;;  -ERR [no such message]
504
505 ;; NOOP
506 ;; Arguments: none
507 ;; Restrictions: transaction state
508 ;; Possible responses:
509 ;;  +OK
510
511 ;; LAST
512 ;; Arguments: none
513 ;; Restrictions: transaction state
514 ;; Possible responses:
515 ;;  +OK nn [highest numbered message accessed]
516
517 ;; RSET
518 ;; Arguments: none
519 ;; Restrictions: transaction state
520 ;; Possible responses:
521 ;;  +OK [all delete marks removed]
522
523 ;;; UPDATE STATE
524
525 ;; QUIT
526 ;; Arguments: none
527 ;; Restrictions: none
528 ;; Possible responses:
529 ;;  +OK [TCP connection closed]
530
531 (provide 'pop3)
532
533 ;;; arch-tag: 2facc142-1d74-498e-82af-4659b64cac12
534 ;;; pop3.el ends here