Importing Pterodactyl Gnus v0.74.
[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
32 (defgroup mail-source nil
33   "The mail-fetching library."
34   :group 'gnus)
35
36 (defcustom mail-source-movemail-program "movemail"
37   "*A command to be executed to move mail from the inbox.
38 The default is \"movemail\".
39
40 This can also be a function.  In that case, the function will be
41 called with two parameters -- the name of the INBOX file, and the file
42 to be moved to."
43   :group 'mail-source
44   :type '(choice string
45                  function))
46
47 (defcustom mail-source-movemail-args nil
48   "*Extra arguments to give to `mail-source-movemail-program'  to move mail from the inbox.
49 The default is nil."
50   :group 'mail-source
51   :type '(choice string
52                  (constant nil)))
53
54 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
55   "File where mail will be stored while processing it."
56   :group 'mail-source
57   :type 'file)
58
59 (defcustom mail-source-directory "~/Mail/"
60   "Directory where files (if any) will be stored."
61   :group 'mail-source
62   :type 'directory)
63
64 (defcustom mail-source-default-file-modes 384
65   "Set the mode bits of all new mail files to this integer."
66   :group 'mail-source
67   :type 'integer)
68
69 (defcustom mail-source-delete-incoming nil
70   "*If non-nil, delete incoming files after handling."
71   :group 'mail-source
72   :type 'boolean)
73
74 ;;; Internal variables.
75
76 (defvar mail-source-string ""
77   "A dynamically bound string that says what the current mail source is.")
78
79 (eval-and-compile
80   (defvar mail-source-keyword-map
81     '((file
82        (:path (or (getenv "MAIL")
83                   (concat "/usr/spool/mail/" (user-login-name)))))
84       (directory
85        (:path)
86        (:suffix ".spool"))
87       (pop
88        (:server (getenv "MAILHOST"))
89        (:port "pop3")
90        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
91        (:password))
92       (maildir
93        (:path)))
94     "Mapping from keywords to default values.
95 All keywords that can be used must be listed here."))
96
97 (defvar mail-source-fetcher-alist
98   '((file mail-source-fetch-file)
99     (directory mail-source-fetch-directory)
100     (pop mail-source-fetch-pop)
101     (qmail mail-source-fetch-qmail))
102   "A mapping from source type to fetcher function.")
103
104 (defvar mail-source-password-cache nil)
105
106 ;;; Functions
107
108 (eval-and-compile
109   (defun mail-source-strip-keyword (keyword)
110   "Strip the leading colon off the KEYWORD."
111   (intern (substring (symbol-name keyword) 1))))
112
113 (eval-and-compile
114   (defun mail-source-bind-1 (type)
115     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
116            default bind)
117       (while (setq default (pop defaults))
118         (push (list (mail-source-strip-keyword (car default))
119                     nil)
120               bind))
121       bind)))
122
123 (defmacro mail-source-bind (type-source &rest body)
124   "Return a `let' form that binds all variables in source TYPE.
125 At run time, the mail source specifier SOURCE will be inspected,
126 and the variables will be set according to it.  Variables not
127 specified will be given default values.
128
129 After this is done, BODY will be executed in the scope
130 of the `let' form."
131   `(let ,(mail-source-bind-1 (car type-source))
132      (mail-source-set-1 ,(cadr type-source))
133      ,@body))
134
135 (put 'mail-source-bind 'lisp-indent-function 1)
136 (put 'mail-source-bind 'edebug-form-spec '(form body))
137
138 (defun mail-source-set-1 (source)
139   (let* ((type (pop source))
140          (defaults (cdr (assq type mail-source-keyword-map)))
141          default value keyword)
142     (while (setq default (pop defaults))
143       (set (mail-source-strip-keyword (setq keyword (car default)))
144            (if (setq value (plist-get source keyword))
145                (mail-source-value value)
146              (mail-source-value (cadr default)))))))
147
148 (defun mail-source-value (value)
149   "Return the value of VALUE."
150   (cond
151    ;; String
152    ((stringp value)
153     value)
154    ;; Function
155    ((and (listp value)
156          (functionp (car value)))
157     (eval value))
158    ;; Variable
159    ((and (symbolp value)
160          (boundp value))
161     (symbol-value 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   (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
172         (found 0))
173     (unless function
174       (error "%S is an invalid mail source specification" source))
175     ;; If there's anything in the crash box, we do it first.
176     (when (file-exists-p mail-source-crash-box)
177       (message "Processing mail from %s..." mail-source-crash-box)
178       (setq found (mail-source-callback
179                    callback mail-source-crash-box)))
180     (+ found (funcall function source callback))))
181
182 (defun mail-source-make-complex-temp-name (prefix)
183   (let ((newname (make-temp-name prefix))
184         (newprefix prefix))
185     (while (file-exists-p newname)
186       (setq newprefix (concat newprefix "x"))
187       (setq newname (make-temp-name newprefix)))
188     newname))
189
190 (defun mail-source-callback (callback info)
191   "Call CALLBACK on the mail file, and then remove the mail file.
192 Pass INFO on to CALLBACK."
193   (if (or (not (file-exists-p mail-source-crash-box))
194           (zerop (nth 7 (file-attributes mail-source-crash-box))))
195       (progn
196         (when (file-exists-p mail-source-crash-box)
197           (delete-file mail-source-crash-box))
198         0)
199     (funcall callback mail-source-crash-box info)
200     (if mail-source-delete-incoming
201         (when (file-exists-p mail-source-crash-box)
202           (delete-file mail-source-crash-box))
203       (let ((incoming
204              (mail-source-make-complex-temp-name
205               (expand-file-name
206                "Incoming" mail-source-directory))))
207         (unless (file-exists-p (file-name-directory incoming))
208           (make-directory (file-name-directory incoming) t))
209         (rename-file mail-source-crash-box incoming t)))
210     1))
211
212 (defun mail-source-movemail (from to)
213   "Move FROM to TO using movemail."
214   (if (not (file-writable-p to))
215       (error "Can't write to crash box %s.  Not moving mail" to)
216     (let ((to (file-truename (expand-file-name to)))
217           errors result)
218       (setq to (file-truename to)
219             from (file-truename from))
220       ;; Set TO if have not already done so, and rename or copy
221       ;; the file FROM to TO if and as appropriate.
222       (cond
223        ((file-exists-p to)
224         ;; The crash box exists already.
225         t)
226        ((not (file-exists-p from))
227         ;; There is no inbox.
228         (setq to nil))
229        ((zerop (nth 7 (file-attributes from)))
230         ;; Empty file.
231         (setq to nil))
232        (t
233         ;; If getting from mail spool directory, use movemail to move
234         ;; rather than just renaming, so as to interlock with the
235         ;; mailer.
236         (unwind-protect
237             (save-excursion
238               (setq errors (generate-new-buffer " *mail source loss*"))
239               (buffer-disable-undo errors)
240               (if (functionp mail-source-movemail-program)
241                   (condition-case err
242                       (progn
243                         (funcall mail-source-movemail-program from to)
244                         (setq result 0))
245                     (error
246                      (save-excursion
247                        (set-buffer errors)
248                        (insert (prin1-to-string err))
249                        (setq result 255))))
250                 (let ((default-directory "/"))
251                   (setq result
252                         (apply
253                          'call-process
254                          (append
255                           (list
256                            (expand-file-name
257                             mail-source-movemail-program exec-directory)
258                            nil errors nil from to)
259                           (when mail-source-movemail-args
260                             mail-source-movemail-args))))))
261               (when (file-exists-p to)
262                 (set-file-modes to mail-source-default-file-modes))
263               (if (and (not (buffer-modified-p errors))
264                        (zerop result))
265                   ;; No output => movemail won.
266                   t
267                 (set-buffer errors)
268                 ;; There may be a warning about older revisions.  We
269                 ;; ignore that.
270                 (goto-char (point-min))
271                 (if (search-forward "older revision" nil t)
272                     t
273                   ;; Probably a real error.
274                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
275                   (goto-char (point-max))
276                   (skip-chars-backward " \t")
277                   (delete-region (point) (point-max))
278                   (goto-char (point-min))
279                   (when (looking-at "movemail: ")
280                     (delete-region (point-min) (match-end 0)))
281                   (unless (yes-or-no-p
282                            (format "movemail: %s (%d return).  Continue? "
283                                    (buffer-string) result))
284                     (error "%s" (buffer-string)))
285                   (setq to nil)))))))
286       (when (and errors
287                  (buffer-name errors))
288         (kill-buffer errors))
289       ;; Return whether we moved successfully or not.
290       to)))
291
292 (defvar mail-source-read-passwd nil)
293 (defun mail-source-read-passwd (prompt &rest args)
294   "Read a password using PROMPT.
295 If ARGS, PROMPT is used as an argument to `format'."
296   (let ((prompt
297          (if args
298              (apply 'format prompt args)
299            prompt)))
300     (unless mail-source-read-passwd
301       (if (load "passwd" t)
302           (setq mail-source-read-passwd 'read-passwd)
303         (unless (fboundp 'ange-ftp-read-passwd)
304           (autoload 'ange-ftp-read-passwd "ange-ftp"))
305         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
306     (funcall mail-source-read-passwd prompt)))
307
308 (defun mail-source-fetch-file (source callback)
309   "Fetcher for single-file sources."
310   (mail-source-bind (file source)
311     (let ((mail-source-string (format "file:%s" path)))
312       (if (mail-source-movemail path mail-source-crash-box)
313           (mail-source-callback callback path)
314         0))))
315
316 (defun mail-source-fetch-directory (source callback)
317   "Fetcher for directory sources."
318   (mail-source-bind (directory source)
319     (let ((files (directory-files
320                   path t
321                   (concat (regexp-quote suffix) "$")))
322           (found 0)
323           (mail-source-string (format "directory:%s" path))
324           file)
325       (while (setq file (pop files))
326         (when (mail-source-movemail file mail-source-crash-box)
327           (incf found (mail-source-callback callback file))))
328       found)))
329
330 (defun mail-source-fetch-pop (source callback)
331   "Fetcher for single-file sources."
332   (mail-source-bind (pop source)
333     (let ((from (format "%s:%s:%s" server user port))
334           (mail-source-string (format "pop:%s@%s" user server)))
335       (setq password
336             (or password
337                 (cdr (assoc from mail-source-password-cache))
338                 (mail-source-read-passwd
339                  (format "Password for %s at %s: " user server))))
340       (unless (assoc from mail-source-password-cache)
341         (push (cons from password) mail-source-password-cache))
342       (let ((pop3-password password)
343             (pop3-maildrop user)
344             (pop3-mailhost server))
345         (if (pop3-movemail mail-source-crash-box)
346             (mail-source-callback callback server)
347           ;; We nix out the password in case the error
348           ;; was because of a wrong password being given.
349           (setq mail-source-password-cache
350                 (delq (assoc from mail-source-password-cache)
351                       mail-source-password-cache))
352           0)))))
353
354 (provide 'mail-source)
355
356 ;;; mail-source.el ends here