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