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