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