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