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