]>
diplodocus.org Git - minc/blob - minc
cfac97f247651f21ed6d603f440dd9072bc55b1f
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 # Autoflush STDOUT for the benefit of the status reporting in kill_spam().
42 # If a filter set's header is $MAGIC_TO_TOKEN, that set is compared
43 # against headers matching this regex (taken from procmail).
44 my $MAGIC_TO_REGEX = '^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope |Apparently(-Resent)?)-To)';
45 my $MAGIC_TO_TOKEN = ' TO';
47 # List of SPAM message numbers, scanned at the end so the user can
48 # check for false positives.
57 Dump (using Data::Dumper) the FILTERS list and exit. This is useful
58 for testing the syntax of .mincfilter.
66 Dry run; do not actually incorporate the mail, but log and report to
67 stdout/stderr as normal.
71 Print the filename of each message before checking it for spam. This
72 can be handy if a particular message is giving the spam checker a
81 my $printfilenames = 0;
88 if (not getopts
('dhnp')) {
95 print("Sorry bub, no help.\n");
111 Where configuration files (.mincfilter) are found. Also,
112 $HOME/Maildir is used for the maildir if MAILDIR is not set.
116 Where mail is delivered.
122 use Env
qw(HOME MAILDIR);
125 die("HOME environment variable must be set.\n");
128 $MAILDIR = "$HOME/Maildir";
135 =item $HOME/.mincfilter
137 This file is Perl code (included via the 'require' directive) which is
138 expected to define the FILTERS list.
140 =item $HOME/.mincspam
142 If this file exists, B<minc> will include it with the expectation that
143 it will define a B<spam_check> function. This function takes a
144 message filename as an argument and returns 1 if the message is spam,
145 else 0. If this file does not exist, B<minc> will define a simple
146 function that always returns 0.
148 One of B<minc>'s global variables is available to the user-defined
149 B<spam_check> function: $run. This boolean should be honored;
150 B<spam_check> should only take real action (i.e. removing or creating
151 files, running external programs, etc.) if $run is non-zero.
153 This file may also declare two other functions: B<spam_start_hook> and
154 B<spam_stop_hook>. The former is passed no arguments and is expected
155 to return a list. This list is a "baton" that will also be passed to
156 B<spam_check> and B<spam_stop_hook>. It can hold anything
157 B<spam_check> will need to do its job, whether network sockets, pipes,
160 XXX: need more details about the spam-handling process; for now read
163 =item `mhpath +`/logs/minc.log
165 Where B<minc> logs what it does, unless in -n mode.
167 =item `mhpath +`/logs/dryrun.log
169 Where B<minc> logs what it would do; used in -n mode.
171 =item `mhpath +`/.minc.context
173 B<minc> uses this file for context (i.e. current folder) instead of
174 `mhpath +`/context. This allows you some amount of freedom to use mh
175 while B<minc> is running. For example, you can changed folders without
176 causing a message to be stored in the wrong folder. Care must still
177 be taken, however, about the unseen sequence; if you change it
178 (whether via show, or mark, or anything else) while in the same folder
179 as B<minc>, it is likely the new message B<minc> stores will not end up
187 require "$HOME/.mincfilter";
189 if (-f
"$HOME/.mincspam") {
190 require "$HOME/.mincspam";
192 eval "sub spam_start_hook { return (); }";
193 eval "sub spam_stop_hook { }";
194 eval "sub spam_check { return 0; }";
204 $logfile = $mh . '/logs/minc.log';
206 $logfile = $mh . '/logs/dryrun.log';
209 $ENV{"MHCONTEXT"} = $mh . '/.minc.context';
212 ###############################################################################
215 # debuglevels for the logger
216 use constant LOG_DEBUGLEVEL
=> 'info';
217 use constant SCREEN_DEBUGLEVEL
=> 'debug';
219 # characters used to wrap around the id field in the log so I can more
220 # easily parse the msg flow
221 use constant DEBUGCHAR
=> '%';
222 use constant INFOCHAR
=> '=';
223 use constant INCOMINGCHAR
=> '<';
224 use constant SAVECHAR
=> '>';
225 use constant WARNCHAR
=> 'W';
226 use constant ERRORCHAR
=> 'E';
228 my $logger = new Log
::Dispatch
;
229 $logger->add(new Log
::Dispatch
::File
(name
=>'logfile',
234 # log alias, handles getting passed vars that are undef
238 my $timestamp = strftime
('%b %e %H:%M:%S', localtime);
240 foreach my $part (@_) {
241 if (defined($part)) {
245 # no newlines in the log message, thanks
247 $msg = sprintf("%s %s%s %s\n", $timestamp, $act, $act, $msg);
248 $logger->log(level
=>$level, message
=>$msg);
250 if ($act eq SAVECHAR
) {
251 $logger->log(level
=>$level, message
=>"\n");
255 sub logsave
{ mylog
('notice', SAVECHAR
, @_); }
256 sub loginfo
{ mylog
('info', INFOCHAR
, @_); }
257 sub logdebug
{ mylog
('debug', DEBUGCHAR
, @_); }
258 sub logwarn
{ mylog
('warning', WARNCHAR
, @_); }
259 sub logerr
{ mylog
('error', ERRORCHAR
, @_); }
262 my ($text, @contents) = @_;
266 $last = $contents[-1];
271 mylog
('info', INCOMINGCHAR
, $text, $last);
277 # For an explanation of the %headers structure, see the
278 # get_headers function below.
279 logincoming
('From: ', @{$headers{'return-path'}});
280 logincoming
('To: ', @{$headers{'to'}});
281 logincoming
('Subject: ', @{$headers{'subject'}});
282 logincoming
('Message-Id: ', @{$headers{'message-id'}});
286 ###############################################################################
290 my $mhfolder = shift;
295 $folder = $mh . '/' . $mhfolder;
298 if (not -d
$folder) {
299 foreach $component (split('/', $folder)) {
300 if (defined($component) and length($component) >= 1) {
301 $target = $target . '/' . $component;
302 if (-d
$target or mkdir($target)) {
305 die("Failed to create +$mhfolder ($component)");
316 if (not opendir(DIR
, $dir)) {
317 die("Failed opendir($dir)");
320 # Initialize $! to 0 (success) because stupid stupid Perl provides
321 # no way to distinguish an error from an empty directory; that
322 # means setting $! to 0 and testing it afterwards is the only way
323 # to detect an error. Real Programmers don't handle errors,
327 ($_ ne '.' and $_ ne '..')
328 and $_ = "$MAILDIR/new/$_"
332 die("Failed readdir($dir)");
335 if (scalar(@result) == 0) {
344 sub get_highest_msgnum
{
345 my $mhfolder = shift;
351 $dir = "$mh/$mhfolder";
352 if (not opendir(DIR
, $dir)) {
353 die("Failed opendir($dir)");
357 @list = readdir(DIR
);
360 die("Failed readdir($dir)");
366 foreach $msgnum (@list) {
368 if ($msgnum =~ /^[0-9]+$/) {
369 if ($msgnum > $highest) {
380 my $mhfolder = shift;
386 # We must do this even in -n mode because later steps fail without
387 # it. This should be harmless.
390 # This loop is a modified version of the maildir delivery algorithm.
391 $msgnum = get_highest_msgnum
($mhfolder);
392 for ($try = 0; ; $try++) {
394 $mhmsg = "$mh/$mhfolder/$msgnum";
396 if (not stat($mhmsg)) {
398 # Now we have a non-existent file, let's try to create
399 # it. We must create a zero-byte file first because a
400 # file my appear between our happy stat results and
401 # our later rename(2), which would clobber said file.
402 # So attempt to create a file with this name. If it
403 # succeeds, in just a bit here we'll knowingly clobber
404 # this file with the rename(2) call.
406 # Another way to do this is not to use rename(2), but
407 # use link(2) + unlink(2) instead. That's how the
408 # standard maildir algorithm does it. Each method has
409 # a disadvantage: the program may crash between the
410 # link(2) and unlink(2) calls. With the standard
411 # maildir algorithm, that means the message will end
412 # up duplicated. The advantage of creating an empty
413 # file followed by rename(2) is that an extra empty
414 # file is left behind as opposed to a duplicate
415 # message. This is more easily detected by the user.
417 if (sysopen(MSG
, "$mhmsg",
418 O_WRONLY
| O_EXCL
| O_CREAT
, 0600)) {
428 # This algorithm is different from the maildir one; let's make
429 # 10 tries instead of 3.
431 die("Attempted filename $mhmsg exists.");
434 # This algorithm is different; i don't think we need to sleep.
438 if ($mhfolder ne 'SPAM') {
439 logsave
("+$mhfolder");
443 if (not rename($msg, $mhmsg)) {
444 die("Failed rename($msg, $mhmsg)");
447 # Mark each message as soon as we store it and bomb if that
448 # fails. While it is slow, it is not safe to store multiple
449 # messages and then have a failure before marking some (or
451 if ($mhfolder eq 'SPAM') {
452 push(@SPAM, $msgnum);
454 $status = system('mark', "+$mhfolder", "$msgnum", '-sequence',
456 if (not WIFEXITED
($status)) {
457 die("Failed to run mark");
458 } elsif (WEXITSTATUS
($status) != 0) {
459 die("Failed to mark message unseen.");
467 # Parse a message file into a structure describing the headers. The
468 # structure is a hash of arrays. The hash keys are the names of the
469 # headers found in the message, made all lower-case. Each item in
470 # the hash is an array of header text. The array has one element
471 # per occurrence of the header. Most headers will only have a single
472 # element because they occur only once. The Received header is the
473 # most common header with multiple texts.
477 my $current; # current header, used for unfolding lines
478 my $fieldname; # unmolested header name
479 my $contents; # contents of header
489 # folded header continuation
491 if (not defined($current)) {
492 print(STDERR
"Malformed message, cannot parse headers.\n");
496 @{$headers{$current}}[-1] .= $_;
498 ($fieldname) = split(/:/);
499 $current = lc($fieldname);
500 (undef, $contents) = split(/^\Q$fieldname\E:\s*/);
502 if (defined($headers{$current})) {
503 # multiple occurence of same header
504 push(@{$headers{$current}}, $contents);
506 # first occurence of a header
507 $headers{$current} = [$contents];
517 ###############################################################################
532 %headers = get_headers
($msg);
537 log_headers
(%headers);
539 # Walk the list of filters. This structure is documented in
540 # pod at the end of the program.
541 foreach $filterref (@FILTERS) {
542 @filter = @$filterref;
543 $header = shift(@filter);
545 # Handle filters using the magic TO header specially.
546 if ($header eq $MAGIC_TO_TOKEN) {
547 foreach $header (keys(%headers)) {
548 if ($header =~ /$MAGIC_TO_REGEX/i) {
549 foreach $contents (@{$headers{lc($header)}}) {
550 foreach $pair (@filter) {
551 ($match, $expression) = @$pair;
552 if ($contents =~ /$match/) {
560 # Now that it's been processed specially, skip normal handling.
564 # Walk the list of message headers matching the filter's
566 foreach $contents (@{$headers{lc($header)}}) {
567 # Walk the filter's list of match/expression pairs.
568 foreach $pair (@filter) {
569 ($match, $expression) = @$pair;
570 if ($contents =~ /$match/i) {
571 if (eval "\$result = \"$expression\"") {
584 my $msgcount = scalar(@msglist);
590 my %FOLDERS = ('SPAM'=>1);
592 @baton = spam_start_hook
();
594 print("$msgcount messages...");
595 foreach $msg (@msglist) {
596 if (spam_check
($msg, @baton)) {
598 $spam = scalar(@SPAM)+ 1;
600 $mhfolder = find_mh_folder
($msg);
604 store_message
($msg, $mhfolder);
607 if (not $FOLDERS{$mhfolder}) {
608 print(' ' x
length($msgcount));
609 print(" \r+$mhfolder\n");
610 $FOLDERS{$mhfolder} = 1;
613 printf('%6d SPAM %6d saved %6d/%1d',
614 $spam, $saved, $spam + $saved, $msgcount);
618 spam_stop_hook
(@baton);
627 $Data::Dumper
::Indent
= 1;
628 print(Dumper
(\
@FILTERS));
634 sort { $a->[0] <=> $b->[0] }
636 if (not ($st = stat($_))) {
641 getfiles
("$MAILDIR/new"));
643 filter_mail
(@msglist);
645 @SPAM and (exec('scan', '+SPAM', @SPAM) or die);
651 =head1 THE FILTERS STRUCTURE
653 The user's .mincfilter file must define the @FILTERS structure. This
654 structure is an array. Each element of @FILTERS is a filter. A
655 filter is itself an array. The first element of a filter is a string,
656 the name of the header this filter acts upon. The header name is not
657 case-sensitive. Each subsequent element of a filter is a pair (i.e. a
658 two-element array): first, a regular expression B<minc> uses to
659 determine whether this filter matches or not, and second, an
660 expression which B<minc> evaluates to get the folder name.
662 B<minc> decides where to store a message by iterating over the
663 @FILTERS array. It tests each regexp of each filter against all
664 headers matching that filter's specified header. As soon as a match
665 is found, B<minc> evaluates the second part of the pair. This part
666 may contain positional parameters from the matched regexp ($1, $2,
667 etc.). The result of this expression is used as the folder name.
669 Multiple occurrences of the same header are preserved and tested
670 individually against the filters. That means, for example, that
671 filters can search all the Received headers for a certain string.
673 It is important to note that all the arrays of the @FILTERS structure
674 are traversed I<in order>. This means the filters can be arranged so
675 that some have priority over others. XXX: get Doug to write an
676 example of having the same header matched more than once.
678 Lastly, B<minc> supports a magic ' TO' header. Filters using this
679 header are matched against a collection of headers related to (and
680 including) the To. Which headers to use is determined by a regular
681 expression borrowed from procmail.
688 ['<([[:graph:]]+)-([[:graph:]]+)\.lists\.sourceforge\.net>', 'l/$1/$2'],
689 ['<([[:graph:]]+?)(-list)?\.freedesktop\.org>', 'l/freedesktop/$1'],
690 ['<swig\.cs\.uchicago\.edu>', 'l/swig'],
694 ['<mailto:([[:graph:]]+)+@([[:graph:]]+)\.apache\.org>', 'l/apache/$2/$1'],
702 The first List-Id filter is a surprisingly effective one which creates
703 appropriate folder names (such as l/htdig/updates and l/rox/devel) for
704 all Sourceforge lists to which i subscribe. Certainly there are lists
705 hosted at Sourceforge which do not work well with this, and this is
706 where it is important to remember that the first match is the one
707 uses. Simply put the more specific rules before this one.
709 The next List-Id example is simple. The swig example demonstrates
710 that the folder name does not have to use a portion of the matched
711 header; you can just hardcode the folder name.
713 The List-Post example is a nice one. Most ASF projects have their own
714 apache.org subdomain, with mailing lists hosted there. So, given a
715 list such as dev@httpd.apache.org, this filter will create the folder
716 name l/apache/httpd/dev.
718 For an example B<spam_check> function, see
719 L<http:E<047>E<047>pretzelnet.orgE<047>cvsE<047>dotfilesE<047>.mincspam>
723 Written by Eric Gillespie <epg@pretzelnet.org> with logging code
724 stolen from Adam Lazur <adam@lazur.org>.
726 Design by Eric Gillespie and Doug Porter <dsp@waterspout.com>.
731 # cperl-indent-level: 4
732 # perl-indent-level: 4
733 # indent-tabs-mode: nil
736 # vi: set tabstop=4 expandtab: