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