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