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