5 B<minc> - incorporate mail from a maildir into mh folders
9 B<minc> [B<-m> I<MAX>] [B<-n>]
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.
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
38 $SIG{'PIPE'} = 'IGNORE';
45 use File::Temp qw(tempfile);
47 use Getopt::Long qw(:config gnu_getopt no_ignore_case);
50 use constant LOCK_TRIES => 60;
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';
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.
71 Dump (using Data::Dumper) the FILTERS list and exit. This is useful
72 for testing the syntax of .minc.
80 Stop processing after I<MAX> messages.
84 Dry run; do not actually incorporate the mail, but log and report to
85 stdout/stderr as normal.
89 Rebuild `mhpath +`/.folders from scratch, processing no mail.
99 my $rebuild_dot_folders;
103 'd' => \$dumpfilters,
107 'r' => \$rebuild_dot_folders,
109 $help and pod2usage(-exitstatus=>0, -verbose=>1);
110 @ARGV == 0 or pod2usage();
121 How many columns the user's terminal can hold, used to print scan
122 lines for each processed message. Defaults to 80.
126 Where the configuration file (.minc) is found. Also,
127 $HOME/Maildir is used for the maildir if MAILDIR is not set.
131 Where mail is delivered.
137 use Env qw(COLUMNS HOME MAILDIR);
142 die("HOME environment variable must be set.\n");
145 $MAILDIR = "$HOME/Maildir";
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.
158 =item `mhpath +`/.folders
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).
163 =item `mhpath +`/.minc.context
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
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) };
191 $ENV{"MHCONTEXT"} = $mh . '/.minc.context';
194 ###############################################################################
223 foreach $component (split('/', $folder)) {
224 $target = join('/', $target, $component);
225 -d $target or mkdir($target) or die("mkdir($target): $!");
233 if (not opendir(DIR, $dir)) {
234 die("opendir($dir): $!");
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,
243 @result = readdir(DIR);
245 die("readdir($dir): $!");
252 STDOUT->autoflush(1);
254 print('1 message...');
256 print(@result - 2, ' messages...');
265 sub get_highest_msgnum {
266 my $mhfolder = shift;
272 if (defined($msgnum_cache{$mhfolder})) {
273 return $msgnum_cache{$mhfolder}++;
276 $dir = "$mh/$mhfolder";
277 if (not opendir(DIR, $dir)) {
278 die("opendir($dir): $!");
281 # Insert rant from getfiles here.
283 @list = readdir(DIR);
286 die("readdir($dir): $!");
292 foreach $msgnum (@list) {
294 if ($msgnum =~ /^[0-9]+$/) {
295 if ($msgnum > $highest) {
301 $msgnum_cache{$mhfolder} = $highest;
302 return $msgnum_cache{$mhfolder}++;
309 my $fn = "$mh/$folder/.mh_sequences";
313 if (not open($fh, $fn)) {
314 $!{ENOENT} or die("open($fn): $!");
321 open($fh, '>', $fn) or die("open(>$fn): $!");
322 for $_ (@sequences) {
327 for my $part (split(' ', $1)) {
329 my ($st, $en) = split('-', $part);
330 if ((defined($en) and ($msgnum >= $st and $msgnum <= $en))
332 # It's already there.
336 if ($st - 1 == $msgnum) {
337 $part = "$msgnum-$en";
339 } elsif ($en + 1 == $msgnum) {
340 $part = "$st-$msgnum";
344 if ($part - 1 == $msgnum) {
345 $part = "$msgnum-$part";
347 } elsif ($part + 1 == $msgnum) {
348 $part = "$part-$msgnum";
353 push(@result, $part);
356 push(@result, $msgnum);
358 print($fh "$seq: ", join(' ', @result), "\n");
364 $marked or print($fh "$seq: $msgnum\n");
365 close($fh) or die("close(>$fn): $!");
368 # Based on nmh's lkopen_fcntl
369 # Return 0 for success, errno on failure.
376 # The assumption here is that if you open the file for writing, you
377 # need an exclusive lock.
379 my $tries = LOCK_TRIES;
381 sysopen(my $fh, $file, $access, $mode) or die("sysopen($file): $!");
383 my $flk = File::FcntlLock->new;
386 $flk->l_type(($access & O_ACCMODE) == O_RDONLY ? F_RDLCK : F_WRLCK);
387 $flk->l_whence(SEEK_SET);
389 # Really should only retry on EAGAIN and EINTR...
390 if ($flk->lock($fh, F_SETLK)) {
394 $errno = $flk->lock_errno;
395 close($fh) or die("close($file): $!");
403 return undef, $errno;
408 my $mhfolder = shift;
413 # We must do this even in -n mode because later steps fail without
414 # it. This should be harmless.
417 # This loop is a modified version of the maildir delivery algorithm.
418 $msgnum = get_highest_msgnum($mhfolder);
419 for ($try = 0; ; $try++) {
421 $mhmsg = "$mh/$mhfolder/$msgnum";
423 if (not stat($mhmsg)) {
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.
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.
444 if (sysopen(MSG, $mhmsg,
445 O_WRONLY | O_EXCL | O_CREAT, 0600)) {
455 # This algorithm is different from the maildir one; let's make
456 # 10 tries instead of 3.
458 die("Attempted filename $mhmsg exists.");
461 # This algorithm is different; i don't think we need to sleep.
466 if (not rename($msg, $mhmsg)) {
467 die("rename($msg, $mhmsg): $!");
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
474 if ($mhfolder ne 'SPAM') {
475 mark($mhfolder, $msgnum, 'unseen');
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.
492 my $current; # current header, used for unfolding lines
493 my $fieldname; # unmolested header name
494 my $contents; # contents of header
496 open(MSG, $msg) or die("open(MSG, $msg): $!");
504 # folded header continuation
506 if (not defined($current)) {
507 warn('Malformed message, cannot parse headers.');
511 @{$headers{$current}}[-1] .= $_;
513 ($fieldname) = split(/:/);
514 $current = lc($fieldname);
515 (undef, $contents) = split(/^\Q$fieldname\E:\s*/);
517 if (defined($headers{$current})) {
518 # multiple occurence of same header
519 push(@{$headers{$current}}, $contents);
521 # first occurence of a header
522 $headers{$current} = [$contents];
532 ###############################################################################
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);
552 my $m = match($header, @$filterref);
559 # Test all the header fields against each [regexp, folder-expression] pair.
562 my $filter_field = shift;
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);
573 # Now that it's been processed specially, skip normal handling.
577 # Walk the list of header fields matching the filter's specified header.
578 my $m = match_one_field($header->{lc($filter_field)}, \@filters);
582 # Test all the values of one header field against each [regexp,
583 # folder-expression] pair.
584 sub match_one_field {
587 for my $value (@$values) {
588 for my $pair (@$filters) {
589 my ($regexp, $expression) = @$pair;
590 if ($value =~ $regexp) {
592 if (eval "\$result = \"$expression\"") {
601 my ($headers, $mhfolder, $msgnum, $nf, $nm, $nF, $ns) = @_;
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/?/;
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));
619 my $msgcount = @_ - 2; # don't count . and ..
620 my $len = length($msgcount);
629 if (-f "$HOME/.minc") {
630 require "$HOME/.minc";
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;
640 for my $hook (@start_hooks) {
641 my ($handle, @baton) = $hook->();
642 if (defined($handle)) {
643 $batons{$handle} = [@baton];
649 # Print a newline after the incomplete "N messages..." line.
654 ($msg eq '.' or $msg eq '..') and next;
656 my $headers = get_headers($msg);
659 for my $hook (@filter_hooks) {
660 my $result = $hook->(\%batons, $headers, $msg);
661 defined($result) and ($mhfolder = $result);
664 defined($mhfolder) or ($mhfolder = find_mh_folder($msg, $headers));
666 $msgnum = store_message($msg, $mhfolder);
667 $folders{$mhfolder}++;
673 if ($mhfolder eq 'SPAM') {
675 $SPAM{$msgnum} = [$headers, undef];
678 print(scan_line($headers, $mhfolder, $msgnum, $nf, $nm, $nF, $ns),
682 for my $hook (@post_store_hooks) {
683 $hook->(\%batons, $headers, $mhfolder, $msgnum);
687 printf(" \%${len}d SPAM \%${len}d saved \%${len}d/%1d",
688 $spam, $saved, $spam + $saved, $msgcount);
691 defined($maxmsgs) and ($spam + $saved < $maxmsgs or last);
695 for my $hook (@stop_hooks) {
702 sub build_dot_folders {
714 eval { ($fh, $fn) = tempfile("$mh/.folders.XXXXX") };
720 for my $folder (sort { $folder_sorter->($a,$b) } keys(%$folders)) {
721 print($fh "$folder\n");
724 if (not close($fh)) {
725 warn("close($fn): $!");
726 unlink($fn) or warn("unlink($fn): $!");
730 rename($fn, "$mh/.folders") or warn("rename($fn, $mh/.folders): $!");
733 sub create_dot_folders {
734 if (-f "$HOME/.minc") {
735 require "$HOME/.minc";
739 open(my $fh, '-|', 'folders', '-fast', '-recur')
740 or die("open(folders|): $!");
741 build_dot_folders(\%folders, $fh);
745 sub update_dot_folders {
749 if (not open($fh, "$mh/.folders") and not $!{ENOENT}) {
750 # For ENOENT, we go ahead and create it, else we error and
752 warn("open($mh/.folders): $!");
756 build_dot_folders($folders, $fh);
759 # XXX Could use some unification with getfiles...
761 my $dir = "$MAILDIR/spam/new";
763 if (not chdir($dir)) {
764 $!{ENOENT} or print(STDERR "skipping maildir spam: chdir($dir): $!\n");
768 if (not opendir(DIR, '.')) {
769 print(STDERR "skipping maildir spam: opendir($dir): $!\n");
774 my @spams = readdir(DIR);
776 print(STDERR "skipping maildir spam: readdir($dir): $!\n");
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];
791 my ($msgnum, $header, $tuple, $msg);
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;
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.
811 # The message has been filed, load it from $mh.
812 $msg = "$mh/SPAM/$msgnum";
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).
819 $header = get_headers($msg);
822 "BUG: corrupt SPAM tuple, neither element defined",
823 " for message $msgnum\n");
826 print(scan_line($header, '', $msgnum, 0, $nm, $nF, $ns),
836 require "$HOME/.minc";
837 $Data::Dumper::Indent = 1;
838 print(Dumper(\@FILTERS));
842 $rebuild_dot_folders and exit(create_dot_folders);
844 chdir("$MAILDIR/new") or die("chdir($MAILDIR/new): $!");
845 my %folders = filter_mail(map { $_->[1] }
846 sort { $a->[0] <=> $b->[0] }
848 if (not ($st = stat($_))) {
855 $run and %folders and update_dot_folders(\%folders);
866 =head1 THE FILTERS STRUCTURE
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.
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.
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.
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.
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.
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.
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.
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
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
920 XXX: need more details about the hook process; for now read the code.
927 ['<([[:graph:]]+)-([[:graph:]]+)\.lists\.sourceforge\.net>', 'l/$1/$2'],
928 ['<([[:graph:]]+?)(-list)?\.freedesktop\.org>', 'l/freedesktop/$1'],
929 ['<swig\.cs\.uchicago\.edu>', 'l/swig'],
933 ['<mailto:([[:graph:]]+)+@([[:graph:]]+)\.apache\.org>', 'l/apache/$2/$1'],
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.
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.
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.
957 XXX Need hook examples.
961 Written by Eric Gillespie <epg@pretzelnet.org>. Design by Eric
962 Gillespie and Doug Porter <dsp@waterspout.com>.
964 This program is free software; you can redistribute it and/or modify
965 it under the same terms as Perl itself.
970 # cperl-indent-level: 4
971 # perl-indent-level: 4
972 # indent-tabs-mode: nil
975 # vi: set tabstop=4 expandtab: