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