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