87eebb544974056b775752c9663a9b6319c69e5d
[gnus] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2 ;; Copyright (C) 1999 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;; Keywords: news, mail
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
23
24 ;;; Commentary:
25
26 ;;; Code:
27
28 (eval-when-compile (require 'cl))
29 (eval-and-compile
30   (autoload 'pop3-movemail "pop3"))
31 (require 'format-spec)
32
33 (defgroup mail-source nil
34   "The mail-fetching library."
35   :group 'gnus)
36
37 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
38   "File where mail will be stored while processing it."
39   :group 'mail-source
40   :type 'file)
41
42 (defcustom mail-source-directory "~/Mail/"
43   "Directory where files (if any) will be stored."
44   :group 'mail-source
45   :type 'directory)
46
47 (defcustom mail-source-default-file-modes 384
48   "Set the mode bits of all new mail files to this integer."
49   :group 'mail-source
50   :type 'integer)
51
52 (defcustom mail-source-delete-incoming nil
53   "*If non-nil, delete incoming files after handling."
54   :group 'mail-source
55   :type 'boolean)
56
57 ;;; Internal variables.
58
59 (defvar mail-source-string ""
60   "A dynamically bound string that says what the current mail source is.")
61
62 (eval-and-compile
63   (defvar mail-source-keyword-map
64     '((file
65        (:path (or (getenv "MAIL")
66                   (concat "/usr/spool/mail/" (user-login-name)))))
67       (directory
68        (:path)
69        (:suffix ".spool")
70        (:predicate identity))
71       (pop
72        (:prescript)
73        (:postscript)
74        (:server (getenv "MAILHOST"))
75        (:port "pop")
76        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
77        (:program)
78        (:function)
79        (:password)
80        (:authentication password))
81       (maildir
82        (:path "~/Maildir/new/")))
83     "Mapping from keywords to default values.
84 All keywords that can be used must be listed here."))
85
86 (defvar mail-source-fetcher-alist
87   '((file mail-source-fetch-file)
88     (directory mail-source-fetch-directory)
89     (pop mail-source-fetch-pop)
90     (maildir mail-source-fetch-maildir))
91   "A mapping from source type to fetcher function.")
92
93 (defvar mail-source-password-cache nil)
94
95 ;;; Functions
96
97 (eval-and-compile
98   (defun mail-source-strip-keyword (keyword)
99   "Strip the leading colon off the KEYWORD."
100   (intern (substring (symbol-name keyword) 1))))
101
102 (eval-and-compile
103   (defun mail-source-bind-1 (type)
104     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
105            default bind)
106       (while (setq default (pop defaults))
107         (push (list (mail-source-strip-keyword (car default))
108                     nil)
109               bind))
110       bind)))
111
112 (defmacro mail-source-bind (type-source &rest body)
113   "Return a `let' form that binds all variables in source TYPE.
114 At run time, the mail source specifier SOURCE will be inspected,
115 and the variables will be set according to it.  Variables not
116 specified will be given default values.
117
118 After this is done, BODY will be executed in the scope
119 of the `let' form."
120   `(let ,(mail-source-bind-1 (car type-source))
121      (mail-source-set-1 ,(cadr type-source))
122      ,@body))
123
124 (put 'mail-source-bind 'lisp-indent-function 1)
125 (put 'mail-source-bind 'edebug-form-spec '(form body))
126
127 (defun mail-source-set-1 (source)
128   (let* ((type (pop source))
129          (defaults (cdr (assq type mail-source-keyword-map)))
130          default value keyword)
131     (while (setq default (pop defaults))
132       (set (mail-source-strip-keyword (setq keyword (car default)))
133            (if (setq value (plist-get source keyword))
134                (mail-source-value value)
135              (mail-source-value (cadr default)))))))
136
137 (defun mail-source-value (value)
138   "Return the value of VALUE."
139   (cond
140    ;; String
141    ((stringp value)
142     value)
143    ;; Function
144    ((and (listp value)
145          (functionp (car value)))
146     (eval value))
147    ;; Just return the value.
148    (t
149     value)))
150
151 (defun mail-source-fetch (source callback)
152   "Fetch mail from SOURCE and call CALLBACK zero or more times.
153 CALLBACK will be called with the name of the file where (some of)
154 the mail from SOURCE is put.
155 Return the number of files that were found."
156   (save-excursion
157     (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
158           (found 0))
159       (unless function
160         (error "%S is an invalid mail source specification" source))
161       ;; If there's anything in the crash box, we do it first.
162       (when (file-exists-p mail-source-crash-box)
163         (message "Processing mail from %s..." mail-source-crash-box)
164         (setq found (mail-source-callback
165                      callback mail-source-crash-box)))
166       (+ found (funcall function source callback)))))
167
168 (defun mail-source-make-complex-temp-name (prefix)
169   (let ((newname (make-temp-name prefix))
170         (newprefix prefix))
171     (while (file-exists-p newname)
172       (setq newprefix (concat newprefix "x"))
173       (setq newname (make-temp-name newprefix)))
174     newname))
175
176 (defun mail-source-callback (callback info)
177   "Call CALLBACK on the mail file, and then remove the mail file.
178 Pass INFO on to CALLBACK."
179   (if (or (not (file-exists-p mail-source-crash-box))
180           (zerop (nth 7 (file-attributes mail-source-crash-box))))
181       (progn
182         (when (file-exists-p mail-source-crash-box)
183           (delete-file mail-source-crash-box))
184         0)
185     (funcall callback mail-source-crash-box info)
186     (when (file-exists-p mail-source-crash-box)
187       ;; Delete or move the incoming mail out of the way.
188       (if mail-source-delete-incoming
189           (delete-file mail-source-crash-box)
190         (let ((incoming
191                (mail-source-make-complex-temp-name
192                 (expand-file-name
193                  "Incoming" mail-source-directory))))
194           (unless (file-exists-p (file-name-directory incoming))
195             (make-directory (file-name-directory incoming) t))
196           (rename-file mail-source-crash-box incoming t))))
197     1))
198
199 (defun mail-source-movemail (from to)
200   "Move FROM to TO using movemail."
201   (if (not (file-writable-p to))
202       (error "Can't write to crash box %s.  Not moving mail" to)
203     (let ((to (file-truename (expand-file-name to)))
204           errors result)
205       (setq to (file-truename to)
206             from (file-truename from))
207       ;; Set TO if have not already done so, and rename or copy
208       ;; the file FROM to TO if and as appropriate.
209       (cond
210        ((file-exists-p to)
211         ;; The crash box exists already.
212         t)
213        ((not (file-exists-p from))
214         ;; There is no inbox.
215         (setq to nil))
216        ((zerop (nth 7 (file-attributes from)))
217         ;; Empty file.
218         (setq to nil))
219        (t
220         ;; If getting from mail spool directory, use movemail to move
221         ;; rather than just renaming, so as to interlock with the
222         ;; mailer.
223         (unwind-protect
224             (save-excursion
225               (setq errors (generate-new-buffer " *mail source loss*"))
226               (let ((default-directory "/"))
227                 (setq result
228                       (apply
229                        'call-process
230                        (append
231                         (list
232                          (expand-file-name "movemail" exec-directory)
233                          nil errors nil from to)))))
234               (when (file-exists-p to)
235                 (set-file-modes to mail-source-default-file-modes))
236               (if (and (not (buffer-modified-p errors))
237                        (zerop result))
238                   ;; No output => movemail won.
239                   t
240                 (set-buffer errors)
241                 ;; There may be a warning about older revisions.  We
242                 ;; ignore that.
243                 (goto-char (point-min))
244                 (if (search-forward "older revision" nil t)
245                     t
246                   ;; Probably a real error.
247                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
248                   (goto-char (point-max))
249                   (skip-chars-backward " \t")
250                   (delete-region (point) (point-max))
251                   (goto-char (point-min))
252                   (when (looking-at "movemail: ")
253                     (delete-region (point-min) (match-end 0)))
254                   (unless (yes-or-no-p
255                            (format "movemail: %s (%d return).  Continue? "
256                                    (buffer-string) result))
257                     (error "%s" (buffer-string)))
258                   (setq to nil)))))))
259       (when (and errors
260                  (buffer-name errors))
261         (kill-buffer errors))
262       ;; Return whether we moved successfully or not.
263       to)))
264
265 (defvar mail-source-read-passwd nil)
266 (defun mail-source-read-passwd (prompt &rest args)
267   "Read a password using PROMPT.
268 If ARGS, PROMPT is used as an argument to `format'."
269   (let ((prompt
270          (if args
271              (apply 'format prompt args)
272            prompt)))
273     (unless mail-source-read-passwd
274       (if (or (fboundp 'read-passwd) (load "passwd" t))
275           (setq mail-source-read-passwd 'read-passwd)
276         (unless (fboundp 'ange-ftp-read-passwd)
277           (autoload 'ange-ftp-read-passwd "ange-ftp"))
278         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
279     (funcall mail-source-read-passwd prompt)))
280
281 (defun mail-source-fetch-with-program (program)
282   (zerop (call-process shell-file-name nil nil nil
283                        shell-command-switch program)))
284
285 ;;;
286 ;;; Different fetchers
287 ;;;
288
289 (defun mail-source-fetch-file (source callback)
290   "Fetcher for single-file sources."
291   (mail-source-bind (file source)
292     (let ((mail-source-string (format "file:%s" path)))
293       (if (mail-source-movemail path mail-source-crash-box)
294           (mail-source-callback callback path)
295         0))))
296
297 (defun mail-source-fetch-directory (source callback)
298   "Fetcher for directory sources."
299   (mail-source-bind (directory source)
300     (let ((found 0)
301           (mail-source-string (format "directory:%s" path)))
302       (dolist (file (directory-files
303                      path t (concat (regexp-quote suffix) "$")))
304         (when (and (file-regular-p file)
305                    (funcall predicate file)
306                    (mail-source-movemail file mail-source-crash-box))
307           (incf found (mail-source-callback callback file))))
308       found)))
309
310 (defun mail-source-fetch-pop (source callback)
311   "Fetcher for single-file sources."
312   (mail-source-bind (pop source)
313     (when prescript
314       (if (fboundp prescript)
315           (funcall prescript)
316         (call-process shell-file-name nil nil nil
317                       shell-command-switch 
318                       (format-spec
319                        prescript
320                        (format-spec-make ?p password ?t mail-source-crash-box
321                                          ?s server ?P port ?u user)))))
322     (let ((from (format "%s:%s:%s" server user port))
323           (mail-source-string (format "pop:%s@%s" user server))
324           result)
325       (when (and (not (eq authentication 'apop))
326                  (not program))
327         (setq password
328               (or password
329                   (cdr (assoc from mail-source-password-cache))
330                   (mail-source-read-passwd
331                    (format "Password for %s at %s: " user server))))
332         (unless (assoc from mail-source-password-cache)
333           (push (cons from password) mail-source-password-cache)))
334       (when server
335         (setenv "MAILHOST" server))
336       (setq result
337             (cond
338              (program
339               (mail-source-fetch-with-program
340                (format-spec
341                 program
342                 (format-spec-make ?p password ?t mail-source-crash-box
343                                   ?s server ?P port ?u user))))
344              (function
345               (funcall function mail-source-crash-box))
346              ;; The default is to use pop3.el.
347              (t
348               (let ((pop3-password password)
349                     (pop3-maildrop user)
350                     (pop3-mailhost server)
351                     (pop3-port port)
352                     (pop3-authentication-scheme
353                      (if (eq authentication 'apop) 'apop 'pass)))
354                 (save-excursion (pop3-movemail mail-source-crash-box))))))
355       (if result
356           (prog1
357               (mail-source-callback callback server)
358             (when prescript
359               (if (fboundp prescript)
360                   (funcall prescript)
361                 (call-process shell-file-name nil nil nil
362                               shell-command-switch 
363                               (format-spec
364                                postscript
365                                (format-spec-make
366                                 ?p password ?t mail-source-crash-box
367                                 ?s server ?P port ?u user)))))
368             1)
369         ;; We nix out the password in case the error
370         ;; was because of a wrong password being given.
371         (setq mail-source-password-cache
372               (delq (assoc from mail-source-password-cache)
373                     mail-source-password-cache))
374         0))))
375
376 (defun mail-source-fetch-maildir (source callback)
377   "Fetcher for maildir sources."
378   (mail-source-bind (maildir source)
379     (let ((found 0)
380           (mail-source-string (format "maildir:%s" path)))
381       (dolist (file (directory-files path t))
382         (when (and (file-regular-p file)
383                    (not (rename-file file mail-source-crash-box)))
384           (incf found (mail-source-callback callback file))))
385       found)))
386
387 (provide 'mail-source)
388
389 ;;; mail-source.el ends here