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