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