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