]> diplodocus.org Git - minc/blob - minc
790ecfeab2ab42a0f9dbd448bd416eded9ed2b9f
[minc] / minc
1 #! /usr/local/bin/perl
2
3 # $Id$
4
5 =head1 NAME
6
7 B<minc> - Incorporate mail from a maildir into mh folders.
8
9 =head1 SYNOPSIS
10
11 B<minc> [-B<dfhnps>]
12
13 =head1 DESCRIPTION
14
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.
19
20 The filtering is quite sophisticated, as it is done using real Perl
21 matching (m//) commands.
22
23 =cut
24
25 use strict;
26 use warnings;
27
28 use Data::Dumper;
29 use Errno;
30 use Fcntl qw(O_WRONLY O_EXCL O_CREAT);
31 use FileHandle;
32 use File::Basename;
33 use File::stat;
34 use Getopt::Std;
35 use Log::Dispatch;
36 use Log::Dispatch::File;
37 use POSIX qw(strftime WEXITSTATUS WIFEXITED);
38
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';
43
44 # List of SPAM message numbers, scanned at the end so the user can
45 # check for false positives.
46 my @SPAM;
47
48 =head1 OPTIONS
49
50 =over 4
51
52 =item B<-d>
53
54 Dump (using Data::Dumper) the FILTERS list and exit. This is useful
55 for testing the syntax of .mincfilter.
56
57 =item B<-h>
58
59 Show help.
60
61 =item B<-n>
62
63 Dry run; do not actually incorporate the mail, but log and report to
64 stdout/stderr as normal.
65
66 =item B<-p>
67
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
70 problem.
71
72 =back
73
74 =cut
75
76 my $dumpfilters = 0;
77 our $run = 1;
78 my $printfilenames = 0;
79
80 our $opt_d;
81 our $opt_h;
82 our $opt_n;
83 our $opt_p;
84
85 if (not getopts('dhnp')) {
86 exit(2);
87 }
88
89 if ($opt_d) {
90 $dumpfilters = 1;
91 } elsif ($opt_h) {
92 print("Sorry bub, no help.\n");
93 exit;
94 } elsif ($opt_n) {
95 $run = 0;
96 }
97
98 if ($opt_p) {
99 $printfilenames = 1;
100 }
101
102 =head1 ENVIRONMENT
103
104 =over 4
105
106 =item HOME
107
108 Where configuration files (.mincfilter) are found. Also,
109 $HOME/Maildir is used for the maildir if MAILDIR is not set.
110
111 =item MAILDIR
112
113 Where mail is delivered.
114
115 =back
116
117 =cut
118
119 use Env qw(HOME MAILDIR);
120
121 if (not $HOME) {
122 die("HOME environment variable must be set.\n");
123 }
124 if (not $MAILDIR) {
125 $MAILDIR = "$HOME/Maildir";
126 }
127
128 =head1 FILES
129
130 =over 4
131
132 =item $HOME/.mincfilter
133
134 This file is Perl code (included via the 'require' directive) which is
135 expected to define the FILTERS list.
136
137 =item $HOME/.mincspam
138
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.
144
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.
149
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,
155 or whatever.
156
157 XXX: need more details about the spam-handling process; for now read
158 the code.
159
160 =item `mhpath +`/logs/minc.log
161
162 Where B<minc> logs what it does, unless in -n mode.
163
164 =item `mhpath +`/logs/dryrun.log
165
166 Where B<minc> logs what it would do; used in -n mode.
167
168 =item `mhpath +`/.minc.context
169
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
177 marked unseen.
178
179 =back
180
181 =cut
182
183 our @FILTERS;
184 require "$HOME/.mincfilter";
185
186 if (-f "$HOME/.mincspam") {
187 require "$HOME/.mincspam";
188 } else {
189 eval "sub spam_start_hook { return (); }";
190 eval "sub spam_stop_hook { }";
191 eval "sub spam_check { return 0; }";
192 }
193
194 my $mh;
195 my $logfile;
196
197 $mh = `mhpath +`;
198 chomp($mh);
199
200 if ($run) {
201 $logfile = $mh . '/logs/minc.log';
202 } else {
203 $logfile = $mh . '/logs/dryrun.log';
204 }
205
206 $ENV{"MHCONTEXT"} = $mh . '/.minc.context';
207
208 \f
209 ###############################################################################
210 # Logging
211
212 # debuglevels for the logger
213 use constant LOG_DEBUGLEVEL => 'info';
214 use constant SCREEN_DEBUGLEVEL => 'debug';
215
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';
224
225 my $logger = new Log::Dispatch;
226 $logger->add(new Log::Dispatch::File (name=>'logfile',
227 filename=>$logfile,
228 min_level=>'info',
229 mode=>'append'));
230
231 # log alias, handles getting passed vars that are undef
232 sub mylog {
233 my $level = shift;
234 my $act = shift;
235 my $timestamp = strftime('%b %e %H:%M:%S', localtime);
236 my $msg;
237 foreach my $part (@_) {
238 if (defined($part)) {
239 $msg .= $part;
240 }
241 }
242 # no newlines in the log message, thanks
243 $msg =~ s/\n/ /gm;
244 $msg = sprintf("%s %s%s %s\n", $timestamp, $act, $act, $msg);
245 $logger->log(level=>$level, message=>$msg);
246
247 if ($act eq SAVECHAR) {
248 $logger->log(level=>$level, message=>"\n");
249 }
250 }
251
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, @_); }
257
258 sub logincoming {
259 my ($text, @contents) = @_;
260 my $last;
261
262 if (@contents) {
263 $last = $contents[-1];
264 } else {
265 $last = '';
266 }
267
268 mylog('info', INCOMINGCHAR, $text, $last);
269 }
270
271 sub log_headers {
272 my %headers = @_;
273
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'}});
280 }
281
282 \f
283 ###############################################################################
284 # Utility procedures
285
286 sub mkfolder {
287 my $mhfolder = shift;
288 my $folder;
289 my $target;
290 my $component;
291
292 $folder = $mh . '/' . $mhfolder;
293 $target = '';
294
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)) {
300 next;
301 } else {
302 die("Failed to create +$mhfolder ($component)");
303 }
304 }
305 }
306 }
307 }
308
309 sub getfiles {
310 my $dir = shift;
311 my @result;
312
313 if (not opendir(DIR, $dir)) {
314 die("Failed opendir($dir)");
315 }
316
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,
321 # right? >sigh<
322 $! = 0;
323 @result = grep {
324 ($_ ne '.' and $_ ne '..')
325 and $_ = "$MAILDIR/new/$_"
326 } readdir(DIR);
327
328 if ($! != 0) {
329 die("Failed readdir($dir)");
330 }
331
332 if (scalar(@result) == 0) {
333 exit(0);
334 }
335
336 closedir(DIR);
337
338 return @result;
339 }
340
341 sub get_highest_msgnum {
342 my $mhfolder = shift;
343 my $dir;
344 my @list;
345 my $highest;
346 my $msgnum;
347
348 $dir = "$mh/$mhfolder";
349 if (not opendir(DIR, $dir)) {
350 die("Failed opendir($dir)");
351 }
352
353 $! = 0;
354 @list = readdir(DIR);
355
356 if ($! != 0) {
357 die("Failed readdir($dir)");
358 }
359
360 closedir(DIR);
361
362 $highest = 0;
363 foreach $msgnum (@list) {
364 # Look for integers.
365 if ($msgnum =~ /^[0-9]+$/) {
366 if ($msgnum > $highest) {
367 $highest = $msgnum;
368 }
369 }
370 }
371
372 return $highest;
373 }
374
375 sub store_message {
376 my $msg = shift;
377 my $mhfolder = shift;
378 my $msgnum;
379 my $try;
380 my $mhmsg;
381 my $status;
382
383 # We must do this even in -n mode because later steps fail without
384 # it. This should be harmless.
385 mkfolder($mhfolder);
386
387 # This loop is a modified version of the maildir delivery algorithm.
388 $msgnum = get_highest_msgnum($mhfolder);
389 for ($try = 0; ; $try++) {
390 $msgnum++;
391 $mhmsg = "$mh/$mhfolder/$msgnum";
392
393 if (not stat($mhmsg)) {
394 if ($!{ENOENT}) {
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.
402
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.
413 if ($run) {
414 if (sysopen(MSG, "$mhmsg",
415 O_WRONLY | O_EXCL | O_CREAT, 0600)) {
416 close(MSG);
417 last;
418 }
419 } else {
420 last;
421 }
422 }
423 }
424
425 # This algorithm is different from the maildir one; let's make
426 # 10 tries instead of 3.
427 if ($try == 9) {
428 die("Attempted filename $mhmsg exists.");
429 }
430
431 # This algorithm is different; i don't think we need to sleep.
432 #sleep(2);
433 }
434
435 if ($mhfolder ne 'SPAM') {
436 logsave("+$mhfolder");
437 }
438
439 if ($run) {
440 if (not rename($msg, $mhmsg)) {
441 die("Failed rename($msg, $mhmsg)");
442 }
443
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
447 # all).
448 if ($mhfolder eq 'SPAM') {
449 push(@SPAM, $msgnum);
450 } else {
451 $status = system('mark', "+$mhfolder", "$msgnum", '-sequence',
452 'unseen', '-add');
453 if (not WIFEXITED($status)) {
454 die("Failed to run mark");
455 } elsif (WEXITSTATUS($status) != 0) {
456 die("Failed to mark message unseen.");
457 }
458 }
459 }
460
461 return $msgnum;
462 }
463
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.
471 sub get_headers {
472 my $msg = shift;
473 my %headers;
474 my $current; # current header, used for unfolding lines
475 my $fieldname; # unmolested header name
476 my $contents; # contents of header
477
478 open(MSG, $msg);
479 while (<MSG>) {
480 chomp;
481 if (length == 0) {
482 last;
483 }
484
485 if (/^\s/) {
486 # folded header continuation
487
488 if (not defined($current)) {
489 print(STDERR "Malformed message, cannot parse headers.\n");
490 return ();
491 }
492
493 @{$headers{$current}}[-1] .= $_;
494 } else {
495 ($fieldname) = split(/:/);
496 $current = lc($fieldname);
497 (undef, $contents) = split(/^\Q$fieldname\E:\s*/);
498
499 if (defined($headers{$current})) {
500 # multiple occurence of same header
501 push(@{$headers{$current}}, $contents);
502 } else {
503 # first occurence of a header
504 $headers{$current} = [$contents];
505 }
506 }
507 }
508 close(MSG);
509
510 return %headers;
511 }
512
513 \f
514 ###############################################################################
515 # Filtering
516
517 sub find_mh_folder {
518 my $msg = shift;
519 my %headers;
520 my $filterref;
521 my @filter;
522 my $header;
523 my $contents;
524 my $pair;
525 my $match;
526 my $expression;
527 my $result;
528
529 %headers = get_headers($msg);
530 if (not %headers) {
531 return 'malformed';
532 }
533
534 log_headers(%headers);
535
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);
541
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/) {
550 return $expression;
551 }
552 }
553 }
554 }
555 }
556
557 # Now that it's been processed specially, skip normal handling.
558 next;
559 }
560
561 # Walk the list of message headers matching the filter's
562 # specified header.
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\"") {
569 return $result;
570 }
571 }
572 }
573 }
574 }
575
576 return 'inbox';
577 }
578
579 sub filter_mail {
580 my @msglist = @_;
581 my $msgcount = scalar(@msglist);
582 my @baton;
583 my $msg;
584 my $mhfolder;
585 my $spam = 0;
586 my $saved = 0;
587 my %FOLDERS = ('SPAM'=>1);
588
589 @baton = spam_start_hook();
590
591
592 STDOUT->autoflush(1);
593 print("$msgcount messages...");
594 foreach $msg (@msglist) {
595 if (spam_check($msg, @baton)) {
596 $mhfolder = 'SPAM';
597 $spam = scalar(@SPAM)+ 1;
598 } else {
599 $mhfolder = find_mh_folder($msg);
600 $saved++;
601 }
602
603 store_message($msg, $mhfolder);
604
605 print("\r");
606 if (not $FOLDERS{$mhfolder}) {
607 print(' ' x length($msgcount));
608 print(" \r+$mhfolder\n");
609 $FOLDERS{$mhfolder} = 1;
610 }
611
612 printf('%6d SPAM %6d saved %6d/%1d',
613 $spam, $saved, $spam + $saved, $msgcount);
614 }
615 print("\n");
616
617 spam_stop_hook(@baton);
618 }
619
620 \f
621 MAIN: {
622 my @msglist;
623 my $st;
624
625 if ($dumpfilters) {
626 $Data::Dumper::Indent = 1;
627 print(Dumper(\@FILTERS));
628 exit;
629 }
630
631 @msglist = (
632 map { $_->[1] }
633 sort { $a->[0] <=> $b->[0] }
634 map {
635 if (not ($st = stat($_))) {
636 die("stat($_): $!");
637 }
638 [$st->mtime, $_]
639 }
640 getfiles("$MAILDIR/new"));
641
642 filter_mail(@msglist);
643
644 @SPAM and (exec('scan', '+SPAM', @SPAM) or die);
645 }
646
647 \f
648 __END__
649
650 =head1 THE FILTERS STRUCTURE
651
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.
660
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.
667
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.
671
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.
676
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.
681
682 =head1 EXAMPLES
683
684 @FILTERS = (
685
686 ['List-Id',
687 ['<([[:graph:]]+)-([[:graph:]]+)\.lists\.sourceforge\.net>', 'l/$1/$2'],
688 ['<([[:graph:]]+?)(-list)?\.freedesktop\.org>', 'l/freedesktop/$1'],
689 ['<swig\.cs\.uchicago\.edu>', 'l/swig'],
690 ],
691
692 ['List-Post',
693 ['<mailto:([[:graph:]]+)+@([[:graph:]]+)\.apache\.org>', 'l/apache/$2/$1'],
694 ],
695
696 ['To',
697 ['root', 'root'],
698 ],
699 );
700
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.
707
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.
711
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.
716
717 For an example B<spam_check> function, see
718 L<http:E<047>E<047>pretzelnet.orgE<047>cvsE<047>dotfilesE<047>.mincspam>
719
720 =head1 AUTHORS
721
722 Written by Eric Gillespie <epg@pretzelnet.org> with logging code
723 stolen from Adam Lazur <adam@lazur.org>.
724
725 Design by Eric Gillespie and Doug Porter <dsp@waterspout.com>.
726
727 =cut
728
729 # Local variables:
730 # cperl-indent-level: 4
731 # perl-indent-level: 4
732 # indent-tabs-mode: nil
733 # End:
734
735 # vi: set tabstop=4 expandtab: