2001-07-29 Simon Josefsson <jas@extundo.com>
[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-crash-box "~/.emacs-mail-crash-box"
228   "File where mail will be stored while processing it."
229   :group 'mail-source
230   :type 'file)
231
232 (defcustom mail-source-directory message-directory
233   "Directory where files (if any) will be stored."
234   :group 'mail-source
235   :type 'directory)
236
237 (defcustom mail-source-default-file-modes 384
238   "Set the mode bits of all new mail files to this integer."
239   :group 'mail-source
240   :type 'integer)
241
242 (defcustom mail-source-delete-incoming nil
243   "*If non-nil, delete incoming files after handling."
244   :group 'mail-source
245   :type 'boolean)
246
247 (defcustom mail-source-incoming-file-prefix "Incoming"
248   "Prefix for file name for storing incoming mail"
249   :group 'mail-source
250   :type 'string)
251
252 (defcustom mail-source-report-new-mail-interval 5
253   "Interval in minutes between checks for new mail."
254   :group 'mail-source
255   :type 'number)
256
257 (defcustom mail-source-idle-time-delay 5
258   "Number of idle seconds to wait before checking for new mail."
259   :group 'mail-source
260   :type 'number)
261
262 ;;; Internal variables.
263
264 (defvar mail-source-string ""
265   "A dynamically bound string that says what the current mail source is.")
266
267 (defvar mail-source-new-mail-available nil
268   "Flag indicating when new mail is available.")
269
270 (eval-and-compile
271   (defvar mail-source-common-keyword-map
272     '((:plugged))
273     "Mapping from keywords to default values.
274 Common keywords should be listed here.")
275
276   (defvar mail-source-keyword-map
277     '((file
278        (:prescript)
279        (:prescript-delay)
280        (:postscript)
281        (:path (or (getenv "MAIL")
282                   (expand-file-name (user-login-name) rmail-spool-directory))))
283       (directory
284        (:path)
285        (:suffix ".spool")
286        (:predicate identity))
287       (pop
288        (:prescript)
289        (:prescript-delay)
290        (:postscript)
291        (:server (getenv "MAILHOST"))
292        (:port 110)
293        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
294        (:program)
295        (:function)
296        (:password)
297        (:authentication password))
298       (maildir
299        (:path (or (getenv "MAILDIR") "~/Maildir/"))
300        (:subdirs ("new" "cur"))
301        (:function))
302       (imap
303        (:server (getenv "MAILHOST"))
304        (:port)
305        (:stream)
306        (:program)
307        (:authentication)
308        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
309        (:password)
310        (:mailbox "INBOX")
311        (:predicate "UNSEEN UNDELETED")
312        (:fetchflag "\\Deleted")
313        (:dontexpunge))
314       (webmail
315        (:subtype hotmail)
316        (:user (or (user-login-name) (getenv "LOGNAME") (getenv "USER")))
317        (:password)
318        (:dontexpunge)
319        (:authentication password)))
320     "Mapping from keywords to default values.
321 All keywords that can be used must be listed here."))
322
323 (defvar mail-source-fetcher-alist
324   '((file mail-source-fetch-file)
325     (directory mail-source-fetch-directory)
326     (pop mail-source-fetch-pop)
327     (maildir mail-source-fetch-maildir)
328     (imap mail-source-fetch-imap)
329     (webmail mail-source-fetch-webmail))
330   "A mapping from source type to fetcher function.")
331
332 (defvar mail-source-password-cache nil)
333
334 (defvar mail-source-plugged t)
335
336 ;;; Functions
337
338 (eval-and-compile
339   (defun mail-source-strip-keyword (keyword)
340     "Strip the leading colon off the KEYWORD."
341     (intern (substring (symbol-name keyword) 1))))
342
343 (eval-and-compile
344   (defun mail-source-bind-1 (type)
345     (let* ((defaults (cdr (assq type mail-source-keyword-map)))
346            default bind)
347       (while (setq default (pop defaults))
348         (push (list (mail-source-strip-keyword (car default))
349                     nil)
350               bind))
351       bind)))
352
353 (defmacro mail-source-bind (type-source &rest body)
354   "Return a `let' form that binds all variables in source TYPE.
355 TYPE-SOURCE is a list where the first element is the TYPE, and
356 the second variable is the SOURCE.
357 At run time, the mail source specifier SOURCE will be inspected,
358 and the variables will be set according to it.  Variables not
359 specified will be given default values.
360
361 After this is done, BODY will be executed in the scope
362 of the `let' form.
363
364 The variables bound and their default values are described by
365 the `mail-source-keyword-map' variable."
366   `(let ,(mail-source-bind-1 (car type-source))
367      (mail-source-set-1 ,(cadr type-source))
368      ,@body))
369
370 (put 'mail-source-bind 'lisp-indent-function 1)
371 (put 'mail-source-bind 'edebug-form-spec '(form body))
372
373 (defun mail-source-set-1 (source)
374   (let* ((type (pop source))
375          (defaults (cdr (assq type mail-source-keyword-map)))
376          default value keyword)
377     (while (setq default (pop defaults))
378       (set (mail-source-strip-keyword (setq keyword (car default)))
379            (if (setq value (plist-get source keyword))
380                (mail-source-value value)
381              (mail-source-value (cadr default)))))))
382
383 (eval-and-compile
384   (defun mail-source-bind-common-1 ()
385     (let* ((defaults mail-source-common-keyword-map)
386            default bind)
387       (while (setq default (pop defaults))
388         (push (list (mail-source-strip-keyword (car default))
389                     nil)
390               bind))
391       bind)))
392
393 (defun mail-source-set-common-1 (source)
394   (let* ((type (pop source))
395          (defaults mail-source-common-keyword-map)
396          (defaults-1 (cdr (assq type mail-source-keyword-map)))
397          default value keyword)
398     (while (setq default (pop defaults))
399       (set (mail-source-strip-keyword (setq keyword (car default)))
400            (if (setq value (plist-get source keyword))
401                (mail-source-value value)
402              (if (setq value (assq  keyword defaults-1))
403                  (mail-source-value (cadr value))
404                (mail-source-value (cadr default))))))))
405
406 (defmacro mail-source-bind-common (source &rest body)
407   "Return a `let' form that binds all common variables.
408 See `mail-source-bind'."
409   `(let ,(mail-source-bind-common-1)
410      (mail-source-set-common-1 source)
411      ,@body))
412
413 (put 'mail-source-bind-common 'lisp-indent-function 1)
414 (put 'mail-source-bind-common 'edebug-form-spec '(form body))
415
416 (defun mail-source-value (value)
417   "Return the value of VALUE."
418   (cond
419    ;; String
420    ((stringp value)
421     value)
422    ;; Function
423    ((and (listp value)
424          (functionp (car value)))
425     (eval value))
426    ;; Just return the value.
427    (t
428     value)))
429
430 (defun mail-source-fetch (source callback)
431   "Fetch mail from SOURCE and call CALLBACK zero or more times.
432 CALLBACK will be called with the name of the file where (some of)
433 the mail from SOURCE is put.
434 Return the number of files that were found."
435   (mail-source-bind-common source
436     (if (or mail-source-plugged plugged)
437         (save-excursion
438           (let ((function (cadr (assq (car source) mail-source-fetcher-alist)))
439                 (found 0))
440             (unless function
441               (error "%S is an invalid mail source specification" source))
442             ;; If there's anything in the crash box, we do it first.
443             (when (file-exists-p mail-source-crash-box)
444               (message "Processing mail from %s..." mail-source-crash-box)
445               (setq found (mail-source-callback
446                            callback mail-source-crash-box)))
447             (+ found
448                (condition-case err
449                    (funcall function source callback)
450                  (error
451                   (unless (yes-or-no-p
452                            (format "Mail source error (%s).  Continue? " err))
453                     (error "Cannot get new mail"))
454                   0))))))))
455
456 (defun mail-source-make-complex-temp-name (prefix)
457   (let ((newname (make-temp-name prefix))
458         (newprefix prefix))
459     (while (file-exists-p newname)
460       (setq newprefix (concat newprefix "x"))
461       (setq newname (make-temp-name newprefix)))
462     newname))
463
464 (defun mail-source-callback (callback info)
465   "Call CALLBACK on the mail file, and then remove the mail file.
466 Pass INFO on to CALLBACK."
467   (if (or (not (file-exists-p mail-source-crash-box))
468           (zerop (nth 7 (file-attributes mail-source-crash-box))))
469       (progn
470         (when (file-exists-p mail-source-crash-box)
471           (delete-file mail-source-crash-box))
472         0)
473     (prog1
474         (funcall callback mail-source-crash-box info)
475       (when (file-exists-p mail-source-crash-box)
476         ;; Delete or move the incoming mail out of the way.
477         (if mail-source-delete-incoming
478             (delete-file mail-source-crash-box)
479           (let ((incoming
480                  (mail-source-make-complex-temp-name
481                   (expand-file-name
482                    mail-source-incoming-file-prefix
483                    mail-source-directory))))
484             (unless (file-exists-p (file-name-directory incoming))
485               (make-directory (file-name-directory incoming) t))
486             (rename-file mail-source-crash-box incoming t)))))))
487
488 (defun mail-source-movemail (from to)
489   "Move FROM to TO using movemail."
490   (if (not (file-writable-p to))
491       (error "Can't write to crash box %s.  Not moving mail" to)
492     (let ((to (file-truename (expand-file-name to)))
493           errors result)
494       (setq to (file-truename to)
495             from (file-truename from))
496       ;; Set TO if have not already done so, and rename or copy
497       ;; the file FROM to TO if and as appropriate.
498       (cond
499        ((file-exists-p to)
500         ;; The crash box exists already.
501         t)
502        ((not (file-exists-p from))
503         ;; There is no inbox.
504         (setq to nil))
505        ((zerop (nth 7 (file-attributes from)))
506         ;; Empty file.
507         (setq to nil))
508        (t
509         ;; If getting from mail spool directory, use movemail to move
510         ;; rather than just renaming, so as to interlock with the
511         ;; mailer.
512         (unwind-protect
513             (save-excursion
514               (setq errors (generate-new-buffer " *mail source loss*"))
515               (let ((default-directory "/"))
516                 (setq result
517                       (apply
518                        'call-process
519                        (append
520                         (list
521                          (expand-file-name "movemail" exec-directory)
522                          nil errors nil from to)))))
523               (when (file-exists-p to)
524                 (set-file-modes to mail-source-default-file-modes))
525               (if (and (not (buffer-modified-p errors))
526                        (zerop result))
527                   ;; No output => movemail won.
528                   t
529                 (set-buffer errors)
530                 ;; There may be a warning about older revisions.  We
531                 ;; ignore that.
532                 (goto-char (point-min))
533                 (if (search-forward "older revision" nil t)
534                     t
535                   ;; Probably a real error.
536                   (subst-char-in-region (point-min) (point-max) ?\n ?\  )
537                   (goto-char (point-max))
538                   (skip-chars-backward " \t")
539                   (delete-region (point) (point-max))
540                   (goto-char (point-min))
541                   (when (looking-at "movemail: ")
542                     (delete-region (point-min) (match-end 0)))
543                   ;; Result may be a signal description string.
544                   (unless (yes-or-no-p
545                            (format "movemail: %s (%s return).  Continue? "
546                                    (buffer-string) result))
547                     (error "%s" (buffer-string)))
548                   (setq to nil)))))))
549       (when (and errors
550                  (buffer-name errors))
551         (kill-buffer errors))
552       ;; Return whether we moved successfully or not.
553       to)))
554
555 (defun mail-source-movemail-and-remove (from to)
556   "Move FROM to TO using movemail, then remove FROM if empty."
557   (or (not (mail-source-movemail from to))
558       (not (zerop (nth 7 (file-attributes from))))
559       (delete-file from)))
560
561 (defvar mail-source-read-passwd nil)
562 (defun mail-source-read-passwd (prompt &rest args)
563   "Read a password using PROMPT.
564 If ARGS, PROMPT is used as an argument to `format'."
565   (let ((prompt
566          (if args
567              (apply 'format prompt args)
568            prompt)))
569     (unless mail-source-read-passwd
570       (if (or (fboundp 'read-passwd) (load "passwd" t))
571           (setq mail-source-read-passwd 'read-passwd)
572         (unless (fboundp 'ange-ftp-read-passwd)
573           (autoload 'ange-ftp-read-passwd "ange-ftp"))
574         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
575     (funcall mail-source-read-passwd prompt)))
576
577 (defun mail-source-fetch-with-program (program)
578   (zerop (call-process shell-file-name nil nil nil
579                        shell-command-switch program)))
580
581 (defun mail-source-run-script (script spec &optional delay)
582   (when script
583     (if (and (symbolp script) (fboundp script))
584         (funcall script)
585       (mail-source-call-script
586        (format-spec script spec))))
587   (when delay
588     (sleep-for delay)))
589
590 (defun mail-source-call-script (script)
591   (let ((background nil))
592     (when (string-match "& *$" script)
593       (setq script (substring script 0 (match-beginning 0))
594             background 0))
595     (call-process shell-file-name nil background nil
596                   shell-command-switch script)))
597
598 ;;;
599 ;;; Different fetchers
600 ;;;
601
602 (defun mail-source-fetch-file (source callback)
603   "Fetcher for single-file sources."
604   (mail-source-bind (file source)
605     (mail-source-run-script
606      prescript (format-spec-make ?t mail-source-crash-box)
607      prescript-delay)
608     (let ((mail-source-string (format "file:%s" path)))
609       (if (mail-source-movemail path mail-source-crash-box)
610           (prog1
611               (mail-source-callback callback path)
612             (mail-source-run-script
613              postscript (format-spec-make ?t mail-source-crash-box)))
614         0))))
615
616 (defun mail-source-fetch-directory (source callback)
617   "Fetcher for directory sources."
618   (mail-source-bind (directory source)
619     (let ((found 0)
620           (mail-source-string (format "directory:%s" path)))
621       (dolist (file (directory-files
622                      path t (concat (regexp-quote suffix) "$")))
623         (when (and (file-regular-p file)
624                    (funcall predicate file)
625                    (mail-source-movemail file mail-source-crash-box))
626           (incf found (mail-source-callback callback file))))
627       found)))
628
629 (defun mail-source-fetch-pop (source callback)
630   "Fetcher for single-file sources."
631   (mail-source-bind (pop source)
632     (mail-source-run-script
633      prescript
634      (format-spec-make ?p password ?t mail-source-crash-box
635                        ?s server ?P port ?u user)
636      prescript-delay)
637     (let ((from (format "%s:%s:%s" server user port))
638           (mail-source-string (format "pop:%s@%s" user server))
639           result)
640       (when (eq authentication 'password)
641         (setq password
642               (or password
643                   (cdr (assoc from mail-source-password-cache))
644                   (mail-source-read-passwd
645                    (format "Password for %s at %s: " user server)))))
646       (when server
647         (setenv "MAILHOST" server))
648       (setq result
649             (cond
650              (program
651               (mail-source-fetch-with-program
652                (format-spec
653                 program
654                 (format-spec-make ?p password ?t mail-source-crash-box
655                                   ?s server ?P port ?u user))))
656              (function
657               (funcall function mail-source-crash-box))
658              ;; The default is to use pop3.el.
659              (t
660               (let ((pop3-password password)
661                     (pop3-maildrop user)
662                     (pop3-mailhost server)
663                     (pop3-port port)
664                     (pop3-authentication-scheme
665                      (if (eq authentication 'apop) 'apop 'pass)))
666                 (condition-case err
667                     (save-excursion (pop3-movemail mail-source-crash-box))
668                   (error
669                    ;; We nix out the password in case the error
670                    ;; was because of a wrong password being given.
671                    (setq mail-source-password-cache
672                          (delq (assoc from mail-source-password-cache)
673                                mail-source-password-cache))
674                    (signal (car err) (cdr err))))))))
675       (if result
676           (progn
677             (when (eq authentication 'password)
678               (unless (assoc from mail-source-password-cache)
679                 (push (cons from password) mail-source-password-cache)))
680             (prog1
681                 (mail-source-callback callback server)
682               ;; Update display-time's mail flag, if relevant.
683               (if (equal source mail-source-primary-source)
684                   (setq mail-source-new-mail-available nil))
685               (mail-source-run-script
686                postscript
687                (format-spec-make ?p password ?t mail-source-crash-box
688                                  ?s server ?P port ?u user))))
689         ;; We nix out the password in case the error
690         ;; was because of a wrong password being given.
691         (setq mail-source-password-cache
692               (delq (assoc from mail-source-password-cache)
693                     mail-source-password-cache))
694         0))))
695
696 (defun mail-source-check-pop (source)
697   "Check whether there is new mail."
698   (mail-source-bind (pop source)
699     (let ((from (format "%s:%s:%s" server user port))
700           (mail-source-string (format "pop:%s@%s" user server))
701           result)
702       (when (eq authentication 'password)
703         (setq password
704               (or password
705                   (cdr (assoc from mail-source-password-cache))
706                   (mail-source-read-passwd
707                    (format "Password for %s at %s: " user server))))
708         (unless (assoc from mail-source-password-cache)
709           (push (cons from password) mail-source-password-cache)))
710       (when server
711         (setenv "MAILHOST" server))
712       (setq result
713             (cond
714              ;; No easy way to check whether mail is waiting for these.
715              (program)
716              (function)
717              ;; The default is to use pop3.el.
718              (t
719               (let ((pop3-password password)
720                     (pop3-maildrop user)
721                     (pop3-mailhost server)
722                     (pop3-port port)
723                     (pop3-authentication-scheme
724                      (if (eq authentication 'apop) 'apop 'pass)))
725                 (condition-case err
726                     (save-excursion (pop3-get-message-count))
727                   (error
728                    ;; We nix out the password in case the error
729                    ;; was because of a wrong password being given.
730                    (setq mail-source-password-cache
731                          (delq (assoc from mail-source-password-cache)
732                                mail-source-password-cache))
733                    (signal (car err) (cdr err))))))))
734       (if result
735           ;; Inform display-time that we have new mail.
736           (setq mail-source-new-mail-available (> result 0))
737         ;; We nix out the password in case the error
738         ;; was because of a wrong password being given.
739         (setq mail-source-password-cache
740               (delq (assoc from mail-source-password-cache)
741                     mail-source-password-cache)))
742       result)))
743
744 (defun mail-source-new-mail-p ()
745   "Handler for `display-time' to indicate when new mail is available."
746   ;; Only report flag setting; flag is updated on a different schedule.
747   mail-source-new-mail-available)
748
749
750 (defvar mail-source-report-new-mail nil)
751 (defvar mail-source-report-new-mail-timer nil)
752 (defvar mail-source-report-new-mail-idle-timer nil)
753
754 (eval-when-compile
755   (if (featurep 'xemacs)
756       (require 'itimer)
757     (require 'timer)))
758
759 (defun mail-source-start-idle-timer ()
760   ;; Start our idle timer if necessary, so we delay the check until the
761   ;; user isn't typing.
762   (unless mail-source-report-new-mail-idle-timer
763     (setq mail-source-report-new-mail-idle-timer
764           (run-with-idle-timer
765            mail-source-idle-time-delay
766            nil
767            (lambda ()
768              (mail-source-check-pop mail-source-primary-source)
769              (setq mail-source-report-new-mail-idle-timer nil))))
770     ;; Since idle timers created when Emacs is already in the idle
771     ;; state don't get activated until Emacs _next_ becomes idle, we
772     ;; need to force our timer to be considered active now.  We do
773     ;; this by being naughty and poking the timer internals directly
774     ;; (element 0 of the vector is nil if the timer is active).
775     (aset mail-source-report-new-mail-idle-timer 0 nil)))
776
777 (defun mail-source-report-new-mail (arg)
778   "Toggle whether to report when new mail is available.
779 This only works when `display-time' is enabled."
780   (interactive "P")
781   (if (not mail-source-primary-source)
782       (error "Need to set `mail-source-primary-source' to check for new mail"))
783   (let ((on (if (null arg)
784                 (not mail-source-report-new-mail)
785               (> (prefix-numeric-value arg) 0))))
786     (setq mail-source-report-new-mail on)
787     (and mail-source-report-new-mail-timer
788          (nnheader-cancel-timer mail-source-report-new-mail-timer))
789     (and mail-source-report-new-mail-idle-timer
790          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
791     (setq mail-source-report-new-mail-timer nil)
792     (setq mail-source-report-new-mail-idle-timer nil)
793     (if on
794         (progn
795           (require 'time)
796           ;; display-time-mail-function is an Emacs 21 feature.
797           (setq display-time-mail-function #'mail-source-new-mail-p)
798           ;; Set up the main timer.
799           (setq mail-source-report-new-mail-timer
800                 (nnheader-run-at-time
801                  (* 60 mail-source-report-new-mail-interval)
802                  (* 60 mail-source-report-new-mail-interval)
803                  #'mail-source-start-idle-timer))
804           ;; When you get new mail, clear "Mail" from the mode line.
805           (add-hook 'nnmail-post-get-new-mail-hook
806                     'display-time-event-handler)
807           (message "Mail check enabled"))
808       (setq display-time-mail-function nil)
809       (remove-hook 'nnmail-post-get-new-mail-hook
810                    'display-time-event-handler)
811       (message "Mail check disabled"))))
812
813 (defun mail-source-fetch-maildir (source callback)
814   "Fetcher for maildir sources."
815   (mail-source-bind (maildir source)
816     (let ((found 0)
817           mail-source-string)
818       (unless (string-match "/$" path)
819         (setq path (concat path "/")))
820       (dolist (subdir subdirs)
821         (when (file-directory-p (concat path subdir))
822           (setq mail-source-string (format "maildir:%s%s" path subdir))
823           (dolist (file (directory-files (concat path subdir) t))
824             (when (and (not (file-directory-p file))
825                        (not (if function
826                                 (funcall function file mail-source-crash-box)
827                               (let ((coding-system-for-write
828                                      mm-text-coding-system)
829                                     (coding-system-for-read
830                                      mm-text-coding-system))
831                                 (with-temp-file mail-source-crash-box
832                                   (insert-file-contents file)
833                                   (goto-char (point-min))
834 ;;;                               ;; Unix mail format
835 ;;;                               (unless (looking-at "\n*From ")
836 ;;;                                 (insert "From maildir "
837 ;;;                                         (current-time-string) "\n"))
838 ;;;                               (while (re-search-forward "^From " nil t)
839 ;;;                                 (replace-match ">From "))
840 ;;;                               (goto-char (point-max))
841 ;;;                               (insert "\n\n")
842                                   ;; MMDF mail format
843                                   (insert "\001\001\001\001\n"))
844                                 (delete-file file)))))
845               (incf found (mail-source-callback callback file))))))
846       found)))
847
848 (eval-and-compile
849   (autoload 'imap-open "imap")
850   (autoload 'imap-authenticate "imap")
851   (autoload 'imap-mailbox-select "imap")
852   (autoload 'imap-mailbox-unselect "imap")
853   (autoload 'imap-mailbox-close "imap")
854   (autoload 'imap-search "imap")
855   (autoload 'imap-fetch "imap")
856   (autoload 'imap-close "imap")
857   (autoload 'imap-error-text "imap")
858   (autoload 'imap-message-flags-add "imap")
859   (autoload 'imap-list-to-message-set "imap")
860   (autoload 'imap-range-to-message-set "imap")
861   (autoload 'nnheader-ms-strip-cr "nnheader"))
862
863 (defvar mail-source-imap-file-coding-system 'binary
864   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
865
866 (defun mail-source-fetch-imap (source callback)
867   "Fetcher for imap sources."
868   (mail-source-bind (imap source)
869     (let ((from (format "%s:%s:%s" server user port))
870           (found 0)
871           (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
872           (mail-source-string (format "imap:%s:%s" server mailbox))
873           (imap-shell-program (or (list program) imap-shell-program))
874           remove)
875       (if (and (imap-open server port stream authentication buf)
876                (imap-authenticate
877                 user (or (cdr (assoc from mail-source-password-cache))
878                          password) buf)
879                (imap-mailbox-select mailbox nil buf))
880           (let ((coding-system-for-write mail-source-imap-file-coding-system)
881                 str)
882             (with-temp-file mail-source-crash-box
883               ;; Avoid converting 8-bit chars from inserted strings to
884               ;; multibyte.
885               (mm-disable-multibyte)
886               ;; remember password
887               (with-current-buffer buf
888                 (when (or imap-password
889                           (assoc from mail-source-password-cache))
890                   (push (cons from imap-password) mail-source-password-cache)))
891               ;; if predicate is nil, use all uids
892               (dolist (uid (imap-search (or predicate "1:*") buf))
893                 (when (setq str (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf))
894                   (push uid remove)
895                   (insert "From imap " (current-time-string) "\n")
896                   (save-excursion
897                     (insert str "\n\n"))
898                   (while (re-search-forward "^From " nil t)
899                     (replace-match ">From "))
900                   (goto-char (point-max))))
901               (nnheader-ms-strip-cr))
902             (incf found (mail-source-callback callback server))
903             (when (and remove fetchflag)
904               (imap-message-flags-add
905                (imap-range-to-message-set (gnus-compress-sequence remove))
906                fetchflag nil buf))
907             (if dontexpunge
908                 (imap-mailbox-unselect buf)
909               (imap-mailbox-close buf))
910             (imap-close buf))
911         (imap-close buf)
912         ;; We nix out the password in case the error
913         ;; was because of a wrong password being given.
914         (setq mail-source-password-cache
915               (delq (assoc from mail-source-password-cache)
916                     mail-source-password-cache))
917         (error (imap-error-text buf)))
918       (kill-buffer buf)
919       found)))
920
921 (eval-and-compile
922   (autoload 'webmail-fetch "webmail"))
923
924 (defun mail-source-fetch-webmail (source callback)
925   "Fetch for webmail source."
926   (mail-source-bind (webmail source)
927     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
928           (webmail-newmail-only dontexpunge)
929           (webmail-move-to-trash-can (not dontexpunge)))
930       (when (eq authentication 'password)
931         (setq password
932               (or password
933                   (cdr (assoc (format "webmail:%s:%s" subtype user)
934                               mail-source-password-cache))
935                   (mail-source-read-passwd
936                    (format "Password for %s at %s: " user subtype))))
937         (when (and password
938                    (not (assoc (format "webmail:%s:%s" subtype user)
939                                mail-source-password-cache)))
940           (push (cons (format "webmail:%s:%s" subtype user) password)
941                 mail-source-password-cache)))
942       (webmail-fetch mail-source-crash-box subtype user password)
943       (mail-source-callback callback (symbol-name subtype)))))
944
945 (provide 'mail-source)
946
947 ;;; mail-source.el ends here