]>
diplodocus.org Git - minc/blob - minc
3e30d8cfd03759cf9f424fec0b4aeac3697d3e88
7 B<minc> - incorporate mail from a maildir into mh folders
11 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
40 use Fcntl
qw(O_WRONLY O_EXCL O_CREAT);
42 use File
::Temp
qw(tempfile);
44 use Getopt
::Long
qw(:config gnu_getopt no_ignore_case);
45 use POSIX
qw(strftime WEXITSTATUS WIFEXITED);
50 # If a filter set's header is $MAGIC_TO_TOKEN, that set is compared
51 # against headers matching this regex (taken from procmail).
52 my $MAGIC_TO_REGEX = '^((Original-)?(Resent-)?(To|Cc|Bcc)|(X-Envelope |Apparently(-Resent)?)-To)';
53 my $MAGIC_TO_TOKEN = ' TO';
55 # List of SPAM message numbers, scanned at the end so the user can
56 # check for false positives.
65 Dump (using Data::Dumper) the FILTERS list and exit. This is useful
66 for testing the syntax of .minc.
74 Stop processing after I<MAX> messages.
78 Dry run; do not actually incorporate the mail, but log and report to
79 stdout/stderr as normal.
83 Rebuild `mhpath +`/.folders from scratch, processing no mail.
93 my $rebuild_dot_folders;
100 'r' => \
$rebuild_dot_folders,
102 $help and pod2usage
(-exitstatus
=>0, -verbose
=>1);
103 @ARGV == 0 or pod2usage
();
113 How many columns the user's terminal can hold, used to print scan
114 lines for each processed message. Defaults to 80.
118 Where the configuration file (.minc) is found. Also,
119 $HOME/Maildir is used for the maildir if MAILDIR is not set.
123 Where mail is delivered.
129 use Env
qw(COLUMNS HOME MAILDIR);
134 die("HOME environment variable must be set.\n");
137 $MAILDIR = "$HOME/Maildir";
146 This file is Perl code (included via the 'require' directive) which
147 may define the FILTERS list, @start_hooks, @filter_hooks,
148 @post_store_hooks, and @stop_hooks.
150 =item `mhpath +`/.folders
152 B<minc> adds all folders it filters into to this file, which is used
153 by lukem's B<new(1)> (XXX need a link).
155 =item `mhpath +`/logs/minc.log
157 Where B<minc> logs what it does, unless in -n mode.
159 =item `mhpath +`/.minc.context
161 B<minc> uses this file for context (i.e. current folder) instead of
162 `mhpath +`/context. This allows you some amount of freedom to use mh
163 while B<minc> is running. For example, you can changed folders without
164 causing a message to be stored in the wrong folder. Care must still
165 be taken, however, about the unseen sequence; if you change it
166 (whether via show, or mark, or anything else) while in the same folder
167 as B<minc>, it is likely the new message B<minc> stores will not end up
175 our (@start_hooks, @stop_hooks, @filter_hooks, @post_store_hooks);
176 our $SCAN_P_FOLDER = 0.1;
177 our $SCAN_P_MESSAGE = 0.0625;
178 our $SCAN_P_FROM = 0.175;
181 sub { my ($a,$b) = @_;
182 $a eq 'inbox' and return -1;
183 $b eq 'inbox' and return 1;
192 my $logfile = $mh . '/logs/minc.log';
194 $ENV{"MHCONTEXT"} = $mh . '/.minc.context';
197 ###############################################################################
203 my $timestamp = strftime
('%b %e %H:%M:%S', localtime);
205 foreach my $part (@_) {
206 if (defined($part)) {
210 # no newlines in the log message, thanks
213 open(LOG
, ">>$logfile") or die("open(>>$logfile): $!");
214 print(LOG
"$timestamp $msg\n") or die("print(>>$logfile): $!");
215 close(LOG
) or die("close($logfile): $!");
219 my ($text, @contents) = @_;
223 $last = $contents[-1];
228 mylog
('<< ', $text, $last);
234 # For an explanation of the %headers structure, see the
235 # get_headers function below.
236 logheader
('From: ', @{$headers{'return-path'}});
237 logheader
('To: ', @{$headers{'to'}});
238 logheader
('Subject: ', @{$headers{'subject'}});
239 logheader
('Message-Id: ', @{$headers{'message-id'}});
243 ###############################################################################
252 foreach $component (split('/', $folder)) {
253 $target = join('/', $target, $component);
254 -d
$target or mkdir($target) or die("mkdir($target): $!");
262 if (not opendir(DIR
, $dir)) {
263 die("opendir($dir): $!");
266 # Initialize $! to 0 (success) because stupid stupid Perl provides
267 # no way to distinguish an error from an empty directory; that
268 # means setting $! to 0 and testing it afterwards is the only way
269 # to detect an error. Real Programmers don't handle errors,
272 @result = readdir(DIR
);
274 die("readdir($dir): $!");
281 STDOUT-
>autoflush(1);
282 print(@result - 2, " messages...");
289 sub get_highest_msgnum
{
290 my $mhfolder = shift;
296 $dir = "$mh/$mhfolder";
297 if (not opendir(DIR
, $dir)) {
298 die("opendir($dir): $!");
301 # Insert rant from getfiles here.
303 @list = readdir(DIR
);
306 die("readdir($dir): $!");
312 foreach $msgnum (@list) {
314 if ($msgnum =~ /^[0-9]+$/) {
315 if ($msgnum > $highest) {
326 my $mhfolder = shift;
332 # We must do this even in -n mode because later steps fail without
333 # it. This should be harmless.
336 # This loop is a modified version of the maildir delivery algorithm.
337 $msgnum = get_highest_msgnum
($mhfolder);
338 for ($try = 0; ; $try++) {
340 $mhmsg = "$mh/$mhfolder/$msgnum";
342 if (not stat($mhmsg)) {
344 # Now we have a non-existent file, let's try to create
345 # it. We must create a zero-byte file first because a
346 # file my appear between our happy stat results and
347 # our later rename(2), which would clobber said file.
348 # So attempt to create a file with this name. If it
349 # succeeds, in just a bit here we'll knowingly clobber
350 # this file with the rename(2) call.
352 # Another way to do this is not to use rename(2), but
353 # use link(2) + unlink(2) instead. That's how the
354 # standard maildir algorithm does it. Each method has
355 # a disadvantage: the program may crash between the
356 # link(2) and unlink(2) calls. With the standard
357 # maildir algorithm, that means the message will end
358 # up duplicated. The advantage of creating an empty
359 # file followed by rename(2) is that an extra empty
360 # file is left behind as opposed to a duplicate
361 # message. This is more easily detected by the user.
363 if (sysopen(MSG
, $mhmsg,
364 O_WRONLY
| O_EXCL
| O_CREAT
, 0600)) {
374 # This algorithm is different from the maildir one; let's make
375 # 10 tries instead of 3.
377 die("Attempted filename $mhmsg exists.");
380 # This algorithm is different; i don't think we need to sleep.
384 mylog
('+', $mhfolder);
387 if (not rename($msg, $mhmsg)) {
388 die("rename($msg, $mhmsg): $!");
391 # Mark each message as soon as we store it and bomb if that
392 # fails. While it is slow, it is not safe to store multiple
393 # messages and then have a failure before marking some (or
395 if ($mhfolder eq 'SPAM') {
396 push(@SPAM, $msgnum);
398 $status = system('mark', "+$mhfolder", "$msgnum", '-sequence',
400 # XXX need to handle signalled and stopped, and print
401 # the exit code or signal number.
402 if (not WIFEXITED
($status)) {
403 die("Failed to run mark");
404 } elsif (WEXITSTATUS
($status) != 0) {
405 die("Failed to mark message unseen.");
413 # Parse a message file into a structure describing the headers. The
414 # structure is a hash of arrays. The hash keys are the names of the
415 # headers found in the message, made all lower-case. Each item in
416 # the hash is an array of header text. The array has one element
417 # per occurrence of the header. Most headers will only have a single
418 # element because they occur only once. The Received header is the
419 # most common header with multiple texts.
423 my $current; # current header, used for unfolding lines
424 my $fieldname; # unmolested header name
425 my $contents; # contents of header
427 open(MSG
, $msg) or die("open(MSG, $msg): $!");
435 # folded header continuation
437 if (not defined($current)) {
438 warn('Malformed message, cannot parse headers.');
442 @{$headers{$current}}[-1] .= $_;
444 ($fieldname) = split(/:/);
445 $current = lc($fieldname);
446 (undef, $contents) = split(/^\Q$fieldname\E:\s*/);
448 if (defined($headers{$current})) {
449 # multiple occurence of same header
450 push(@{$headers{$current}}, $contents);
452 # first occurence of a header
453 $headers{$current} = [$contents];
463 ###############################################################################
482 # Walk the list of filters. This structure is documented in
483 # pod at the end of the program.
484 foreach $filterref (@FILTERS) {
485 @filter = @$filterref;
486 $header = shift(@filter);
488 # Handle filters using the magic TO header specially.
489 if ($header eq $MAGIC_TO_TOKEN) {
490 foreach $header (keys(%headers)) {
491 if ($header =~ /$MAGIC_TO_REGEX/i) {
492 foreach $contents (@{$headers{lc($header)}}) {
493 foreach $pair (@filter) {
494 ($match, $expression) = @$pair;
495 if ($contents =~ /$match/i) {
496 if (eval "\$result = \"$expression\"") {
505 # Now that it's been processed specially, skip normal handling.
509 # Walk the list of message headers matching the filter's
511 foreach $contents (@{$headers{lc($header)}}) {
512 # Walk the filter's list of match/expression pairs.
513 foreach $pair (@filter) {
514 ($match, $expression) = @$pair;
515 if ($contents =~ /$match/i) {
516 if (eval "\$result = \"$expression\"") {
528 my $msgcount = @_ - 2; # don't count . and ..
529 my $len = length($msgcount);
538 if (-f
"$HOME/.minc") {
539 require "$HOME/.minc";
543 my $nf = int($COLUMNS * $SCAN_P_FOLDER);
544 my $nm = int($COLUMNS * $SCAN_P_MESSAGE);
545 my $nF = int($COLUMNS * $SCAN_P_FROM);
546 my $ns = $COLUMNS - $nf - $nm - $nF - 3;
549 for my $hook (@start_hooks) {
550 my ($handle, @baton) = $hook->();
551 if (defined($handle)) {
552 $batons{$handle} = [@baton];
557 ($msg eq '.' or $msg eq '..') and next;
559 my %headers = get_headers
($msg);
560 log_headers
(%headers);
563 for my $hook (@filter_hooks) {
564 my $result = $hook->(\
%batons, \
%headers, $msg);
565 defined($result) and ($mhfolder = $result);
568 defined($mhfolder) or ($mhfolder = find_mh_folder
($msg, %headers));
570 $msgnum = store_message
($msg, $mhfolder);
571 $folders{$mhfolder}++;
573 if ($mhfolder eq 'SPAM') {
579 # Sometimes these headers are missing...
580 eval { $from = [@{$headers{'from'}}]->[-1] };
581 eval { $subject = [@{$headers{'subject'}}]->[-1] };
582 for ($from, $subject) {
583 tr/\x00-\x1f\x80-\xff/ /;
586 print(' ' x
$COLUMNS);
587 printf("\r\%-${nf}s \%${nm}d \%-${nF}s \%s\n",
588 substr($mhfolder, 0, $nf), substr($msgnum, 0, $nm),
589 substr($from, 0, $nF),
590 substr($subject, 0, $ns));
593 for my $hook (@post_store_hooks) {
594 $hook->(\
%batons, \
%headers, $mhfolder, $msgnum);
598 printf(" \%${len}d SPAM \%${len}d saved \%${len}d/%1d",
599 $spam, $saved, $spam + $saved, $msgcount);
601 defined($maxmsgs) and ($spam + $saved < $maxmsgs or last);
605 for my $hook (@stop_hooks) {
612 sub build_dot_folders
{
624 eval { ($fh, $fn) = tempfile
("$mh/.folders.XXXXX") };
630 for my $folder (sort { $folder_sorter->($a,$b) } keys(%$folders)) {
631 print($fh "$folder\n");
634 if (not close($fh)) {
635 warn("close($fn): $!");
636 unlink($fn) or warn("unlink($fn): $!");
640 rename($fn, "$mh/.folders") or warn("rename($fn, $mh/.folders): $!");
643 sub create_dot_folders
{
645 open(my $fh, '-|', 'folders', '-fast', '-recur')
646 or die("open(folders|): $!");
647 build_dot_folders
(\
%folders, $fh);
651 sub update_dot_folders
{
655 if (not open($fh, "$mh/.folders") and not $!{ENOENT
}) {
656 # For ENOENT, we go ahead and create it, else we error and
658 warn("open($mh/.folders): $!");
662 build_dot_folders
($folders, $fh);
670 require "$HOME/.minc";
671 $Data::Dumper
::Indent
= 1;
672 print(Dumper
(\
@FILTERS));
676 $rebuild_dot_folders and exit(create_dot_folders
);
678 chdir("$MAILDIR/new") or die("chdir($MAILDIR/new): $!");
679 my %folders = filter_mail
(map { $_->[1] }
680 sort { $a->[0] <=> $b->[0] }
682 if (not ($st = stat($_))) {
689 $run and update_dot_folders
(\
%folders);
691 @SPAM and (exec('scan', '+SPAM', @SPAM) or die);
697 =head1 THE FILTERS STRUCTURE
699 Each element of @FILTERS is a filter. A filter is itself an array.
700 The first element of a filter is a string, the name of the header this
701 filter acts upon. The header name is not case-sensitive. Each
702 subsequent element of a filter is a pair (i.e. a two-element array):
703 first, a regular expression B<minc> uses to determine whether this
704 filter matches or not, and second, an expression which B<minc>
705 evaluates to get the folder name.
707 B<minc> decides where to store a message by iterating over the
708 @FILTERS array. It tests each regexp of each filter against all
709 headers matching that filter's specified header. As soon as a match
710 is found, B<minc> evaluates the second part of the pair. This part
711 may contain positional parameters from the matched regexp ($1, $2,
712 etc.). The result of this expression is used as the folder name.
714 Multiple occurrences of the same header are preserved and tested
715 individually against the filters. That means, for example, that
716 filters can search all the Received headers for a certain string.
718 It is important to note that all the arrays of the @FILTERS structure
719 are traversed I<in order>. This means the filters can be arranged so
720 that some have priority over others. XXX: get Doug to write an
721 example of having the same header matched more than once.
723 Lastly, B<minc> supports a magic ' TO' header. Filters using this
724 header are matched against a collection of headers related to (and
725 including) the To. Which headers to use is determined by a regular
726 expression borrowed from procmail.
730 Filter hooks take a reference to a hash of batons, a reference to a
731 hash of headers, and the message filename as arguments. It returns
732 undef to decline filtering of this message (thus falling back to
733 subsequent filter hooks, and finally @FILTERS), or the name of the
734 folder to store this message into.
736 One of B<minc>'s global variables is available to the user-defined
737 hooks: $run. This boolean should be honored; hooks should only take
738 real action (i.e. removing or creating files, running external
739 programs, etc.) if $run is non-zero.
741 The baton hash is created simply from the start hooks; if the hook
742 returns at least one defined value, this value is used as the key and
743 all other return values are put into a list reference as the value.
744 This hash is then passed by reference to all filter, post-store, and
747 Post store hooks take a reference to a hash of batons, a reference to
748 a hash of headers, the folder this message was stored in, and its new
751 XXX: need more details about the hook process; for now read the code.
758 ['<([[:graph:]]+)-([[:graph:]]+)\.lists\.sourceforge\.net>', 'l/$1/$2'],
759 ['<([[:graph:]]+?)(-list)?\.freedesktop\.org>', 'l/freedesktop/$1'],
760 ['<swig\.cs\.uchicago\.edu>', 'l/swig'],
764 ['<mailto:([[:graph:]]+)+@([[:graph:]]+)\.apache\.org>', 'l/apache/$2/$1'],
772 The first List-Id filter is a surprisingly effective one which creates
773 appropriate folder names (such as l/htdig/updates and l/rox/devel) for
774 all Sourceforge lists to which i subscribe. Certainly there are lists
775 hosted at Sourceforge which do not work well with this, and this is
776 where it is important to remember that the first match is the one
777 uses. Simply put the more specific rules before this one.
779 The next List-Id example is simple. The swig example demonstrates
780 that the folder name does not have to use a portion of the matched
781 header; you can just hardcode the folder name.
783 The List-Post example is a nice one. Most ASF projects have their own
784 apache.org subdomain, with mailing lists hosted there. So, given a
785 list such as dev@httpd.apache.org, this filter will create the folder
786 name l/apache/httpd/dev.
788 XXX Need hook examples.
792 Written by Eric Gillespie <epg@pretzelnet.org>. Design by Eric
793 Gillespie and Doug Porter <dsp@waterspout.com>.
795 This program is free software; you can redistribute it and/or modify
796 it under the same terms as Perl itself.
801 # cperl-indent-level: 4
802 # perl-indent-level: 4
803 # indent-tabs-mode: nil
806 # vi: set tabstop=4 expandtab: