]> diplodocus.org Git - minc/blobdiff - minc
Fix pod buglet.
[minc] / minc
diff --git a/minc b/minc
index 8c3d7f9..72c7ca1 100755 (executable)
--- a/minc
+++ b/minc
@@ -14,8 +14,9 @@ B<minc> [-B<dhns>]
 
 B<minc> is a program for incorporating mail from a maildir to a mh
 folder hierarchy.  It takes mail from a maildir folder (not a maildir
-folder hierarchy), checks for spam with razor (XXX crossref), and
-optionally filters mail into separate mh folders.
+folder hierarchy), checks for spam with razor
+(http://razor.sourceforge.net/), and optionally filters mail into
+separate mh folders.
 
 The filtering is quite sophisticated, as it is done using real Perl
 substitution (s//) commands.
@@ -28,25 +29,14 @@ use warnings;
 require 'sysexits.ph';
 
 use Data::Dumper;
+use Errno;
+use Fcntl qw(O_WRONLY O_EXCL O_CREAT);
 use File::Basename;
 use Getopt::Std;
 use Log::Dispatch;
 use Log::Dispatch::File;
 use POSIX qw(strftime WEXITSTATUS WIFEXITED);
 
-# debuglevels for the logger
-use constant LOG_DEBUGLEVEL     => 'info';
-use constant SCREEN_DEBUGLEVEL  => 'debug';
-
-# characters used to wrap around the id field in the log so I can more
-# easily parse the msg flow
-use constant DEBUGCHAR          => '%';
-use constant INFOCHAR           => '=';
-use constant INCOMINGCHAR       => '<';
-use constant SAVECHAR           => '>';
-use constant WARNCHAR           => 'W';
-use constant ERRORCHAR          => 'E';
-
 =head1 OPTIONS
 
 =over 4
@@ -56,6 +46,10 @@ use constant ERRORCHAR          => 'E';
 Dump (using Data::Dumper) the FILTERS hash and exit.  This is useful
 for testing the syntax of .mincfilter.
 
+=item B<-f>
+
+Filter only, then exit.  This is useful after running B<minc -s>.
+
 =item B<-h>
 
 Show help.
@@ -75,15 +69,17 @@ maildir.
 =cut
 
 my $dumpfilters = 0;
+my $filteronly = 0;
 my $run = 1;
 my $spamonly = 0;
 
 our $opt_d;
+our $opt_f;
 our $opt_h;
 our $opt_n;
 our $opt_s;                     # ;; # stupid cperl-mode
 
-if (!getopts('dhns')) {
+if (not getopts('dhns')) {
     exit(&EX_USAGE);
 }
 
@@ -96,7 +92,9 @@ if ($opt_d) {
     $run = 0;
 }
 
-if ($opt_s) {                   # ))){ # stupid cperl-mode
+if ($opt_f) {
+    $filteronly = 1;
+} elsif ($opt_s) {              # ))){ # stupid cperl-mode
     $spamonly = 1;
 }
 
@@ -106,7 +104,8 @@ if ($opt_s) {                   # ))){ # stupid cperl-mode
 
 =item HOME
 
-Where configuration files (.mincfilter) are found.
+Where configuration files (.mincfilter) are found.  Also,
+$HOME/Maildir is used for the maildir if MAILDIR is not set.
 
 =item MAILDIR
 
@@ -116,8 +115,7 @@ Where mail is delivered.
 
 =cut
 
-use Env qw(HOME);
-use Env qw(MAILDIR);
+use Env qw(HOME MAILDIR);
 
 if (not $HOME) {
     die("HOME environment variable must be set.\n");
@@ -143,6 +141,8 @@ Where minc logs what it does, unless in -n mode.
 
 Where minc logs what it would do; used in -n mode.
 
+=back
+
 =cut
 
 our %FILTERS;
@@ -164,6 +164,19 @@ if ($run) {
 ###############################################################################
 # Logging
 
+# debuglevels for the logger
+use constant LOG_DEBUGLEVEL     => 'info';
+use constant SCREEN_DEBUGLEVEL  => 'debug';
+
+# characters used to wrap around the id field in the log so I can more
+# easily parse the msg flow
+use constant DEBUGCHAR          => '%';
+use constant INFOCHAR           => '=';
+use constant INCOMINGCHAR       => '<';
+use constant SAVECHAR           => '>';
+use constant WARNCHAR           => 'W';
+use constant ERRORCHAR          => 'E';
+
 my $logger = new Log::Dispatch;
 $logger->add(new Log::Dispatch::File (name=>'logfile',
                                       filename=>$logfile,
@@ -212,7 +225,7 @@ sub log_headers {
 # Utility procedures
 
 sub _errprint {
-    printf("%s:%s", __FILE__, __LINE__);
+    printf('%s:%s', __FILE__, __LINE__);
 
     if (@_) {
         print(': ');
@@ -249,7 +262,7 @@ sub mkfolder {
     $folder = $mh . '/' . $mhfolder;
     $target = '';
 
-    if (! -d $folder) {
+    if (not -d $folder) {
         foreach $component (split('/', $folder)) {
             if (defined($component) and length($component) >= 1) {
                 $target = $target . '/' . $component;
@@ -264,6 +277,68 @@ sub mkfolder {
     }
 }
 
+sub getfiles {
+    my $dir = shift;
+    my @result;
+
+    if (not opendir(DIR, $dir)) {
+        err(&EX_TEMPFAIL, "Failed opendir($dir)");
+    }
+
+    # Initialize $! to 0 (success) because stupid stupid Perl provides
+    # no way to distinguish an error from an empty directory; that
+    # means setting $! to 0 and testing it afterwards is the only way
+    # to detect an error.  Real Programmers don't handle errors,
+    # right?  >sigh<
+    $! = 0;
+    @result = grep {
+        ($_ ne '.' and $_ ne '..')
+          and $_ = "$MAILDIR/new/$_"
+      } readdir(DIR);
+
+    if ($! != 0) {
+        err(&EX_TEMPFAIL, "Failed readdir($dir)");
+    }
+
+    closedir(DIR);
+
+    return @result;
+}
+
+sub get_highest_msgnum {
+    my $mhfolder = shift;
+    my $dir;
+    my @list;
+    my $highest;
+    my $msgnum;
+
+    $dir = "$mh/$mhfolder";
+    if (not opendir(DIR, $dir)) {
+        err(&EX_TEMPFAIL, "Failed opendir($dir)");
+    }
+
+    $! = 0;
+    @list = readdir(DIR);
+
+    if ($! != 0) {
+        err(&EX_TEMPFAIL, "Failed readdir($dir)");
+    }
+
+    closedir(DIR);
+
+    $highest = 0;
+    foreach $msgnum (@list) {
+        # Look for integers.
+        if ($msgnum =~ /^[0-9]+$/) {
+            if ($msgnum > $highest) {
+                $highest = $msgnum;
+            }
+        }
+    }
+
+    return $highest;
+}
+
 # We want to print the name of each list that has new mail only once,
 # so use this hash to store the lists that have already been printed.
 # Start the list out with SPAM already in it, since we don't care when
@@ -273,16 +348,50 @@ my %FOLDERS = ('SPAM'=>1);
 sub store_message {
     my $msg = shift;
     my $mhfolder = shift;
-    my $mhmsg;
     my $msgnum;
+    my $try;
+    my $mhmsg;
+    my $status;
 
     # We must do this even in -n mode because later steps fail without
     # it.  This should be harmless.
     mkfolder($mhfolder);
 
-    $mhmsg = `mhpath +$mhfolder new`;
-    chomp($mhmsg);
-    $msgnum = basename($mhmsg);
+    $msgnum = get_highest_msgnum($mhfolder);
+    for ($try = 0; ; $try++) {
+        $msgnum++;
+        $mhmsg = "$mh/$mhfolder/$msgnum";
+
+        if (not stat($mhmsg)) {
+            if ($!{ENOENT}) {
+                # Now we have a non-existent file, let's try to create
+                # it.  We must create a zero-byte file first because a
+                # file my appear between our happy stat results and
+                # our later rename(2), which would clobber said file.
+                # So attempt to create a file with this name.  If it
+                # succeeds, in just a bit here we'll knowingly clobber
+                # this file with the rename(2) call.
+                if ($run) {
+                    if (sysopen(MSG, "$mhmsg",
+                                O_WRONLY | O_EXCL | O_CREAT, 0600)) {
+                        close(MSG);
+                        last;
+                    }
+                } else {
+                    last;
+                }
+            }
+        }
+
+        # This algorithm is different from the maildir one; let's make
+        # 10 tries instead of 3.
+        if ($try == 9) {
+            errx(&EX_TEMPFAIL, "Attempted filename $mhmsg exists.");
+        }
+
+        # This algorithm is different; i don't think we need to sleep.
+        #sleep(2);
+    }
 
     logsave("+$mhfolder");
 
@@ -291,8 +400,15 @@ sub store_message {
             err(&EX_TEMPFAIL, "Failed rename($msg, $mhmsg)");
         }
 
+        # Mark each message as soon as we store it and bomb if that
+        # fails.  While it is slow, it is not safe to store multiple
+        # messages and then have a failure before marking some (or
+        # all).
         if ($mhfolder ne 'SPAM') {
-            system("mark +$mhfolder $msgnum -sequence unseen -add");
+            $status = system("mark +$mhfolder $msgnum -sequence unseen -add");
+            if (not (WIFEXITED($status) and WEXITSTATUS($status) == 0)) {
+                errx(&EX_TEMPFAIL, "Failed to mark message unseen");
+            }
         }
     }
 
@@ -318,7 +434,7 @@ sub get_headers {
         if (/^\s/) {
             # folded header continuation
 
-            if (!defined($current)) {
+            if (not defined($current)) {
                 print("Malformed message, cannot parse headers.\n");
                 return ();
             }
@@ -343,15 +459,14 @@ sub is_spam {
     my $msg = shift;
     my $err;
     my $sig;
+    my $line;
+    my $message;
     my $status;
 
     $err = $sig = $msg;
     $err =~ s|/new/|/err/|;
     $sig =~ s|/new/|/sig/|;
     if (-f $err) {
-        my $line;
-        my $message;
-
         open(ERR, $err);
         $line = <ERR>;
         close(ERR);
@@ -382,7 +497,9 @@ sub is_spam {
 
     if ($run) {
         $status = system("razor-check < $msg");
-        if (WIFEXITED($status) and WEXITSTATUS($status) == 0) {
+        if (not WIFEXITED($status)) {
+            err(&EX_TEMPFAIL, "Failed to run razor-check < $msg");
+        } elsif (WEXITSTATUS($status) == 0) {
             return 1;
         } else {
             return 0;
@@ -411,7 +528,7 @@ sub kill_spam {
             push(@result, $msg);
         }
     }
-    print("\nDone: ", scalar(@result), "\n");
+    print("\nDone: ", scalar(@result), " survivors\n");
 
     return @result;
 }
@@ -437,8 +554,7 @@ sub find_mh_folder {
     log_headers(%headers);
 
     foreach $header (keys(%FILTERS)) {
-        $header = lc($header);
-        $contents = $headers{$header};
+        $contents = $headers{lc($header)};
 
         if (defined($contents)) {
             foreach $regex (keys(%{$FILTERS{$header}})) {
@@ -477,7 +593,11 @@ MAIN: {
         exit(&EX_OK);
     }
 
-    @msglist = kill_spam(glob("$MAILDIR/new/*"));
+    @msglist = getfiles("$MAILDIR/new");
+
+    if (not $filteronly) {
+        @msglist = kill_spam(@msglist);
+    }
 
     if (not $spamonly) {
         filter_mail(@msglist);