*** empty log message ***
[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
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                   ;; Result may be a signal description string.
543                   (unless (yes-or-no-p
544                            (format "movemail: %s (%s return).  Continue? "
545                                    (buffer-string) result))
546                     (error "%s" (buffer-string)))
547                   (setq to nil)))))))
548       (when (and errors
549                  (buffer-name errors))
550         (kill-buffer errors))
551       ;; Return whether we moved successfully or not.
552       to)))
553
554 (defun mail-source-movemail-and-remove (from to)
555   "Move FROM to TO using movemail, then remove FROM if empty."
556   (or (not (mail-source-movemail from to))
557       (not (zerop (nth 7 (file-attributes from))))
558       (delete-file from)))
559
560 (defvar mail-source-read-passwd nil)
561 (defun mail-source-read-passwd (prompt &rest args)
562   "Read a password using PROMPT.
563 If ARGS, PROMPT is used as an argument to `format'."
564   (let ((prompt
565          (if args
566              (apply 'format prompt args)
567            prompt)))
568     (unless mail-source-read-passwd
569       (if (or (fboundp 'read-passwd) (load "passwd" t))
570           (setq mail-source-read-passwd 'read-passwd)
571         (unless (fboundp 'ange-ftp-read-passwd)
572           (autoload 'ange-ftp-read-passwd "ange-ftp"))
573         (setq mail-source-read-passwd 'ange-ftp-read-passwd)))
574     (funcall mail-source-read-passwd prompt)))
575
576 (defun mail-source-fetch-with-program (program)
577   (zerop (call-process shell-file-name nil nil nil
578                        shell-command-switch program)))
579
580 (defun mail-source-run-script (script spec &optional delay)
581   (when script
582     (if (and (symbolp script) (fboundp script))
583         (funcall script)
584       (mail-source-call-script
585        (format-spec script spec))))
586   (when delay
587     (sleep-for delay)))
588
589 (defun mail-source-call-script (script)
590   (let ((background nil))
591     (when (string-match "& *$" script)
592       (setq script (substring script 0 (match-beginning 0))
593             background 0))
594     (call-process shell-file-name nil background nil
595                   shell-command-switch script)))
596
597 ;;;
598 ;;; Different fetchers
599 ;;;
600
601 (defun mail-source-fetch-file (source callback)
602   "Fetcher for single-file sources."
603   (mail-source-bind (file source)
604     (mail-source-run-script
605      prescript (format-spec-make ?t mail-source-crash-box)
606      prescript-delay)
607     (let ((mail-source-string (format "file:%s" path)))
608       (if (mail-source-movemail path mail-source-crash-box)
609           (prog1
610               (mail-source-callback callback path)
611             (mail-source-run-script
612              postscript (format-spec-make ?t mail-source-crash-box)))
613         0))))
614
615 (defun mail-source-fetch-directory (source callback)
616   "Fetcher for directory sources."
617   (mail-source-bind (directory source)
618     (let ((found 0)
619           (mail-source-string (format "directory:%s" path)))
620       (dolist (file (directory-files
621                      path t (concat (regexp-quote suffix) "$")))
622         (when (and (file-regular-p file)
623                    (funcall predicate file)
624                    (mail-source-movemail file mail-source-crash-box))
625           (incf found (mail-source-callback callback file))))
626       found)))
627
628 (defun mail-source-fetch-pop (source callback)
629   "Fetcher for single-file sources."
630   (mail-source-bind (pop source)
631     (mail-source-run-script
632      prescript
633      (format-spec-make ?p password ?t mail-source-crash-box
634                        ?s server ?P port ?u user)
635      prescript-delay)
636     (let ((from (format "%s:%s:%s" server user port))
637           (mail-source-string (format "pop:%s@%s" user server))
638           result)
639       (when (eq authentication 'password)
640         (setq password
641               (or password
642                   (cdr (assoc from mail-source-password-cache))
643                   (mail-source-read-passwd
644                    (format "Password for %s at %s: " user server)))))
645       (when server
646         (setenv "MAILHOST" server))
647       (setq result
648             (cond
649              (program
650               (mail-source-fetch-with-program
651                (format-spec
652                 program
653                 (format-spec-make ?p password ?t mail-source-crash-box
654                                   ?s server ?P port ?u user))))
655              (function
656               (funcall function mail-source-crash-box))
657              ;; The default is to use pop3.el.
658              (t
659               (let ((pop3-password password)
660                     (pop3-maildrop user)
661                     (pop3-mailhost server)
662                     (pop3-port port)
663                     (pop3-authentication-scheme
664                      (if (eq authentication 'apop) 'apop 'pass)))
665                 (condition-case err
666                     (save-excursion (pop3-movemail mail-source-crash-box))
667                   (error
668                    ;; We nix out the password in case the error
669                    ;; was because of a wrong password being given.
670                    (setq mail-source-password-cache
671                          (delq (assoc from mail-source-password-cache)
672                                mail-source-password-cache))
673                    (signal (car err) (cdr err))))))))
674       (if result
675           (progn
676             (when (eq authentication 'password)
677               (unless (assoc from mail-source-password-cache)
678                 (push (cons from password) mail-source-password-cache)))
679             (prog1
680                 (mail-source-callback callback server)
681               ;; Update display-time's mail flag, if relevant.
682               (if (equal source mail-source-primary-source)
683                   (setq mail-source-new-mail-available nil))
684               (mail-source-run-script
685                postscript
686                (format-spec-make ?p password ?t mail-source-crash-box
687                                  ?s server ?P port ?u user))))
688         ;; We nix out the password in case the error
689         ;; was because of a wrong password being given.
690         (setq mail-source-password-cache
691               (delq (assoc from mail-source-password-cache)
692                     mail-source-password-cache))
693         0))))
694
695 (defun mail-source-check-pop (source)
696   "Check whether there is new mail."
697   (mail-source-bind (pop source)
698     (let ((from (format "%s:%s:%s" server user port))
699           (mail-source-string (format "pop:%s@%s" user server))
700           result)
701       (when (eq authentication 'password)
702         (setq password
703               (or password
704                   (cdr (assoc from mail-source-password-cache))
705                   (mail-source-read-passwd
706                    (format "Password for %s at %s: " user server))))
707         (unless (assoc from mail-source-password-cache)
708           (push (cons from password) mail-source-password-cache)))
709       (when server
710         (setenv "MAILHOST" server))
711       (setq result
712             (cond
713              ;; No easy way to check whether mail is waiting for these.
714              (program)
715              (function)
716              ;; The default is to use pop3.el.
717              (t
718               (let ((pop3-password password)
719                     (pop3-maildrop user)
720                     (pop3-mailhost server)
721                     (pop3-port port)
722                     (pop3-authentication-scheme
723                      (if (eq authentication 'apop) 'apop 'pass)))
724                 (condition-case err
725                     (save-excursion (pop3-get-message-count))
726                   (error
727                    ;; We nix out the password in case the error
728                    ;; was because of a wrong password being given.
729                    (setq mail-source-password-cache
730                          (delq (assoc from mail-source-password-cache)
731                                mail-source-password-cache))
732                    (signal (car err) (cdr err))))))))
733       (if result
734           ;; Inform display-time that we have new mail.
735           (setq mail-source-new-mail-available (> result 0))
736         ;; We nix out the password in case the error
737         ;; was because of a wrong password being given.
738         (setq mail-source-password-cache
739               (delq (assoc from mail-source-password-cache)
740                     mail-source-password-cache)))
741       result)))
742
743 (defun mail-source-new-mail-p ()
744   "Handler for `display-time' to indicate when new mail is available."
745   ;; Only report flag setting; flag is updated on a different schedule.
746   mail-source-new-mail-available)
747
748
749 (defvar mail-source-report-new-mail nil)
750 (defvar mail-source-report-new-mail-timer nil)
751 (defvar mail-source-report-new-mail-idle-timer nil)
752
753 (eval-when-compile
754   (if (featurep 'xemacs)
755       (require 'itimer)
756     (require 'timer)))
757
758 (defun mail-source-start-idle-timer ()
759   ;; Start our idle timer if necessary, so we delay the check until the
760   ;; user isn't typing.
761   (unless mail-source-report-new-mail-idle-timer
762     (setq mail-source-report-new-mail-idle-timer
763           (run-with-idle-timer
764            mail-source-idle-time-delay
765            nil
766            (lambda ()
767              (mail-source-check-pop mail-source-primary-source)
768              (setq mail-source-report-new-mail-idle-timer nil))))
769     ;; Since idle timers created when Emacs is already in the idle
770     ;; state don't get activated until Emacs _next_ becomes idle, we
771     ;; need to force our timer to be considered active now.  We do
772     ;; this by being naughty and poking the timer internals directly
773     ;; (element 0 of the vector is nil if the timer is active).
774     (aset mail-source-report-new-mail-idle-timer 0 nil)))
775
776 (defun mail-source-report-new-mail (arg)
777   "Toggle whether to report when new mail is available.
778 This only works when `display-time' is enabled."
779   (interactive "P")
780   (if (not mail-source-primary-source)
781       (error "Need to set `mail-source-primary-source' to check for new mail."))
782   (let ((on (if (null arg)
783                 (not mail-source-report-new-mail)
784               (> (prefix-numeric-value arg) 0))))
785     (setq mail-source-report-new-mail on)
786     (and mail-source-report-new-mail-timer
787          (nnheader-cancel-timer mail-source-report-new-mail-timer))
788     (and mail-source-report-new-mail-idle-timer
789          (nnheader-cancel-timer mail-source-report-new-mail-idle-timer))
790     (setq mail-source-report-new-mail-timer nil)
791     (setq mail-source-report-new-mail-idle-timer nil)
792     (if on
793         (progn
794           (require 'time)
795           ;; display-time-mail-function is an Emacs 21 feature.
796           (setq display-time-mail-function #'mail-source-new-mail-p)
797           ;; Set up the main timer.
798           (setq mail-source-report-new-mail-timer
799                 (nnheader-run-at-time
800                  (* 60 mail-source-report-new-mail-interval)
801                  (* 60 mail-source-report-new-mail-interval)
802                  #'mail-source-start-idle-timer))
803           ;; When you get new mail, clear "Mail" from the mode line.
804           (add-hook 'nnmail-post-get-new-mail-hook
805                     'display-time-event-handler)
806           (message "Mail check enabled"))
807       (setq display-time-mail-function nil)
808       (remove-hook 'nnmail-post-get-new-mail-hook
809                    'display-time-event-handler)
810       (message "Mail check disabled"))))
811
812 (defun mail-source-fetch-maildir (source callback)
813   "Fetcher for maildir sources."
814   (mail-source-bind (maildir source)
815     (let ((found 0)
816           mail-source-string)
817       (unless (string-match "/$" path)
818         (setq path (concat path "/")))
819       (dolist (subdir subdirs)
820         (when (file-directory-p (concat path subdir))
821           (setq mail-source-string (format "maildir:%s%s" path subdir))
822           (dolist (file (directory-files (concat path subdir) t))
823             (when (and (not (file-directory-p file))
824                        (not (if function
825                                 (funcall function file mail-source-crash-box)
826                               (let ((coding-system-for-write
827                                      mm-text-coding-system)
828                                     (coding-system-for-read
829                                      mm-text-coding-system))
830                                 (with-temp-file mail-source-crash-box
831                                   (insert-file-contents file)
832                                   (goto-char (point-min))
833 ;;;                               ;; Unix mail format
834 ;;;                               (unless (looking-at "\n*From ")
835 ;;;                                 (insert "From maildir "
836 ;;;                                         (current-time-string) "\n"))
837 ;;;                               (while (re-search-forward "^From " nil t)
838 ;;;                                 (replace-match ">From "))
839 ;;;                               (goto-char (point-max))
840 ;;;                               (insert "\n\n")
841                                   ;; MMDF mail format
842                                   (insert "\001\001\001\001\n"))
843                                 (delete-file file)))))
844               (incf found (mail-source-callback callback file))))))
845       found)))
846
847 (eval-and-compile
848   (autoload 'imap-open "imap")
849   (autoload 'imap-authenticate "imap")
850   (autoload 'imap-mailbox-select "imap")
851   (autoload 'imap-mailbox-unselect "imap")
852   (autoload 'imap-mailbox-close "imap")
853   (autoload 'imap-search "imap")
854   (autoload 'imap-fetch "imap")
855   (autoload 'imap-close "imap")
856   (autoload 'imap-error-text "imap")
857   (autoload 'imap-message-flags-add "imap")
858   (autoload 'imap-list-to-message-set "imap")
859   (autoload 'imap-range-to-message-set "imap")
860   (autoload 'nnheader-ms-strip-cr "nnheader"))
861
862 (defvar mail-source-imap-file-coding-system 'binary
863   "Coding system for the crashbox made by `mail-source-fetch-imap'.")
864
865 (defun mail-source-fetch-imap (source callback)
866   "Fetcher for imap sources."
867   (mail-source-bind (imap source)
868     (let ((from (format "%s:%s:%s" server user port))
869           (found 0)
870           (buf (get-buffer-create (generate-new-buffer-name " *imap source*")))
871           (mail-source-string (format "imap:%s:%s" server mailbox))
872           (imap-shell-program (or (list program) imap-shell-program))
873           remove)
874       (if (and (imap-open server port stream authentication buf)
875                (imap-authenticate
876                 user (or (cdr (assoc from mail-source-password-cache))
877                          password) buf)
878                (imap-mailbox-select mailbox nil buf))
879           (let ((coding-system-for-write mail-source-imap-file-coding-system)
880                 str)
881             (with-temp-file mail-source-crash-box
882               ;; Avoid converting 8-bit chars from inserted strings to
883               ;; multibyte.
884               (mm-disable-multibyte)
885               ;; remember password
886               (with-current-buffer buf
887                 (when (or imap-password
888                           (assoc from mail-source-password-cache))
889                   (push (cons from imap-password) mail-source-password-cache)))
890               ;; if predicate is nil, use all uids
891               (dolist (uid (imap-search (or predicate "1:*") buf))
892                 (when (setq str (imap-fetch uid "RFC822.PEEK" 'RFC822 nil buf))
893                   (push uid remove)
894                   (insert "From imap " (current-time-string) "\n")
895                   (save-excursion
896                     (insert str "\n\n"))
897                   (while (re-search-forward "^From " nil t)
898                     (replace-match ">From "))
899                   (goto-char (point-max))))
900               (nnheader-ms-strip-cr))
901             (incf found (mail-source-callback callback server))
902             (when (and remove fetchflag)
903               (imap-message-flags-add
904                (imap-range-to-message-set (gnus-compress-sequence remove))
905                fetchflag nil buf))
906             (if dontexpunge
907                 (imap-mailbox-unselect buf)
908               (imap-mailbox-close buf))
909             (imap-close buf))
910         (imap-close buf)
911         ;; We nix out the password in case the error
912         ;; was because of a wrong password being given.
913         (setq mail-source-password-cache
914               (delq (assoc from mail-source-password-cache)
915                     mail-source-password-cache))
916         (error (imap-error-text buf)))
917       (kill-buffer buf)
918       found)))
919
920 (eval-and-compile
921   (autoload 'webmail-fetch "webmail"))
922
923 (defun mail-source-fetch-webmail (source callback)
924   "Fetch for webmail source."
925   (mail-source-bind (webmail source)
926     (let ((mail-source-string (format "webmail:%s:%s" subtype user))
927           (webmail-newmail-only dontexpunge)
928           (webmail-move-to-trash-can (not dontexpunge)))
929       (when (eq authentication 'password)
930         (setq password
931               (or password
932                   (cdr (assoc (format "webmail:%s:%s" subtype user)
933                               mail-source-password-cache))
934                   (mail-source-read-passwd
935                    (format "Password for %s at %s: " user subtype))))
936         (when (and password
937                    (not (assoc (format "webmail:%s:%s" subtype user)
938                                mail-source-password-cache)))
939           (push (cons (format "webmail:%s:%s" subtype user) password)
940                 mail-source-password-cache)))
941       (webmail-fetch mail-source-crash-box subtype user password)
942       (mail-source-callback callback (symbol-name subtype)))))
943
944 (provide 'mail-source)
945
946 ;;; mail-source.el ends here