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