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