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