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