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