]> diplodocus.org Git - minc/blob - minc
db8cdff6e97d197d3221e814960b84ab2f325ade
[minc] / minc
1 #!/usr/bin/perl
2
3 =head1 NAME
4
5 B<minc> - incorporate mail from a maildir into mh folders
6
7 =head1 SYNOPSIS
8
9 B<minc> [B<-m> I<MAX>] [B<-n>]
10
11 B<minc> B<-d>
12
13 B<minc> B<-r>
14
15 =head1 DESCRIPTION
16
17 B<minc> incorporates mail from a maildir to a mh folder hierarchy. It
18 takes mail from a maildir folder (not a maildir folder hierarchy),
19 running each message through regular expression based filter and hook
20 functions to determine in which folder to store it or whether it's
21 spam. Post-processing hooks may be applied to each message.
22
23 As it processes each message, B<minc> prints a line for each message
24 similar to B<inc(1)> and B<scan(1)>. This line includes the folder
25 and message number in which the message was stored, the last 'From'
26 header, and the last 'Subject' header. These fields are truncated to
27 fit in the user's terminal (see COLUMNS in B<ENVIRONMENT> below) in
28 the following proportions: folder (0.1), message number (0.0625), from
29 header (0.175). Any of these may be overridden with $SCAN_P_FOLDER,
30 $SCAN_P_MESSAGE, or $SCAN_P_FROM. The subject always fills out the
31 rest of the line.
32
33 =cut
34
35 use strict;
36 use warnings;
37
38 $SIG{'PIPE'} = 'IGNORE';
39
40 use Data::Dumper;
41 use Errno;
42 use Fcntl;
43 use FileHandle;
44 use File::FcntlLock;
45 use File::Temp qw(tempfile);
46 use File::stat;
47 use Getopt::Long qw(:config gnu_getopt no_ignore_case);
48 use Pod::Usage;
49
50 use constant LOCK_TRIES => 60;
51
52 our $VERSION = 1;
53
54 # If a filter set's header is $MAGIC_TO_TOKEN, that set is compared
55 # against headers matching this regex (taken from procmail).
56 my $MAGIC_TO_REGEX = '^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope |Apparently(-Resent)?)-To)';
57 my $MAGIC_TO_TOKEN = ' TO';
58
59 # Mapping of message numbers to array references. The first element is set by
60 # filter_mail to a reference to a header hash for the message; the second is
61 # set by maildier_spam to the name of the message file in the spam maildir.
62 # scan_spam scans this at the end so the user can check for false positives.
63 my %SPAM;
64
65 =head1 OPTIONS
66
67 =over 4
68
69 =item B<-d>
70
71 Dump (using Data::Dumper) the FILTERS list and exit. This is useful
72 for testing the syntax of .minc.
73
74 =item B<-h>
75
76 Show help.
77
78 =item B<-m> I<MAX>
79
80 Stop processing after I<MAX> messages.
81
82 =item B<-n>
83
84 Dry run; do not actually incorporate the mail, but log and report to
85 stdout/stderr as normal.
86
87 =item B<-r>
88
89 Rebuild `mhpath +`/.folders from scratch, processing no mail.
90
91 =back
92
93 =cut
94
95 my $dumpfilters;
96 my $help;
97 my $maxmsgs;
98 my $norun;
99 my $rebuild_dot_folders;
100
101 if (!caller()) {
102 GetOptions(
103 'd' => \$dumpfilters,
104 'h|help' => \$help,
105 'm=i' => \$maxmsgs,
106 'n' => \$norun,
107 'r' => \$rebuild_dot_folders,
108 ) or pod2usage();
109 $help and pod2usage(-exitstatus=>0, -verbose=>1);
110 @ARGV == 0 or pod2usage();
111 }
112
113 our $run = !$norun;
114
115 =head1 ENVIRONMENT
116
117 =over 4
118
119 =item COLUMNS
120
121 How many columns the user's terminal can hold, used to print scan
122 lines for each processed message. Defaults to 80.
123
124 =item HOME
125
126 Where the configuration file (.minc) is found. Also,
127 $HOME/Maildir is used for the maildir if MAILDIR is not set.
128
129 =item MAILDIR
130
131 Where mail is delivered.
132
133 =back
134
135 =cut
136
137 use Env qw(COLUMNS HOME MAILDIR);
138
139 $COLUMNS ||= 80;
140
141 if (not $HOME) {
142 die("HOME environment variable must be set.\n");
143 }
144 if (not $MAILDIR) {
145 $MAILDIR = "$HOME/Maildir";
146 }
147
148 =head1 FILES
149
150 =over 4
151
152 =item $HOME/.minc
153
154 This file is Perl code (included via the 'require' directive) which
155 may define the FILTERS list, @start_hooks, @filter_hooks,
156 @post_store_hooks, and @stop_hooks.
157
158 =item `mhpath +`/.folders
159
160 B<minc> adds all folders it filters into to this file, which is used
161 by lukem's B<new(1)> (XXX need a link).
162
163 =item `mhpath +`/.minc.context
164
165 B<minc> uses this file for context (i.e. current folder) instead of
166 `mhpath +`/context. This allows you some amount of freedom to use mh
167 while B<minc> is running. For example, you can changed folders without
168 causing a message to be stored in the wrong folder. Care must still
169 be taken, however, about the unseen sequence; if you change it
170 (whether via show, or mark, or anything else) while in the same folder
171 as B<minc>, it is likely the new message B<minc> stores will not end up
172 marked unseen.
173
174 =back
175
176 =cut
177
178 our @FILTERS;
179 our (@start_hooks, @stop_hooks, @filter_hooks, @post_store_hooks);
180 our $SCAN_P_FOLDER = 0.1;
181 our $SCAN_P_MESSAGE = 0.0625;
182 our $SCAN_P_FROM = 0.175;
183 our @folder_sort_list = (qr/^inbox$/);
184 our $folder_sorter = sub { sort_by_list(@_, @folder_sort_list) };
185
186 my $mh;
187
188 $mh = `mhpath +`;
189 chomp($mh);
190
191 $ENV{"MHCONTEXT"} = $mh . '/.minc.context';
192
193 \f
194 ###############################################################################
195 # Utility procedures
196
197 sub sort_by_list {
198 my $a = shift;
199 my $b = shift;
200
201 for my $i (@_) {
202 my $am = $a =~ $i;
203 my $bm = $b =~ $i;
204 if ($am) {
205 if ($bm) {
206 last;
207 }
208 return -1;
209 } elsif ($bm) {
210 return 1;
211 }
212 }
213
214 return $a cmp $b;
215 }
216
217 sub mkfolder {
218 my $folder = shift;
219 my $target;
220 my $component;
221
222 $target = $mh;
223 foreach $component (split('/', $folder)) {
224 $target = join('/', $target, $component);
225 -d $target or mkdir($target) or die("mkdir($target): $!");
226 }
227 }
228
229 sub getfiles {
230 my $dir = shift;
231 my @result;
232
233 if (not opendir(DIR, $dir)) {
234 die("opendir($dir): $!");
235 }
236
237 # Initialize $! to 0 (success) because stupid stupid Perl provides
238 # no way to distinguish an error from an empty directory; that
239 # means setting $! to 0 and testing it afterwards is the only way
240 # to detect an error. Real Programmers don't handle errors,
241 # right? >sigh<
242 $! = 0;
243 @result = readdir(DIR);
244 if ($! != 0) {
245 die("readdir($dir): $!");
246 }
247
248 if (@result <= 2) {
249 return ();
250 }
251
252 STDOUT->autoflush(1);
253 if (@result == 3) {
254 print('1 message...');
255 } else {
256 print(@result - 2, ' messages...');
257 }
258
259 closedir(DIR);
260
261 return @result;
262 }
263
264 my %msgnum_cache;
265 sub get_highest_msgnum {
266 my $mhfolder = shift;
267 my $dir;
268 my @list;
269 my $highest;
270 my $msgnum;
271
272 if (defined($msgnum_cache{$mhfolder})) {
273 return $msgnum_cache{$mhfolder}++;
274 }
275
276 $dir = "$mh/$mhfolder";
277 if (not opendir(DIR, $dir)) {
278 die("opendir($dir): $!");
279 }
280
281 # Insert rant from getfiles here.
282 $! = 0;
283 @list = readdir(DIR);
284
285 if ($! != 0) {
286 die("readdir($dir): $!");
287 }
288
289 closedir(DIR);
290
291 $highest = 0;
292 foreach $msgnum (@list) {
293 # Look for integers.
294 if ($msgnum =~ /^[0-9]+$/) {
295 if ($msgnum > $highest) {
296 $highest = $msgnum;
297 }
298 }
299 }
300
301 $msgnum_cache{$mhfolder} = $highest;
302 return $msgnum_cache{$mhfolder}++;
303 }
304
305 sub mark {
306 my $folder = shift;
307 my $msgnum = shift;
308 my $seq = shift;
309 my $fn = "$mh/$folder/.mh_sequences";
310 my $fh;
311 my @sequences;
312
313 if (not open($fh, $fn)) {
314 $!{ENOENT} or die("open($fn): $!");
315 } else {
316 @sequences = <$fh>;
317 chomp(@sequences);
318 }
319
320 my $marked = 0;
321 open($fh, '>', $fn) or die("open(>$fn): $!");
322 for $_ (@sequences) {
323 if (/^$seq: (.*)/) {
324 my @parts;
325 my @result;
326 my $done = 0;
327 for my $part (split(' ', $1)) {
328 if (not $done) {
329 my ($st, $en) = split('-', $part);
330 if ((defined($en) and ($msgnum >= $st and $msgnum <= $en))
331 or $msgnum == $st) {
332 # It's already there.
333 $done = 1;
334 }
335 if (defined($en)) {
336 if ($st - 1 == $msgnum) {
337 $part = "$msgnum-$en";
338 $done = 1;
339 } elsif ($en + 1 == $msgnum) {
340 $part = "$st-$msgnum";
341 $done = 1;
342 }
343 } else {
344 if ($part - 1 == $msgnum) {
345 $part = "$msgnum-$part";
346 $done = 1;
347 } elsif ($part + 1 == $msgnum) {
348 $part = "$part-$msgnum";
349 $done = 1;
350 }
351 }
352 }
353 push(@result, $part);
354 }
355 if (not $done) {
356 push(@result, $msgnum);
357 }
358 print($fh "$seq: ", join(' ', @result), "\n");
359 $marked = 1;
360 } else {
361 print($fh "$_\n");
362 }
363 }
364 $marked or print($fh "$seq: $msgnum\n");
365 close($fh) or die("close(>$fn): $!");
366 }
367
368 # Based on nmh's lkopen_fcntl
369 # Return 0 for success, errno on failure.
370 sub lkopen_fcntl {
371 my $file = shift;
372 my $access = shift;
373 my $mode = shift;
374 my $errno = 0;
375
376 # The assumption here is that if you open the file for writing, you
377 # need an exclusive lock.
378
379 my $tries = LOCK_TRIES;
380 for (;;) {
381 sysopen(my $fh, $file, $access, $mode) or die("sysopen($file): $!");
382
383 my $flk = File::FcntlLock->new;
384 $flk->l_start(0);
385 $flk->l_len(0);
386 $flk->l_type(($access & O_ACCMODE) == O_RDONLY ? F_RDLCK : F_WRLCK);
387 $flk->l_whence(SEEK_SET);
388
389 # Really should only retry on EAGAIN and EINTR...
390 if ($flk->lock($fh, F_SETLK)) {
391 return $fh, undef;
392 }
393
394 $errno = $flk->lock_errno;
395 close($fh) or die("close($file): $!");
396
397 if (--$tries == 0) {
398 last;
399 }
400 sleep(1);
401 }
402
403 return undef, $errno;
404 }
405
406 sub store_message {
407 my $msg = shift;
408 my $mhfolder = shift;
409 my $msgnum;
410 my $try;
411 my $mhmsg;
412
413 # We must do this even in -n mode because later steps fail without
414 # it. This should be harmless.
415 mkfolder($mhfolder);
416
417 # This loop is a modified version of the maildir delivery algorithm.
418 $msgnum = get_highest_msgnum($mhfolder);
419 for ($try = 0; ; $try++) {
420 $msgnum++;
421 $mhmsg = "$mh/$mhfolder/$msgnum";
422
423 if (not stat($mhmsg)) {
424 if ($!{ENOENT}) {
425 # Now we have a non-existent file, let's try to create
426 # it. We must create a zero-byte file first because a
427 # file my appear between our happy stat results and
428 # our later rename(2), which would clobber said file.
429 # So attempt to create a file with this name. If it
430 # succeeds, in just a bit here we'll knowingly clobber
431 # this file with the rename(2) call.
432
433 # Another way to do this is not to use rename(2), but
434 # use link(2) + unlink(2) instead. That's how the
435 # standard maildir algorithm does it. Each method has
436 # a disadvantage: the program may crash between the
437 # link(2) and unlink(2) calls. With the standard
438 # maildir algorithm, that means the message will end
439 # up duplicated. The advantage of creating an empty
440 # file followed by rename(2) is that an extra empty
441 # file is left behind as opposed to a duplicate
442 # message. This is more easily detected by the user.
443 if ($run) {
444 if (sysopen(MSG, $mhmsg,
445 O_WRONLY | O_EXCL | O_CREAT, 0600)) {
446 close(MSG);
447 last;
448 }
449 } else {
450 last;
451 }
452 }
453 }
454
455 # This algorithm is different from the maildir one; let's make
456 # 10 tries instead of 3.
457 if ($try == 9) {
458 die("Attempted filename $mhmsg exists.");
459 }
460
461 # This algorithm is different; i don't think we need to sleep.
462 #sleep(2);
463 }
464
465 if ($run) {
466 if (not rename($msg, $mhmsg)) {
467 die("rename($msg, $mhmsg): $!");
468 }
469
470 # Mark each message as soon as we store it and bomb if that
471 # fails. While it is slow, it is not safe to store multiple
472 # messages and then have a failure before marking some (or
473 # all).
474 if ($mhfolder ne 'SPAM') {
475 mark($mhfolder, $msgnum, 'unseen');
476 }
477 }
478
479 return $msgnum;
480 }
481
482 # Parse a message file into a structure describing the headers. The
483 # structure is a hash of arrays. The hash keys are the names of the
484 # headers found in the message, made all lower-case. Each item in
485 # the hash is an array of header text. The array has one element
486 # per occurrence of the header. Most headers will only have a single
487 # element because they occur only once. The Received header is the
488 # most common header with multiple texts.
489 sub get_headers {
490 my $msg = shift;
491 my %headers;
492 my $current; # current header, used for unfolding lines
493 my $fieldname; # unmolested header name
494 my $contents; # contents of header
495
496 open(MSG, $msg) or die("open(MSG, $msg): $!");
497 while (<MSG>) {
498 chomp;
499 if (length == 0) {
500 last;
501 }
502
503 if (/^\s/) {
504 # folded header continuation
505
506 if (not defined($current)) {
507 warn('Malformed message, cannot parse headers.');
508 next;
509 }
510
511 @{$headers{$current}}[-1] .= $_;
512 } else {
513 ($fieldname) = split(/:/);
514 $current = lc($fieldname);
515 (undef, $contents) = split(/^\Q$fieldname\E:\s*/);
516
517 if (defined($headers{$current})) {
518 # multiple occurence of same header
519 push(@{$headers{$current}}, $contents);
520 } else {
521 # first occurence of a header
522 $headers{$current} = [$contents];
523 }
524 }
525 }
526 close(MSG);
527
528 return \%headers;
529 }
530
531 \f
532 ###############################################################################
533 # Filtering
534
535 sub find_mh_folder {
536 my $msg = shift;
537 my $header = shift;
538
539 if (not %$header) {
540 return 'malformed';
541 }
542
543 # Walk the list of filters. This structure is documented in
544 # pod at the end of the program.
545 for my $filterref (@FILTERS) {
546 if (ref($filterref) eq 'CODE') {
547 my $m = $filterref->($header, $msg);
548 $m && return $m;
549 next;
550 }
551
552 my $m = match($header, @$filterref);
553 $m && return $m;
554 }
555
556 return 'inbox';
557 }
558
559 # Test all the header fields against each [regexp, folder-expression] pair.
560 sub match {
561 my $header = shift;
562 my $filter_field = shift;
563 my @filters = @_;
564
565 # Handle filters using the magic TO header specially.
566 if ($filter_field eq $MAGIC_TO_TOKEN) {
567 for my $field_name (keys(%$header)) {
568 if ($field_name =~ /$MAGIC_TO_REGEX/i) {
569 my $m = match_one_field($header->{$field_name}, \@filters);
570 $m && return $m;
571 }
572 }
573 # Now that it's been processed specially, skip normal handling.
574 return;
575 }
576
577 # Walk the list of header fields matching the filter's specified header.
578 my $m = match_one_field($header->{lc($filter_field)}, \@filters);
579 $m && return $m;
580 }
581
582 # Test all the values of one header field against each [regexp,
583 # folder-expression] pair.
584 sub match_one_field {
585 my $values = shift;
586 my $filters = shift;
587 for my $value (@$values) {
588 for my $pair (@$filters) {
589 my ($regexp, $expression) = @$pair;
590 if ($value =~ $regexp) {
591 my $result;
592 if (eval "\$result = \"$expression\"") {
593 return $result;
594 }
595 }
596 }
597 }
598 }
599
600 sub scan_line {
601 my ($headers, $mhfolder, $msgnum, $nf, $nm, $nF, $ns) = @_;
602 my $from = '';
603 my $subject = '';
604 # Sometimes these headers are missing...
605 eval { $from = [@{$headers->{'from'}}]->[-1] };
606 eval { $subject = [@{$headers->{'subject'}}]->[-1] };
607 # Replace garbage characters.
608 for ($from, $subject) {
609 tr/\x00-\x1f\x80-\xff/?/;
610 }
611 return sprintf("\%-${nf}s \%${nm}d \%-${nF}s \%s",
612 substr($mhfolder, 0, $nf), substr($msgnum, 0, $nm),
613 substr($from, 0, $nF),
614 substr($subject, 0, $ns));
615 }
616
617 sub filter_mail {
618 @_ or return ();
619 my $msgcount = @_ - 2; # don't count . and ..
620 my $len = length($msgcount);
621 my @baton;
622 my $msg;
623 my $mhfolder;
624 my $spam = 0;
625 my $saved = 0;
626 my $msgnum;
627 my %folders;
628
629 if (-f "$HOME/.minc") {
630 require "$HOME/.minc";
631 }
632
633 # XXX lame names
634 my $nf = int($COLUMNS * $SCAN_P_FOLDER);
635 my $nm = int($COLUMNS * $SCAN_P_MESSAGE);
636 my $nF = int($COLUMNS * $SCAN_P_FROM);
637 my $ns = $COLUMNS - $nf - $nm - $nF - 3;
638
639 my %batons;
640 for my $hook (@start_hooks) {
641 my ($handle, @baton) = $hook->();
642 if (defined($handle)) {
643 $batons{$handle} = [@baton];
644 }
645 }
646
647 my $tty = -t STDOUT;
648 if (not $tty) {
649 # Print a newline after the incomplete "N messages..." line.
650 print("\n");
651 }
652
653 for $msg (@_) {
654 ($msg eq '.' or $msg eq '..') and next;
655
656 my $headers = get_headers($msg);
657
658 undef($mhfolder);
659 for my $hook (@filter_hooks) {
660 my $result = $hook->(\%batons, $headers, $msg);
661 defined($result) and ($mhfolder = $result);
662 }
663
664 defined($mhfolder) or ($mhfolder = find_mh_folder($msg, $headers));
665
666 $msgnum = store_message($msg, $mhfolder);
667 $folders{$mhfolder}++;
668
669 if ($tty) {
670 print("\r");
671 }
672
673 if ($mhfolder eq 'SPAM') {
674 $spam++;
675 $SPAM{$msgnum} = [$headers, undef];
676 } else {
677 $saved++;
678 print(scan_line($headers, $mhfolder, $msgnum, $nf, $nm, $nF, $ns),
679 "\n");
680 }
681
682 for my $hook (@post_store_hooks) {
683 $hook->(\%batons, $headers, $mhfolder, $msgnum);
684 }
685
686 if ($tty) {
687 printf(" \%${len}d SPAM \%${len}d saved \%${len}d/%1d",
688 $spam, $saved, $spam + $saved, $msgcount);
689 }
690
691 defined($maxmsgs) and ($spam + $saved < $maxmsgs or last);
692 }
693 print("\n");
694
695 for my $hook (@stop_hooks) {
696 $hook->(\%batons);
697 }
698
699 return %folders;
700 }
701
702 sub build_dot_folders {
703 my $folders = shift;
704 my $fh = shift;
705 my $fn;
706
707 if (defined($fh)) {
708 while (<$fh>) {
709 chomp;
710 $folders->{$_}++;
711 }
712 }
713
714 eval { ($fh, $fn) = tempfile("$mh/.folders.XXXXX") };
715 if ($@) {
716 warn("$@");
717 return;
718 }
719
720 for my $folder (sort { $folder_sorter->($a,$b) } keys(%$folders)) {
721 print($fh "$folder\n");
722 }
723
724 if (not close($fh)) {
725 warn("close($fn): $!");
726 unlink($fn) or warn("unlink($fn): $!");
727 return;
728 }
729
730 rename($fn, "$mh/.folders") or warn("rename($fn, $mh/.folders): $!");
731 }
732
733 sub create_dot_folders {
734 if (-f "$HOME/.minc") {
735 require "$HOME/.minc";
736 }
737
738 my %folders;
739 open(my $fh, '-|', 'folders', '-fast', '-recur')
740 or die("open(folders|): $!");
741 build_dot_folders(\%folders, $fh);
742 return 0;
743 }
744
745 sub update_dot_folders {
746 my $folders = shift;
747 my $fh;
748
749 if (not open($fh, "$mh/.folders") and not $!{ENOENT}) {
750 # For ENOENT, we go ahead and create it, else we error and
751 # don't clobber it.
752 warn("open($mh/.folders): $!");
753 return;
754 }
755
756 build_dot_folders($folders, $fh);
757 }
758
759 # XXX Could use some unification with getfiles...
760 sub maildir_spam {
761 my $dir = "$MAILDIR/spam/new";
762
763 if (not chdir($dir)) {
764 $!{ENOENT} or print(STDERR "skipping maildir spam: chdir($dir): $!\n");
765 return;
766 }
767
768 if (not opendir(DIR, '.')) {
769 print(STDERR "skipping maildir spam: opendir($dir): $!\n");
770 return;
771 }
772
773 $! = 0;
774 my @spams = readdir(DIR);
775 if ($! != 0) {
776 print(STDERR "skipping maildir spam: readdir($dir): $!\n");
777 return;
778 }
779
780 closedir(DIR);
781
782 for my $msg (@spams) {
783 ($msg eq '.' or $msg eq '..') and next;
784 my $msgnum = store_message($msg, 'SPAM');
785 # Store the original file name for scan_spam in -n mode.
786 $SPAM{$msgnum} = [undef, $msg];
787 }
788 }
789
790 sub scan_spam {
791 my ($msgnum, $header, $tuple, $msg);
792
793 # Unlike filter_mail, we don't need to print the folder name.
794 # Calculate how many columns would be allocated to it...
795 my $nf = int($COLUMNS * $SCAN_P_FOLDER);
796 # ...and add that amount to COLUMNS to calculate the number of columns to
797 # allocate to msgnum and from snippet, thus filling the line without
798 # printing the folder name.
799 my $nm = int(($COLUMNS + $nf) * $SCAN_P_MESSAGE);
800 my $nF = int(($COLUMNS + $nf) * $SCAN_P_FROM);
801 my $ns = $COLUMNS - $nm - $nF - 3;
802
803 for $msgnum (sort(keys(%SPAM))) {
804 $tuple = $SPAM{$msgnum};
805 if (defined($tuple->[0])) {
806 # Filed by filter_mail, so we have the header.
807 $header = $tuple->[0];
808 } elsif (defined($tuple->[1])) {
809 # Filed by maildir_spam, so we don't have the header.
810 if ($run) {
811 # The message has been filed, load it from $mh.
812 $msg = "$mh/SPAM/$msgnum";
813 } else {
814 # The message has not been filed, load it from the maildir.
815 # $tuple->[1] is just a basename, not a path; this works
816 # because maildir_spam did chdir(Maildir/spam/new).
817 $msg = $tuple->[1];
818 }
819 $header = get_headers($msg);
820 } else {
821 print(STDERR
822 "BUG: corrupt SPAM tuple, neither element defined",
823 " for message $msgnum\n");
824 next;
825 }
826 print(scan_line($header, '', $msgnum, 0, $nm, $nF, $ns),
827 "\n");
828 }
829 }
830
831 \f
832 if (!caller()) {
833 my $st;
834
835 if ($dumpfilters) {
836 require "$HOME/.minc";
837 $Data::Dumper::Indent = 1;
838 print(Dumper(\@FILTERS));
839 exit;
840 }
841
842 $rebuild_dot_folders and exit(create_dot_folders);
843
844 chdir("$MAILDIR/new") or die("chdir($MAILDIR/new): $!");
845 my %folders = filter_mail(map { $_->[1] }
846 sort { $a->[0] <=> $b->[0] }
847 map {
848 if (not ($st = stat($_))) {
849 die("stat($_): $!");
850 }
851 [$st->mtime, $_]
852 }
853 getfiles('.'));
854
855 $run and %folders and update_dot_folders(\%folders);
856
857 maildir_spam();
858 scan_spam();
859 }
860
861 1;
862
863 \f
864 __END__
865
866 =head1 THE FILTERS STRUCTURE
867
868 Each element of @FILTERS is a filter. A filter is itself an array.
869 The first element of a filter is a string, the name of the header this
870 filter acts upon. The header name is not case-sensitive. Each
871 subsequent element of a filter is a pair (i.e. a two-element array):
872 first, a regular expression B<minc> uses to determine whether this
873 filter matches or not, and second, an expression which B<minc>
874 evaluates to get the folder name.
875
876 B<minc> decides where to store a message by iterating over the
877 @FILTERS array. It tests each regexp of each filter against all
878 headers matching that filter's specified header. As soon as a match
879 is found, B<minc> evaluates the second part of the pair. This part
880 may contain positional parameters from the matched regexp ($1, $2,
881 etc.). The result of this expression is used as the folder name.
882
883 Multiple occurrences of the same header are preserved and tested
884 individually against the filters. That means, for example, that
885 filters can search all the Received headers for a certain string.
886
887 It is important to note that all the arrays of the @FILTERS structure
888 are traversed I<in order>. This means the filters can be arranged so
889 that some have priority over others. XXX: get Doug to write an
890 example of having the same header matched more than once.
891
892 Lastly, B<minc> supports a magic ' TO' header. Filters using this
893 header are matched against a collection of headers related to (and
894 including) the To. Which headers to use is determined by a regular
895 expression borrowed from procmail.
896
897 =head1 HOOKS
898
899 Filter hooks take a reference to a hash of batons, a reference to a
900 hash of headers, and the message filename as arguments. It returns
901 undef to decline filtering of this message (thus falling back to
902 subsequent filter hooks, and finally @FILTERS), or the name of the
903 folder to store this message into.
904
905 One of B<minc>'s global variables is available to the user-defined
906 hooks: $run. This boolean should be honored; hooks should only take
907 real action (i.e. removing or creating files, running external
908 programs, etc.) if $run is non-zero.
909
910 The baton hash is created simply from the start hooks; if the hook
911 returns at least one defined value, this value is used as the key and
912 all other return values are put into a list reference as the value.
913 This hash is then passed by reference to all filter, post-store, and
914 stop hooks.
915
916 Post store hooks take a reference to a hash of batons, a reference to
917 a hash of headers, the folder this message was stored in, and its new
918 message number.
919
920 XXX: need more details about the hook process; for now read the code.
921
922 =head1 EXAMPLES
923
924 @FILTERS = (
925
926 ['List-Id',
927 ['<([[:graph:]]+)-([[:graph:]]+)\.lists\.sourceforge\.net>', 'l/$1/$2'],
928 ['<([[:graph:]]+?)(-list)?\.freedesktop\.org>', 'l/freedesktop/$1'],
929 ['<swig\.cs\.uchicago\.edu>', 'l/swig'],
930 ],
931
932 ['List-Post',
933 ['<mailto:([[:graph:]]+)+@([[:graph:]]+)\.apache\.org>', 'l/apache/$2/$1'],
934 ],
935
936 ['To',
937 ['root', 'root'],
938 ],
939 );
940
941 The first List-Id filter is a surprisingly effective one which creates
942 appropriate folder names (such as l/htdig/updates and l/rox/devel) for
943 all Sourceforge lists to which i subscribe. Certainly there are lists
944 hosted at Sourceforge which do not work well with this, and this is
945 where it is important to remember that the first match is the one
946 uses. Simply put the more specific rules before this one.
947
948 The next List-Id example is simple. The swig example demonstrates
949 that the folder name does not have to use a portion of the matched
950 header; you can just hardcode the folder name.
951
952 The List-Post example is a nice one. Most ASF projects have their own
953 apache.org subdomain, with mailing lists hosted there. So, given a
954 list such as dev@httpd.apache.org, this filter will create the folder
955 name l/apache/httpd/dev.
956
957 XXX Need hook examples.
958
959 =head1 AUTHORS
960
961 Written by Eric Gillespie <epg@pretzelnet.org>. Design by Eric
962 Gillespie and Doug Porter <dsp@waterspout.com>.
963
964 This program is free software; you can redistribute it and/or modify
965 it under the same terms as Perl itself.
966
967 =cut
968
969 # Local variables:
970 # cperl-indent-level: 4
971 # perl-indent-level: 4
972 # indent-tabs-mode: nil
973 # End:
974
975 # vi: set tabstop=4 expandtab: