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