(nnimap-request-list): Protect against not being able to open the server.
[gnus] / lisp / mail-source.el
1 ;;; mail-source.el --- functions for fetching mail
2
3 ;; Copyright (C) 1999-2011  Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news, mail
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;;; Code:
26
27 ;; For Emacs <22.2 and XEmacs.
28 (eval-and-compile
29   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
30
31 (require 'format-spec)
32 (eval-when-compile
33   (require 'cl)
34   (require 'imap))
35 (autoload 'auth-source-search "auth-source")
36 (autoload 'pop3-movemail "pop3")
37 (autoload 'pop3-get-message-count "pop3")
38 (autoload 'nnheader-cancel-timer "nnheader")
39 (require 'mm-util)
40 (require 'message) ;; for `message-directory'
41
42 (defvar display-time-mail-function)
43
44 (defgroup mail-source nil
45   "The mail-fetching library."
46   :version "21.1"
47   :group 'gnus)
48
49 ;; Define these at compile time to avoid dragging in imap always.
50 (defconst mail-source-imap-authenticators
51   (eval-when-compile
52     (mapcar (lambda (a)
53               (list 'const (car a)))
54      imap-authenticator-alist)))
55 (defconst mail-source-imap-streams
56   (eval-when-compile
57     (mapcar (lambda (a)
58               (list 'const (car a)))
59      imap-stream-alist)))
60
61 (defcustom mail-sources '((file))
62   "Where the mail backends will look for incoming mail.
63 This variable is a list of mail source specifiers.
64 See Info node `(gnus)Mail Source Specifiers'."
65   :group 'mail-source
66   :version "23.1" ;; No Gnus
67   :link '(custom-manual "(gnus)Mail Source Specifiers")
68   :type `(choice
69           (const :tag "None" nil)
70           (repeat :tag "List"
71            (choice :format "%[Value Menu%] %v"
72                    :value (file)
73                    (cons :tag "Group parameter `mail-source'"
74                          (const :format "" group))
75                    (cons :tag "Spool file"
76                          (const :format "" file)
77                          (checklist :tag "Options" :greedy t
78                                     (group :inline t
79                                            (const :format "" :value :path)
80                                            file)))
81                    (cons :tag "Several files in a directory"
82                          (const :format "" directory)
83                          (checklist :tag "Options" :greedy t
84                                     (group :inline t
85                                            (const :format "" :value :path)
86                                            (directory :tag "Path"))
87                                     (group :inline t
88                                            (const :format "" :value :suffix)
89                                            (string :tag "Suffix"))
90                                     (group :inline t
91                                            (const :format "" :value :predicate)
92                                            (function :tag "Predicate"))
93                                     (group :inline t
94                                            (const :format "" :value :prescript)
95                                            (choice :tag "Prescript"
96                                                    :value nil
97                                                    (string :format "%v")
98                                                    (function :format "%v")))
99                                     (group :inline t
100                                            (const :format "" :value :postscript)
101                                            (choice :tag "Postscript"
102                                                    :value nil
103                                                    (string :format "%v")
104                                                    (function :format "%v")))
105                                     (group :inline t
106                                            (const :format "" :value :plugged)
107                                            (boolean :tag "Plugged"))))
108                    (cons :tag "POP3 server"
109                          (const :format "" pop)
110                          (checklist :tag "Options" :greedy t
111                                     (group :inline t
112                                            (const :format "" :value :server)
113                                            (string :tag "Server"))
114                                     (group :inline t
115                                            (const :format "" :value :port)
116                                            (choice :tag "Port"
117                                                    :value "pop3"
118                                                    (integer :format "%v")
119                                                    (string :format "%v")))
120                                     (group :inline t
121                                            (const :format "" :value :user)
122                                            (string :tag "User"))
123                                     (group :inline t
124                                            (const :format "" :value :password)
125                                            (string :tag "Password"))
126                                     (group :inline t
127                                            (const :format "" :value :program)
128                                            (string :tag "Program"))
129                                     (group :inline t
130                                            (const :format "" :value :prescript)
131                                            (choice :tag "Prescript"
132                                                    :value nil
133                                                    (string :format "%v")
134                                                    (function :format "%v")
135                                                    (const :tag "None" nil)))
136                                     (group :inline t
137                                            (const :format "" :value :postscript)
138                                            (choice :tag "Postscript"
139                                                    :value nil
140                                                    (string :format "%v")
141                                                    (function :format "%v")
142                                                    (const :tag "None" nil)))
143                                     (group :inline t
144                                            (const :format "" :value :function)
145                                            (function :tag "Function"))
146                                     (group :inline t
147                                            (const :format ""
148                                                   :value :authentication)
149                                            (choice :tag "Authentication"
150                                                    :value apop
151                                                    (const password)
152                                                    (const apop)))
153                                     (group :inline t
154                                            (const :format "" :value :plugged)
155                                            (boolean :tag "Plugged"))
156                                     (group :inline t
157                                            (const :format "" :value :stream)
158                                            (choice :tag "Stream"
159                                                    :value nil
160                                                    (const :tag "Clear" nil)
161                                                    (const starttls)
162                                                    (const :tag "SSL/TLS" ssl)))))
163                    (cons :tag "Maildir (qmail, postfix...)"
164                          (const :format "" maildir)
165                          (checklist :tag "Options" :greedy t
166                                     (group :inline t
167                                            (const :format "" :value :path)
168                                            (directory :tag "Path"))
169                                     (group :inline t
170                                            (const :format "" :value :plugged)
171                                            (boolean :tag "Plugged"))))
172                    (cons :tag "IMAP server"
173                          (const :format "" imap)
174                          (checklist :tag "Options" :greedy t
175                                     (group :inline t
176                                            (const :format "" :value :server)
177                                            (string :tag "Server"))
178                                     (group :inline t
179                                            (const :format "" :value :port)
180                                            (choice :tag "Port"
181                                                    :value 143
182                                                    integer string))
183                                     (group :inline t
184                                            (const :format "" :value :user)
185                                            (string :tag "User"))
186                                     (group :inline t
187                                            (const :format "" :value :password)
188                                            (string :tag "Password"))
189                                     (group :inline t
190                                            (const :format "" :value :stream)
191                                            (choice :tag "Stream"
192                                                    :value network
193                                                    ,@mail-source-imap-streams))
194                                     (group :inline t
195                                            (const :format "" :value :program)
196                                            (string :tag "Program"))
197                                     (group :inline t
198                                            (const :format ""
199                                                   :value :authenticator)
200                                            (choice :tag "Authenticator"
201                                                    :value login
202                                                    ,@mail-source-imap-authenticators))
203                                     (group :inline t
204                                            (const :format "" :value :mailbox)
205                                            (string :tag "Mailbox"
206                                                    :value "INBOX"))
207                                     (group :inline t
208                                            (const :format "" :value :predicate)
209                                            (string :tag "Predicate"
210                                                    :value "UNSEEN UNDELETED"))
211                                     (group :inline t
212                                            (const :format "" :value :fetchflag)
213                                            (string :tag "Fetchflag"
214                                                    :value  "\\Deleted"))
215                                     (group :inline t
216                                            (const :format ""
217                                                   :value :dontexpunge)
218                                            (boolean :tag "Dontexpunge"))
219                                     (group :inline t
220                                            (const :format "" :value :plugged)
221                                            (boolean :tag "Plugged"))))))))
222
223 (defcustom mail-source-ignore-errors nil
224   "*Ignore errors when querying mail sources.
225 If nil, the user will be prompted when an error occurs.  If non-nil,
226 the error will be ignored."
227   :version "22.1"
228   :group 'mail-source
229   :type 'boolean)
230
231 (defcustom mail-source-primary-source nil
232   "*Primary source for incoming mail.
233 If non-nil, this maildrop will be checked periodically for new mail."
234   :group 'mail-source
235   :type 'sexp)
236
237 (defcustom mail-source-flash t
238   "*If non-nil, flash periodically when mail is available."
239   :group 'mail-source
240   :type 'boolean)
241
242 (defcustom mail-source-crash-box "~/.emacs-mail-crash-box"
243   "File where mail will be stored while processing it."
244   :group 'mail-source
245   :type 'file)
246
247 (defcustom mail-source-directory message-directory
248   "Directory where incoming mail source files (if any) will be stored."
249   :group 'mail-source
250   :type 'directory)
251
252 (defcustom mail-source-default-file-modes 384
253   "Set the mode bits of all new mail files to this integer."
254   :group 'mail-source
255   :type 'integer)
256
257 (defcustom mail-source-delete-incoming
258   10 ;; development versions
259   ;; 2 ;; released versions
260   "If non-nil, delete incoming files after handling.
261 If t, delete immediately, if nil, never delete.  If a positive number, delete
262 files older than number of days.
263
264 Removing of old files happens in `mail-source-callback', i.e. no
265 old incoming files will be deleted unless you receive new mail.
266 You may also set this variable to nil and call
267 `mail-source-delete-old-incoming' interactively."
268   :group 'mail-source
269   :version "22.2" ;; No Gnus / Gnus 5.10.10 (default changed)
270   :type '(choice (const :tag "immediately" t)
271                  (const :tag "never" nil)
272                  (integer :tag "days")))
273
274 (defcustom mail-source-delete-old-incoming-confirm nil
275   "If non-nil, ask for confirmation before deleting old incoming files.
276 This variable only applies when `mail-source-delete-incoming' is a positive
277 number."
278   :version "22.2" ;; No Gnus / Gnus 5.10.10 (default changed)
279   :group 'mail-source
280   :type 'boolean)
281
282 (defcustom mail-source-incoming-file-prefix "Incoming"
283   "Prefix for file name for storing incoming mail"
284   :group 'mail-source
285   :type 'string)
286
287 (defcustom mail-source-report-new-mail-interval 5
288   "Interval in minutes between checks for new mail."
289   :group 'mail-source
290   :type 'number)
291
292 (defcustom mail-source-idle-time-delay 5
293   "Number of idle seconds to wait before checking for new mail."
294   :group 'mail-source
295   :type 'number)
296
297 (defcustom mail-source-movemail-program nil
298   "If non-nil, name of program for fetching new mail."
299   :version "22.1"
300   :group 'mail-source
301   :type '(choice (const nil) string))
302
303 ;;; Internal variables.
304
305 (defvar mail-source-string ""
306   "A dynamically bound string that says what the current mail source is.")
307
308 (defvar mail-source-new-mail-available nil
309   "Flag indicating when new mail is available.")
310
311 (eval-and-compile
312   (defvar mail-source-common-keyword-map
313     '((:plugged))
314     "Mapping from keywords to default values.
315 Common keywords should be listed here.")
316
317   (defvar mail-source-keyword-map
318     '((file
319        (:prescript)
320        (:prescript-delay)
321        (:postscript)
322        (:path (or (getenv "MAIL")
323                   (expand-file-name (user-login-name) rmail-spool-directory))))
324       (directory
325        (:prescript)
326        (:prescript-delay)
327        (:postscript)
328        (:path)
329        (:suffix ".spool")
330        (:predicate identity))
331       (pop
332        (:prescript)
333        (:prescript-delay)
334        (:postscript)
335        ;; note server and port need to come before user and password
336        (:server (getenv "MAILHOST"))
337        (:port 110)
338        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
339        (:program)
340        (:function)
341        (:password)
342        (:authentication password)
343        (:stream nil))
344       (maildir
345        (:path (or (getenv "MAILDIR") "~/Maildir/"))
346        (:subdirs ("cur" "new"))
347        (:function))
348       (imap
349        ;; note server and port need to come before user and password
350        (:server (getenv "MAILHOST"))
351        (:port)
352        (:stream)
353        (:program)
354        (:authentication)
355        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
356        (:password)
357        (:mailbox "INBOX")
358        (:predicate "UNSEEN UNDELETED")
359        (:fetchflag "\\Deleted")
360        (:prescript)
361        (:prescript-delay)
362        (:postscript)
363        (:dontexpunge)))
364     "Mapping from keywords to default values.
365 All keywords that can be used must be listed here."))
366
367 (defvar mail-source-fetcher-alist
368   '((file mail-source-fetch-file)
369     (directory mail-source-fetch-directory)
370     (pop mail-source-fetch-pop)
371     (maildir mail-source-fetch-maildir)
372     (imap mail-source-fetch-imap))
373   "A mapping from source type to fetcher function.")
374
375 (defvar mail-source-password-cache nil)
376
377 (defvar mail-source-plugged t)
378
379 ;;; Functions
380
381 (eval-and-compile
382   (defun mail-source-strip-keyword (keyword)
383     "Strip the leading colon off the KEYWORD."
384     (intern (substring (symbol-name keyword) 1))))
385
386 ;; generate a list of variable names paired with nil values
387 ;; suitable for usage in a `let' form
388 (eval-and-compile
389   (defun mail-source-bind-1 (type)
390     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
391            default bind)
392       (while (setq default (pop defaults))
393         (push (list (mail-source-strip-keyword (car default))
394                     nil)
395               bind))
396       bind)))
397
398 (defmacro mail-source-bind (type-source &rest body)
399   "Return a `let' form that binds all variables in source TYPE.
400 TYPE-SOURCE is a list where the first element is the TYPE, and
401 the second variable is the SOURCE.
402 At run time, the mail source specifier SOURCE will be inspected,
403 and the variables will be set according to it.  Variables not
404 specified will be given default values.
405
406 The user and password will be loaded from the auth-source values
407 if those are available.  They override the original user and
408 password in a second `let' form.
409
410 After this is done, BODY will be executed in the scope
411 of the second `let' form.
412
413 The variables bound and their default values are described by
414 the `mail-source-keyword-map' variable."
415   `(let* ,(mail-source-bind-1 (car type-source))
416      (mail-source-set-1 ,(cadr type-source))
417      ,@body))
418
419 (put 'mail-source-bind 'lisp-indent-function 1)
420 (put 'mail-source-bind 'edebug-form-spec '(sexp body))
421
422 (defun mail-source-set-1 (source)
423   (let* ((type (pop source))
424          (defaults (cdr (assq type mail-source-keyword-map)))
425          (search '(:max 1))
426          found default value keyword auth-info user-auth pass-auth)
427
428     ;; append to the search the useful info from the source and the defaults:
429     ;; user, host, and port
430
431     ;; the msname is the mail-source parameter
432     (dolist (msname '(:server :user :port))
433       ;; the asname is the auth-source parameter
434       (let* ((asname (case msname
435                        (:server :host)  ; auth-source uses :host
436                        (t msname)))
437              ;; this is the mail-source default
438              (msdef1 (or (plist-get source msname)
439                          (nth 1 (assoc msname defaults))))
440              ;; ...evaluated
441              (msdef (mail-source-value msdef1)))
442         (setq search (append (list asname
443                                    (if msdef msdef t))
444                              search))))
445     ;; if the port is unknown yet, get it from the mail-source type
446     (unless (plist-get search :port)
447       (setq search (append (list :port (symbol-name type)))))
448
449     (while (setq default (pop defaults))
450       ;; for each default :SYMBOL, set SYMBOL to the plist value for :SYMBOL
451       ;; using `mail-source-value' to evaluate the plist value
452       (set (mail-source-strip-keyword (setq keyword (car default)))
453            ;; note the following reasons for this structure:
454            ;; 1) the auth-sources user and password override everything
455            ;; 2) it avoids macros, so it's cleaner
456            ;; 3) it falls through to the mail-sources and then default values
457            (cond
458             ((and
459              (eq keyword :user)
460              (setq user-auth (plist-get
461                               ;; cache the search result in `found'
462                               (or found
463                                   (setq found (nth 0 (apply 'auth-source-search
464                                                             search))))
465                               :user)))
466              user-auth)
467             ((and
468               (eq keyword :password)
469               (setq pass-auth (plist-get
470                                ;; cache the search result in `found'
471                                (or found
472                                    (setq found (nth 0 (apply 'auth-source-search
473                                                              search))))
474                                :secret)))
475              ;; maybe set the password to the return of the :secret function
476              (if (functionp pass-auth)
477                  (setq pass-auth (funcall pass-auth))
478                pass-auth))
479             (t (if (setq value (plist-get source keyword))
480                  (mail-source-value value)
481                (mail-source-value (cadr default)))))))))
482
483 (eval-and-compile
484   (defun mail-source-bind-common-1 ()
485     (let* ((defaults mail-source-common-keyword-map)
486            default bind)
487       (while (setq default (pop defaults))
488         (push (list (mail-source-strip-keyword (car default))
489                     nil)
490               bind))
491       bind)))
492
493 (defun mail-source-set-common-1 (source)
494   (let* ((type (pop source))
495          (defaults mail-source-common-keyword-map)
496          (defaults-1 (cdr (assq type mail-source-keyword-map)))
497          default value keyword)
498     (while (setq default (pop defaults))
499       (set (mail-source-strip-keyword (setq keyword (car default)))
500            (if (setq value (plist-get source keyword))
501                (mail-source-value value)
502              (if (setq value (assq  keyword defaults-1))
503                  (mail-source-value (cadr value))
504                (mail-source-value (cadr default))))))))
505
506 (defmacro mail-source-bind-common (source &rest body)
507   "Return a `let' form that binds all common variables.
508 See `mail-source-bind'."
509   `(let ,(mail-source-bind-common-1)
510      (mail-source-set-common-1 source)
511      ,@body))
512
513 (put 'mail-source-bind-common 'lisp-indent-function 1)
514 (put 'mail-source-bind-common 'edebug-form-spec '(sexp body))
515
516 (defun mail-source-value (value)
517   "Return the value of VALUE."
518   (cond
519    ;; String
520    ((stringp value)
521     value)
522    ;; Function
523    ((and (listp value) (symbolp (car value)) (fboundp (car value)))
524     (eval value))
525    ;; Just return the value.
526    (t
527     value)))
528
529 (autoload 'nnheader-message "nnheader")
530
531 (defun mail-source-fetch (source callback &optional method)
532   "Fetch mail from SOURCE and call CALLBACK zero or more times.
533 CALLBACK will be called with the name of the file where (some of)
534 the mail from SOURCE is put.
535 Return the number of files that were found."
536   (mail-source-bind-common source
537     (if (or mail-source-plugged plugged)
538         (save-excursion
539           ;; Special-case the `file' handler since it's so common and
540           ;; just adds noise.
541           (when (or (not (eq (car source) 'file))
542                     (mail-source-bind (file source)
543                       (file-exists-p path)))
544             (nnheader-message 4 "%sReading incoming mail from %s..."
545                               (if method
546                                   (format "%s: " method)
547                                 "")
548                               (car source)))
549           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
550                 (found 0))
551             (unless function
552               (error "%S is an invalid mail source specification" source))
553             ;; If there's anything in the crash box, we do it first.
554             (when (file-exists-p mail-source-crash-box)
555               (message "Processing mail from %s..." mail-source-crash-box)
556               (setq found (mail-source-callback
557                            callback mail-source-crash-box))
558               (mail-source-delete-crash-box))
559             (+ found
560                (if (or debug-on-quit debug-on-error)
561                    (funcall function source callback)
562                  (condition-case err
563                      (funcall function source callback)
564                    (error
565                     (if (and (not mail-source-ignore-errors)
566                              (not
567                               (yes-or-no-p
568                                (format "Mail source %s error (%s).  Continue? "
569                                        (if (memq ':password source)
570                                            (let ((s (copy-sequence source)))
571                                              (setcar (cdr (memq ':password s))
572                                                      "********")
573                                              s)
574                                          source)
575                                        (cadr err)))))
576                       (error "Cannot get new mail"))
577                     0)))))))))
578
579 (declare-function gnus-message "gnus-util" (level &rest args))
580
581 (defun mail-source-delete-old-incoming (&optional age confirm)
582   "Remove incoming files older than AGE days.
583 If CONFIRM is non-nil, ask for confirmation before removing a file."
584   (interactive "P")
585   (require 'gnus-util)
586   (let* ((high2days (/ 65536.0 60 60 24));; convert high bits to days
587          (low2days  (/ 1.0 65536.0))     ;; convert low bits to days
588          (diff (if (natnump age) age 30));; fallback, if no valid AGE given
589          currday files)
590     (setq files (directory-files
591                  mail-source-directory t
592                  (concat "\\`"
593                          (regexp-quote mail-source-incoming-file-prefix)))
594           currday (* (car (current-time)) high2days)
595           currday (+ currday (* low2days (nth 1 (current-time)))))
596     (while files
597       (let* ((ffile (car files))
598              (bfile (gnus-replace-in-string
599                      ffile "\\`.*/\\([^/]+\\)\\'" "\\1"))
600              (filetime (nth 5 (file-attributes ffile)))
601              (fileday (* (car filetime) high2days))
602              (fileday (+ fileday (* low2days (nth 1 filetime)))))
603         (setq files (cdr files))
604         (when (and (> (- currday fileday) diff)
605                    (if confirm
606                        (y-or-n-p
607                         (format "\
608 Delete old (> %s day(s)) incoming mail file `%s'? " diff bfile))
609                      (gnus-message 8 "\
610 Deleting old (> %s day(s)) incoming mail file `%s'." diff bfile)
611                      t))
612           (delete-file ffile))))))
613
614 (defun mail-source-callback (callback info)
615   "Call CALLBACK on the mail file.  Pass INFO on to CALLBACK."
616   (if (or (not (file-exists-p mail-source-crash-box))
617           (zerop (nth 7 (file-attributes mail-source-crash-box))))
618       (progn
619         (when (file-exists-p mail-source-crash-box)
620           (delete-file mail-source-crash-box))
621         0)
622     (funcall callback mail-source-crash-box info)))
623
624 (autoload 'gnus-float-time "gnus-util")
625
626 (defvar mail-source-incoming-last-checked-time nil)
627
628 (defun mail-source-delete-crash-box ()
629   (when (file-exists-p mail-source-crash-box)
630     ;; Delete or move the incoming mail out of the way.
631     (if (eq mail-source-delete-incoming t)
632         (delete-file mail-source-crash-box)
633       (let ((incoming
634              (mm-make-temp-file
635               (expand-file-name
636                mail-source-incoming-file-prefix
637                mail-source-directory))))
638         (unless (file-exists-p (file-name-directory incoming))
639           (make-directory (file-name-directory incoming) t))
640         (rename-file mail-source-crash-box incoming t)
641         ;; remove old incoming files?
642         (when (natnump mail-source-delete-incoming)
643           ;; Don't check for old incoming files more than once per day to
644           ;; save a lot of file accesses.
645           (when (or (null mail-source-incoming-last-checked-time)
646                     (> (gnus-float-time
647                         (time-since mail-source-incoming-last-checked-time))
648                        (* 24 60 60)))
649             (setq mail-source-incoming-last-checked-time (current-time))
650             (mail-source-delete-old-incoming
651              mail-source-delete-incoming
652              mail-source-delete-old-incoming-confirm)))))))
653
654 (defun mail-source-movemail (from to)
655   "Move FROM to TO using movemail."
656   (if (not (file-writable-p to))
657       (error "Can't write to crash box %s.  Not moving mail" to)
658     (let ((to (file-truename (expand-file-name to)))
659           errors result)
660       (setq to (file-truename to)
661             from (file-truename from))
662       ;; Set TO if have not already done so, and rename or copy
663       ;; the file FROM to TO if and as appropriate.
664       (cond
665        ((file-exists-p to)
666         ;; The crash box exists already.
667         t)
668        ((not (file-exists-p from))
669         ;; There is no inbox.
670         (setq to nil))
671        ((zerop (nth 7 (file-attributes from)))
672         ;; Empty file.
673         (setq to nil))
674        (t
675         ;; If getting from mail spool directory, use movemail to move
676         ;; rather than just renaming, so as to interlock with the
677         ;; mailer.
678         (unwind-protect
679             (save-excursion
680               (setq errors (generate-new-buffer " *mail source loss*"))
681               (let ((default-directory "/"))
682                 (setq result
683                       (apply
684                        'call-process
685                        (append
686                         (list
687                          (or mail-source-movemail-program
688                              (expand-file-name "movemail" exec-directory))
689                          nil errors nil from to)))))
690               (when (file-exists-p to)
691                 (set-file-modes to mail-source-default-file-modes))
692               (if (and (or (not (buffer-modified-p errors))
693                            (zerop (buffer-size errors)))
694                        (and (numberp result)
695                             (zerop result)))
696                   ;; No output => movemail won.
697                   t
698                 (set-buffer errors)
699                 ;; There may be a warning about older revisions.  We
700                 ;; ignore that.
701                 (goto-char (point-min))
702                 (if (search-forward "older revision" nil t)
703                     t
704                   ;; Probably a real error.
705                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
706                   (goto-char (point-max))
707                   (skip-chars-backward " \t")
708                   (delete-region (point) (point-max))
709                   (goto-char (point-min))
710                   (when (looking-at "movemail: ")
711                     (delete-region (point-min) (match-end 0)))
712                   ;; Result may be a signal description string.
713                   (unless (yes-or-no-p
714                            (format "movemail: %s (%s return).  Continue? "
715                                    (buffer-string) result))
716                     (error "%s" (buffer-string)))
717                   (setq to nil)))))))
718       (when (and errors
719                  (buffer-name errors))
720         (kill-buffer errors))
721       ;; Return whether we moved successfully or not.
722       to)))
723
724 (defun mail-source-movemail-and-remove (from to)
725   "Move FROM to TO using movemail, then remove FROM if empty."
726   (or (not (mail-source-movemail from to))
727       (not (zerop (nth 7 (file-attributes from))))
728       (delete-file from)))
729
730 (defun mail-source-fetch-with-program (program)
731   (eq 0 (call-process shell-file-name nil nil nil
732                       shell-command-switch program)))
733
734 (defun mail-source-run-script (script spec &optional delay)
735   (when script
736     (if (functionp script)
737         (funcall script)
738       (mail-source-call-script
739        (format-spec script spec))))
740   (when delay
741     (sleep-for delay)))
742
743 (defun mail-source-call-script (script)
744   (let ((background nil)
745         (stderr (get-buffer-create " *mail-source-stderr*"))
746         result)
747     (when (string-match "& *$" script)
748       (setq script (substring script 0 (match-beginning 0))
749             background 0))
750     (setq result
751           (call-process shell-file-name nil background nil
752                         shell-command-switch script))
753     (when (and result
754                (not (zerop result)))
755       (set-buffer stderr)
756       (message "Mail source error: %s" (buffer-string)))
757     (kill-buffer stderr)))
758
759 ;;;
760 ;;; Different fetchers
761 ;;;
762
763 (defun mail-source-fetch-file (source callback)
764   "Fetcher for single-file sources."
765   (mail-source-bind (file source)
766     (mail-source-run-script
767      prescript (format-spec-make ?t mail-source-crash-box)
768      prescript-delay)
769     (let ((mail-source-string (format "file:%s" path)))
770       (if (mail-source-movemail path mail-source-crash-box)
771           (prog1
772               (mail-source-callback callback path)
773             (mail-source-run-script
774              postscript (format-spec-make ?t mail-source-crash-box))
775             (mail-source-delete-crash-box))
776         0))))
777
778 (defun mail-source-fetch-directory (source callback)
779   "Fetcher for directory sources."
780   (mail-source-bind (directory source)
781     (mail-source-run-script
782      prescript (format-spec-make ?t path) prescript-delay)
783     (let ((found 0)
784           (mail-source-string (format "directory:%s" path)))
785       (dolist (file (directory-files
786                      path t (concat (regexp-quote suffix) "$")))
787         (when (and (file-regular-p file)
788                    (funcall predicate file)
789                    (mail-source-movemail file mail-source-crash-box))
790           (incf found (mail-source-callback callback file))
791           (mail-source-run-script postscript (format-spec-make ?t path))
792           (mail-source-delete-crash-box)))
793       found)))
794
795 (defun mail-source-fetch-pop (source callback)
796   "Fetcher for single-file sources."
797   (mail-source-bind (pop source)
798     ;; fixme: deal with stream type in format specs
799     (mail-source-run-script
800      prescript
801      (format-spec-make ?p password ?t mail-source-crash-box
802                        ?s server ?P port ?u user)
803      prescript-delay)
804     (let ((from (format "%s:%s:%s" server user port))
805           (mail-source-string (format "pop:%s@%s" user server))
806           result)
807       (when (eq authentication 'password)
808         (setq password
809               (or password
810                   (cdr (assoc from mail-source-password-cache))
811                   (read-passwd
812                    (format "Password for %s at %s: " user server)))))
813       (when server
814         (setenv "MAILHOST" server))
815       (setq result
816             (cond
817              (program
818               (mail-source-fetch-with-program
819                (format-spec
820                 program
821                 (format-spec-make ?p password ?t mail-source-crash-box
822                                   ?s server ?P port ?u user))))
823              (function
824               (funcall function mail-source-crash-box))
825              ;; The default is to use pop3.el.
826              (t
827               (require 'pop3)
828               (let ((pop3-password password)
829                     (pop3-maildrop user)
830                     (pop3-mailhost server)
831                     (pop3-port port)
832                     (pop3-authentication-scheme
833                      (if (eq authentication 'apop) 'apop 'pass))
834                     (pop3-stream-type stream))
835                 (if (or debug-on-quit debug-on-error)
836                     (save-excursion (pop3-movemail mail-source-crash-box))
837                   (condition-case err
838                       (save-excursion (pop3-movemail mail-source-crash-box))
839                     (error
840                      ;; We nix out the password in case the error
841                      ;; was because of a wrong password being given.
842                      (setq mail-source-password-cache
843                            (delq (assoc from mail-source-password-cache)
844                                  mail-source-password-cache))
845                      (signal (car err) (cdr err)))))))))
846       (if result
847           (progn
848             (when (eq authentication 'password)
849               (unless (assoc from mail-source-password-cache)
850                 (push (cons from password) mail-source-password-cache)))
851             (prog1
852                 (mail-source-callback callback server)
853               ;; Update display-time's mail flag, if relevant.
854               (if (equal source mail-source-primary-source)
855                   (setq mail-source-new-mail-available nil))
856               (mail-source-run-script
857                postscript
858                (format-spec-make ?p password ?t mail-source-crash-box
859                                  ?s server ?P port ?u user))
860               (mail-source-delete-crash-box)))
861         ;; We nix out the password in case the error
862         ;; was because of a wrong password being given.
863         (setq mail-source-password-cache
864               (delq (assoc from mail-source-password-cache)
865                     mail-source-password-cache))
866         0))))
867
868 (defun mail-source-check-pop (source)
869   "Check whether there is new mail."
870   (mail-source-bind (pop source)
871     (let ((from (format "%s:%s:%s" server user port))
872           (mail-source-string (format "pop:%s@%s" user server))
873           result)
874       (when (eq authentication 'password)
875         (setq password
876               (or password
877                   (cdr (assoc from mail-source-password-cache))
878                   (read-passwd
879                    (format "Password for %s at %s: " user server))))
880         (unless (assoc from mail-source-password-cache)
881           (push (cons from password) mail-source-password-cache)))
882       (when server
883         (setenv "MAILHOST" server))
884       (setq result
885             (cond
886              ;; No easy way to check whether mail is waiting for these.
887              (program)
888              (function)
889              ;; The default is to use pop3.el.
890              (t
891               (require 'pop3)
892               (let ((pop3-password password)
893                     (pop3-maildrop user)
894                     (pop3-mailhost server)
895                     (pop3-port port)
896                     (pop3-authentication-scheme
897                      (if (eq authentication 'apop) 'apop 'pass)))
898                 (if (or debug-on-quit debug-on-error)
899                     (save-excursion (pop3-get-message-count))
900                   (condition-case err
901                       (save-excursion (pop3-get-message-count))
902                     (error
903                      ;; We nix out the password in case the error
904                      ;; was because of a wrong password being given.
905                      (setq mail-source-password-cache
906                            (delq (assoc from mail-source-password-cache)
907                                  mail-source-password-cache))
908                      (signal (car err) (cdr err)))))))))
909       (if result
910           ;; Inform display-time that we have new mail.
911           (setq mail-source-new-mail-available (> result 0))
912         ;; We nix out the password in case the error
913         ;; was because of a wrong password being given.
914         (setq mail-source-password-cache
915               (delq (assoc from mail-source-password-cache)
916                     mail-source-password-cache)))
917       result)))
918
919 (defun mail-source-touch-pop ()
920   "Open and close a POP connection shortly.
921 POP server should be defined in `mail-source-primary-source' (which is
922 preferred) or `mail-sources'.  You may use it for the POP-before-SMTP
923 authentication.  To do that, you need to set the
924 `message-send-mail-function' variable as `message-smtpmail-send-it'
925 and put the following line in your ~/.gnus.el file:
926
927 \(add-hook 'message-send-mail-hook 'mail-source-touch-pop)
928
929 See the Gnus manual for details."
930   (let ((sources (if mail-source-primary-source
931                      (list mail-source-primary-source)
932                    mail-sources)))
933     (while sources
934       (if (eq 'pop (car (car sources)))
935           (mail-source-check-pop (car sources)))
936       (setq sources (cdr sources)))))
937
938 (defun mail-source-new-mail-p ()
939   "Handler for `display-time' to indicate when new mail is available."
940   ;; Flash (ie. ring the visible bell) if mail is available.
941   (if (and mail-source-flash mail-source-new-mail-available)
942       (let ((visible-bell t))
943         (ding)))
944   ;; Only report flag setting; flag is updated on a different schedule.
945   mail-source-new-mail-available)
946
947
948 (defvar mail-source-report-new-mail nil)
949 (defvar mail-source-report-new-mail-timer nil)
950 (defvar mail-source-report-new-mail-idle-timer nil)
951
952 (defun mail-source-start-idle-timer ()
953   ;; Start our idle timer if necessary, so we delay the check until the
954   ;; user isn't typing.
955   (unless mail-source-report-new-mail-idle-timer
956     (setq mail-source-report-new-mail-idle-timer
957           (run-with-idle-timer
958            mail-source-idle-time-delay
959            nil
960            (lambda ()
961              (unwind-protect
962                  (mail-source-check-pop mail-source-primary-source)
963                (setq mail-source-report-new-mail-idle-timer nil)))))
964     ;; Since idle timers created when Emacs is already in the idle
965     ;; state don't get activated until Emacs _next_ becomes idle, we
966     ;; need to force our timer to be considered active now.  We do
967     ;; this by being naughty and poking the timer internals directly
968     ;; (element 0 of the vector is nil if the timer is active).
969     (aset mail-source-report-new-mail-idle-timer 0 nil)))
970
971 (defun mail-source-report-new-mail (arg)
972   "Toggle whether to report when new mail is available.
973 This only works when `display-time' is enabled."
974   (interactive "P")
975   (if (not mail-source-primary-source)
976       (error "Need to set `mail-source-primary-source' to check for new mail"))
977   (let ((on (if (null arg)
978                 (not mail-source-report-new-mail)
979               (> (prefix-numeric-value arg) 0))))
980     (setq mail-source-report-new-mail on)
981     (and mail-source-report-new-mail-timer
982          (nnheader-cancel-timer mail-source-report-new-mail-timer))
983     (and mail-source-report-new-mail-idle-timer
984          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
985     (setq mail-source-report-new-mail-timer nil)
986     (setq mail-source-report-new-mail-idle-timer nil)
987     (if on
988         (progn
989           (require 'time)
990           ;; display-time-mail-function is an Emacs feature.
991           (setq display-time-mail-function #'mail-source-new-mail-p)
992           ;; Set up the main timer.
993           (setq mail-source-report-new-mail-timer
994                 (run-at-time
995                  (* 60 mail-source-report-new-mail-interval)
996                  (* 60 mail-source-report-new-mail-interval)
997                  #'mail-source-start-idle-timer))
998           ;; When you get new mail, clear "Mail" from the mode line.
999           (add-hook 'nnmail-post-get-new-mail-hook
1000                     'display-time-event-handler)
1001           (message "Mail check enabled"))
1002       (setq display-time-mail-function nil)
1003       (remove-hook 'nnmail-post-get-new-mail-hook
1004                    'display-time-event-handler)
1005       (message "Mail check disabled"))))
1006
1007 (defun mail-source-fetch-maildir (source callback)
1008   "Fetcher for maildir sources."
1009   (mail-source-bind (maildir source)
1010     (let ((found 0)
1011           mail-source-string)
1012       (unless (string-match "/$" path)
1013         (setq path (concat path "/")))
1014       (dolist (subdir subdirs)
1015         (when (file-directory-p (concat path subdir))
1016           (setq mail-source-string (format "maildir:%s%s" path subdir))
1017           (dolist (file (directory-files (concat path subdir) t))
1018             (when (and (not (file-directory-p file))
1019                        (not (if function
1020                                 (funcall function file mail-source-crash-box)
1021                               (let ((coding-system-for-write
1022                                      mm-text-coding-system)
1023                                     (coding-system-for-read
1024                                      mm-text-coding-system))
1025                                 (with-temp-file mail-source-crash-box
1026                                   (insert-file-contents file)
1027                                   (goto-char (point-min))
1028 ;;;                               ;; Unix mail format
1029 ;;;                               (unless (looking-at "\n*From ")
1030 ;;;                                 (insert "From maildir "
1031 ;;;                                         (current-time-string) "\n"))
1032 ;;;                               (while (re-search-forward "^From " nil t)
1033 ;;;                                 (replace-match ">From "))
1034 ;;;                               (goto-char (point-max))
1035 ;;;                               (insert "\n\n")
1036                                   ;; MMDF mail format
1037                                   (insert "\001\001\001\001\n"))
1038                                 (delete-file file)))))
1039               (incf found (mail-source-callback callback file))
1040               (mail-source-delete-crash-box)))))
1041       found)))
1042
1043 (autoload 'imap-open "imap")
1044 (autoload 'imap-authenticate "imap")
1045 (autoload 'imap-mailbox-select "imap")
1046 (autoload 'imap-mailbox-unselect "imap")
1047 (autoload 'imap-mailbox-close "imap")
1048 (autoload 'imap-search "imap")
1049 (autoload 'imap-fetch "imap")
1050 (autoload 'imap-close "imap")
1051 (autoload 'imap-error-text "imap")
1052 (autoload 'imap-message-flags-add "imap")
1053 (autoload 'imap-list-to-message-set "imap")
1054 (autoload 'imap-range-to-message-set "imap")
1055 (autoload 'nnheader-ms-strip-cr "nnheader")
1056
1057 (autoload 'gnus-compress-sequence "gnus-range")
1058
1059 (defvar mail-source-imap-file-coding-system 'binary
1060   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
1061
1062 ;; Autoloads will bring in imap before this is called.
1063 (declare-function imap-capability "imap" (&optional identifier buffer))
1064
1065 (defun mail-source-fetch-imap (source callback)
1066   "Fetcher for imap sources."
1067   (mail-source-bind (imap source)
1068     (mail-source-run-script
1069      prescript (format-spec-make ?p password ?t mail-source-crash-box
1070                                  ?s server ?P port ?u user)
1071      prescript-delay)
1072     (let ((from (format "%s:%s:%s" server user port))
1073           (found 0)
1074           (buf (generate-new-buffer " *imap source*"))
1075           (mail-source-string (format "imap:%s:%s" server mailbox))
1076           (imap-shell-program (or (list program) imap-shell-program))
1077           remove)
1078       (if (and (imap-open server port stream authentication buf)
1079                (imap-authenticate
1080                 user (or (cdr (assoc from mail-source-password-cache))
1081                          password) buf)
1082                (imap-mailbox-select mailbox nil buf))
1083           (let ((coding-system-for-write mail-source-imap-file-coding-system)
1084                 str)
1085             (with-temp-file mail-source-crash-box
1086               ;; Avoid converting 8-bit chars from inserted strings to
1087               ;; multibyte.
1088               (mm-disable-multibyte)
1089               ;; remember password
1090               (with-current-buffer buf
1091                 (when (and imap-password
1092                            (not (assoc from mail-source-password-cache)))
1093                   (push (cons from imap-password) mail-source-password-cache)))
1094               ;; if predicate is nil, use all uids
1095               (dolist (uid (imap-search (or predicate "1:*") buf))
1096                 (when (setq str
1097                             (if (imap-capability 'IMAP4rev1 buf)
1098                                 (caddar (imap-fetch uid "BODY.PEEK[]"
1099                                                     'BODYDETAIL nil buf))
1100                               (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf)))
1101                   (push uid remove)
1102                   (insert "From imap " (current-time-string) "\n")
1103                   (save-excursion
1104                     (insert str "\n\n"))
1105                   (while (let ((case-fold-search nil))
1106                            (re-search-forward "^From " nil t))
1107                     (replace-match ">From "))
1108                   (goto-char (point-max))))
1109               (nnheader-ms-strip-cr))
1110             (incf found (mail-source-callback callback server))
1111             (mail-source-delete-crash-box)
1112             (when (and remove fetchflag)
1113               (setq remove (nreverse remove))
1114               (imap-message-flags-add
1115                (imap-range-to-message-set (gnus-compress-sequence remove))
1116                fetchflag nil buf))
1117             (if dontexpunge
1118                 (imap-mailbox-unselect buf)
1119               (imap-mailbox-close nil buf))
1120             (imap-close buf))
1121         (imap-close buf)
1122         ;; We nix out the password in case the error
1123         ;; was because of a wrong password being given.
1124         (setq mail-source-password-cache
1125               (delq (assoc from mail-source-password-cache)
1126                     mail-source-password-cache))
1127         (error "IMAP error: %s" (imap-error-text buf)))
1128       (kill-buffer buf)
1129       (mail-source-run-script
1130        postscript
1131        (format-spec-make ?p password ?t mail-source-crash-box
1132                          ?s server ?P port ?u user))
1133       found)))
1134
1135 (provide 'mail-source)
1136
1137 ;;; mail-source.el ends here