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