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