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