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