*** 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
32 (defgroup mail-source nil
33   "The mail-fetching library."
34   :group 'gnus)
35
36 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
37   "File where mail will be stored while processing it."
38   :group 'mail-source
39   :type 'file)
40
41 (defcustom mail-source-directory "~/Mail/"
42   "Directory where files (if any) will be stored."
43   :group 'mail-source
44   :type 'directory)
45
46 (defcustom mail-source-default-file-modes 384
47   "Set the mode bits of all new mail files to this integer."
48   :group 'mail-source
49   :type 'integer)
50
51 (defcustom mail-source-delete-incoming nil
52   "*If non-nil, delete incoming files after handling."
53   :group 'mail-source
54   :type 'boolean)
55
56 ;;; Internal variables.
57
58 (defvar mail-source-string ""
59   "A dynamically bound string that says what the current mail source is.")
60
61 (eval-and-compile
62   (defvar mail-source-keyword-map
63     '((file
64        (:path (or (getenv "MAIL")
65                   (concat "/usr/spool/mail/" (user-login-name)))))
66       (directory
67        (:path)
68        (:suffix ".spool"))
69       (pop
70        (:server (getenv "MAILHOST"))
71        (:port "pop3")
72        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
73        (:program)
74        (:args)
75        (:function)
76        (:password))
77       (maildir
78        (:path)))
79     "Mapping from keywords to default values.
80 All keywords that can be used must be listed here."))
81
82 (defvar mail-source-fetcher-alist
83   '((file mail-source-fetch-file)
84     (directory mail-source-fetch-directory)
85     (pop mail-source-fetch-pop)
86     (qmail mail-source-fetch-qmail))
87   "A mapping from source type to fetcher function.")
88
89 (defvar mail-source-password-cache nil)
90
91 ;;; Functions
92
93 (eval-and-compile
94   (defun mail-source-strip-keyword (keyword)
95   "Strip the leading colon off the KEYWORD."
96   (intern (substring (symbol-name keyword) 1))))
97
98 (eval-and-compile
99   (defun mail-source-bind-1 (type)
100     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
101            default bind)
102       (while (setq default (pop defaults))
103         (push (list (mail-source-strip-keyword (car default))
104                     nil)
105               bind))
106       bind)))
107
108 (defmacro mail-source-bind (type-source &rest body)
109   "Return a `let' form that binds all variables in source TYPE.
110 At run time, the mail source specifier SOURCE will be inspected,
111 and the variables will be set according to it.  Variables not
112 specified will be given default values.
113
114 After this is done, BODY will be executed in the scope
115 of the `let' form."
116   `(let ,(mail-source-bind-1 (car type-source))
117      (mail-source-set-1 ,(cadr type-source))
118      ,@body))
119
120 (put 'mail-source-bind 'lisp-indent-function 1)
121 (put 'mail-source-bind 'edebug-form-spec '(form body))
122
123 (defun mail-source-set-1 (source)
124   (let* ((type (pop source))
125          (defaults (cdr (assq type mail-source-keyword-map)))
126          default value keyword)
127     (while (setq default (pop defaults))
128       (set (mail-source-strip-keyword (setq keyword (car default)))
129            (if (setq value (plist-get source keyword))
130                (mail-source-value value)
131              (mail-source-value (cadr default)))))))
132
133 (defun mail-source-value (value)
134   "Return the value of VALUE."
135   (cond
136    ;; String
137    ((stringp value)
138     value)
139    ;; Function
140    ((and (listp value)
141          (functionp (car value)))
142     (eval value))
143    ;; Variable
144    ((and (symbolp value)
145          (boundp value))
146     (symbol-value 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 args to)
282   (zerop (apply 'call-process program nil nil nil
283                 (append (split-string args) (list to)))))
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                    (mail-source-movemail file mail-source-crash-box))
306           (incf found (mail-source-callback callback file))))
307       found)))
308
309 (defun mail-source-fetch-pop (source callback)
310   "Fetcher for single-file sources."
311   (mail-source-bind (pop source)
312     (let ((from (format "%s:%s:%s" server user port))
313           (mail-source-string (format "pop:%s@%s" user server)))
314       (setq password
315             (or password
316                 (cdr (assoc from mail-source-password-cache))
317                 (mail-source-read-passwd
318                  (format "Password for %s at %s: " user server))))
319       (unless (assoc from mail-source-password-cache)
320         (push (cons from password) mail-source-password-cache))
321       (when server
322         (setenv "MAILHOST" server))
323       (if (cond
324            (program
325             (when (listp args)
326               (setq args (eval args)))
327             (mail-source-fetch-with-program
328              program args mail-source-crash-box))
329            (function
330               (funcall function mail-source-crash-box))
331            ;; The default is to use pop3.el.
332            (t
333             (let ((pop3-password password)
334                   (pop3-maildrop user)
335                   (pop3-mailhost server))
336               (save-excursion (pop3-movemail mail-source-crash-box)))))
337           (mail-source-callback callback server)
338         ;; We nix out the password in case the error
339         ;; was because of a wrong password being given.
340         (setq mail-source-password-cache
341               (delq (assoc from mail-source-password-cache)
342                     mail-source-password-cache))
343         0))))
344
345 (provide 'mail-source)
346
347 ;;; mail-source.el ends here