*** empty log message ***
[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        (:server (getenv "MAILHOST"))
73        (:port "pop3")
74        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
75        (:program)
76        (:function)
77        (:password)
78        (:authentication password))
79       (maildir
80        (:path "~/Maildir/new/")))
81     "Mapping from keywords to default values.
82 All keywords that can be used must be listed here."))
83
84 (defvar mail-source-fetcher-alist
85   '((file mail-source-fetch-file)
86     (directory mail-source-fetch-directory)
87     (pop mail-source-fetch-pop)
88     (maildir mail-source-fetch-maildir))
89   "A mapping from source type to fetcher function.")
90
91 (defvar mail-source-password-cache nil)
92
93 ;;; Functions
94
95 (eval-and-compile
96   (defun mail-source-strip-keyword (keyword)
97   "Strip the leading colon off the KEYWORD."
98   (intern (substring (symbol-name keyword) 1))))
99
100 (eval-and-compile
101   (defun mail-source-bind-1 (type)
102     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
103            default bind)
104       (while (setq default (pop defaults))
105         (push (list (mail-source-strip-keyword (car default))
106                     nil)
107               bind))
108       bind)))
109
110 (defmacro mail-source-bind (type-source &rest body)
111   "Return a `let' form that binds all variables in source TYPE.
112 At run time, the mail source specifier SOURCE will be inspected,
113 and the variables will be set according to it.  Variables not
114 specified will be given default values.
115
116 After this is done, BODY will be executed in the scope
117 of the `let' form."
118   `(let ,(mail-source-bind-1 (car type-source))
119      (mail-source-set-1 ,(cadr type-source))
120      ,@body))
121
122 (put 'mail-source-bind 'lisp-indent-function 1)
123 (put 'mail-source-bind 'edebug-form-spec '(form body))
124
125 (defun mail-source-set-1 (source)
126   (let* ((type (pop source))
127          (defaults (cdr (assq type mail-source-keyword-map)))
128          default value keyword)
129     (while (setq default (pop defaults))
130       (set (mail-source-strip-keyword (setq keyword (car default)))
131            (if (setq value (plist-get source keyword))
132                (mail-source-value value)
133              (mail-source-value (cadr default)))))))
134
135 (defun mail-source-value (value)
136   "Return the value of VALUE."
137   (cond
138    ;; String
139    ((stringp value)
140     value)
141    ;; Function
142    ((and (listp value)
143          (functionp (car value)))
144     (eval value))
145    ;; Just return the value.
146    (t
147     value)))
148
149 (defun mail-source-fetch (source callback)
150   "Fetch mail from SOURCE and call CALLBACK zero or more times.
151 CALLBACK will be called with the name of the file where (some of)
152 the mail from SOURCE is put.
153 Return the number of files that were found."
154   (save-excursion
155     (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
156           (found 0))
157       (unless function
158         (error "%S is an invalid mail source specification" source))
159       ;; If there's anything in the crash box, we do it first.
160       (when (file-exists-p mail-source-crash-box)
161         (message "Processing mail from %s..." mail-source-crash-box)
162         (setq found (mail-source-callback
163                      callback mail-source-crash-box)))
164       (+ found (funcall function source callback)))))
165
166 (defun mail-source-make-complex-temp-name (prefix)
167   (let ((newname (make-temp-name prefix))
168         (newprefix prefix))
169     (while (file-exists-p newname)
170       (setq newprefix (concat newprefix "x"))
171       (setq newname (make-temp-name newprefix)))
172     newname))
173
174 (defun mail-source-callback (callback info)
175   "Call CALLBACK on the mail file, and then remove the mail file.
176 Pass INFO on to CALLBACK."
177   (if (or (not (file-exists-p mail-source-crash-box))
178           (zerop (nth 7 (file-attributes mail-source-crash-box))))
179       (progn
180         (when (file-exists-p mail-source-crash-box)
181           (delete-file mail-source-crash-box))
182         0)
183     (funcall callback mail-source-crash-box info)
184     (when (file-exists-p mail-source-crash-box)
185       ;; Delete or move the incoming mail out of the way.
186       (if mail-source-delete-incoming
187           (delete-file mail-source-crash-box)
188         (let ((incoming
189                (mail-source-make-complex-temp-name
190                 (expand-file-name
191                  "Incoming" mail-source-directory))))
192           (unless (file-exists-p (file-name-directory incoming))
193             (make-directory (file-name-directory incoming) t))
194           (rename-file mail-source-crash-box incoming t))))
195     1))
196
197 (defun mail-source-movemail (from to)
198   "Move FROM to TO using movemail."
199   (if (not (file-writable-p to))
200       (error "Can't write to crash box %s.  Not moving mail" to)
201     (let ((to (file-truename (expand-file-name to)))
202           errors result)
203       (setq to (file-truename to)
204             from (file-truename from))
205       ;; Set TO if have not already done so, and rename or copy
206       ;; the file FROM to TO if and as appropriate.
207       (cond
208        ((file-exists-p to)
209         ;; The crash box exists already.
210         t)
211        ((not (file-exists-p from))
212         ;; There is no inbox.
213         (setq to nil))
214        ((zerop (nth 7 (file-attributes from)))
215         ;; Empty file.
216         (setq to nil))
217        (t
218         ;; If getting from mail spool directory, use movemail to move
219         ;; rather than just renaming, so as to interlock with the
220         ;; mailer.
221         (unwind-protect
222             (save-excursion
223               (setq errors (generate-new-buffer " *mail source loss*"))
224               (let ((default-directory "/"))
225                 (setq result
226                       (apply
227                        'call-process
228                        (append
229                         (list
230                          (expand-file-name "movemail" exec-directory)
231                          nil errors nil from to)))))
232               (when (file-exists-p to)
233                 (set-file-modes to mail-source-default-file-modes))
234               (if (and (not (buffer-modified-p errors))
235                        (zerop result))
236                   ;; No output => movemail won.
237                   t
238                 (set-buffer errors)
239                 ;; There may be a warning about older revisions.  We
240                 ;; ignore that.
241                 (goto-char (point-min))
242                 (if (search-forward "older revision" nil t)
243                     t
244                   ;; Probably a real error.
245                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
246                   (goto-char (point-max))
247                   (skip-chars-backward " \t")
248                   (delete-region (point) (point-max))
249                   (goto-char (point-min))
250                   (when (looking-at "movemail: ")
251                     (delete-region (point-min) (match-end 0)))
252                   (unless (yes-or-no-p
253                            (format "movemail: %s (%d return).  Continue? "
254                                    (buffer-string) result))
255                     (error "%s" (buffer-string)))
256                   (setq to nil)))))))
257       (when (and errors
258                  (buffer-name errors))
259         (kill-buffer errors))
260       ;; Return whether we moved successfully or not.
261       to)))
262
263 (defvar mail-source-read-passwd nil)
264 (defun mail-source-read-passwd (prompt &rest args)
265   "Read a password using PROMPT.
266 If ARGS, PROMPT is used as an argument to `format'."
267   (let ((prompt
268          (if args
269              (apply 'format prompt args)
270            prompt)))
271     (unless mail-source-read-passwd
272       (if (or (fboundp 'read-passwd) (load "passwd" t))
273           (setq mail-source-read-passwd 'read-passwd)
274         (unless (fboundp 'ange-ftp-read-passwd)
275           (autoload 'ange-ftp-read-passwd "ange-ftp"))
276         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
277     (funcall mail-source-read-passwd prompt)))
278
279 (defun mail-source-fetch-with-program (program)
280   (zerop (call-process shell-file-name nil nil nil
281                        shell-command-switch program)))
282
283 ;;;
284 ;;; Different fetchers
285 ;;;
286
287 (defun mail-source-fetch-file (source callback)
288   "Fetcher for single-file sources."
289   (mail-source-bind (file source)
290     (let ((mail-source-string (format "file:%s" path)))
291       (if (mail-source-movemail path mail-source-crash-box)
292           (mail-source-callback callback path)
293         0))))
294
295 (defun mail-source-fetch-directory (source callback)
296   "Fetcher for directory sources."
297   (mail-source-bind (directory source)
298     (let ((found 0)
299           (mail-source-string (format "directory:%s" path)))
300       (dolist (file (directory-files
301                      path t (concat (regexp-quote suffix) "$")))
302         (when (and (file-regular-p file)
303                    (funcall predicate file)
304                    (mail-source-movemail file mail-source-crash-box))
305           (incf found (mail-source-callback callback file))))
306       found)))
307
308 (defun mail-source-fetch-pop (source callback)
309   "Fetcher for single-file sources."
310   (mail-source-bind (pop source)
311     (let ((from (format "%s:%s:%s" server user port))
312           (mail-source-string (format "pop:%s@%s" user server)))
313       (when (and (not (eq authentication 'apop))
314                  (not program))
315         (setq password
316               (or password
317                   (cdr (assoc from mail-source-password-cache))
318                   (mail-source-read-passwd
319                    (format "Password for %s at %s: " user server))))
320         (unless (assoc from mail-source-password-cache)
321           (push (cons from password) mail-source-password-cache)))
322       (when server
323         (setenv "MAILHOST" server))
324       (if (cond
325            (program
326             (mail-source-fetch-with-program
327              (format-spec
328               program
329               (format-spec-make ?p password ?t mail-source-crash-box
330                                 ?s server ?P port ?u user))))
331            (function
332             (funcall function mail-source-crash-box))
333            ;; The default is to use pop3.el.
334            (t
335             (let ((pop3-password password)
336                   (pop3-maildrop user)
337                   (pop3-mailhost server)
338                   (pop3-authentication-scheme
339                    (if (eq authentication 'apop) 'apop 'pass)))
340               (save-excursion (pop3-movemail mail-source-crash-box)))))
341           (mail-source-callback callback server)
342         ;; We nix out the password in case the error
343         ;; was because of a wrong password being given.
344         (setq mail-source-password-cache
345               (delq (assoc from mail-source-password-cache)
346                     mail-source-password-cache))
347         0))))
348
349 (defun mail-source-fetch-maildir (source callback)
350   "Fetcher for maildir sources."
351   (mail-source-bind (maildir source)
352     (let ((found 0)
353           (mail-source-string (format "maildir:%s" path)))
354       (dolist (file (directory-files path t))
355         (when (and (file-regular-p file)
356                    (not (rename-file file mail-source-crash-box)))
357           (incf found (mail-source-callback callback file))))
358       found)))
359
360 (provide 'mail-source)
361
362 ;;; mail-source.el ends here