32a9f4dbe9dda4cd66c4471919cd1ac2654cbc69
[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.3r
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.3r")
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 command)
185     (process-send-string process "\r\n")
186     )
187
188 (defun pop3-read-response (process &optional return)
189   "Read the response from the server.
190 Return the response string if optional second argument is non-nil."
191   (let ((case-fold-search nil)
192         match-end)
193     (save-excursion
194       (set-buffer (process-buffer process))
195       (goto-char pop3-read-point)
196       (while (not (search-forward "\r\n" nil t))
197         (accept-process-output process 3)
198         (goto-char pop3-read-point))
199       (setq match-end (point))
200       (goto-char pop3-read-point)
201       (if (looking-at "-ERR")
202           (signal 'error (list (buffer-substring (point) (- match-end 2))))
203         (if (not (looking-at "+OK"))
204             (progn (setq pop3-read-point match-end) nil)
205           (setq pop3-read-point match-end)
206           (if return
207               (buffer-substring (point) match-end)
208             t)
209           )))))
210
211 (defun pop3-string-to-list (string &optional regexp)
212   "Chop up a string into a list."
213   (let ((list)
214         (regexp (or regexp " "))
215         (string (if (string-match "\r" string)
216                     (substring string 0 (match-beginning 0))
217                   string)))
218     (store-match-data nil)
219     (while string
220       (if (string-match regexp string)
221           (setq list (cons (substring string 0 (- (match-end 0) 1)) list)
222                 string (substring string (match-end 0)))
223         (setq list (cons string list)
224               string nil)))
225     (nreverse list)))
226
227 (defvar pop3-read-passwd nil)
228 (defun pop3-read-passwd (prompt)
229   (if (not pop3-read-passwd)
230       (if (functionp 'read-passwd)
231           (setq pop3-read-passwd 'read-passwd)
232         (if (load "passwd" t)
233             (setq pop3-read-passwd 'read-passwd)
234           (autoload 'ange-ftp-read-passwd "ange-ftp")
235           (setq pop3-read-passwd 'ange-ftp-read-passwd))))
236   (funcall pop3-read-passwd prompt))
237
238 (defun pop3-clean-region (start end)
239   (setq end (set-marker (make-marker) end))
240   (save-excursion
241     (goto-char start)
242     (while (and (< (point) end) (search-forward "\r\n" end t))
243       (replace-match "\n" t t))
244     (goto-char start)
245     (while (and (< (point) end) (re-search-forward "^\\." end t))
246       (replace-match "" t t)
247       (forward-char)))
248   (set-marker end nil))
249
250 (defun pop3-munge-message-separator (start end)
251   "Check to see if a message separator exists.  If not, generate one."
252   (if (not (fboundp 'parse-time-string))
253       (autoload 'parse-time-string "parse-time"))
254   (save-excursion
255     (save-restriction
256       (narrow-to-region start end)
257       (goto-char (point-min))
258       (if (not (or (looking-at "From .?") ; Unix mail
259                    (looking-at "\001\001\001\001\n") ; MMDF
260                    (looking-at "BABYL OPTIONS:") ; Babyl
261                    ))
262           (let ((from (mail-strip-quoted-names (mail-fetch-field "From")))
263                 (date (mail-fetch-field "Date"))
264                 (From_))
265             ;; sample date formats I have seen
266             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
267             ;; Date: 08 Jul 1996 23:22:24 -0400
268             ;; should be
269             ;; Tue Jul 9 09:04:21 1996
270             (setq date (format-time-string
271                         "%a %b %e %T %Y"
272                         (if date
273                             (condition-case nil
274                                 (apply 'encode-time (parse-time-string date))
275                               (error (current-time)))
276                           (current-time))))
277             (setq From_ (format "\nFrom %s  %s\n" from date))
278             (while (string-match "," From_)
279               (setq From_ (concat (substring From_ 0 (match-beginning 0))
280                                   (substring From_ (match-end 0)))))
281             (goto-char (point-min))
282             (insert From_)
283             (re-search-forward "\n\n")
284             (narrow-to-region (point) (point-max))
285             (let ((size (- (point-max) (point-min))))
286               (goto-char (point-min))
287               (widen)
288               (forward-line -1)
289               (insert (format "Content-Length: %s\n" size)))
290             )))))
291
292 ;; The Command Set
293
294 ;; AUTHORIZATION STATE
295
296 (defun pop3-user (process user)
297   "Send USER information to POP3 server."
298   (pop3-send-command process (format "USER %s" user))
299   (let ((response (pop3-read-response process t)))
300     (if (not (and response (string-match "+OK" response)))
301         (error (format "USER %s not valid." user)))))
302
303 (defun pop3-pass (process)
304   "Send authentication information to the server."
305   (pop3-send-command process (format "PASS %s" pop3-password))
306   (let ((response (pop3-read-response process t)))
307     (if (not (and response (string-match "+OK" response)))
308         (pop3-quit process))))
309
310 (defun pop3-apop (process user)
311   "Send alternate authentication information to the server."
312   (if (not (fboundp 'md5)) (autoload 'md5 "md5"))
313   (let ((hash (md5 (concat pop3-timestamp pop3-password))))
314     (pop3-send-command process (format "APOP %s %s" user hash))
315     (let ((response (pop3-read-response process t)))
316       (if (not (and response (string-match "+OK" response)))
317           (pop3-quit process)))))
318
319 ;; TRANSACTION STATE
320
321 (defun pop3-stat (process)
322   "Return the number of messages in the maildrop and the maildrop's size."
323   (pop3-send-command process "STAT")
324   (let ((response (pop3-read-response process t)))
325     (list (string-to-int (nth 1 (split-string response)))
326           (string-to-int (nth 2 (split-string response))))
327     ))
328
329 (defun pop3-list (process &optional msg)
330   "Scan listing of available messages.
331 This function currently does nothing.")
332
333 (defun pop3-retr (process msg crashbuf)
334   "Retrieve message-id MSG to buffer CRASHBUF."
335   (pop3-send-command process (format "RETR %s" msg))
336   (pop3-read-response process)
337   (let ((start pop3-read-point) end)
338     (save-excursion
339       (set-buffer (process-buffer process))
340       (while (not (re-search-forward "^\\.\r\n" nil t))
341         (accept-process-output process 3)
342         ;; bill@att.com ... to save wear and tear on the heap
343         ;; uncommented because the condensed version below is a problem for
344         ;; some.
345         (if (> (buffer-size)  20000) (sleep-for 1))
346         (if (> (buffer-size)  50000) (sleep-for 1))
347         (if (> (buffer-size) 100000) (sleep-for 1))
348         (if (> (buffer-size) 200000) (sleep-for 1))
349         (if (> (buffer-size) 500000) (sleep-for 1))
350         ;; bill@att.com
351         ;; condensed into:
352         ;; (sometimes causes problems for really large messages.)
353 ;       (if (> (buffer-size) 20000) (sleep-for (/ (buffer-size) 20000)))
354         (goto-char start))
355       (setq pop3-read-point (point-marker))
356 ;; this code does not seem to work for some POP servers...
357 ;; and I cannot figure out why not.
358 ;      (goto-char (match-beginning 0))
359 ;      (backward-char 2)
360 ;      (if (not (looking-at "\r\n"))
361 ;         (insert "\r\n"))
362 ;      (re-search-forward "\\.\r\n")
363       (goto-char (match-beginning 0))
364       (setq end (point-marker))
365       (pop3-clean-region start end)
366       (pop3-munge-message-separator start end)
367       (save-excursion
368         (set-buffer crashbuf)
369         (erase-buffer))
370       (copy-to-buffer crashbuf start end)
371       (delete-region start end)
372       )))
373
374 (defun pop3-dele (process msg)
375   "Mark message-id MSG as deleted."
376   (pop3-send-command process (format "DELE %s" msg))
377   (pop3-read-response process))
378
379 (defun pop3-noop (process msg)
380   "No-operation."
381   (pop3-send-command process "NOOP")
382   (pop3-read-response process))
383
384 (defun pop3-last (process)
385   "Return highest accessed message-id number for the session."
386   (pop3-send-command process "LAST")
387   (let ((response (pop3-read-response process t)))
388     (string-to-int (nth 1 (split-string response)))
389     ))
390
391 (defun pop3-rset (process)
392   "Remove all delete marks from current maildrop."
393   (pop3-send-command process "RSET")
394   (pop3-read-response process))
395
396 ;; UPDATE
397
398 (defun pop3-quit (process)
399   "Close connection to POP3 server.
400 Tell server to remove all messages marked as deleted, unlock the maildrop,
401 and close the connection."
402   (pop3-send-command process "QUIT")
403   (pop3-read-response process t)
404   (if process
405       (save-excursion
406         (set-buffer (process-buffer process))
407         (goto-char (point-max))
408         (delete-process process))))
409 \f
410 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
411
412 ;;; AUTHORIZATION STATE
413
414 ;; Initial TCP connection
415 ;; Arguments: none
416 ;; Restrictions: none
417 ;; Possible responses:
418 ;;  +OK [POP3 server ready]
419
420 ;; USER name
421 ;; Arguments: a server specific user-id (required)
422 ;; Restrictions: authorization state [after unsuccessful USER or PASS
423 ;; Possible responses:
424 ;;  +OK [valid user-id]
425 ;;  -ERR [invalid user-id]
426
427 ;; PASS string
428 ;; Arguments: a server/user-id specific password (required)
429 ;; Restrictions: authorization state, after successful USER
430 ;; Possible responses:
431 ;;  +OK [maildrop locked and ready]
432 ;;  -ERR [invalid password]
433 ;;  -ERR [unable to lock maildrop]
434
435 ;;; TRANSACTION STATE
436
437 ;; STAT
438 ;; Arguments: none
439 ;; Restrictions: transaction state
440 ;; Possible responses:
441 ;;  +OK nn mm [# of messages, size of maildrop]
442
443 ;; LIST [msg]
444 ;; Arguments: a message-id (optional)
445 ;; Restrictions: transaction state; msg must not be deleted
446 ;; Possible responses:
447 ;;  +OK [scan listing follows]
448 ;;  -ERR [no such message]
449
450 ;; RETR msg
451 ;; Arguments: a message-id (required)
452 ;; Restrictions: transaction state; msg must not be deleted
453 ;; Possible responses:
454 ;;  +OK [message contents follow]
455 ;;  -ERR [no such message]
456
457 ;; DELE msg
458 ;; Arguments: a message-id (required)
459 ;; Restrictions: transaction state; msg must not be deleted
460 ;; Possible responses:
461 ;;  +OK [message deleted]
462 ;;  -ERR [no such message]
463
464 ;; NOOP
465 ;; Arguments: none
466 ;; Restrictions: transaction state
467 ;; Possible responses:
468 ;;  +OK
469
470 ;; LAST
471 ;; Arguments: none
472 ;; Restrictions: transaction state
473 ;; Possible responses:
474 ;;  +OK nn [highest numbered message accessed]
475
476 ;; RSET
477 ;; Arguments: none
478 ;; Restrictions: transaction state
479 ;; Possible responses:
480 ;;  +OK [all delete marks removed]
481
482 ;;; UPDATE STATE
483
484 ;; QUIT
485 ;; Arguments: none
486 ;; Restrictions: none
487 ;; Possible responses:
488 ;;  +OK [TCP connection closed]