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