* gnus.el (gnus-version-number): Update to 6.10.062.
[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                             (apply 'encode-time (parse-time-string date))
219                           (current-time))))
220             (setq From_ (format "\nFrom %s  %s\n" from date))
221             (while (string-match "," From_)
222               (setq From_ (concat (substring From_ 0 (match-beginning 0))
223                                   (substring From_ (match-end 0)))))
224             (goto-char (point-min))
225             (insert From_))))))
226
227 ;; The Command Set
228
229 ;; AUTHORIZATION STATE
230
231 (defun pop3-user (process user)
232   "Send USER information to POP3 server."
233   (pop3-send-command process (format "USER %s" user))
234   (let ((response (pop3-read-response process t)))
235     (if (not (and response (string-match "+OK" response)))
236         (error (format "USER %s not valid." user)))))
237
238 (defun pop3-pass (process)
239   "Send authentication information to the server."
240   (pop3-send-command process (format "PASS %s" pop3-password))
241   (let ((response (pop3-read-response process t)))
242     (if (not (and response (string-match "+OK" response)))
243         (pop3-quit process))))
244
245 (defun pop3-apop (process user)
246   "Send alternate authentication information to the server."
247   (if (not (fboundp 'md5)) (autoload 'md5 "md5"))
248   (let ((hash (md5 (concat pop3-timestamp pop3-password))))
249     (pop3-send-command process (format "APOP %s %s" user hash))
250     (let ((response (pop3-read-response process t)))
251       (if (not (and response (string-match "+OK" response)))
252           (pop3-quit process)))))
253
254 ;; TRANSACTION STATE
255
256 (defun pop3-stat (process)
257   "Return the number of messages in the maildrop and the maildrop's size."
258   (pop3-send-command process "STAT")
259   (let ((response (pop3-read-response process t)))
260     (list (string-to-int (nth 1 (split-string response)))
261           (string-to-int (nth 2 (split-string response))))
262     ))
263
264 (defun pop3-list (process &optional msg)
265   "Scan listing of available messages.
266 This function currently does nothing.")
267
268 (defun pop3-retr (process msg crashbuf)
269   "Retrieve message-id MSG to buffer CRASHBUF."
270   (pop3-send-command process (format "RETR %s" msg))
271   (pop3-read-response process)
272   (let ((start pop3-read-point) end)
273     (save-excursion
274       (set-buffer (process-buffer process))
275       (while (not (re-search-forward "^\\.\r\n" nil t))
276         (accept-process-output process 3)
277         ;; bill@att.com ... to save wear and tear on the heap
278         ;; uncommented because the condensed version below is a problem for
279         ;; some.
280         (if (> (buffer-size)  20000) (sleep-for 1))
281         (if (> (buffer-size)  50000) (sleep-for 1))
282         (if (> (buffer-size) 100000) (sleep-for 1))
283         (if (> (buffer-size) 200000) (sleep-for 1))
284         (if (> (buffer-size) 500000) (sleep-for 1))
285         ;; bill@att.com
286         ;; condensed into:
287         ;; (sometimes causes problems for really large messages.)
288 ;       (if (> (buffer-size) 20000) (sleep-for (/ (buffer-size) 20000)))
289         (goto-char start))
290       (setq pop3-read-point (point-marker))
291 ;; this code does not seem to work for some POP servers...
292 ;; and I cannot figure out why not.
293 ;      (goto-char (match-beginning 0))
294 ;      (backward-char 2)
295 ;      (if (not (looking-at "\r\n"))
296 ;         (insert "\r\n"))
297 ;      (re-search-forward "\\.\r\n")
298       (goto-char (match-beginning 0))
299       (setq end (point-marker))
300       (pop3-clean-region start end)
301       (pop3-munge-message-separator start end)
302       (save-excursion
303         (set-buffer crashbuf)
304         (erase-buffer))
305       (copy-to-buffer crashbuf start end)
306       (delete-region start end)
307       )))
308
309 (defun pop3-dele (process msg)
310   "Mark message-id MSG as deleted."
311   (pop3-send-command process (format "DELE %s" msg))
312   (pop3-read-response process))
313
314 (defun pop3-noop (process msg)
315   "No-operation."
316   (pop3-send-command process "NOOP")
317   (pop3-read-response process))
318
319 (defun pop3-last (process)
320   "Return highest accessed message-id number for the session."
321   (pop3-send-command process "LAST")
322   (let ((response (pop3-read-response process t)))
323     (string-to-int (nth 1 (split-string response)))
324     ))
325
326 (defun pop3-rset (process)
327   "Remove all delete marks from current maildrop."
328   (pop3-send-command process "RSET")
329   (pop3-read-response process))
330
331 ;; UPDATE
332
333 (defun pop3-quit (process)
334   "Close connection to POP3 server.
335 Tell server to remove all messages marked as deleted, unlock the maildrop,
336 and close the connection."
337   (pop3-send-command process "QUIT")
338   (pop3-read-response process t)
339   (if process
340       (save-excursion
341         (set-buffer (process-buffer process))
342         (goto-char (point-max))
343         (delete-process process))))
344 \f
345 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
346
347 ;;; AUTHORIZATION STATE
348
349 ;; Initial TCP connection
350 ;; Arguments: none
351 ;; Restrictions: none
352 ;; Possible responses:
353 ;;  +OK [POP3 server ready]
354
355 ;; USER name
356 ;; Arguments: a server specific user-id (required)
357 ;; Restrictions: authorization state [after unsuccessful USER or PASS
358 ;; Possible responses:
359 ;;  +OK [valid user-id]
360 ;;  -ERR [invalid user-id]
361
362 ;; PASS string
363 ;; Arguments: a server/user-id specific password (required)
364 ;; Restrictions: authorization state, after successful USER
365 ;; Possible responses:
366 ;;  +OK [maildrop locked and ready]
367 ;;  -ERR [invalid password]
368 ;;  -ERR [unable to lock maildrop]
369
370 ;;; TRANSACTION STATE
371
372 ;; STAT
373 ;; Arguments: none
374 ;; Restrictions: transaction state
375 ;; Possible responses:
376 ;;  +OK nn mm [# of messages, size of maildrop]
377
378 ;; LIST [msg]
379 ;; Arguments: a message-id (optional)
380 ;; Restrictions: transaction state; msg must not be deleted
381 ;; Possible responses:
382 ;;  +OK [scan listing follows]
383 ;;  -ERR [no such message]
384
385 ;; RETR msg
386 ;; Arguments: a message-id (required)
387 ;; Restrictions: transaction state; msg must not be deleted
388 ;; Possible responses:
389 ;;  +OK [message contents follow]
390 ;;  -ERR [no such message]
391
392 ;; DELE msg
393 ;; Arguments: a message-id (required)
394 ;; Restrictions: transaction state; msg must not be deleted
395 ;; Possible responses:
396 ;;  +OK [message deleted]
397 ;;  -ERR [no such message]
398
399 ;; NOOP
400 ;; Arguments: none
401 ;; Restrictions: transaction state
402 ;; Possible responses:
403 ;;  +OK
404
405 ;; LAST
406 ;; Arguments: none
407 ;; Restrictions: transaction state
408 ;; Possible responses:
409 ;;  +OK nn [highest numbered message accessed]
410
411 ;; RSET
412 ;; Arguments: none
413 ;; Restrictions: transaction state
414 ;; Possible responses:
415 ;;  +OK [all delete marks removed]
416
417 ;;; UPDATE STATE
418
419 ;; QUIT
420 ;; Arguments: none
421 ;; Restrictions: none
422 ;; Possible responses:
423 ;;  +OK [TCP connection closed]