Sync up with gnus-6_9.
[elisp/gnus.git-] / lisp / pop3.el
1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
2
3 ;; Copyright (C) 1996,1997,1998 Free Software Foundation, Inc.
4
5 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
6 ;; Keywords: mail, pop3
7 ;; Version: 1.3m+
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
29 ;; are implemented.  The LIST command has not been implemented due to lack
30 ;; of actual usefulness.
31 ;; The optional POP3 command TOP has not been implemented.
32
33 ;; This program was inspired by Kyle E. Jones's vm-pop program.
34
35 ;;; Code:
36
37 (require 'mail-utils)
38 (provide 'pop3)
39
40 (defconst pop3-version "1.3m+")
41
42 (defvar pop3-maildrop (or (user-login-name) (getenv "LOGNAME") (getenv "USER") nil)
43   "*POP3 maildrop.")
44 (defvar pop3-mailhost (or (getenv "MAILHOST") nil)
45   "*POP3 mailhost.")
46 (defvar pop3-port 110
47   "*POP3 port.")
48
49 (defvar pop3-password-required t
50   "*Non-nil if a password is required when connecting to POP server.")
51 (defvar pop3-password nil
52   "*Password to use when connecting to POP server.")
53
54 (defvar pop3-authentication-scheme 'pass
55   "*POP3 authentication scheme.
56 Defaults to 'pass, for the standard USER/PASS authentication.  Other valid
57 values are 'apop.")
58
59 (defvar pop3-authentication-scheme-alist nil
60   "*Alist of host and POP3 authentication scheme.")
61
62 (defvar pop3-timestamp nil
63   "Timestamp returned when initially connected to the POP server.
64 Used for APOP authentication.")
65
66 (defvar pop3-movemail-file-coding-system 'binary
67   "Crashbox made by pop3-movemail with this coding system.")
68
69 (defvar pop3-read-point nil)
70 (defvar pop3-debug nil)
71
72 (defun pop3-movemail (&optional crashbox)
73   "Transfer contents of a maildrop to the specified CRASHBOX."
74   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
75   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
76          (crashbuf (get-buffer-create " *pop3-retr*"))
77          (n 1)
78          message-count
79          (pop3-password pop3-password)
80          (pop3-authentication-scheme pop3-authentication-scheme)
81          )
82     ;; for debugging only
83     (if pop3-debug (switch-to-buffer (process-buffer process)))
84     ;; query for password
85     (if (and pop3-password-required (not pop3-password))
86         (setq pop3-password
87               (pop3-read-passwd (format "Password for %s: " pop3-maildrop))))
88     (let ((tmp-scheme (cdr (assoc pop3-mailhost
89                                   pop3-authentication-scheme-alist))))
90       (when tmp-scheme
91         (setq pop3-authentication-scheme tmp-scheme)))
92     (cond ((equal 'apop pop3-authentication-scheme)
93            (pop3-apop process pop3-maildrop))
94           ((equal 'pass pop3-authentication-scheme)
95            (pop3-user process pop3-maildrop)
96            (pop3-pass process))
97           (t (error "Invalid POP3 authentication scheme.")))
98     (setq message-count (car (pop3-stat process)))
99     (while (<= n message-count)
100       (message (format "Retrieving message %d of %d from %s..."
101                        n message-count pop3-mailhost))
102       (pop3-retr process n crashbuf)
103       (save-excursion
104         (set-buffer crashbuf)
105         (let ((coding-system-for-write pop3-movemail-file-coding-system))
106           (append-to-file (point-min) (point-max) crashbox))
107         (set-buffer (process-buffer process))
108         (while (> (buffer-size) 5000)
109           (goto-char (point-min))
110           (forward-line 50)
111           (delete-region (point-min) (point))))
112       (pop3-dele process n)
113       (setq n (+ 1 n))
114       (if pop3-debug (sit-for 1) (sit-for 0.1))
115       )
116     (pop3-quit process)
117     (kill-buffer crashbuf)
118     )
119   )
120
121 (defun pop3-open-server (mailhost port)
122   "Open TCP connection to MAILHOST.
123 Returns the process associated with the connection."
124   (let ((process-buffer
125          (get-buffer-create (format "trace of POP session to %s" mailhost)))
126         (process))
127     (save-excursion
128       (set-buffer process-buffer)
129       (erase-buffer)
130       (setq pop3-read-point (point-min))
131       )
132     (setq process
133           (open-network-stream-as-binary "POP" process-buffer mailhost port))
134     (let ((response (pop3-read-response process t)))
135       (setq pop3-timestamp
136             (substring response (or (string-match "<" response) 0)
137                        (+ 1 (or (string-match ">" response) -1)))))
138     process))
139
140 ;; Support functions
141
142 (defun pop3-process-filter (process output)
143   (save-excursion
144     (set-buffer (process-buffer process))
145     (goto-char (point-max))
146     (insert output)))
147
148 (defun pop3-send-command (process command)
149     (set-buffer (process-buffer process))
150     (goto-char (point-max))
151 ;;    (if (= (aref command 0) ?P)
152 ;;      (insert "PASS <omitted>\r\n")
153 ;;      (insert command "\r\n"))
154     (setq pop3-read-point (point))
155     (goto-char (point-max))
156     (process-send-string process command)
157     (process-send-string process "\r\n")
158     )
159
160 (defun pop3-read-response (process &optional return)
161   "Read the response from the server.
162 Return the response string if optional second argument is non-nil."
163   (let ((case-fold-search nil)
164         match-end)
165     (save-excursion
166       (set-buffer (process-buffer process))
167       (goto-char pop3-read-point)
168       (while (not (search-forward "\r\n" nil t))
169         (accept-process-output process 3)
170         (goto-char pop3-read-point))
171       (setq match-end (point))
172       (goto-char pop3-read-point)
173       (if (looking-at "-ERR")
174           (error (buffer-substring (point) (- match-end 2)))
175         (if (not (looking-at "+OK"))
176             (progn (setq pop3-read-point match-end) nil)
177           (setq pop3-read-point match-end)
178           (if return
179               (buffer-substring (point) match-end)
180             t)
181           )))))
182
183 (defun pop3-string-to-list (string &optional regexp)
184   "Chop up a string into a list."
185   (let ((list)
186         (regexp (or regexp " "))
187         (string (if (string-match "\r" string)
188                     (substring string 0 (match-beginning 0))
189                   string)))
190     (store-match-data nil)
191     (while string
192       (if (string-match regexp string)
193           (setq list (cons (substring string 0 (- (match-end 0) 1)) list)
194                 string (substring string (match-end 0)))
195         (setq list (cons string list)
196               string nil)))
197     (nreverse list)))
198
199 (defvar pop3-read-passwd nil)
200 (defun pop3-read-passwd (prompt)
201   (if (not pop3-read-passwd)
202       (if (functionp 'read-passwd)
203           (setq pop3-read-passwd 'read-passwd)
204         (if (load "passwd" t)
205             (setq pop3-read-passwd 'read-passwd)
206           (autoload 'ange-ftp-read-passwd "ange-ftp")
207           (setq pop3-read-passwd 'ange-ftp-read-passwd))))
208   (funcall pop3-read-passwd prompt))
209
210 (defun pop3-clean-region (start end)
211   (setq end (set-marker (make-marker) end))
212   (save-excursion
213     (goto-char start)
214     (while (and (< (point) end) (search-forward "\r\n" end t))
215       (replace-match "\n" t t))
216     (goto-char start)
217     (while (and (< (point) end) (re-search-forward "^\\." end t))
218       (replace-match "" t t)
219       (forward-char)))
220   (set-marker end nil))
221
222 (defun pop3-munge-message-separator (start end)
223   "Check to see if a message separator exists.  If not, generate one."
224   (if (not (fboundp 'message-make-date)) (autoload 'message-make-date "message"))
225   (save-excursion
226     (save-restriction
227       (narrow-to-region start end)
228       (goto-char (point-min))
229       (if (not (or (looking-at "From .?") ; Unix mail
230                    (looking-at "\001\001\001\001\n") ; MMDF
231                    (looking-at "BABYL OPTIONS:") ; Babyl
232                    ))
233           (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
234                 (date (pop3-string-to-list (or (mail-fetch-field "Date")
235                                                (message-make-date))))
236                 (From_))
237             ;; sample date formats I have seen
238             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
239             ;; Date: 08 Jul 1996 23:22:24 -0400
240             ;; should be
241             ;; Tue Jul 9 09:04:21 1996
242             (setq date
243                   (cond ((string-match "[A-Z]" (nth 0 date))
244                          (format "%s %s %s %s %s"
245                                  (nth 0 date) (nth 2 date) (nth 1 date)
246                                  (nth 4 date) (nth 3 date)))
247                         (t
248                          ;; this really needs to be better but I don't feel
249                          ;; like writing a date to day converter.
250                          (format "Sun %s %s %s %s"
251                                  (nth 1 date) (nth 0 date)
252                                  (nth 3 date) (nth 2 date)))
253                         ))
254             (setq From_ (format "\nFrom %s  %s\n" from date))
255             (while (string-match "," From_)
256               (setq From_ (concat (substring From_ 0 (match-beginning 0))
257                                   (substring From_ (match-end 0)))))
258             (goto-char (point-min))
259             (insert From_))))))
260
261 ;; The Command Set
262
263 ;; AUTHORIZATION STATE
264
265 (defun pop3-user (process user)
266   "Send USER information to POP3 server."
267   (pop3-send-command process (format "USER %s" user))
268   (let ((response (pop3-read-response process t)))
269     (if (not (and response (string-match "+OK" response)))
270         (error (format "USER %s not valid." user)))))
271
272 (defun pop3-pass (process)
273   "Send authentication information to the server."
274   (pop3-send-command process (format "PASS %s" pop3-password))
275   (let ((response (pop3-read-response process t)))
276     (if (not (and response (string-match "+OK" response)))
277         (pop3-quit process))))
278
279 (defun pop3-apop (process user)
280   "Send alternate authentication information to the server."
281   (if (not (fboundp 'md5)) (autoload 'md5 "md5"))
282   (let ((hash (md5 (concat pop3-timestamp pop3-password))))
283     (pop3-send-command process (format "APOP %s %s" user hash))
284     (let ((response (pop3-read-response process t)))
285       (if (not (and response (string-match "+OK" response)))
286           (pop3-quit process)))))
287
288 ;; TRANSACTION STATE
289
290 (defun pop3-stat (process)
291   "Return the number of messages in the maildrop and the maildrop's size."
292   (pop3-send-command process "STAT")
293   (let ((response (pop3-read-response process t)))
294     (list (string-to-int (nth 1 (pop3-string-to-list response)))
295           (string-to-int (nth 2 (pop3-string-to-list response))))
296     ))
297
298 (defun pop3-list (process &optional msg)
299   "Scan listing of available messages.
300 This function currently does nothing.")
301
302 (defun pop3-retr (process msg crashbuf)
303   "Retrieve message-id MSG to buffer CRASHBUF."
304   (pop3-send-command process (format "RETR %s" msg))
305   (pop3-read-response process)
306   (let ((start pop3-read-point) end)
307     (save-excursion
308       (set-buffer (process-buffer process))
309       (while (not (re-search-forward "^\\.\r\n" nil t))
310         (accept-process-output process 3)
311         ;; bill@att.com ... to save wear and tear on the heap
312         ;; uncommented because the condensed version below is a problem for
313         ;; some.
314         (if (> (buffer-size)  20000) (sleep-for 1))
315         (if (> (buffer-size)  50000) (sleep-for 1))
316         (if (> (buffer-size) 100000) (sleep-for 1))
317         (if (> (buffer-size) 200000) (sleep-for 1))
318         (if (> (buffer-size) 500000) (sleep-for 1))
319         ;; bill@att.com
320         ;; condensed into:
321         ;; (sometimes causes problems for really large messages.)
322 ;       (if (> (buffer-size) 20000) (sleep-for (/ (buffer-size) 20000)))
323         (goto-char start))
324       (setq pop3-read-point (point-marker))
325 ;; this code does not seem to work for some POP servers...
326 ;; and I cannot figure out why not.
327 ;      (goto-char (match-beginning 0))
328 ;      (backward-char 2)
329 ;      (if (not (looking-at "\r\n"))
330 ;         (insert "\r\n"))
331 ;      (re-search-forward "\\.\r\n")
332       (goto-char (match-beginning 0))
333       (setq end (point-marker))
334       (pop3-clean-region start end)
335       (pop3-munge-message-separator start end)
336       (save-excursion
337         (set-buffer crashbuf)
338         (erase-buffer))
339       (copy-to-buffer crashbuf start end)
340       (delete-region start end)
341       )))
342
343 (defun pop3-dele (process msg)
344   "Mark message-id MSG as deleted."
345   (pop3-send-command process (format "DELE %s" msg))
346   (pop3-read-response process))
347
348 (defun pop3-noop (process msg)
349   "No-operation."
350   (pop3-send-command process "NOOP")
351   (pop3-read-response process))
352
353 (defun pop3-last (process)
354   "Return highest accessed message-id number for the session."
355   (pop3-send-command process "LAST")
356   (let ((response (pop3-read-response process t)))
357     (string-to-int (nth 1 (pop3-string-to-list response)))
358     ))
359
360 (defun pop3-rset (process)
361   "Remove all delete marks from current maildrop."
362   (pop3-send-command process "RSET")
363   (pop3-read-response process))
364
365 ;; UPDATE
366
367 (defun pop3-quit (process)
368   "Close connection to POP3 server.
369 Tell server to remove all messages marked as deleted, unlock the maildrop,
370 and close the connection."
371   (pop3-send-command process "QUIT")
372   (pop3-read-response process t)
373   (if process
374       (save-excursion
375         (set-buffer (process-buffer process))
376         (goto-char (point-max))
377         (delete-process process))))
378 \f
379 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
380
381 ;;; AUTHORIZATION STATE
382
383 ;; Initial TCP connection
384 ;; Arguments: none
385 ;; Restrictions: none
386 ;; Possible responses:
387 ;;  +OK [POP3 server ready]
388
389 ;; USER name
390 ;; Arguments: a server specific user-id (required)
391 ;; Restrictions: authorization state [after unsuccessful USER or PASS
392 ;; Possible responses:
393 ;;  +OK [valid user-id]
394 ;;  -ERR [invalid user-id]
395
396 ;; PASS string
397 ;; Arguments: a server/user-id specific password (required)
398 ;; Restrictions: authorization state, after successful USER
399 ;; Possible responses:
400 ;;  +OK [maildrop locked and ready]
401 ;;  -ERR [invalid password]
402 ;;  -ERR [unable to lock maildrop]
403
404 ;;; TRANSACTION STATE
405
406 ;; STAT
407 ;; Arguments: none
408 ;; Restrictions: transaction state
409 ;; Possible responses:
410 ;;  +OK nn mm [# of messages, size of maildrop]
411
412 ;; LIST [msg]
413 ;; Arguments: a message-id (optional)
414 ;; Restrictions: transaction state; msg must not be deleted
415 ;; Possible responses:
416 ;;  +OK [scan listing follows]
417 ;;  -ERR [no such message]
418
419 ;; RETR msg
420 ;; Arguments: a message-id (required)
421 ;; Restrictions: transaction state; msg must not be deleted
422 ;; Possible responses:
423 ;;  +OK [message contents follow]
424 ;;  -ERR [no such message]
425
426 ;; DELE msg
427 ;; Arguments: a message-id (required)
428 ;; Restrictions: transaction state; msg must not be deleted
429 ;; Possible responses:
430 ;;  +OK [message deleted]
431 ;;  -ERR [no such message]
432
433 ;; NOOP
434 ;; Arguments: none
435 ;; Restrictions: transaction state
436 ;; Possible responses:
437 ;;  +OK
438
439 ;; LAST
440 ;; Arguments: none
441 ;; Restrictions: transaction state
442 ;; Possible responses:
443 ;;  +OK nn [highest numbered message accessed]
444
445 ;; RSET
446 ;; Arguments: none
447 ;; Restrictions: transaction state
448 ;; Possible responses:
449 ;;  +OK [all delete marks removed]
450
451 ;;; UPDATE STATE
452
453 ;; QUIT
454 ;; Arguments: none
455 ;; Restrictions: none
456 ;; Possible responses:
457 ;;  +OK [TCP connection closed]