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