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