(pop3-read-response): Check whether the process is
[gnus] / lisp / pop3.el
1 ;;; pop3.el --- Post Office Protocol (RFC 1460) interface
2
3 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
4 ;;        Free Software Foundation, Inc.
5
6 ;; Author: Richard L. Pieri <ratinox@peorth.gweep.net>
7 ;; Maintainer: FSF
8 ;; Keywords: mail
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; Most of the standard Post Office Protocol version 3 (RFC 1460) commands
30 ;; are implemented.  The LIST command has not been implemented due to lack
31 ;; of actual usefulness.
32 ;; The optional POP3 command TOP has not been implemented.
33
34 ;; This program was inspired by Kyle E. Jones's vm-pop program.
35
36 ;;; Code:
37
38 (require 'mail-utils)
39
40 (defvar pop3-maildrop (or (user-login-name) (getenv "LOGNAME") (getenv "USER") nil)
41   "*POP3 maildrop.")
42 (defvar pop3-mailhost (or (getenv "MAILHOST") nil)
43   "*POP3 mailhost.")
44 (defvar pop3-port 110
45   "*POP3 port.")
46
47 (defvar pop3-password-required t
48   "*Non-nil if a password is required when connecting to POP server.")
49 (defvar pop3-password nil
50   "*Password to use when connecting to POP server.")
51
52 (defvar pop3-authentication-scheme 'pass
53   "*POP3 authentication scheme.
54 Defaults to 'pass, for the standard USER/PASS authentication.  Other valid
55 values are 'apop.")
56
57 (defvar pop3-timestamp nil
58   "Timestamp returned when initially connected to the POP server.
59 Used for APOP authentication.")
60
61 (defvar pop3-read-point nil)
62 (defvar pop3-debug nil)
63
64 (defun pop3-movemail (&optional crashbox)
65   "Transfer contents of a maildrop to the specified CRASHBOX."
66   (or crashbox (setq crashbox (expand-file-name "~/.crashbox")))
67   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
68          (crashbuf (get-buffer-create " *pop3-retr*"))
69          (n 1)
70          message-count
71          (pop3-password pop3-password)
72          )
73     ;; for debugging only
74     (if pop3-debug (switch-to-buffer (process-buffer process)))
75     ;; query for password
76     (if (and pop3-password-required (not pop3-password))
77         (setq pop3-password
78               (read-passwd (format "Password for %s: " pop3-maildrop))))
79     (cond ((equal 'apop pop3-authentication-scheme)
80            (pop3-apop process pop3-maildrop))
81           ((equal 'pass pop3-authentication-scheme)
82            (pop3-user process pop3-maildrop)
83            (pop3-pass process))
84           (t (error "Invalid POP3 authentication scheme")))
85     (setq message-count (car (pop3-stat process)))
86     (unwind-protect
87         (while (<= n message-count)
88           (message "Retrieving message %d of %d from %s..."
89                    n message-count pop3-mailhost)
90           (pop3-retr process n crashbuf)
91           (save-excursion
92             (set-buffer crashbuf)
93             (let ((coding-system-for-write 'binary))
94               (write-region (point-min) (point-max) crashbox t 'nomesg))
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   t)
108
109 (defun pop3-get-message-count ()
110   "Return the number of messages in the maildrop."
111   (let* ((process (pop3-open-server pop3-mailhost pop3-port))
112          message-count
113          (pop3-password pop3-password)
114          )
115     ;; for debugging only
116     (if pop3-debug (switch-to-buffer (process-buffer process)))
117     ;; query for password
118     (if (and pop3-password-required (not pop3-password))
119         (setq pop3-password
120               (read-passwd (format "Password for %s: " pop3-maildrop))))
121     (cond ((equal 'apop pop3-authentication-scheme)
122            (pop3-apop process pop3-maildrop))
123           ((equal 'pass pop3-authentication-scheme)
124            (pop3-user process pop3-maildrop)
125            (pop3-pass process))
126           (t (error "Invalid POP3 authentication scheme")))
127     (setq message-count (car (pop3-stat process)))
128     (pop3-quit process)
129     message-count))
130
131 (defun pop3-open-server (mailhost port)
132   "Open TCP connection to MAILHOST on PORT.
133 Returns the process associated with the connection."
134   (let ((coding-system-for-read 'binary)
135         (coding-system-for-write 'binary)
136         process)
137     (save-excursion
138       (set-buffer (get-buffer-create (concat " trace of POP session to "
139                                              mailhost)))
140       (erase-buffer)
141       (setq pop3-read-point (point-min))
142       (setq process (open-network-stream "POP" (current-buffer) mailhost port))
143       (let ((response (pop3-read-response process t)))
144         (setq pop3-timestamp
145               (substring response (or (string-match "<" response) 0)
146                          (+ 1 (or (string-match ">" response) -1)))))
147       process)))
148
149 ;; Support functions
150
151 (defun pop3-process-filter (process output)
152   (save-excursion
153     (set-buffer (process-buffer process))
154     (goto-char (point-max))
155     (insert output)))
156
157 (defun pop3-send-command (process command)
158     (set-buffer (process-buffer process))
159     (goto-char (point-max))
160 ;;    (if (= (aref command 0) ?P)
161 ;;      (insert "PASS <omitted>\r\n")
162 ;;      (insert command "\r\n"))
163     (setq pop3-read-point (point))
164     (goto-char (point-max))
165     (process-send-string process (concat command "\r\n"))
166     )
167
168 (defun pop3-read-response (process &optional return)
169   "Read the response from the server.
170 Return the response string if optional second argument is non-nil."
171   (let ((case-fold-search nil)
172         match-end)
173     (save-excursion
174       (set-buffer (process-buffer process))
175       (goto-char pop3-read-point)
176       (while (and (memq (process-status process) '(open run))
177                   (not (search-forward "\r\n" nil t)))
178         (nnheader-accept-process-output process)
179         (goto-char pop3-read-point))
180       (setq match-end (point))
181       (goto-char pop3-read-point)
182       (if (looking-at "-ERR")
183           (error (buffer-substring (point) (- match-end 2)))
184         (if (not (looking-at "+OK"))
185             (progn (setq pop3-read-point match-end) nil)
186           (setq pop3-read-point match-end)
187           (if return
188               (buffer-substring (point) match-end)
189             t)
190           )))))
191
192 (defun pop3-clean-region (start end)
193   (setq end (set-marker (make-marker) end))
194   (save-excursion
195     (goto-char start)
196     (while (and (< (point) end) (search-forward "\r\n" end t))
197       (replace-match "\n" t t))
198     (goto-char start)
199     (while (and (< (point) end) (re-search-forward "^\\." end t))
200       (replace-match "" t t)
201       (forward-char)))
202   (set-marker end nil))
203
204 (eval-when-compile (defvar parse-time-months))
205
206 ;; Copied from message-make-date.
207 (defun pop3-make-date (&optional now)
208   "Make a valid date header.
209 If NOW, use that time instead."
210   (require 'parse-time)
211   (let* ((now (or now (current-time)))
212          (zone (nth 8 (decode-time now)))
213          (sign "+"))
214     (when (< zone 0)
215       (setq sign "-")
216       (setq zone (- zone)))
217     (concat
218      (format-time-string "%d" now)
219      ;; The month name of the %b spec is locale-specific.  Pfff.
220      (format " %s "
221              (capitalize (car (rassoc (nth 4 (decode-time now))
222                                       parse-time-months))))
223      (format-time-string "%Y %H:%M:%S " now)
224      ;; We do all of this because XEmacs doesn't have the %z spec.
225      (format "%s%02d%02d" sign (/ zone 3600) (/ (% zone 3600) 60)))))
226
227 (defun pop3-munge-message-separator (start end)
228   "Check to see if a message separator exists.  If not, generate one."
229   (save-excursion
230     (save-restriction
231       (narrow-to-region start end)
232       (goto-char (point-min))
233       (if (not (or (looking-at "From .?") ; Unix mail
234                    (looking-at "\001\001\001\001\n") ; MMDF
235                    (looking-at "BABYL OPTIONS:") ; Babyl
236                    ))
237           (let* ((from (mail-strip-quoted-names (mail-fetch-field "From")))
238                  (tdate (mail-fetch-field "Date"))
239                  (date (split-string (or (and tdate
240                                               (not (string= "" tdate))
241                                               tdate)
242                                          (pop3-make-date))
243                                      " "))
244                  (From_))
245             ;; sample date formats I have seen
246             ;; Date: Tue, 9 Jul 1996 09:04:21 -0400 (EDT)
247             ;; Date: 08 Jul 1996 23:22:24 -0400
248             ;; should be
249             ;; Tue Jul 9 09:04:21 1996
250             (setq date
251                   (cond ((not date)
252                          "Tue Jan 1 00:00:0 1900")
253                         ((string-match "[A-Z]" (nth 0 date))
254                          (format "%s %s %s %s %s"
255                                  (nth 0 date) (nth 2 date) (nth 1 date)
256                                  (nth 4 date) (nth 3 date)))
257                         (t
258                          ;; this really needs to be better but I don't feel
259                          ;; like writing a date to day converter.
260                          (format "Sun %s %s %s %s"
261                                  (nth 1 date) (nth 0 date)
262                                  (nth 3 date) (nth 2 date)))
263                         ))
264             (setq From_ (format "\nFrom %s  %s\n" from date))
265             (while (string-match "," From_)
266               (setq From_ (concat (substring From_ 0 (match-beginning 0))
267                                   (substring From_ (match-end 0)))))
268             (goto-char (point-min))
269             (insert From_)
270             (if (search-forward "\n\n" nil t)
271                 nil
272               (goto-char (point-max))
273               (insert "\n"))
274             (narrow-to-region (point) (point-max))
275             (let ((size (- (point-max) (point-min))))
276               (goto-char (point-min))
277               (widen)
278               (forward-line -1)
279               (insert (format "Content-Length: %s\n" size)))
280             )))))
281
282 ;; The Command Set
283
284 ;; AUTHORIZATION STATE
285
286 (defun pop3-user (process user)
287   "Send USER information to POP3 server."
288   (pop3-send-command process (format "USER %s" user))
289   (let ((response (pop3-read-response process t)))
290     (if (not (and response (string-match "+OK" response)))
291         (error (format "USER %s not valid" user)))))
292
293 (defun pop3-pass (process)
294   "Send authentication information to the server."
295   (pop3-send-command process (format "PASS %s" pop3-password))
296   (let ((response (pop3-read-response process t)))
297     (if (not (and response (string-match "+OK" response)))
298         (pop3-quit process))))
299
300 (defun pop3-apop (process user)
301   "Send alternate authentication information to the server."
302   (let ((pass pop3-password))
303     (if (and pop3-password-required (not pass))
304         (setq pass
305               (read-passwd (format "Password for %s: " pop3-maildrop))))
306     (if pass
307         (let ((hash (pop3-md5 (concat pop3-timestamp pass))))
308           (pop3-send-command process (format "APOP %s %s" user hash))
309           (let ((response (pop3-read-response process t)))
310             (if (not (and response (string-match "+OK" response)))
311                 (pop3-quit process)))))
312     ))
313
314 ;; TRANSACTION STATE
315
316 (eval-and-compile
317   (if (fboundp 'md5)
318       (defalias 'pop3-md5 'md5)
319     (defvar pop3-md5-program "md5"
320       "*Program to encode its input in MD5.")
321
322     (defun pop3-md5 (string)
323       (with-temp-buffer
324         (insert string)
325         (call-process-region (point-min) (point-max)
326                              pop3-md5-program
327                              t (current-buffer) nil)
328         ;; The meaningful output is the first 32 characters.
329         ;; Don't return the newline that follows them!
330         (buffer-substring (point-min) (+ 32 (point-min)))))))
331
332 (defun pop3-stat (process)
333   "Return the number of messages in the maildrop and the maildrop's size."
334   (pop3-send-command process "STAT")
335   (let ((response (pop3-read-response process t)))
336     (list (string-to-int (nth 1 (split-string response " ")))
337           (string-to-int (nth 2 (split-string response " "))))
338     ))
339
340 (defun pop3-list (process &optional msg)
341   "Scan listing of available messages.
342 This function currently does nothing.")
343
344 (defun pop3-retr (process msg crashbuf)
345   "Retrieve message-id MSG to buffer CRASHBUF."
346   (pop3-send-command process (format "RETR %s" msg))
347   (pop3-read-response process)
348   (let ((start pop3-read-point) end)
349     (save-excursion
350       (set-buffer (process-buffer process))
351       (while (not (re-search-forward "^\\.\r\n" nil t))
352         ;; Fixme: Shouldn't depend on nnheader.
353         (nnheader-accept-process-output process)
354         ;; bill@att.com ... to save wear and tear on the heap
355         ;; uncommented because the condensed version below is a problem for
356         ;; some.
357         (if (> (buffer-size)  20000) (sleep-for 1))
358         (if (> (buffer-size)  50000) (sleep-for 1))
359         (if (> (buffer-size) 100000) (sleep-for 1))
360         (if (> (buffer-size) 200000) (sleep-for 1))
361         (if (> (buffer-size) 500000) (sleep-for 1))
362         ;; bill@att.com
363         ;; condensed into:
364         ;; (sometimes causes problems for really large messages.)
365 ;       (if (> (buffer-size) 20000) (sleep-for (/ (buffer-size) 20000)))
366         (goto-char start))
367       (setq pop3-read-point (point-marker))
368 ;; this code does not seem to work for some POP servers...
369 ;; and I cannot figure out why not.
370 ;      (goto-char (match-beginning 0))
371 ;      (backward-char 2)
372 ;      (if (not (looking-at "\r\n"))
373 ;         (insert "\r\n"))
374 ;      (re-search-forward "\\.\r\n")
375       (goto-char (match-beginning 0))
376       (setq end (point-marker))
377       (pop3-clean-region start end)
378       (pop3-munge-message-separator start end)
379       (save-excursion
380         (set-buffer crashbuf)
381         (erase-buffer))
382       (copy-to-buffer crashbuf start end)
383       (delete-region start end)
384       )))
385
386 (defun pop3-dele (process msg)
387   "Mark message-id MSG as deleted."
388   (pop3-send-command process (format "DELE %s" msg))
389   (pop3-read-response process))
390
391 (defun pop3-noop (process msg)
392   "No-operation."
393   (pop3-send-command process "NOOP")
394   (pop3-read-response process))
395
396 (defun pop3-last (process)
397   "Return highest accessed message-id number for the session."
398   (pop3-send-command process "LAST")
399   (let ((response (pop3-read-response process t)))
400     (string-to-int (nth 1 (split-string response " ")))
401     ))
402
403 (defun pop3-rset (process)
404   "Remove all delete marks from current maildrop."
405   (pop3-send-command process "RSET")
406   (pop3-read-response process))
407
408 ;; UPDATE
409
410 (defun pop3-quit (process)
411   "Close connection to POP3 server.
412 Tell server to remove all messages marked as deleted, unlock the maildrop,
413 and close the connection."
414   (pop3-send-command process "QUIT")
415   (pop3-read-response process t)
416   (if process
417       (save-excursion
418         (set-buffer (process-buffer process))
419         (goto-char (point-max))
420         (delete-process process))))
421 \f
422 ;; Summary of POP3 (Post Office Protocol version 3) commands and responses
423
424 ;;; AUTHORIZATION STATE
425
426 ;; Initial TCP connection
427 ;; Arguments: none
428 ;; Restrictions: none
429 ;; Possible responses:
430 ;;  +OK [POP3 server ready]
431
432 ;; USER name
433 ;; Arguments: a server specific user-id (required)
434 ;; Restrictions: authorization state [after unsuccessful USER or PASS
435 ;; Possible responses:
436 ;;  +OK [valid user-id]
437 ;;  -ERR [invalid user-id]
438
439 ;; PASS string
440 ;; Arguments: a server/user-id specific password (required)
441 ;; Restrictions: authorization state, after successful USER
442 ;; Possible responses:
443 ;;  +OK [maildrop locked and ready]
444 ;;  -ERR [invalid password]
445 ;;  -ERR [unable to lock maildrop]
446
447 ;;; TRANSACTION STATE
448
449 ;; STAT
450 ;; Arguments: none
451 ;; Restrictions: transaction state
452 ;; Possible responses:
453 ;;  +OK nn mm [# of messages, size of maildrop]
454
455 ;; LIST [msg]
456 ;; Arguments: a message-id (optional)
457 ;; Restrictions: transaction state; msg must not be deleted
458 ;; Possible responses:
459 ;;  +OK [scan listing follows]
460 ;;  -ERR [no such message]
461
462 ;; RETR msg
463 ;; Arguments: a message-id (required)
464 ;; Restrictions: transaction state; msg must not be deleted
465 ;; Possible responses:
466 ;;  +OK [message contents follow]
467 ;;  -ERR [no such message]
468
469 ;; DELE msg
470 ;; Arguments: a message-id (required)
471 ;; Restrictions: transaction state; msg must not be deleted
472 ;; Possible responses:
473 ;;  +OK [message deleted]
474 ;;  -ERR [no such message]
475
476 ;; NOOP
477 ;; Arguments: none
478 ;; Restrictions: transaction state
479 ;; Possible responses:
480 ;;  +OK
481
482 ;; LAST
483 ;; Arguments: none
484 ;; Restrictions: transaction state
485 ;; Possible responses:
486 ;;  +OK nn [highest numbered message accessed]
487
488 ;; RSET
489 ;; Arguments: none
490 ;; Restrictions: transaction state
491 ;; Possible responses:
492 ;;  +OK [all delete marks removed]
493
494 ;;; UPDATE STATE
495
496 ;; QUIT
497 ;; Arguments: none
498 ;; Restrictions: none
499 ;; Possible responses:
500 ;;  +OK [TCP connection closed]
501
502 (provide 'pop3)
503
504 ;;; pop3.el ends here