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