Source

css / lib / python / cs / app / mailfiler.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
#!/usr/bin/python
#
# Handler for rulesets in the format of cats2procmailrc(1cs).
#       - Cameron Simpson <cs@zip.com.au> 22may2011
#

from __future__ import print_function
from collections import namedtuple
from email import message_from_string
import email.parser
from getopt import getopt, GetoptError
import io
from logging import DEBUG
import mailbox
import os
import os.path
import re
import sys
from time import sleep
if sys.hexversion < 0x02060000: from sets import Set as set
import subprocess
from tempfile import TemporaryFile
from threading import Lock
import time
from cs.env import envsub
from cs.fileutils import abspath_from_file, file_property, files_property, Pathname
from cs.lex import get_white, get_nonwhite, get_qstr, unrfc2047
from cs.logutils import Pfx, setup_logging, debug, info, warning, error, D, LogTime
from cs.mailutils import Maildir, message_addresses, shortpath
from cs.misc import O, slist
from cs.threads import locked_property
from cs.app.maildb import MailDB
from cs.py3 import unicode as u

DEFAULT_MAILDIR_RULES = '$HOME/.mailfiler/{maildir.basename}'

def main(argv, stdin=None):
  if stdin is None:
    stdin = sys.stdin
  argv = list(argv)
  cmd = os.path.basename(argv.pop(0))
  setup_logging(cmd)
  usage = ( '''Usage: %s monitor [-1] [-d delay] [-n] [-N] [-R rules_pattern] maildirs...
  -1  File at most 1 message per Maildir.
  -d delay
      Delay between runs in seconds.
      Default is to make only one run over the Maildirs.
  -n  No remove. Keep filed messages in the origin Maildir.
  -R rules_pattern
      Specify the rules file pattern used to specify rules files from Maildir names.
      Default: %s'''
            % (cmd, DEFAULT_MAILDIR_RULES)
          )
  badopts = False

  if not argv:
    warning("missing op")
    badopts = True
  else:
    op = argv.pop(0)
    with Pfx(op):
      if op == 'monitor':
        justone = False
        delay = None
        no_remove = False
        no_save = False
        rules_pattern = DEFAULT_MAILDIR_RULES
        try:
          opts, argv = getopt(argv, '1d:nNR:')
        except GetoptError as e:
          warning("%s", e)
          badopts = True
        for opt, val in opts:
          with Pfx(opt):
            if opt == '-1':
              justone = True
            elif opt == '-d':
              try:
                delay = int(val)
              except ValueError as e:
                warning("%s: %s", e, val)
                badopts = True
              else:
                if delay <= 0:
                  warning("delay must be positive, got: %d", delay)
                  badopts = True
            elif opt == '-n':
              no_remove = True
            elif opt == '-N':
              no_save = True
            elif opt == '-R':
              rules_pattern = val
            else:
              warning("unimplemented option")
              badopts = True
        if not argv:
          warning("missing maildirs")
          badopts = True
        else:
          mdirpaths = [ Pathname(arg) for arg in argv ]
      else:
        warning("unrecognised op: %s", op)
        badopts = True

  if badopts:
    print(usage, file=sys.stderr)
    return 2

  with Pfx(op):
    if op == 'monitor':
      maildir_cache = {}
      filter_modes = FilterModes(justone=justone,
                                 delay=delay,
                                 no_remove=no_remove,
                                 no_save=no_save,
                                 maildb_path=os.environ['MAILDB'],
                                 maildir_cache={})
      maildirs = [ WatchedMaildir(mdirpath,
                                  filter_modes=filter_modes,
                                  rules_path=envsub(
                                               rules_pattern.format(maildir=mdirpath)))
                   for mdirpath in mdirpaths
                 ]
      try:
        while True:
          for MW in maildirs:
            debug("process %s", (MW.shortname,))
            with LogTime("%s.filter()" % (MW.shortname,), threshold=1.0):
              for key, reports in MW.filter():
                pass
          if delay is None:
            break
          debug("sleep %ds", delay)
          sleep(delay)
        return 0
      except KeyboardInterrupt:
        for MW in maildirs:
          MW.close()
        return 1
    else:
      raise RunTimeError("unimplemented op")

def maildir_from_name(mdirname, maildir_root, maildir_cache):
    ''' Return the Maildir derived from mdirpath.
    '''
    mdirpath = resolve_maildir_path(mdirname, maildir_root)
    if mdirpath not in maildir_cache:
      maildir_cache[mdirpath] = Maildir(mdirpath, create=True)
    return maildir_cache[mdirpath]

def resolve_maildir_path(mdirpath, maildir_root):
  ''' Return the full path to the requested maildir.
  '''
  if not os.path.isabs(mdirpath):
    if mdirpath.startswith('./') or mdirpath.startswith('../'):
      mdirpath = os.path.abspath(mdirpath)
    else:
      mdirpath = os.path.join(maildir_root, mdirpath)
  return mdirpath

class FilterModes(O):

  def __init__(self, **kw):
    self._O_omit = ('maildir_cache',)
    self._maildb_path = kw.pop('maildb_path')
    self._maildb_lock = Lock()
    O.__init__(self, **kw)

  @file_property
  def maildb(self, path):
    info("reload maildb %s", shortpath(path))
    return MailDB(path, readonly=True)

  def maildir(self, mdirname, environ=None):
    return maildir_from_name(mdirname, environ['MAILDIR'], self.maildir_cache)

class RuleState(O):
  ''' State information for rule evaluation.
      .message  Current message.
      .maildb   Current MailDB.
      .environ  Storage for variable settings.
  '''
 
  maildirs = {}

  def __init__(self, M, outer_state, environ=None):
    ''' `M`:           The Message object to be filed.
        `outer_state`: External state object, with maildb etc.
        `environ`:     Mapping which supplies initial variable names.
                       Default from os.environ.
    '''
    self.message = M
    self.outer_state = outer_state
    if environ is None:
      environ = os.environ
    self.environ = dict(environ)
    self.reuse_maildir = False
    self.used_maildirs = set()
    self._log = None

  @property
  def maildb(self):
    return self.outer_state.maildb

  def maildir(self, mdirpath):
    return self.outer_state.maildir(mdirpath, self.environ)

  @property
  def message(self):
    return self._message

  @message.setter
  def message(self, new_message):
    self._message = new_message
    self.message_path = None
    self.header_addresses = {}

  def log(self, *a):
    ''' Log a message.
    '''
    log = self._log
    if log is None:
      log = sys.stdout
    try:
      print(*[ unicode(s) for s in a], file=log)
    except UnicodeDecodeError as e:
      print("RuleState.log: %s: a=%r" % (e, a), file=sys.stderr)

  def logto(self, logfilepath):
    ''' Direct log messages to the supplied `logfilepath`.
    '''
    if self._log:
      self._log.close()
      self._log = None
    try:
      self._log = io.open(logfilepath, "a", encoding='utf-8')
    except OSError as e:
      self.log("open(%s): %s" % (logfilepath, e))

  @property
  def groups(self):
    ''' The group mapping from the MailDB.
    '''
    return self.maildb.address_groups

  def ingroup(self, coreaddr, group_name):
    ''' Test if a core address is a member of the named group.
    '''
    group = self.groups.get(group_name)
    if group is None:
      warning("unknown group: %s", group_name)
      self.groups[group_name] = set()
      return False
    return coreaddr.lower() in group

  def addresses(self, *headers):
    ''' Return the core addresses from the current Message and supplied
        `headers`. Caches results for rapid rule evaluation.
    '''
    M = self.message
    if M is not self.message:
      # new message - discard cache
      self.message = M
      self.header_addresses = {}
    if len(headers) != 1:
      addrs = set()
      for header in headers:
        addrs.update(self.addresses(header))
      return addrs
    header = headers[0]
    hamap = self.header_addresses
    if header not in hamap:
      hamap[header] = set( [ A for N, A in message_addresses(M, (header,)) ] )
    return hamap[header]

  def save_to_maildir(self, mdir, label):
    mdirpath = mdir.dir
    if mdirpath in self.used_maildirs:
      if not self.reuse_maildir:
        return None
    M = self.message
    if label and M.get('x-label', '') != label:
      # modifying message - make copy
      path = None
      M = message_from_string(M.as_string())
      M['X-Label'] = label
    else:
      path = self.message_path
    if path is None:
      savekey = mdir.save_message(M)
    else:
      savekey = mdir.save_filepath(path)
    savepath = mdir.keypath(savekey)
    if not path and not label:
      self.message_path = savepath
    self.log("    OK %s" % (shortpath(savepath),))
    return savepath

  def pipe_message(self, argv, mfp=None):
    ''' Pipe a message to the command specific by `argv`.
        `mfp` is a file containing the message text.
        If `mfp` is None, use the text of the current message.
    '''
    if mfp is None:
      message_path = self.message_path
      if message_path:
        with open(message_path) as mfp:
          return self.pipe_message(argv, mfp)
      else:
        with TemporaryFile('w+') as mfp:
          mfp.write(str(self.message))
          mfp.flush()
          mfp.seek(0)
          return self.pipe_message(argv, mfp)
    retcode = subprocess.call(argv, env=self.environ, stdin=mfp)
    self.log("    %s => | %s" % (("OK" if retcode == 0 else "FAIL"), argv))
    return retcode == 0

  def sendmail(self, address, mfp=None):
    ''' Dispatch a message to `address`.
        `mfp` is a file containing the message text.
        If `mfp` is None, use the text of the current message.
    '''
    return self.pipe_message([self.environ.get('SENDMAIL', 'sendmail'), '-oi', address], mfp=mfp)

re_UNQWORD = re.compile(r'[^,\s]+')
re_HEADERLIST = re.compile(r'([a-z][\-a-z0-9]*(,[a-z][\-a-z0-9]*)*):', re.I)
re_ASSIGN = re.compile(r'([a-z]\w+)=', re.I)
re_INGROUP = re.compile(r'\(\s*[a-z]\w+(\s*\|\s*[a-z]\w+)*\s*\)', re.I)

def parserules(fp):
  ''' Read rules from `fp`, yield Rules.
  '''
  if type(fp) is str:
    with open(fp) as rfp:
      for R in parserules(rfp):
        yield R
    return

  filename = fp.name
  info("PARSE RULES: %s", shortpath(filename))
  lineno = 0
  R = None
  for line in fp:
    lineno += 1
    with Pfx("%s:%d", shortpath(filename), lineno):
      if not line.endswith('\n'):
        raise ValueError("short line at EOF")

      # skip comments
      if line.startswith('#'):
        continue

      # remove newline and trailing whitespace
      line = line.rstrip()

      # skip blank lines
      if not line:
        continue

      _, offset = get_white(line, 0)
      if not _:
        # new rule
        # yield old rule if in progress
        if R:
          yield R
        R = None

        if line[offset] == '<':
          # include another categories file
          _, offset = get_white(line, offset+1)
          subfilename, offset = get_nonwhite(line, offset=offset)
          if not subfilename:
            raise ValueError("missing filename")
          subfilename = envsub(subfilename)
          subfilename = abspath_from_file(subfilename, filename)
          for R in parserules(subfilename):
            yield R
          continue

        # new rule
        R = Rule(filename=filename, lineno=lineno)

        m = re_ASSIGN.match(line, offset)
        if m:
          R.actions.append( ('ASSIGN', (m.group(1), line[m.end():])) )
          yield R
          R = None
          continue

        if line[offset] == '+':
          R.flags.halt = False
          offset += 1
        elif line[offset] == '=':
          R.flags.halt = True
          offset += 1
        if line[offset] == '!':
          R.flags.alert = True
          offset += 1

        # gather targets
        while offset < len(line) and not line[offset].isspace():
          if line[offset] == '"':
            target, offset = get_qstr(line, offset)
          else:
            m = re_UNQWORD.match(line, offset)
            if m:
              target = m.group()
              offset = m.end()
            else:
              error("parse failure at %d: %s", offset, line)
              raise ValueError("syntax error")
          R.actions.append( ('TARGET', target) )
          if offset < len(line) and line[offset] == ',':
            offset += 1

        # gather label
        _, offset = get_white(line, offset)
        if not _ or offset == len(line):
          R.label = ''
          warning("no label or condition")
          continue
        if line[offset] == '"':
          label, offset = get_qstr(line, offset)
        else:
          label, offset = get_nonwhite(line, offset)
        if label == '.':
          label = ''
        R.label = label
        _, offset = get_white(line, offset)

      # condition
      if not _ or offset == len(line):
        warning("no condition")
        continue

      # . always matches - don't bother storing it as a test
      if line[offset:] == '.':
        continue

      # leading hdr1,hdr2,...:
      m = re_HEADERLIST.match(line, offset)
      if m:
        headernames = [ H.lower() for H in m.group(1).split(',') if H ]
        offset = m.end()
        if offset == len(line):
          raise ValueError("missing match after header names")
      else:
        headernames = ('to', 'cc', 'bcc')

      if line[offset] == '/':
        regexp = line[offset+1:]
        if regexp.startswith('^'):
          atstart = True
          regexp = regexp[1:]
        else:
          atstart = False
        C = Condition_Regexp(headernames, atstart, regexp)
      else:
        # (group[|group...])
        m = re_INGROUP.match(line, offset)
        if m:
          group_names = set( w.strip().lower() for w in m.group()[1:-1].split('|') )
          offset = m.end()
          if offset < len(line):
            raise ValueError("extra text after groups: %s" % (line,))
          C = Condition_InGroups(headernames, group_names)
        else:
          if line[offset] == '(':
            raise ValueError("incomplete group match at: %s" % (line[offset:]))
          # just a comma separated list of addresses
          # TODO: should be RFC2822 list instead?
          addrkeys = [ w.strip() for w in line[offset:].split(',') ]
          C = Condition_AddressMatch(headernames, addrkeys)
      R.conditions.append(C)

  if R is not None:
    yield R

class _Condition(O):
  pass

class Condition_Regexp(_Condition):

  def __init__(self, headernames, atstart, regexp):
    self.headernames = headernames
    self.atstart = atstart
    self.regexp = re.compile(regexp)
    self.regexptxt = regexp

  def match(self, state):
    M = state.message
    for hdr in self.headernames:
      for value in M.get_all(hdr, ()):
        if self.atstart:
          if self.regexp.match(value):
            return True
        else:
          if self.regexp.search(value):
            return True
    return False

class Condition_AddressMatch(_Condition):

  def __init__(self, headernames, addrkeys):
    self.headernames = headernames
    self.addrkeys = [ k for k in addrkeys if len(k) > 0 ]

  def match(self, state):
    for address in state.addresses(*self.headernames):
      for key in self.addrkeys:
        if key.startswith('{{') and key.endswith('}}'):
          warning("OBSOLETE address key: %s", key)
          group_name = key[2:-2].lower()
          if state.ingroup(address, group_name):
            return True
        elif address.lower() == key.lower():
          return True
    return False

class Condition_InGroups(_Condition):

  def __init__(self, headernames, group_names):
    self.headernames = headernames
    self.group_names = group_names

  def match(self, state):
    for address in state.addresses(*self.headernames):
      for group_name in self.group_names:
        if state.ingroup(address, group_name):
          debug("match %s to (%s)", address, group_name)
          return True
    return False

_FilterReport = namedtuple('FilterReport',
                          'rule matched saved_to ok_actions failed_actions')
def FilterReport(rule, matched, saved_to, ok_actions, failed_actions):
  if not matched:
    if saved_to:
      raise RunTimeError("matched(%r) and not saved_to(%r)" % (matched, saved_to))
  return _FilterReport(rule, matched, saved_to, ok_actions, failed_actions)

class Rule(O):

  def __init__(self, filename, lineno):
    self.filename = filename
    self.lineno = lineno
    self.conditions = slist()
    self.actions = slist()
    self.flags = O(alert=False, halt=False)
    self.label = ''

  def match(self, state):
    for C in self.conditions:
      if not C.match(state):
        return False
    return True

  def filter(self, state):
    M = state.message
    with Pfx("%s:%d", self.filename, self.lineno):
      saved_to = []
      ok_actions = []
      failed_actions = []
      matched = self.match(state)
      if matched:
        for action, arg in self.actions:
          ok = False
          try:
            if action == 'TARGET':
              target = envsub(arg, state.environ)
              if target.startswith('|'):
                shcmd = target[1:]
                if state.pipe_message(['/bin/sh', '-c', shcmd]):
                  ok = True
                  saved_to.append(target)
                else:
                  error("failed to pipe to %s", target)
                  failed_actions.append( (action, arg, "pipe "+target) )
              elif '@' in target:
                if state.sendmail(target):
                  ok = True
                  saved_to.append(target)
                else:
                  error("failed to sendmail to %s", target)
                  failed_actions.append( (action, arg, "sendmail "+target) )
              else:
                mdir = state.maildir(target)
                savepath = state.save_to_maildir(mdir, self.label)
                ok = True
                # we get None if the message has already been saved here
                if savepath is not None:
                  saved_to.append(savepath)
                else:
                  debug("repeated filing to maildir, skipping %s", mdir)
            elif action == 'ASSIGN':
              envvar, s = arg
              value = state.environ[envvar] = envsub(s, state.environ)
              ok = True
              debug("ASSIGN %s=%s", envvar, value)
              if envvar == 'LOGFILE':
                state.logto(value)
              elif envvar == 'DEFAULT':
                R = state.default_rule = Rule(self.filename, self.lineno)
                R.actions.append( ('TARGET', '$DEFAULT') )
            else:
              raise RuntimeError("unimplemented action \"%s\"" % action)
          except (AttributeError, NameError):
            raise
          except Exception as e:
            warning("EXCEPTION %r", e)
            failed_actions.append( (action, arg, e) )
            raise
          else:
            if ok:
              ok_actions.append( (action, arg) )
        if not saved_to:
          debug("MATCHED but no saved_to: %s", self)
        else:
          debug("MATCHED and saved_to=%s: %s", saved_to, self)
      return FilterReport(self, matched, saved_to, ok_actions, failed_actions)

class Rules(list):
  ''' Simple subclass of list storing rules, with methods to load
      rules and filter a message using the rules.
  '''

  def __init__(self, rules_file=None):
    list.__init__(self)
    self.vars = {}
    self.rule_files = set()
    if rules_file is not None:
      self.load(rules_file)

  def load(self, fp):
    ''' Import an open rule file.
    '''
    new_rules = list(parserules(fp))
    self.rule_files.update( R.filename for R in new_rules )
    self.extend(new_rules)

  def filter(self, state):
    ''' Filter the current message according to the rules.
        Yield FilterReports for each rule consulted.
        If no rule matches and $DEFAULT is set, yield a FilterReport for
        filing to $DEFAULT, with .rule set to None.
    '''
    done = False
    saved_to = []
    for R in self:
      report = R.filter(state)
      M = state.message
      if report.matched:
        if not report.saved_to:
          debug("matched but not saved_to: %s", R)
        saved_to.extend(report.saved_to)
        if R.flags.alert:
          self.alert("%s: %s" % (M.get('from', '').strip(), M.get('subject', '').strip()))
      else:
        if report.saved_to:
          raise RunTimeError("matched is False, but saved_to = %s" % (saved_to,))
      yield report
      if report.matched:
        if R.flags.halt:
          done = True
          break
    if not done:
      if not saved_to:
        R = state.default_rule
        if not R:
          warning("NO DEFAULT: message not saved and no $DEFAULT")
        else:
          report = R.filter(state)
          if not report.matched:
            raise RunTimeError("default rule faled to match! %r", R)
          saved_to.extend(report.saved_to)
          if not saved_to:
            warning("message not saved by any rules")
          yield report
      else:
        debug("%d filings, skipping $DEFAULT", len(saved_to))

  def alert(self, alert_message):
    xit = subprocess.call(['alert', 'MAILFILER: ' + alert_message])
    if xit != 0:
      warning("non-zero exit from alert: %d", xit)
    return xit

class WatchedMaildir(O):
  ''' A class to monitor a Maildir and filter messages.
  '''

  def __init__(self, mdir, filter_modes, rules_path=None):
    self.mdir = Maildir(resolve_maildir_path(mdir, os.environ['MAILDIR']))
    self.filter_modes = filter_modes
    if rules_path is None:
      rules_path = os.path.join(self.mdir.dir, '.rules')
    self._rules_paths = [ rules_path ]
    self._rules_lock = Lock()
    self.lurking = set()
    self.flush()
    warning("%d rules", len(self.rules))

  def __str__(self):
    return "<WatchedMaildir %s modes=%s, %d rules, %d lurking>" \
           % (self.shortname,
              self.filter_modes,
              len(self.rules),
              len(self.lurking))

  @property
  def shortname(self):
    return self.mdir.shortname

  def flush(self):
    ''' Forget state.
        The set of lurkers is emptied.
    '''
    self.lurking = set()

  def close(self):
    self.filter_modes.maildb.close()

  @files_property
  def rules(self, rules_paths):
    # base file is at index 0
    path0 = rules_paths[0]
    R = Rules(path0)
    # produce rules file list with base file at index 0
    paths = [ path0 ] + [ path for path in R.rule_files if path != path0 ]
    return paths, R

  def filter(self):
    ''' Scan this spool Maildir for messages to filter.
        Yield (key, FilterReports) for all messages filed.
	Update the set of lurkers with any keys not removed to prevent
	filtering on subsequent calls.
    '''
    with Pfx("%s: filter", self.shortname):
      self.mdir.flush()
      nmsgs = 0
      skipped = 0
      with LogTime("all keys") as all_keys_time:
        mdir = self.mdir
        for key in mdir.keys():
          if key in self.lurking:
            debug("skip processed key: %s", key)
            skipped += 1
            continue
          nmsgs += 1
          with LogTime("key = %s" % (key,), threshold=1.0, level=DEBUG):
            M = mdir[key]
            state = RuleState(M, self.filter_modes)
            state.message_path = mdir.keypath(key)
            state.logto(envsub("$HOME/var/log/mailfiler"))
            state.log( (u("%s %s") % (time.strftime("%Y-%m-%d %H:%M:%S"),
                                         unrfc2047(M.get('subject', '_no_subject'))))
                       .replace('\n', ' ') )
            state.log("  " + unrfc2047(M.get('from', '_no_from')))
            state.log("  " + M['message-id'])
            state.log("  " + shortpath(mdir.keypath(key)))
            saved_to = []
            reports = []
            for report in self.rules.filter(state):
              if report.matched:
                reports.append(report)
                saved_to.extend(report.saved_to)
              else:
                if report.saved_to:
                  error("UNMATCHED RULE: saved_to=%s", report.saved_to)
            if not saved_to:
              state.log("ERROR: message not saved, lurking key %s", key)
              error("message not saved, lurking key %s", key)
              self.lurking.add(key)
            elif self.filter_modes.no_remove:
              state.log("no_remove: message not removed, lurking key %s", key)
              self.lurking.add(key)
            else:
              info("remove message key %s", key)
              mdir.remove(key)
              self.lurking.discard(key)
            yield key, reports
          if self.filter_modes.justone:
            break
      if nmsgs or all_keys_time.elapsed >= 0.2:
        info("filtered %d messages (%d skipped) in %5.3fs", nmsgs, skipped, all_keys_time.elapsed)

if __name__ == '__main__':
  sys.exit(main(sys.argv))