(pop3-authentication-scheme-alist): New variable.
[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         (coding-system-for-read 'binary)   ;; because 0000n0000 S000l 0a0
128         (coding-system-for-write 'binary)  ;; is st00pid
129         )
130     (save-excursion
131       (set-buffer process-buffer)
132       (erase-buffer)
133       (setq pop3-read-point (point-min))
134       )
135     (setq process
136           (open-network-stream "POP" process-buffer mailhost port))
137     (let ((response (pop3-read-response process t)))
138       (setq pop3-timestamp
139             (substring response (or (string-match "<" response) 0)
140                        (+ 1 (or (string-match ">" response) -1)))))
141     process))
142
143 ;; Support functions
144
145 (defun pop3-process-filter (process output)
146   (save-excursion
147     (set-buffer (process-buffer process))
148     (goto-char (point-max))
149     (insert output)))
150
151 (defun pop3-send-command (process command)
152     (set-buffer (process-buffer process))
153     (goto-char (point-max))
154 ;;    (if (= (aref command 0) ?P)
155 ;;      (insert "PASS <omitted>\r\n")
156 ;;      (insert command "\r\n"))
157     (setq pop3-read-point (point))
158     (goto-char (point-max))
159     (process-send-string process command)
160     (process-send-string process "\r\n")
161     )
162
163 (defun pop3-read-response (process &optional return)
164   "Read the response from the server.
165 Return the response string if optional second argument is non-nil."
166   (let ((case-fold-search nil)
167         match-end)
168     (save-excursion
169       (set-buffer (process-buffer process))
170       (goto-char pop3-read-point)
171       (while (not (search-forward "\r\n" nil t))
172         (accept-process-output process 3)
173         (goto-char pop3-read-point))
174       (setq match-end (point))
175       (goto-char pop3-read-point)
176       (if (looking-at "-ERR")
177           (error (buffer-substring (point) (- match-end 2)))
178         (if (not (looking-at "+OK"))
179             (progn (setq pop3-read-point match-end) nil)
180           (setq pop3-read-point match-end)
181           (if return
182               (buffer-substring (point) match-end)
183             t)
184           )))))
185
186 (defun pop3-string-to-list (string &optional regexp)
187   "Chop up a string into a list."
188   (let ((list)
189         (regexp (or regexp " "))
190         (string (if (string-match "\r" string)
191                     (substring string 0 (match-beginning 0))
192                   string)))
193     (store-match-data nil)
194     (while string
195       (if (string-match regexp string)
196           (setq list (cons (substring string 0 (- (match-end 0) 1)) list)
197                 string (substring string (match-end 0)))
198         (setq list (cons string list)
199               string nil)))
200     (nreverse list)))
201
202 (defvar pop3-read-passwd nil)
203 (defun pop3-read-passwd (prompt)
204   (if (not pop3-read-passwd)
205       (if (functionp 'read-passwd)
206           (setq pop3-read-passwd 'read-passwd)
207         (if (load "passwd" t)
208             (setq pop3-read-passwd 'read-passwd)
209           (autoload 'ange-ftp-read-passwd "ange-ftp")
210           (setq pop3-read-passwd 'ange-ftp-read-passwd))))
211   (funcall pop3-read-passwd prompt))
212
213 (defun pop3-clean-region (start end)
214   (setq end (set-marker (make-marker) end))
215   (save-excursion
216     (goto-char start)
217     (while (and (< (point) end) (search-forward "\r\n" end t))
218       (replace-match "\n" t t))
219     (goto-char start)
220     (while (and (< (point) end) (re-search-forward "^\\." end t))
221       (replace-match "" t t)
222       (forward-char)))
223   (set-marker end nil))
224
225 (defun pop3-munge-message-separator (start end)
226   "Check to see if a message separator exists.  If not, generate one."
227   (if (not (fboundp 'message-make-date)) (autoload 'message-make-date "message"))
228   (save-excursion
229     (save-restriction
230       (narrow-to-region start end)
231       (goto-char (point-min))
232       (if (not (or (looking-at "From .?") ; Unix mail
233                    (looking-at "\001\001\001\001\n") ; MMDF
234                    (looking-at "BABYL OPTIONS:") ; Babyl
235                    ))
236           (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
237                 (date (pop3-string-to-list (or (mail-fetch-field "Date")
238                                                (message-make-date))))
239                 (From_))
240             ;; sample date formats I have seen
241             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
242             ;; Date: 08 Jul 1996 23:22:24 -0400
243             ;; should be
244             ;; Tue Jul 9 09:04:21 1996
245             (setq date
246                   (cond ((string-match "[A-Z]" (nth 0 date))
247                          (format "%s %s %s %s %s"
248                                  (nth 0 date) (nth 2 date) (nth 1 date)
249                                  (nth 4 date) (nth 3 date)))
250                         (t
251                          ;; this really needs to be better but I don't feel
252                          ;; like writing a date to day converter.
253                          (format "Sun %s %s %s %s"
254                                  (nth 1 date) (nth 0 date)
255                                  (nth 3 date) (nth 2 date)))
256                         ))
257             (setq From_ (format "\nFrom %s  %s\n" from date))
258             (while (string-match "," From_)
259               (setq From_ (concat (substring From_ 0 (match-beginning 0))
260                                   (substring From_ (match-end 0)))))
261             (goto-char (point-min))
262             (insert From_))))))
263
264 ;; The Command Set
265
266 ;; AUTHORIZATION STATE
267
268 (defun pop3-user (process user)
269   "Send USER information to POP3 server."
270   (pop3-send-command process (format "USER %s" user))
271   (let ((response (pop3-read-response process t)))
272     (if (not (and response (string-match "+OK" response)))
273         (error (format "USER %s not valid." user)))))
274
275 (defun pop3-pass (process)
276   "Send authentication information to the server."
277   (pop3-send-command process (format "PASS %s" pop3-password))
278   (let ((response (pop3-read-response process t)))
279     (if (not (and response (string-match "+OK" response)))
280         (pop3-quit process))))
281
282 (defun pop3-apop (process user)
283   "Send alternate authentication information to the server."
284   (if (not (fboundp 'md5)) (autoload 'md5 "md5"))
285   (let ((hash (md5 (concat pop3-timestamp pop3-password))))
286     (pop3-send-command process (format "APOP %s %s" user hash))
287     (let ((response (pop3-read-response process t)))
288       (if (not (and response (string-match "+OK" response)))
289           (pop3-quit process)))))
290
291 ;; TRANSACTION STATE
292
293 (defun pop3-stat (process)
294   "Return the number of messages in the maildrop and the maildrop's size."
295   (pop3-send-command process "STAT")
296   (let ((response (pop3-read-response process t)))
297     (list (string-to-int (nth 1 (pop3-string-to-list response)))
298           (string-to-int (nth 2 (pop3-string-to-list response))))
299     ))
300
301 (defun pop3-list (process &optional msg)
302   "Scan listing of available messages.
303 This function currently does nothing.")
304
305 (defun pop3-retr (process msg crashbuf)
306   "Retrieve message-id MSG to buffer CRASHBUF."
307   (pop3-send-command process (format "RETR %s" msg))
308   (pop3-read-response process)
309   (let ((start pop3-read-point) end)
310     (save-excursion
311       (set-buffer (process-buffer process))
312       (while (not (re-search-forward "^\\.\r\n" nil t))
313         (accept-process-output process 3)
314         ;; bill@att.com ... to save wear and tear on the heap
315         ;; uncommented because the condensed version below is a problem for
316         ;; some.
317         (if (> (buffer-size)  20000) (sleep-for 1))
318         (if (> (buffer-size)  50000) (sleep-for 1))
319         (if (> (buffer-size) 100000) (sleep-for 1))
320         (if (> (buffer-size) 200000) (sleep-for 1))
321         (if (> (buffer-size) 500000) (sleep-for 1))
322         ;; bill@att.com
323         ;; condensed into:
324         ;; (sometimes causes problems for really large messages.)
325 ;       (if (> (buffer-size) 20000) (sleep-for (/ (buffer-size) 20000)))
326         (goto-char start))
327       (setq pop3-read-point (point-marker))
328 ;; this code does not seem to work for some POP servers...
329 ;; and I cannot figure out why not.
330 ;      (goto-char (match-beginning 0))
331 ;      (backward-char 2)
332 ;      (if (not (looking-at "\r\n"))
333 ;         (insert "\r\n"))
334 ;      (re-search-forward "\\.\r\n")
335       (goto-char (match-beginning 0))
336       (setq end (point-marker))
337       (pop3-clean-region start end)
338       (pop3-munge-message-separator start end)
339       (save-excursion
340         (set-buffer crashbuf)
341         (erase-buffer))
342       (copy-to-buffer crashbuf start end)
343       (delete-region start end)
344       )))
345
346 (defun pop3-dele (process msg)
347   "Mark message-id MSG as deleted."
348   (pop3-send-command process (format "DELE %s" msg))
349   (pop3-read-response process))
350
351 (defun pop3-noop (process msg)
352   "No-operation."
353   (pop3-send-command process "NOOP")
354   (pop3-read-response process))
355
356 (defun pop3-last (process)
357   "Return highest accessed message-id number for the session."
358   (pop3-send-command process "LAST")
359   (let ((response (pop3-read-response process t)))
360     (string-to-int (nth 1 (pop3-string-to-list response)))
361     ))
362
363 (defun pop3-rset (process)
364   "Remove all delete marks from current maildrop."
365   (pop3-send-command process "RSET")
366   (pop3-read-response process))
367
368 ;; UPDATE
369
370 (defun pop3-quit (process)
371   "Close connection to POP3 server.
372 Tell server to remove all messages marked as deleted, unlock the maildrop,
373 and close the connection."
374   (pop3-send-command process "QUIT")
375   (pop3-read-response process t)
376   (if process
377       (save-excursion
378         (set-buffer (process-buffer process))
379         (goto-char (point-max))
380         (delete-process process))))
381 \f
382 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
383
384 ;;; AUTHORIZATION STATE
385
386 ;; Initial TCP connection
387 ;; Arguments: none
388 ;; Restrictions: none
389 ;; Possible responses:
390 ;;  +OK [POP3 server ready]
391
392 ;; USER name
393 ;; Arguments: a server specific user-id (required)
394 ;; Restrictions: authorization state [after unsuccessful USER or PASS
395 ;; Possible responses:
396 ;;  +OK [valid user-id]
397 ;;  -ERR [invalid user-id]
398
399 ;; PASS string
400 ;; Arguments: a server/user-id specific password (required)
401 ;; Restrictions: authorization state, after successful USER
402 ;; Possible responses:
403 ;;  +OK [maildrop locked and ready]
404 ;;  -ERR [invalid password]
405 ;;  -ERR [unable to lock maildrop]
406
407 ;;; TRANSACTION STATE
408
409 ;; STAT
410 ;; Arguments: none
411 ;; Restrictions: transaction state
412 ;; Possible responses:
413 ;;  +OK nn mm [# of messages, size of maildrop]
414
415 ;; LIST [msg]
416 ;; Arguments: a message-id (optional)
417 ;; Restrictions: transaction state; msg must not be deleted
418 ;; Possible responses:
419 ;;  +OK [scan listing follows]
420 ;;  -ERR [no such message]
421
422 ;; RETR msg
423 ;; Arguments: a message-id (required)
424 ;; Restrictions: transaction state; msg must not be deleted
425 ;; Possible responses:
426 ;;  +OK [message contents follow]
427 ;;  -ERR [no such message]
428
429 ;; DELE msg
430 ;; Arguments: a message-id (required)
431 ;; Restrictions: transaction state; msg must not be deleted
432 ;; Possible responses:
433 ;;  +OK [message deleted]
434 ;;  -ERR [no such message]
435
436 ;; NOOP
437 ;; Arguments: none
438 ;; Restrictions: transaction state
439 ;; Possible responses:
440 ;;  +OK
441
442 ;; LAST
443 ;; Arguments: none
444 ;; Restrictions: transaction state
445 ;; Possible responses:
446 ;;  +OK nn [highest numbered message accessed]
447
448 ;; RSET
449 ;; Arguments: none
450 ;; Restrictions: transaction state
451 ;; Possible responses:
452 ;;  +OK [all delete marks removed]
453
454 ;;; UPDATE STATE
455
456 ;; QUIT
457 ;; Arguments: none
458 ;; Restrictions: none
459 ;; Possible responses:
460 ;;  +OK [TCP connection closed]