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