7 B<minc> - Incorporate mail from a maildir into mh folders.
15 B<minc> incorporates mail from a maildir to a mh folder hierarchy. It
16 takes mail from a maildir folder (not a maildir folder hierarchy),
17 optionally checks for spam with a user-defined spam-checking function,
18 and optionally filters mail into separate mh folders.
20 The filtering is quite sophisticated, as it is done using real Perl
21 matching (m//) commands.
30 use Fcntl qw(O_WRONLY O_EXCL O_CREAT);
36 use Log::Dispatch::File;
37 use POSIX qw(strftime WEXITSTATUS WIFEXITED);
39 # If a filter set's header is $MAGIC_TO_TOKEN, that set is compared
40 # against headers matching this regex (taken from procmail).
41 my $MAGIC_TO_REGEX = '^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope |Apparently(-Resent)?)-To)';
42 my $MAGIC_TO_TOKEN = ' TO';
44 # List of SPAM message numbers, scanned at the end so the user can
45 # check for false positives.
54 Dump (using Data::Dumper) the FILTERS list and exit. This is useful
55 for testing the syntax of .mincfilter.
63 Dry run; do not actually incorporate the mail, but log and report to
64 stdout/stderr as normal.
68 Print the filename of each message before checking it for spam. This
69 can be handy if a particular message is giving the spam checker a
78 my $printfilenames = 0;
85 if (not getopts('dhnp')) {
92 print("Sorry bub, no help.\n");
108 Where configuration files (.mincfilter) are found. Also,
109 $HOME/Maildir is used for the maildir if MAILDIR is not set.
113 Where mail is delivered.
119 use Env qw(HOME MAILDIR);
122 die("HOME environment variable must be set.\n");
125 $MAILDIR = "$HOME/Maildir";
132 =item $HOME/.mincfilter
134 This file is Perl code (included via the 'require' directive) which is
135 expected to define the FILTERS list.
137 =item $HOME/.mincspam
139 If this file exists, B<minc> will include it with the expectation that
140 it will define a B<spam_check> function. This function takes a
141 message filename as an argument and returns 1 if the message is spam,
142 else 0. If this file does not exist, B<minc> will define a simple
143 function that always returns 0.
145 One of B<minc>'s global variables is available to the user-defined
146 B<spam_check> function: $run. This boolean should be honored;
147 B<spam_check> should only take real action (i.e. removing or creating
148 files, running external programs, etc.) if $run is non-zero.
150 This file may also declare two other functions: B<spam_start_hook> and
151 B<spam_stop_hook>. The former is passed no arguments and is expected
152 to return a list. This list is a "baton" that will also be passed to
153 B<spam_check> and B<spam_stop_hook>. It can hold anything
154 B<spam_check> will need to do its job, whether network sockets, pipes,
157 XXX: need more details about the spam-handling process; for now read
160 =item `mhpath +`/logs/minc.log
162 Where B<minc> logs what it does, unless in -n mode.
164 =item `mhpath +`/logs/dryrun.log
166 Where B<minc> logs what it would do; used in -n mode.
168 =item `mhpath +`/.minc.context
170 B<minc> uses this file for context (i.e. current folder) instead of
171 `mhpath +`/context. This allows you some amount of freedom to use mh
172 while B<minc> is running. For example, you can changed folders without
173 causing a message to be stored in the wrong folder. Care must still
174 be taken, however, about the unseen sequence; if you change it
175 (whether via show, or mark, or anything else) while in the same folder
176 as B<minc>, it is likely the new message B<minc> stores will not end up
184 require "$HOME/.mincfilter";
186 if (-f "$HOME/.mincspam") {
187 require "$HOME/.mincspam";
189 eval "sub spam_start_hook { return (); }";
190 eval "sub spam_stop_hook { }";
191 eval "sub spam_check { return 0; }";
201 $logfile = $mh . '/logs/minc.log';
203 $logfile = $mh . '/logs/dryrun.log';
206 $ENV{"MHCONTEXT"} = $mh . '/.minc.context';
209 ###############################################################################
212 # debuglevels for the logger
213 use constant LOG_DEBUGLEVEL => 'info';
214 use constant SCREEN_DEBUGLEVEL => 'debug';
216 # characters used to wrap around the id field in the log so I can more
217 # easily parse the msg flow
218 use constant DEBUGCHAR => '%';
219 use constant INFOCHAR => '=';
220 use constant INCOMINGCHAR => '<';
221 use constant SAVECHAR => '>';
222 use constant WARNCHAR => 'W';
223 use constant ERRORCHAR => 'E';
225 my $logger = new Log::Dispatch;
226 $logger->add(new Log::Dispatch::File (name=>'logfile',
231 # log alias, handles getting passed vars that are undef
235 my $timestamp = strftime('%b %e %H:%M:%S', localtime);
237 foreach my $part (@_) {
238 if (defined($part)) {
242 # no newlines in the log message, thanks
244 $msg = sprintf("%s %s%s %s\n", $timestamp, $act, $act, $msg);
245 $logger->log(level=>$level, message=>$msg);
247 if ($act eq SAVECHAR) {
248 $logger->log(level=>$level, message=>"\n");
252 sub logsave { mylog('notice', SAVECHAR, @_); }
253 sub loginfo { mylog('info', INFOCHAR, @_); }
254 sub logdebug { mylog('debug', DEBUGCHAR, @_); }
255 sub logwarn { mylog('warning', WARNCHAR, @_); }
256 sub logerr { mylog('error', ERRORCHAR, @_); }
259 my ($text, @contents) = @_;
263 $last = $contents[-1];
268 mylog('info', INCOMINGCHAR, $text, $last);
274 # For an explanation of the %headers structure, see the
275 # get_headers function below.
276 logincoming('From: ', @{$headers{'return-path'}});
277 logincoming('To: ', @{$headers{'to'}});
278 logincoming('Subject: ', @{$headers{'subject'}});
279 logincoming('Message-Id: ', @{$headers{'message-id'}});
283 ###############################################################################
287 my $mhfolder = shift;
292 $folder = $mh . '/' . $mhfolder;
295 if (not -d $folder) {
296 foreach $component (split('/', $folder)) {
297 if (defined($component) and length($component) >= 1) {
298 $target = $target . '/' . $component;
299 if (-d $target or mkdir($target)) {
302 die("Failed to create +$mhfolder ($component)");
313 if (not opendir(DIR, $dir)) {
314 die("Failed opendir($dir)");
317 # Initialize $! to 0 (success) because stupid stupid Perl provides
318 # no way to distinguish an error from an empty directory; that
319 # means setting $! to 0 and testing it afterwards is the only way
320 # to detect an error. Real Programmers don't handle errors,
324 ($_ ne '.' and $_ ne '..')
325 and $_ = "$MAILDIR/new/$_"
329 die("Failed readdir($dir)");
332 if (scalar(@result) == 0) {
341 sub get_highest_msgnum {
342 my $mhfolder = shift;
348 $dir = "$mh/$mhfolder";
349 if (not opendir(DIR, $dir)) {
350 die("Failed opendir($dir)");
354 @list = readdir(DIR);
357 die("Failed readdir($dir)");
363 foreach $msgnum (@list) {
365 if ($msgnum =~ /^[0-9]+$/) {
366 if ($msgnum > $highest) {
377 my $mhfolder = shift;
383 # We must do this even in -n mode because later steps fail without
384 # it. This should be harmless.
387 # This loop is a modified version of the maildir delivery algorithm.
388 $msgnum = get_highest_msgnum($mhfolder);
389 for ($try = 0; ; $try++) {
391 $mhmsg = "$mh/$mhfolder/$msgnum";
393 if (not stat($mhmsg)) {
395 # Now we have a non-existent file, let's try to create
396 # it. We must create a zero-byte file first because a
397 # file my appear between our happy stat results and
398 # our later rename(2), which would clobber said file.
399 # So attempt to create a file with this name. If it
400 # succeeds, in just a bit here we'll knowingly clobber
401 # this file with the rename(2) call.
403 # Another way to do this is not to use rename(2), but
404 # use link(2) + unlink(2) instead. That's how the
405 # standard maildir algorithm does it. Each method has
406 # a disadvantage: the program may crash between the
407 # link(2) and unlink(2) calls. With the standard
408 # maildir algorithm, that means the message will end
409 # up duplicated. The advantage of creating an empty
410 # file followed by rename(2) is that an extra empty
411 # file is left behind as opposed to a duplicate
412 # message. This is more easily detected by the user.
414 if (sysopen(MSG, "$mhmsg",
415 O_WRONLY | O_EXCL | O_CREAT, 0600)) {
425 # This algorithm is different from the maildir one; let's make
426 # 10 tries instead of 3.
428 die("Attempted filename $mhmsg exists.");
431 # This algorithm is different; i don't think we need to sleep.
435 if ($mhfolder ne 'SPAM') {
436 logsave("+$mhfolder");
440 if (not rename($msg, $mhmsg)) {
441 die("Failed rename($msg, $mhmsg)");
444 # Mark each message as soon as we store it and bomb if that
445 # fails. While it is slow, it is not safe to store multiple
446 # messages and then have a failure before marking some (or
448 if ($mhfolder eq 'SPAM') {
449 push(@SPAM, $msgnum);
451 $status = system('mark', "+$mhfolder", "$msgnum", '-sequence',
453 if (not WIFEXITED($status)) {
454 die("Failed to run mark");
455 } elsif (WEXITSTATUS($status) != 0) {
456 die("Failed to mark message unseen.");
464 # Parse a message file into a structure describing the headers. The
465 # structure is a hash of arrays. The hash keys are the names of the
466 # headers found in the message, made all lower-case. Each item in
467 # the hash is an array of header text. The array has one element
468 # per occurrence of the header. Most headers will only have a single
469 # element because they occur only once. The Received header is the
470 # most common header with multiple texts.
474 my $current; # current header, used for unfolding lines
475 my $fieldname; # unmolested header name
476 my $contents; # contents of header
486 # folded header continuation
488 if (not defined($current)) {
489 print(STDERR "Malformed message, cannot parse headers.\n");
493 @{$headers{$current}}[-1] .= $_;
495 ($fieldname) = split(/:/);
496 $current = lc($fieldname);
497 (undef, $contents) = split(/^\Q$fieldname\E:\s*/);
499 if (defined($headers{$current})) {
500 # multiple occurence of same header
501 push(@{$headers{$current}}, $contents);
503 # first occurence of a header
504 $headers{$current} = [$contents];
514 ###############################################################################
529 %headers = get_headers($msg);
534 log_headers(%headers);
536 # Walk the list of filters. This structure is documented in
537 # pod at the end of the program.
538 foreach $filterref (@FILTERS) {
539 @filter = @$filterref;
540 $header = shift(@filter);
542 # Handle filters using the magic TO header specially.
543 if ($header eq $MAGIC_TO_TOKEN) {
544 foreach $header (keys(%headers)) {
545 if ($header =~ /$MAGIC_TO_REGEX/i) {
546 foreach $contents (@{$headers{lc($header)}}) {
547 foreach $pair (@filter) {
548 ($match, $expression) = @$pair;
549 if ($contents =~ /$match/) {
557 # Now that it's been processed specially, skip normal handling.
561 # Walk the list of message headers matching the filter's
563 foreach $contents (@{$headers{lc($header)}}) {
564 # Walk the filter's list of match/expression pairs.
565 foreach $pair (@filter) {
566 ($match, $expression) = @$pair;
567 if ($contents =~ /$match/i) {
568 if (eval "\$result = \"$expression\"") {
581 my $msgcount = scalar(@msglist);
587 my %FOLDERS = ('SPAM'=>1);
589 @baton = spam_start_hook();
592 STDOUT->autoflush(1);
593 print("$msgcount messages...");
594 foreach $msg (@msglist) {
595 if (spam_check($msg, @baton)) {
597 $spam = scalar(@SPAM)+ 1;
599 $mhfolder = find_mh_folder($msg);
603 store_message($msg, $mhfolder);
606 if (not $FOLDERS{$mhfolder}) {
607 print(' ' x length($msgcount));
608 print(" \r+$mhfolder\n");
609 $FOLDERS{$mhfolder} = 1;
612 printf('%6d SPAM %6d saved %6d/%1d',
613 $spam, $saved, $spam + $saved, $msgcount);
617 spam_stop_hook(@baton);
626 $Data::Dumper::Indent = 1;
627 print(Dumper(\@FILTERS));
633 sort { $a->[0] <=> $b->[0] }
635 if (not ($st = stat($_))) {
640 getfiles("$MAILDIR/new"));
642 filter_mail(@msglist);
644 @SPAM and (exec('scan', '+SPAM', @SPAM) or die);
650 =head1 THE FILTERS STRUCTURE
652 The user's .mincfilter file must define the @FILTERS structure. This
653 structure is an array. Each element of @FILTERS is a filter. A
654 filter is itself an array. The first element of a filter is a string,
655 the name of the header this filter acts upon. The header name is not
656 case-sensitive. Each subsequent element of a filter is a pair (i.e. a
657 two-element array): first, a regular expression B<minc> uses to
658 determine whether this filter matches or not, and second, an
659 expression which B<minc> evaluates to get the folder name.
661 B<minc> decides where to store a message by iterating over the
662 @FILTERS array. It tests each regexp of each filter against all
663 headers matching that filter's specified header. As soon as a match
664 is found, B<minc> evaluates the second part of the pair. This part
665 may contain positional parameters from the matched regexp ($1, $2,
666 etc.). The result of this expression is used as the folder name.
668 Multiple occurrences of the same header are preserved and tested
669 individually against the filters. That means, for example, that
670 filters can search all the Received headers for a certain string.
672 It is important to note that all the arrays of the @FILTERS structure
673 are traversed I<in order>. This means the filters can be arranged so
674 that some have priority over others. XXX: get Doug to write an
675 example of having the same header matched more than once.
677 Lastly, B<minc> supports a magic ' TO' header. Filters using this
678 header are matched against a collection of headers related to (and
679 including) the To. Which headers to use is determined by a regular
680 expression borrowed from procmail.
687 ['<([[:graph:]]+)-([[:graph:]]+)\.lists\.sourceforge\.net>', 'l/$1/$2'],
688 ['<([[:graph:]]+?)(-list)?\.freedesktop\.org>', 'l/freedesktop/$1'],
689 ['<swig\.cs\.uchicago\.edu>', 'l/swig'],
693 ['<mailto:([[:graph:]]+)+@([[:graph:]]+)\.apache\.org>', 'l/apache/$2/$1'],
701 The first List-Id filter is a surprisingly effective one which creates
702 appropriate folder names (such as l/htdig/updates and l/rox/devel) for
703 all Sourceforge lists to which i subscribe. Certainly there are lists
704 hosted at Sourceforge which do not work well with this, and this is
705 where it is important to remember that the first match is the one
706 uses. Simply put the more specific rules before this one.
708 The next List-Id example is simple. The swig example demonstrates
709 that the folder name does not have to use a portion of the matched
710 header; you can just hardcode the folder name.
712 The List-Post example is a nice one. Most ASF projects have their own
713 apache.org subdomain, with mailing lists hosted there. So, given a
714 list such as dev@httpd.apache.org, this filter will create the folder
715 name l/apache/httpd/dev.
717 For an example B<spam_check> function, see
718 L<http:E<047>E<047>pretzelnet.orgE<047>cvsE<047>dotfilesE<047>.mincspam>
722 Written by Eric Gillespie <epg@pretzelnet.org> with logging code
723 stolen from Adam Lazur <adam@lazur.org>.
725 Design by Eric Gillespie and Doug Porter <dsp@waterspout.com>.
730 # cperl-indent-level: 4
731 # perl-indent-level: 4
732 # indent-tabs-mode: nil
735 # vi: set tabstop=4 expandtab: