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