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