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