]> diplodocus.org Git - minc/blob - minc
72c7ca1d8a8e5284f3b5f02decc7fb5736fca04f
[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<dhns>]
12
13 =head1 DESCRIPTION
14
15 B<minc> is a program for incorporating mail from a maildir to a mh
16 folder hierarchy. It takes mail from a maildir folder (not a maildir
17 folder hierarchy), checks for spam with razor
18 (http://razor.sourceforge.net/), and optionally filters mail into
19 separate mh folders.
20
21 The filtering is quite sophisticated, as it is done using real Perl
22 substitution (s//) commands.
23
24 =cut
25
26 use strict;
27 use warnings;
28
29 require 'sysexits.ph';
30
31 use Data::Dumper;
32 use Errno;
33 use Fcntl qw(O_WRONLY O_EXCL O_CREAT);
34 use File::Basename;
35 use Getopt::Std;
36 use Log::Dispatch;
37 use Log::Dispatch::File;
38 use POSIX qw(strftime WEXITSTATUS WIFEXITED);
39
40 =head1 OPTIONS
41
42 =over 4
43
44 =item B<-d>
45
46 Dump (using Data::Dumper) the FILTERS hash and exit. This is useful
47 for testing the syntax of .mincfilter.
48
49 =item B<-f>
50
51 Filter only, then exit. This is useful after running B<minc -s>.
52
53 =item B<-h>
54
55 Show help.
56
57 =item B<-n>
58
59 Dry run; do not actually incorporate the mail, but log and report to
60 stdout/stderr as normal.
61
62 =item B<-s>
63
64 Process SPAM only, then exit, leaving all non-spam messages in the
65 maildir.
66
67 =back
68
69 =cut
70
71 my $dumpfilters = 0;
72 my $filteronly = 0;
73 my $run = 1;
74 my $spamonly = 0;
75
76 our $opt_d;
77 our $opt_f;
78 our $opt_h;
79 our $opt_n;
80 our $opt_s; # ;; # stupid cperl-mode
81
82 if (not getopts('dhns')) {
83 exit(&EX_USAGE);
84 }
85
86 if ($opt_d) {
87 $dumpfilters = 1;
88 } elsif ($opt_h) {
89 print("Sorry bub, no help.\n");
90 exit(&EX_OK);
91 } elsif ($opt_n) {
92 $run = 0;
93 }
94
95 if ($opt_f) {
96 $filteronly = 1;
97 } elsif ($opt_s) { # ))){ # stupid cperl-mode
98 $spamonly = 1;
99 }
100
101 =head1 ENVIRONMENT
102
103 =over 4
104
105 =item HOME
106
107 Where configuration files (.mincfilter) are found. Also,
108 $HOME/Maildir is used for the maildir if MAILDIR is not set.
109
110 =item MAILDIR
111
112 Where mail is delivered.
113
114 =back
115
116 =cut
117
118 use Env qw(HOME MAILDIR);
119
120 if (not $HOME) {
121 die("HOME environment variable must be set.\n");
122 }
123 if (not $MAILDIR) {
124 $MAILDIR = "$HOME/Maildir";
125 }
126
127 =head1 FILES
128
129 =over 4
130
131 =item $HOME/.mincfilter
132
133 This file is Perl code (included via the 'require' directive) which is
134 expected to define the FILTERS hash.
135
136 =item `mhpath +`/logs/minc.log
137
138 Where minc logs what it does, unless in -n mode.
139
140 =item `mhpath +`/logs/dryrun.log
141
142 Where minc logs what it would do; used in -n mode.
143
144 =back
145
146 =cut
147
148 our %FILTERS;
149 require "$HOME/.mincfilter";
150
151 my $mh;
152 my $logfile;
153
154 $mh = `mhpath +`;
155 chomp($mh);
156
157 if ($run) {
158 $logfile = $mh . '/logs/minc.log';
159 } else {
160 $logfile = $mh . '/logs/dryrun.log';
161 }
162
163 \f
164 ###############################################################################
165 # Logging
166
167 # debuglevels for the logger
168 use constant LOG_DEBUGLEVEL => 'info';
169 use constant SCREEN_DEBUGLEVEL => 'debug';
170
171 # characters used to wrap around the id field in the log so I can more
172 # easily parse the msg flow
173 use constant DEBUGCHAR => '%';
174 use constant INFOCHAR => '=';
175 use constant INCOMINGCHAR => '<';
176 use constant SAVECHAR => '>';
177 use constant WARNCHAR => 'W';
178 use constant ERRORCHAR => 'E';
179
180 my $logger = new Log::Dispatch;
181 $logger->add(new Log::Dispatch::File (name=>'logfile',
182 filename=>$logfile,
183 min_level=>'info',
184 mode=>'append'));
185
186 # log alias, handles getting passed vars that are undef
187 sub mylog {
188 my $level = shift;
189 my $act = shift;
190 my $timestamp = strftime('%b %e %H:%M:%S', localtime);
191 my $msg;
192 foreach my $part (@_) {
193 if (defined($part)) {
194 $msg .= $part;
195 }
196 }
197 # no newlines in the log message, thanks
198 $msg =~ s/\n/ /gm;
199 $msg = sprintf("%s %s%s %s\n", $timestamp, $act, $act, $msg);
200 $logger->log(level=>$level, message=>$msg);
201
202 if ($act eq SAVECHAR) {
203 $logger->log(level=>$level, message=>"\n");
204 }
205 }
206
207 sub logincoming { mylog('info', INCOMINGCHAR, @_); }
208 sub logsave { mylog('notice', SAVECHAR, @_); }
209 sub loginfo { mylog('info', INFOCHAR, @_); }
210 sub logdebug { mylog('debug', DEBUGCHAR, @_); }
211 sub logwarn { mylog('warning', WARNCHAR, @_); }
212 sub logerr { mylog('error', ERRORCHAR, @_); }
213
214 sub log_headers {
215 my %headers = @_;
216
217 logincoming('From: ', $headers{'return-path'});
218 logincoming('To: ', $headers{'to'});
219 logincoming('Subject: ', $headers{'subject'});
220 logincoming('Message-Id: ', $headers{'message-id'});
221 }
222
223 \f
224 ###############################################################################
225 # Utility procedures
226
227 sub _errprint {
228 printf('%s:%s', __FILE__, __LINE__);
229
230 if (@_) {
231 print(': ');
232 foreach (@_) {
233 print;
234 }
235 }
236 }
237
238 sub err {
239 my $ex = shift;
240
241 _errprint(@_);
242 print(": $!\n");
243
244 exit($ex);
245 }
246
247 sub errx {
248 my $ex = shift;
249
250 _errprint(@_);
251 print("\n");
252
253 exit($ex);
254 }
255
256 sub mkfolder {
257 my $mhfolder = shift;
258 my $folder;
259 my $target;
260 my $component;
261
262 $folder = $mh . '/' . $mhfolder;
263 $target = '';
264
265 if (not -d $folder) {
266 foreach $component (split('/', $folder)) {
267 if (defined($component) and length($component) >= 1) {
268 $target = $target . '/' . $component;
269 if (-d $target or mkdir($target)) {
270 next;
271 } else {
272 err(&EX_TEMPFAIL,
273 "Failed to create +$mhfolder ($component)");
274 }
275 }
276 }
277 }
278 }
279
280 sub getfiles {
281 my $dir = shift;
282 my @result;
283
284 if (not opendir(DIR, $dir)) {
285 err(&EX_TEMPFAIL, "Failed opendir($dir)");
286 }
287
288 # Initialize $! to 0 (success) because stupid stupid Perl provides
289 # no way to distinguish an error from an empty directory; that
290 # means setting $! to 0 and testing it afterwards is the only way
291 # to detect an error. Real Programmers don't handle errors,
292 # right? >sigh<
293 $! = 0;
294 @result = grep {
295 ($_ ne '.' and $_ ne '..')
296 and $_ = "$MAILDIR/new/$_"
297 } readdir(DIR);
298
299 if ($! != 0) {
300 err(&EX_TEMPFAIL, "Failed readdir($dir)");
301 }
302
303 closedir(DIR);
304
305 return @result;
306 }
307
308 sub get_highest_msgnum {
309 my $mhfolder = shift;
310 my $dir;
311 my @list;
312 my $highest;
313 my $msgnum;
314
315 $dir = "$mh/$mhfolder";
316 if (not opendir(DIR, $dir)) {
317 err(&EX_TEMPFAIL, "Failed opendir($dir)");
318 }
319
320 $! = 0;
321 @list = readdir(DIR);
322
323 if ($! != 0) {
324 err(&EX_TEMPFAIL, "Failed readdir($dir)");
325 }
326
327 closedir(DIR);
328
329 $highest = 0;
330 foreach $msgnum (@list) {
331 # Look for integers.
332 if ($msgnum =~ /^[0-9]+$/) {
333 if ($msgnum > $highest) {
334 $highest = $msgnum;
335 }
336 }
337 }
338
339 return $highest;
340 }
341
342 # We want to print the name of each list that has new mail only once,
343 # so use this hash to store the lists that have already been printed.
344 # Start the list out with SPAM already in it, since we don't care when
345 # new messages are added to it.
346 my %FOLDERS = ('SPAM'=>1);
347
348 sub store_message {
349 my $msg = shift;
350 my $mhfolder = shift;
351 my $msgnum;
352 my $try;
353 my $mhmsg;
354 my $status;
355
356 # We must do this even in -n mode because later steps fail without
357 # it. This should be harmless.
358 mkfolder($mhfolder);
359
360 $msgnum = get_highest_msgnum($mhfolder);
361 for ($try = 0; ; $try++) {
362 $msgnum++;
363 $mhmsg = "$mh/$mhfolder/$msgnum";
364
365 if (not stat($mhmsg)) {
366 if ($!{ENOENT}) {
367 # Now we have a non-existent file, let's try to create
368 # it. We must create a zero-byte file first because a
369 # file my appear between our happy stat results and
370 # our later rename(2), which would clobber said file.
371 # So attempt to create a file with this name. If it
372 # succeeds, in just a bit here we'll knowingly clobber
373 # this file with the rename(2) call.
374 if ($run) {
375 if (sysopen(MSG, "$mhmsg",
376 O_WRONLY | O_EXCL | O_CREAT, 0600)) {
377 close(MSG);
378 last;
379 }
380 } else {
381 last;
382 }
383 }
384 }
385
386 # This algorithm is different from the maildir one; let's make
387 # 10 tries instead of 3.
388 if ($try == 9) {
389 errx(&EX_TEMPFAIL, "Attempted filename $mhmsg exists.");
390 }
391
392 # This algorithm is different; i don't think we need to sleep.
393 #sleep(2);
394 }
395
396 logsave("+$mhfolder");
397
398 if ($run) {
399 if (not rename($msg, $mhmsg)) {
400 err(&EX_TEMPFAIL, "Failed rename($msg, $mhmsg)");
401 }
402
403 # Mark each message as soon as we store it and bomb if that
404 # fails. While it is slow, it is not safe to store multiple
405 # messages and then have a failure before marking some (or
406 # all).
407 if ($mhfolder ne 'SPAM') {
408 $status = system("mark +$mhfolder $msgnum -sequence unseen -add");
409 if (not (WIFEXITED($status) and WEXITSTATUS($status) == 0)) {
410 errx(&EX_TEMPFAIL, "Failed to mark message unseen");
411 }
412 }
413 }
414
415 if (not $FOLDERS{$mhfolder}) {
416 print("+$mhfolder\n");
417 $FOLDERS{$mhfolder} = 1;
418 }
419 }
420
421 sub get_headers {
422 my $msg = shift;
423 my %headers;
424 my $current; # current header, used for unfolding lines
425 my $fieldname; # unmolested header name
426
427 open(MSG, $msg);
428 while (<MSG>) {
429 chomp;
430 if (length == 0) {
431 last;
432 }
433
434 if (/^\s/) {
435 # folded header continuation
436
437 if (not defined($current)) {
438 print("Malformed message, cannot parse headers.\n");
439 return ();
440 }
441
442 $headers{$current} .= $_;
443 } else {
444 ($fieldname) = split(/:/);
445 $current = lc($fieldname);
446 (undef, $headers{$current}) = split(/^$fieldname:\s*/);
447 }
448 }
449 close(MSG);
450
451 return %headers;
452 }
453
454 \f
455 ###############################################################################
456 # Spam handling
457
458 sub is_spam {
459 my $msg = shift;
460 my $err;
461 my $sig;
462 my $line;
463 my $message;
464 my $status;
465
466 $err = $sig = $msg;
467 $err =~ s|/new/|/err/|;
468 $sig =~ s|/new/|/sig/|;
469 if (-f $err) {
470 open(ERR, $err);
471 $line = <ERR>;
472 close(ERR);
473
474 chomp($line);
475 ($message, $!) = split(/:/, $line);
476
477 logerr("$err: $message: $!");
478
479 if ($run) {
480 if (unlink($err) != 1) {
481 err(&EX_TEMPFAIL, "Failed unlink($err)");
482 }
483 }
484 } elsif (-f $sig) {
485 # This is supposed to be a signature created with razor-check
486 # directly after delivery. Currently this isn't supported
487 # because it isn't clear to me how to get that signature back
488 # into razor-check. For now, just unlink any sig files we
489 # find and proceed with full razor-check mode.
490
491 if ($run) {
492 if (unlink($sig) != 1) {
493 err(&EX_TEMPFAIL, "Failed unlink($sig)");
494 }
495 }
496 }
497
498 if ($run) {
499 $status = system("razor-check < $msg");
500 if (not WIFEXITED($status)) {
501 err(&EX_TEMPFAIL, "Failed to run razor-check < $msg");
502 } elsif (WEXITSTATUS($status) == 0) {
503 return 1;
504 } else {
505 return 0;
506 }
507 } else {
508 return 0;
509 }
510 }
511
512 sub kill_spam {
513 my @msglist = @_;
514 my @result;
515 my $msg;
516 my $i;
517
518 @result = ();
519
520 $i = 0;
521 foreach $msg (@msglist) {
522 printf('%sChecking for spam... %6d/%d',
523 "\r", ++$i, scalar(@msglist));
524 if (is_spam($msg)) {
525 print(" SPAM\n");
526 store_message($msg, 'SPAM');
527 } else {
528 push(@result, $msg);
529 }
530 }
531 print("\nDone: ", scalar(@result), " survivors\n");
532
533 return @result;
534 }
535
536 \f
537 ###############################################################################
538 # Filtering
539
540 sub find_mh_folder {
541 my $msg = shift;
542 my %headers;
543 my $header;
544 my $contents;
545 my $regex;
546 my $subst;
547 my $try;
548
549 %headers = get_headers($msg);
550 if (not %headers) {
551 return 'inbox';
552 }
553
554 log_headers(%headers);
555
556 foreach $header (keys(%FILTERS)) {
557 $contents = $headers{lc($header)};
558
559 if (defined($contents)) {
560 foreach $regex (keys(%{$FILTERS{$header}})) {
561 $subst = $FILTERS{$header}->{$regex};
562
563 $try = '$contents =~';
564 $try .= " s|$regex|$subst|is";
565 if (eval $try) {
566 return $contents;
567 }
568 }
569 }
570 }
571
572 return 'inbox';
573 }
574
575 sub filter_mail {
576 my @msglist = @_;
577 my $msg;
578 my $mhfolder;
579
580 foreach $msg (@msglist) {
581 $mhfolder = find_mh_folder($msg);
582 store_message($msg, $mhfolder);
583 }
584 }
585
586 \f
587 MAIN: {
588 my @msglist;
589
590 if ($dumpfilters) {
591 $Data::Dumper::Indent = 1;
592 print(Dumper(\%FILTERS));
593 exit(&EX_OK);
594 }
595
596 @msglist = getfiles("$MAILDIR/new");
597
598 if (not $filteronly) {
599 @msglist = kill_spam(@msglist);
600 }
601
602 if (not $spamonly) {
603 filter_mail(@msglist);
604 }
605 }
606
607 __END__
608
609 =head1 EXAMPLES
610
611 %FILTERS =
612 ('List-Id:'=>
613 {'.*<([[:graph:]]+)-([[:graph:]]+)\.lists\.sourceforge\.net>.*'=>'l/$1/$2',
614 '.*<([[:graph:]]+?)(-list)?\.freedesktop\.org>.*'=>'l/freedesktop/$1',
615 '.*<swig\.cs\.uchicago\.edu>.*'=>'l/swig'},
616
617 'List-Post:'=>
618 {'<mailto:([[:graph:]]+)+@([[:graph:]]+)\.apache\.org>'=>'l/apache/$2/$1'},
619
620 'To:'=>
621 {'root'=>'root'});
622
623 The first List-Id filter is a surprisingly effective one which creates
624 appropriate folder names (such as l/htdig/updates and l/rox/devel) for
625 all Sourceforge lists to which i subscribe. Certainly there are lists
626 hosted at Sourceforge which do not work well with this, and this is
627 where it is important to remember that the first match is the one
628 uses. Simply put the more specific rules before this one.
629
630 The next List-Id example is simple. The swig example demonstrates
631 that the folder name does not have to use a portion of the matched
632 header; you can just hardcode the folder name.
633
634 The List-Post example is a nice one. Most ASF projects have their own
635 apache.org subdomain, with mailing lists hosted there. So, given a
636 list such as dev@httpd.apache.org, this filter will create the folder
637 name l/apache/httpd/dev.
638
639 =head1 AUTHORS
640
641 Written by Eric Gillespie <epg@pretzelnet.org> with logging code
642 stolen from Adam Lazur <adam@lazur.org>.
643
644 Design by Eric Gillespie and Doug Porter <dsp@waterspout.com>.
645
646 =cut