#!/usr/bin/perl -w
#############################################################################
# License:
#
# dspampd (hereafter referred to as "program") is free software;
#   you can redistribute it and/or modify it under the terms of the GNU General
#   Public License as published by the Free Software Foundation; either version
#   2 of the License, or (at your option) any later version.
# Note that when redistributing modified versions of this source code, you
#   must ensure that this disclaimer and the above coder's names are included
#   VERBATIM in the modified code.
#
# Disclaimer:
# This program is provided with no warranty of any kind, either expressed or
#   implied.  It is the responsibility of the user (you) to fully research and
#   comprehend the usage of this program.  As with any tool, it can be misused,
#   either intentionally (you're a vandal) or unintentionally (you're a moron).
#   THE AUTHOR(S) IS(ARE) NOT RESPONSIBLE FOR ANYTHING YOU DO WITH THIS PROGRAM
#   or anything that happens because of your use (or misuse) of this program,
#   including but not limited to anything you, your lawyers, or anyone else
#   can dream up.  And now, a relevant quote directly from the GPL:
#
#                           NO WARRANTY
#
#  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
# FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
# OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
# PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
# OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
# TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
# PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
# REPAIR OR CORRECTION.
#
# The GNU GPL can be found at http://www.fsf.org/copyleft/gpl.html
#
# Whee, that was fun, wasn't it?  Now let's all get together and think happy
#   thoughts - and remember, the same class of people who made all the above
#   legal spaghetti necessary are the same ones who are stripping your rights
#   away with DVD CCA, DMCA, stupid software patents, and retarded legal
#   challenges to everything we've come to hold dear about our internet.
#   So enjoy your dwindling "freedom" while you can, because 1984 is coming
#   sooner than you think.  :[
#
#############################################################################
#
# Description
# 
# DspamPD is a transparent SMTP proxy daemon that passes email through DSPAM.
# It can also pass mail through ClamAV as well, providing you with a one-stop
# anti-spam / anti-virus smtp proxy with no extra perl modules!
# 
#############################################################################
#
#  Changelog:
#     
#      06/17/2004 - v2.00-rc1 - Brandon Zehm
#          - DspamPD is now mostly configured with a configuration file
#            rather than 50 command line parameters.
#          - The program was resesigned to be much more modular, 
#            and has two modules: dspam, and clamav.
#          - You can specify custom smtp responses for messages classified as
#            ham, spam, clean, infected, etc.
#          - DspamPD is designed to run with DSPAM v3.0.0 now, previous 
#            versions of dspam will not work without changing the command
#            line parameters the dspam command is run with.
#          - Too many other changes to list, but the basic functionality 
#            remains the same.
#
#      03/30/2004 - v1.01 - Brandon Zehm
#          - Changed it so the tmp files are chown'd/chmod'd after initial creation
#
#      03/30/2004 - v1.00 - Brandon Zehm
#          - Initial release
#     
#
#############################################################################
use strict;
use IO::Socket;
use IO::File;
use IPC::Open2;
use Symbol;

## Load Time::HiRes if it's available
eval { require Time::HiRes; };
unless ($@) {
    use Time::HiRes qw(time);
}


## Global Variable(s) (I use a few scalars and several hashes rather than one big hash to improve performance)

## Static variables
my $version                = 'v2.00-rc1';
my $authorName             = 'Brandon Zehm';                   ## Author's Name
my $authorEmail            = 'caspian@dotconf.net';            ## Author's Email Address

## These two are almost static, the initialize() function tweaks them ;)
my $programName            = $0;                               ## The name of this program
my $hostname               = $ENV{'HOSTNAME'};                 ## The hostname of the system we're running on

## For printing colors to the console
my $colorRed    = "\033[31;1m";
my $colorGreen  = "\033[32;1m";
my $colorCyan   = "\033[36;1m";
my $colorNormal = "\033[m";

## Dynamic variables - these get used and changed a lot.
my $debug                  = 0;                                ## Debugging level
my $configurationFile      = '/etc/dspampd.conf';              ## Default configuration file location
my $archiveDir             = '/var/spool/dspam-archive';       ## Directory to archive mail to (and use for tmp files)
my $mode                   = '';                               ## This will be 'daemon' is we are supposed to become a daemon
my $error                  = '';                               ## Error messages will sometimes get put in here

## General options (from conf file) are stored here
## The defaults set here are only used if they are not defined in the configuration file
my %general = (
    
    'nofork'                 => 0,                             ## If set to 1 script will not fork
    'pidFile'                => '/var/run/dspampd.pid',        ## Pid file to use
    'user'                   => '',                            ## User to run as
    'group'                  => '',                            ## Group to run as
    'enabled-modules'        => '',                            ## Comma separated list of "modules" to enable
    
    ## These two are only used during the configuration file parsing.
    'debug'                  => 0,
    'archive-dir'            => '',
    
);



## Logging options
## The defaults set here are only used if they are not defined in the configuration file
my %logging = (
    
    'syslog'                 => 1,                             ## Syslog messages by default (--stdout disables this)
    'facility'               => 2,                             ## Syslog faciltiy (2 == MAIL)
    'priority'               => 6,                             ## Syslog priority (6 == INFO)
    'stdout'                 => 0,                             ## Log to stdout
    'logging'                => 0,                             ## Enable or disable logging to a file
    'logFile'                => '',                            ## If logging is enabled, this is the file to log to

);


## Networking options
## The defaults set here are only used if they are not defined in the configuration file
my %networking = (
    
    'listenHost'             => '127.0.0.1',                   ## Local IP to accept smtp connections on
    'listenPort'             => 10025,                         ## Local port to accept smtp connections on
    'concurrentConnections'  => 128,                           ## The number of allowed concurrent connections in the incoming wait queue
    
    'relayHost'              => '127.0.0.1',                   ## Server name/ip to proxy smtp connections to
    'relayPort'              => 10125,                         ## Port to proxy smtp connections to
    
    'timeout'                => 360,                           ## Timeout in seconds for any/all connections
    
);


## This is a global hash to make life easy, info about the 
## current email message gets stored in here.
my %self = ();

## We need one global array for each of the modules in the configuration file
my %dspam = ();
my %clamav = ();













              
                
                
                
















#########################################################
## SUB: help
##
## hehe, for all those newbies ;)
#########################################################
sub help {
print <<EOM;

$colorCyan$programName-$version by $authorName <$authorEmail>$colorNormal

Usage:
  $programName <action> [options]
  
$colorRed  Actions: $colorNormal
    -d,--daemon                     become a daemon (i.e. start)
    --validate                      check the syntax of the configuration file
        
$colorGreen  General Options: $colorNormal
    -c <file>                       configuration file [$configurationFile]
    -n                              dont fork at startup
    -v                              verbosity - use multiple times for greater effect
    
$colorGreen  Logging Options: $colorNormal
    --nosyslog                      dont syslog anything
    --stdout                        print to STDOUT (usually used with -n)
    --logfile=<logfile>             enable logging to the specified file

EOM
exit(1);
}











######################################################################
##  Function: initialize ()
##  
##  Does all the script startup jibberish.
##  
######################################################################
sub initialize {
    
    ## Set STDOUT to flush immediatly
    $| = 1;
    
    ## Intercept signals
    $SIG{'QUIT'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
    $SIG{'INT'}   = sub { quit("EXITING: Received SIG$_[0]", 1); };
    $SIG{'KILL'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
    $SIG{'TERM'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
    
    $SIG{'HUP'}   = sub { quit("EXITING: Received SIG$_[0]", 1); };
    $SIG{'ALRM'}  = sub { quit("EXITING: Received SIG$_[0]", 1); };
    
    ## Let children exit on their own so the parent doesn't have to reap them.
    $SIG{'CHLD'}  = 'IGNORE';
    
    ## Fixup $programName
    $programName =~ s/(.)*[\/,\\]//;
    $0 = $programName . " " . join(" ", @ARGV);
    
    ## Fixup $hostname
    if ($hostname) {
        $hostname = $hostname;
        $hostname =~ s/\..*$//;
    }
    else {
        $hostname = "unknown";
    }
    
    return(0);
}











######################################################################
##  Function: processCommandLine ()
##  
##  Processes command line storing important data in global var %conf
##  
######################################################################
sub processCommandLine {
    
    
    ############################
    ##  Process command line  ##
    ############################
    
    my @ARGS = @ARGV;
    my $numargv = @ARGS;
    help() unless ($numargv);
    my $counter = 0;
    for ($counter = 0; $counter < $numargv; $counter++) {
        
        ## daemon
        if ($ARGS[$counter] =~ /^-d|--daemon$/io) {
            $mode = "daemon";
        }
        
        ## list config file sections
        elsif ($ARGS[$counter] =~ /^--list$/i) {
            $mode = "list";
        }
        
        ## validate configuration
        elsif ($ARGS[$counter] =~ /^--validate$/i) {
            $mode = "validate";
        }
        
        ## configuration file
        elsif ($ARGS[$counter] =~ /^-c$/i) {
            $counter++;
            $configurationFile = $ARGS[$counter];
        }
        
        ## no fork
        elsif ($ARGS[$counter] =~ /^-n$/io) {
            $general{'nofork'} = 1;
        }
        
        ## verbosity
        elsif ($ARGS[$counter] =~ /^-v+/io) {
            $debug += (length($&) - 1);
        }
        
        ## pid file
        elsif ($ARGS[$counter] =~ /^--pid=(.*)/io) {
            $general{'pidFile'} = $1;
        }
        
        ## syslog is disabled
        elsif ($ARGS[$counter] =~ /^--nosyslog/i) {
            $logging{'syslog'} = 0;
        }
        
        ## stdout
        elsif ($ARGS[$counter] =~ /^--stdout/i) {
            $logging{'stdout'} = 1;
        }
        
        ## log file
        elsif ($ARGS[$counter] =~ /^--logfile=(.*)/i) {
            $logging{'logFile'} = $1;
        }

        ## help
        elsif ($ARGS[$counter] =~ /^-h$|^--help/) {
            help();
        }
        
        else {
            printmsg("\"$ARGS[$counter]\" is not a recognised option!", 0);
            quit("", 1);
        }
        
    }
    
    
    ## Print help if we're not becoming a daemon.
    if (!$mode) {
        printmsg("WARNING => The -d parameter must be passed to become a daemon.",1);
        help();
    }
    
    ###################################################
    ##  Input validation
    ###################################################
    
    ## Return 0 errors
    return(0);
}













###############################################################################################
## FUNCTION:    
##   returnConfigurationFileSections ( string $filename )
## 
## 
## DESCRIPTION: 
##   Reads the file $filename, finds any defined sections, and returns a list of them.  
##   This version of this function reads .ini style files.
##
## Example: 
##   my @list = returnConfigurationFileSections("/etc/configuration.conf");
##
###############################################################################################
sub returnConfigurationFileSections {
    
    ## Get incoming variables
    my ($fileName) = @_;
    
    ## Verify input
    if ( (!$fileName) ) {
        $error = "ERROR => returnConfigurationFileSections() One or more incoming parameters were empty";
        return(1);
    }
    
    ## Open the file
    open(CONFFILE, $fileName) or quit("ERROR => Error while opening the configuration file [$fileName].  The error was [$!]",1);
    
    ## Read entire file into a scalar so we can effectivly remove c style /* */ comments
    my $file = "";
    while (<CONFFILE>) {
        $file .= $_;
    }
    close(CONFFILE);
    
    ## Remove comments and whitespace
    $file =~ s/\/\*.*?\*\///ogs;        ## Remove C Style /* */ style comments
    $file =~ s/(^|[^\\])\#.*$//ogm;     ## Remove pound (#) comments - unless backslash escaped
    $file =~ s/\\\#/\#/ogm;             ## Replace '\#' with '#' 
    $file =~ s/\/\/.*$//ogm;            ## Remove slash (//) comments 
    $file =~ s/^\s*(\n|\r\n)//ogm;      ## Remove blank lines
    
    ## Find section names and store them into an array
    my @entries = ();
    foreach my $line (split(/\r?\n/, $file)) {
        if ($line =~ /^\s*\[(.*)\]\s*$/) {
            push(@entries, $1);
        }
    }
    
    ## Check for duplicate entries
    foreach my $entry (@entries) {
        if (scalar(grep(/^$entry$/, @entries)) >= 2) {
            printmsg("WARNING => There are two alert definitions in the configuration file [$file] named [$entry]", 0);
        }
    }
    
    ## Return 0 errors
    return(@entries);
}


















###############################################################################################
## FUNCTION:    
##   readConfigurationFile ( string $filename, string $section, reference $hash_reference )
## 
## 
## DESCRIPTION: 
##   Reads the file $filename, and stores information from the file into the hash 
##   at $hash_reference.  This version of this function reads .ini style files.
##
## Example: 
##   readConfigurationFile("/etc/configuration.conf", "General Configuation", \%myHash);
##
###############################################################################################
sub readConfigurationFile {
    
    ## Get incoming variables
    my ($fileName, $section, $hashref) = @_;
    
    
    ## Verify input
    if ( (!$fileName) or (!$section) or (!$hashref) ) {
        printmsg("DEBUG => readConfigurationFile() Incoming parameters are: file: $fileName,  section: $section, hashref: $hashref", 2);
        $error = "ERROR => readConfigurationFile() One or more incoming parameters were empty";
        return(1);
    }
    
    ## Open the file
    open(CONFFILE, $fileName) or quit("ERROR => Opening the configuration file [$fileName] returned the error [$!]",1);
    
    ## Read the file into a single scalar variable
    my $file = "";
    while (<CONFFILE>) { $file .= $_; }
    close(CONFFILE);
    
    ## Remove comments and whitespace
    $file =~ s/\/\*.*?\*\///ogs;      ## Remove C Style /* */ style comments
    $file =~ s/[^\\]\#.*$//ogm;       ## Remove pound (#) comments - unless backslash escaped
    $file =~ s/\\\#/\#/ogm;           ## Replace '\#' with '#' 
    $file =~ s/\/\/.*$//ogm;          ## Remove slash (//) comments 
    $file =~ s/^\s*(\n|\r\n)//ogm;    ## Remove blank lines
    
    
    ## Find the section we want and store the lines of that section in @lines
    my $inSection = 0;
    foreach my $line (split(/\r?\n/, $file)) {
        if ($inSection == 1) {
            if ($line =~ /^\s*\[.*\]\s*$/) {
                ## We're at the end of the section (starting a new section), stop
                $inSection = 0;
                last;
            }
            else {
                ## This is a normal line in the secion, parse it and add data to $hashref
                if ($line) {
                    ## Remove whitespace
                    $line =~ s/(^\s+)|(\s+$)//og;
                    ## Don't continue unless the line looks valid
                    next if ( (!$line) or ($line !~ /=>/) );
                    ## Get and store the key/value pair
                    my ($key, $value) = split(/\s*=>\s*/, $line);
                    printmsg("DEBUG => readConfigurationFile() Found key value pair: $key => $value", 3);
                    ${$hashref}{$key} = $value;
                }
            }
        }
        ## If we found the right section, start recording it's lines to @lines
        if ($line =~ /^\s*\[$section\]\s*$/) {
            $inSection = 1;
        }
    }
    
    ## Return 0 errors
    return(0);
}














#########################################################
# FUNCTION: handleHUP()
# 
# Handles HUP signals:
#  - Logs a message to the log file
#  - Closes and opens the log file 
#
#########################################################
sub handleHUP  {
    
    printmsg("INFO => Reloading config and refreshing all file handles", 0) if ($mode eq "running");
    
    ##  Reset some variables that should be refreshed
    $logging{'logFile'} = '';
    $logging{'logging'} = 0;
    $debug = 0;
    
    
    ##  Re-read the configuration file
    readConfigurationFile($configurationFile, 'general', \%general) && do {
        quit($error, 1);
    };
    if ($general{'debug'}) { $debug += $general{'debug'}; }
    if ($general{'archive-dir'}) { $archiveDir = $general{'archive-dir'}; }
    
    readConfigurationFile($configurationFile, 'logging', \%logging) && do {
        quit($error, 1);
    };
    
    readConfigurationFile($configurationFile, 'networking', \%networking) && do {
        quit($error, 1);
    };
    
    ## You will need to add a few lines here for each new module
    readConfigurationFile($configurationFile, 'module:dspam', \%dspam) && do {
        quit($error, 1);
    };
    readConfigurationFile($configurationFile, 'module:clamav', \%clamav) && do {
        quit($error, 1);
    };
    
    ## There are a few settings I wanted to leave as normal variables to keep cpu usage low.
    if ($general{'archive-dir'}) {
        $archiveDir = $general{'archive-dir'};
        delete $general{'archive-dir'};
    }
    if ($general{'debug'}) {
        $debug = $general{'debug'};
        delete $general{'debug'};
    }
    
    ##  Re-parse the command line - it takes precedence over the configuration file
    processCommandLine();
    
    ## Debugging: Show the current configuration
    printmsg ("-- Configuration --", 3);
    printmsg ("general: ", 3);    foreach my $key (keys(%general))             { printmsg ("  $key => $general{$key}", 3) if (defined($key) and defined($general{$key})); }
    printmsg ("logging: ", 3);    foreach my $key (keys(%logging))             { printmsg ("  $key => $logging{$key}", 3) if (defined($key) and defined($logging{$key})); }
    printmsg ("networking: ", 3); foreach my $key (keys(%networking))          { printmsg ("  $key => $networking{$key}", 3) if (defined($key) and defined($networking{$key})); }
    printmsg ("module:dspam: ", 3); foreach my $key (keys(%dspam))             { printmsg ("  $key => $dspam{$key}", 3) if (defined($key) and defined($dspam{$key})); }
    printmsg ("module:clamav: ", 3); foreach my $key (keys(%clamav))           { printmsg ("  $key => $clamav{$key}", 3) if (defined($key) and defined($clamav{$key})); }
    
    
    ## If a user or group was specified then convert it to the numeric value
    if ($general{'user'}) { if ($general{'user'} =~ /\w/) {
        $general{'user'} = (getpwnam($general{'user'}))[2];
    }                 }
    if ($general{'group'}) { if ($general{'group'} =~ /\w/) {
        $general{'group'} = (getgrnam($general{'group'}))[2];
    }                 }
    
    ## Make sure the tmp dir exists
    if (! -d $archiveDir) {
        mkdir($archiveDir) or quit("ERROR => The specified archive dir [$archiveDir] does not exist, and I could not create it. $!", 1);
        chown($general{'user'}, $general{'group'}, $archiveDir);
        chmod(0775, $archiveDir);
    }
    
    ## Close and open the log file
    if ($logging{'logFile'}) {
        $logging{'logging'} = 0;
        close LOGFILE;
        if (openLogFile($logging{'logFile'})) { printmsg("ERROR => Opening the log file [$logging{'logFile'}] returned the error: $!", 0); }
        else { $logging{'logging'} = 1; }
    }
    
    ## Check the PID file - if another dpsampd process is running with the same pid file
    ## we want to quit so we don't end up with multiple instances of the same script running.
    if ($general{'pidFile'}) {
        if (checkPidFile($general{'pidFile'}) != 0) {
            quit("ERROR => Another dspampd process seems to already be running.  PID file: $general{'pidFile'}", 1);
        }
    }
    
    
    ## Go back to the normal routine (return 0 errors)
    return(0);
}














###############################################################################################
##  Function:    printmsg (string $message, int $level)
##
##  Description: Handles all messages - 
##               Depending on the state of the program it will log
##               messages to a log file, print them to STDOUT or both.
##               
##
##  Input:       $message          A message to be printed, logged, etc.
##               $level            The debug level of the message. If not defined 0
##                                 will be assumed.  0 is considered a normal message, 
##                                 1 and higher is considered a debug message.
##  
##  Output:      Prints to STDOUT, to LOGFILE, both, or none depending 
##               on the state of the program and the debug level specified.
##  
##  Example:     printmsg("ERROR => The file could not be opened!", 0);
###############################################################################################
sub printmsg {
    ## Assign incoming parameters to variables
    my ( $message, $level ) = @_;
    
    ## Make sure input is sane
    $level = 0 if (!defined($level));
    
    ## Continue only if the debug level of the program is >= message debug level.
    if ($debug >= $level) {
        
        ## Change \r\n's to spaces
        $message =~ s/\r?\n/ /go;
    
        ## Get the date in the format: Dec  3 11:14:04
        my ($sec, $min, $hour, $mday, $mon) = localtime();
        $mon = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[$mon];
        my $date = sprintf("%s %02d %02d:%02d:%02d", $mon, $mday, $hour, $min, $sec);
        
        ## Syslog the message is needed
        if ($logging{'syslog'}) {
            syslog("/dev/log", $logging{'priority'}, $logging{'facility'}, "$programName\[$$\]: $message");
        }
        
        ## Print to STDOUT always if debugging is enabled, or if the mode is NOT "running".
        if ( ($debug >= 1) or ($mode ne "running") or ($logging{'stdout'}) ) {
            print "$date $hostname $programName\[$$\]: $message\n";
        }
        
        ## Print to the log file if $logging{'logging'} is true
        if ($logging{'logging'}) {
            print LOGFILE "$date $hostname $programName\[$$\]: $message\n";
        }
        
    }
    
    ## Return 0 errors
    return(0);
}














###############################################################################################
## FUNCTION:    
##   openLogFile ( $filename )
## 
## 
## DESCRIPTION: 
##   Opens the file $filename and attaches it to the filehandle "LOGFILE".  Returns 0 on success
##   and non-zero on failure.  Error codes are listed below, and the error message gets set in
##   global variable $!.
##   
##   
## Example: 
##   openFile ("/var/log/scanAlert.log");
##
###############################################################################################
sub openLogFile {
    ## Get the incoming filename
    my $filename = $_[0];
    
    ## Make sure our file exists, and if the file doesn't exist then create it
    if ( ! -f $filename ) {
        printmsg("NOTICE => The file [$filename] does not exist.  Creating it now with mode [0600].", 0);
        open (LOGFILE, ">>$filename");
        close LOGFILE;
        chmod (0600, $filename);
    }
    
    ## Now open the file and attach it to a filehandle
    open (LOGFILE,">>$filename") or return (1);
    
    ## Put the file into non-buffering mode
    select LOGFILE;
    $| = 1;
    select STDOUT;
    
    ## Tell the rest of the program that we can log now
    $logging{'logging'} = "yes";
    
    ## Return success
    return(0);
}

















###############################################################################################
## FUNCTION:    
##   syslog (string $socketName, int $priority, int $facility, string $message)
## 
## 
## DESCRIPTION: 
##   Connects to the socket $socketName, and sends it a syslog formatted message.  
##   i.e. it syslog's $message with the priority and facility specified.
##   Returns 0 on success, non-zero on error.  If an error occurs the error message
##   is stored in the global variable $error.
##
## Example: 
##   syslog("/dev/log", 6, 1, "Test syslog message");
##
##
## Priorities (on a Linux system)
##   LOG_EMERG       0       system is unusable
##   LOG_ALERT       1       action must be taken immediately
##   LOG_CRIT        2       critical conditions
##   LOG_ERR         3       error conditions
##   LOG_WARNING     4       warning conditions
##   LOG_NOTICE      5       normal but significant condition
##   LOG_INFO        6       informational
##   LOG_DEBUG       7       debug-level messages
##
##
## Facilities (on a Linux system)
##   LOG_KERN        0       kernel messages
##   LOG_USER        1       random user-level messages
##   LOG_MAIL        2       mail system
##   LOG_DAEMON      3       system daemons
##   LOG_AUTH        4       security/authorization messages
##   LOG_SYSLOG      5       messages generated internally by syslogd
##   LOG_LPR         6       line printer subsystem
##   LOG_NEWS        7       network news subsystem
##   LOG_UUCP        8       UUCP subsystem
##   LOG_CRON        9       clock daemon
##   LOG_AUTHPRIV    10      security/authorization messages (private)
##   LOG_FTP         11      ftp daemon
##   LOG_LOCAL0      16      reserved for local use
##   LOG_LOCAL1      17      reserved for local use
##   LOG_LOCAL2      18      reserved for local use
##   LOG_LOCAL3      19      reserved for local use
##   LOG_LOCAL4      20      reserved for local use
##   LOG_LOCAL5      21      reserved for local use
##   LOG_LOCAL6      22      reserved for local use
##   LOG_LOCAL7      23      reserved for local use
##
## v1.1 - 01/16/2004 - Textual changes to error messages
## v1.2 - 03/27/2004 - Remove hashes to improve performance
###############################################################################################
sub syslog {
    
    ## Get incoming variables
    my ($socketName, $priority, $facility, $message) = @_;
    
    ## Set defaults if some variables are not defined
    $socketName  = "/dev/log"         if (!defined($socketName));
    $priority    = 6                  if (!defined($priority));
    $facility    = 1                  if (!defined($facility));
    $message     = "Default Message"  if (!defined($message));
    
    ## Bit-shift the facility (black magic)
    $facility = ($facility<<3);
    
    ## Make sure values are sane (more black magic)
    $priority = $priority & 0x07;
    $facility = $facility & 0x3f8;
    
    ## Generate syslog value for the priority and facility
    my $value = ($priority + $facility);
    
    if (! -S $socketName) {
        $error = "ERROR => The specified syslog socket [$socketName] either does not exist or is not a socket.";
        return(1);
    }
    
    ## Open a UNIX socket in dgram mode with udp protocol. 
    socket(SOCKET, PF_UNIX, SOCK_DGRAM, 0) or do { 
        $error = "ERROR => syslog(): $!";
        return(2);
    };
    
    ## Connect our socket to SOCKET
    connect(SOCKET, sockaddr_un ($socketName)) or do {
        $error = "ERROR => syslog(): $!";
        return(3);
    };
    
    ## Sending the message to the syslog socket
    print SOCKET "<$value>$message" or do {
        $error = "ERROR => syslog(): $!";
        return(4);
    };
    
    ## Close the socket
    close SOCKET;
    
    ## Return success
    return(0);
}
















###############################################################################################
## FUNCTION:
##   openPidFile ($pidfilename )
##
##
## DESCRIPTION:
##   Opens the file $pidfilename and writes the pid in there
##
## Example:
##   openPidFile ("/var/run/bla.pid");
##
###############################################################################################
sub openPidFile {
    ## Get the pidfile name
    my $pidfilename = $_[0];

    ## If $pidfilename is empty then the user has not specified a PID file and it is
    ## safe for us to return 0 and continue running.
    if (!$pidfilename) {
        printmsg("DEBUG => openPidFile() required parameter missing.", 2);
        return(1);
    }
    
    ## Open the PID file
    if (! open (PIDFILE, ">$pidfilename")) { return 1; }
    
    ## Put the pid in the file
    print PIDFILE "$$\n";
    close PIDFILE;
    if (! chmod (0600, $pidfilename)) { return 2; }
    
    ## Return success (0 errors)
    return(0);
}












###############################################################################################
## FUNCTION:
##   checkPidFile ($pidfilename )
##
##
## DESCRIPTION:
##   Returns an error (a number >= 1) if the pid file exists, and the pid specified in it references
##   a currently running dspampd process.
##   Otherwise it returns 0.
##
## Example:
##   checkPidFile ("/var/run/bla.pid");
##
###############################################################################################
sub checkPidFile {
    ## Get the pidfile name
    my $pidfilename = $_[0];
    
    printmsg("DEBUG => checkPidFile() checking to see if it's safe for us to continue running.", 1);
    
    ## If $pidfilename is empty then the user has not specified a PID file and it is
    ## safe for us to return 0 and continue running.
    if (!$pidfilename) {
        printmsg("DEBUG => checkPidFile() returning 0 since the pid file was empty (not specified.)", 2);
        return(0);
    }
    
    ## Check to see if the file exists
    if (! -e $pidfilename) {
        ## Return success if the PID file doesn't exist.
        printmsg("DEBUG => checkPidFile() returning 0 since the pid file specified doesn't exist.", 2);
        return(0);
    }
    
    ## Open the PID file.
    if (! open(PIDFILE, $pidfilename)) {
        ## Return an error if it exists but we couldn't open it.
        printmsg("DEBUG => checkPidFile() returning 1 since I couldn't open the pid file.", 2);
        return(1);
    }
    
    ## Read the PID from the file into $pid
    my $pid = <PIDFILE>;
    chomp $pid;
    close PIDFILE;
    
    ## If the PID file contains our PID it's safe to continue running.
    if ($pid == $$) {
        printmsg("DEBUG => checkPidFile() returning 0 since the PID file contains my PID.", 2);
        return(0);
    }
    
    ## Check to see if that process is running
    if (! -d "/proc/$pid") {
        ## Return success if the PID is not running
        printmsg("DEBUG => checkPidFile() returning 0 since the PID specified in the pid file is not running.", 2);
        return(0);
    }
    
    ## Open the PID cmdline file so we can get the process name for the running PID.
    if (! open(PIDFILE, "/proc/$pid/cmdline")) {
        ## Return an error if it exists but we couldn't open it.
        printmsg("DEBUG => checkPidFile() returning 2 because for some reason I wasn't able to open the file: /proc/$pid/cmdline", 2);
        return(2);
    }
    
    ## proc/xxx/cmdline can be split by \0 to get the different parts
    my $pidname = <PIDFILE>;
    $pidname =~ s/\0/ /;
    
    if ($pidname =~ /dspampd/io) {
        printmsg("DEBUG => checkPidFile() returning 3 the process referenced in the pid file [$pidname] is another dspampd process.", 2);
        return(3);
    }
    
    ## If we get to here it's safe for us to start
    printmsg("DEBUG => checkPidFile() returning 0 since the process recerenced in the pid file [$pidname] is not another dspampd process.", 2);
    return(0);
}











######################################################################
##  Function:    quit (string $message, int $errorLevel)
##  
##  Description: Exits the program, optionally printing $message.  It 
##               returns an exit error level of $errorLevel to the 
##               system  (0 means no errors, and is assumed if empty.)
##
##  Example:     quit("Exiting program normally", 0);
######################################################################
sub quit {
    my ( $message, $errorLevel ) = @_;
    $errorLevel = 0 if (!defined($errorLevel));
    
    ## Print exit message
    if ($message) { 
        ## Change the syslog facility to 3/daemon if there is an exit error.
        if ($errorLevel >= 0) {
            $logging{'facility'} = 3;
        }
        printmsg($message, 0);
    }
    
    ## Exit
    exit($errorLevel);
}












######################################################################
##  Function:    process_session ()
##  
##  Description: This function proxies one smtp email session/message.
##               It calls any enabled "modules".
##               It relies on the following functions:
##                   
##
######################################################################
sub process_session() {
    
    ## Cleanup a bunch of stuff in %self
    $self{'state'} = '';               ## Where we are at in the smtp session, mail from, rcpt to, data, etc.
    delete $self{'filename'};          ## Basename for tmp files
    delete $self{'data'};              ## Filehandle for eml tmp file
    delete $self{'nfo'};               ## Filehandle for nfo tmp file
    delete $self{'delivery_status'};   ## Used by process_session()
    delete $self{'messageID'};         ## Email's message-id header field
    delete $self{'orig_size'};         ## Size of tmp email file
    delete $self{'new_size'};          ## Size of tmp email file after modules are done
    delete $self{'archive_message'};   ## If set to true the tmp message files are not deleted
    
    ## Deliver Message
    ## 
    ## This variable tells the program what to do with the message after it's 
    ## received the message and passed it through the various enabled modules.
    ## The idea is that a module will change this variable if it wants to.
    ## 
    ##   1 = deliver message
    ##   0 = do not deliver message
    ##
    $self{'deliver_message'} = 1;
    
    ## Acceptance Speech
    ## 
    ## Similar to $self{deliver_message}, this variable is likely to be modified by 
    ## one of the modules.  This variable tells the program what to tell the originating
    ## smtp server after it's sent us the email message (after it ends a message with a .)
    ## Typically once we've received a message we want to tell the remote side we accept 
    ## the message by sending a "220 ok" message.  There are cases, however,
    ## where we may want to accept the message but not deliver it (it has a virus), or 
    ## maybe reject the message (causing a bounce) but deliver it to a mailbox anyway.
    ## 
    ## Valid settings are empty, or any valid SMTP response. Examples:
    ##
    ##    "" (empty)
    ##        Tell the originating server we accept the message.
    ##        i.e. send something like "220 message queued as D34FF87Q"
    ##
    ##    "220 ok. I'm actually discarding this message because it looks like spam."
    ##        Tell the originating server we accept the message.
    ##        In this example we may have set $self{deliver_message} 
    ##        so the end user doesn't get the message, but wanted to give the remote side
    ##        a "220 accepted" response so it doesn't bounce or try again.
    ##    
    ##    "550 Message rejected, found virus WORM.J"
    ##        This is a hard deliver error.  The originating server will
    ##        likely bounce the message.
    ##    
    ##    "450 Please try later, dspam command timed out."
    ##        Tell the originating server we had a temporary error.  This will
    ##        cause the remote server to attempt to deliver the message again later.
    ##        If a 450 response is used in conjunction with "$self{deliver_message} = 1"
    ##        the end user will end up with multiple copies of the message.
    ##
    $self{'acceptance_speech'} = '';
    
    ## Archive Message
    ## 
    ## This variable tells the program what to do with the tmp message files
    ## after we're done, either we save them (archive them) or delete them.
    ## The default is to delete them, but the idea is that a module will 
    ## change this variable if it decides we want to keep a copy of a message.
    ## For example the module_dspam() is configured by default to set this 
    ## variable to 1 if the message is spam.
    ## 
    ##   1 = archive message
    ##   0 = do not archive message
    ##
    $self{'archive_message'} = 0;
    
    
    
    ## Open two tmp files.  One is used to buffer the message before sending to dspam. 
    ## The second is used to store the To and From addresses so that if an external process
    ## wants to deliver the message later it will have that information.
    ## Both are deleted later if we don't want to archive the email.
    $self{'filename'} = "message-" . time() . "-$$";
    $self{'data'} = IO::File->new('+> ' . $archiveDir . '/' . $self{'filename'} . '.eml') or 
        quit("ERROR => Couldn't open temporary file " . $self{'filename'} . '.eml ' . $!, 14);
    $self{'nfo'} = IO::File->new('+> ' . $archiveDir . '/' . $self{'filename'} . '.nfo') or 
        quit("ERROR => Couldn't open temporary file " . $self{'filename'} . '.nfo ' . $!, 15);
    chown($general{'user'}, $general{'group'}, $archiveDir . '/' . $self{'filename'} . '.eml') if ($general{'user'} and $general{'group'});
    chown($general{'user'}, $general{'group'}, $archiveDir . '/' . $self{'filename'} . '.nfo') if ($general{'user'} and $general{'group'});
    chmod(0660, $archiveDir . '/' . $self{'filename'} . '.eml');
    chmod(0660, $archiveDir . '/' . $self{'filename'} . '.nfo');
    
    
    ## Run everything in an eval{} so we can exit gracefully if there is an error.
    eval {
        
        local $SIG{ALRM} = sub { quit("Child server process timed out!", 20); };
        
        ## start a timeout alarm  
        alarm($networking{'timeout'} * 2);
        
        ## Pass the initial greeting relayHost response to the server
        ok($self{listenerSocket}, hear($self{relaySocket})) &&
            quit("Error in proxying initial greeting: $!", 21);
        
        ##
        ## Proxy commands until we get to the data part of the transaction
        ##
        while ( $self{state} ne '.' ) {
            proxyCommand();
        }
        
        
        ##
        ## Now we have the data and need to content scan it
        ##
        $self{state} = 'content_scan';
        
        ## Run each module
        foreach my $module (split(/\s*,\s*/, $general{'enabled-modules'})) {
            my $returnCode = 0;
            
            printmsg("DEBUG => Passing message through module: $module", 1);
            
            ## Like the pretend case statement?
            CASE: {
                ## Run the message through DSPAM - message will be rewritten here
                ($module eq "dspam") && do {
                    $returnCode = module_dspam();
                    last CASE;
                };
                
                ## Run the message through clamav
                ($module eq "clamav") && do {
                    $returnCode = module_clamav();
                    last CASE;
                };
                
                ## They specified an unknown module, complain and go on
                do {
                    printmsg("ERROR => The module [$module] was not a valid module.");
                    last CASE;
                };
            }
            
            ## Report any errors from the module
            ## Set an "acceptance_speech" to a 450 error so the remote smtp server will try again later
            ## when we have the problem taken care of, and set "deliver_message" to 0 so we don't deliver
            ## the message to the end user.
            if ($returnCode) { 
                $self{'deliver_message'} = 0;
                $self{'acceptance_speech'} = "450 Temporary failure processing message, please try again later";
                ## Do some logging
                printmsg("message-id=" . $self{'messageID'} . ", module_" . $module . "_error=" . $returnCode, 0);
            }
            
            
        }
        
        
        ## Stat the file again to get it's size
        $self{new_size} = (stat($self{data}))[7] or quit("Can't stat tmp message file: $!", 28);
        
        ## Log the basics, message-id, to, size
        my $recips = scalar(@{$self{recipients}});
        printmsg("message-id=" . $self{messageID} . ", from=" . $self{from} . ", orig_size=" . $self{orig_size} . ", new_size=" . $self{new_size} . ", nrcpt=" . $recips);
        
        
        
        ##
        ## Deliver the message if we need to
        ##
        my $response = "";
        if ($self{'deliver_message'} == 1) {
            
            ## need to give the client a rewound file
            $self{data}->seek(0,0)
                or quit("message-id=" . $self{'messageID'} . ", status=error, can't rewind temp mail file: $!", 23);
            
            ## now send the data on through the client
            printmsg("DEBUG => proxying DATA", 2);
            sendData($self{'relaySocket'}, $self{'data'})
                or quit("message-id=" . $self{'messageID'} . ", status=error, failure in sendData(relaySocket, self{data}): $!", 24);
            
            ## Receive the relayhost's response
            $response =  hear($self{'relaySocket'});
            
            ## If an error was returned
            if ($response  =~ /^[45]\d{2} /om) {
                $self{'delivery_status'} = 'error';
            }
            ## or if it was successful
            elsif ($response =~ /^[23]\d{2} /om) {
                $self{'delivery_status'} = 'sent';
            }
            ## or if it was unknown
            else {
                $self{'delivery_status'} = 'unknown';
            }
            
            ## Do some logging
            foreach (@{$self{recipients}}) {
                printmsg("message-id=" . $self{'messageID'} . ", to=$_, relay=$networking{'relayHost'}:$networking{'relayPort'}, status=" . $self{delivery_status} . " (" . $response . ")", 0);
            }
            
            ## Send either the relayhost's response or the one specified by one of the modules to the originating smtp server.
            if ($self{'acceptance_speech'}) {
                $response = $self{'acceptance_speech'};
                printmsg("message-id=" . $self{'messageID'} . ", sent custom response message to originating smtp server (" . $response . ")", 0);
            }
            else {
                printmsg("DEBUG => proxying response: '" . $response . "'", 2);
            }
            ok($self{'listenerSocket'}, $response);
            
        }
        
        ##
        ## Otherwise we're not delivering the message
        ##
        else {
            
            ## Set a status to 'not_sent' so we know to not talk to the relay host
            $self{'delivery_status'} = 'not_sent';
            
            ##
            ## Send a response to the originating smtp server
            ##
            
            ## If there's a custom message we need to send the originating smtp server let's send it.
            ## This could be an accept (220) or reject (450, 550) message.
            if ($self{'acceptance_speech'}) {
                $response = $self{'acceptance_speech'};
            }
            ## If there isn't a custom response defined we should tell them the truth, we don't accept it.
            else {
                $response = "550 Message Rejected.";
            }
            
            ## Send the response
            ok($self{'listenerSocket'}, $response);
            
            ## Log what we sent
            printmsg("message-id=" . $self{messageID} . ", status=not_sent ($response)", 0);
            
            ##
            ## We don't need to send anything to the relay smtp server:
            ## most likely the next command we proxy from the originating smtp server 
            ## will be a QUIT anyway.
            ##
            
        }
        
        
        
        
        ##
        ##  Proxy any remaining commands (probably only a QUIT)
        ##
        while ( $self{'state'} !~ /^rset/io && proxyCommand()) {
            ## ...
        }
        
        
        ## Save the delivery status to the nfo file
        $self{'nfo'}->print("status=" . $self{'delivery_status'} . ", response: $response\n") if ($self{'delivery_status'});
        
        ## Close our temporary files so they are safe.
        $self{'data'}->close();
        $self{'nfo'}->close();
        
    }; # end eval block
    
    ## Stop the alarm clock
    alarm(0);
    ## Check for error in eval block
    if ($@ ne '') {
        chomp($@);
        my $msg = "ALERT => message-id=" . $self{'messageID'} . ", Error in process_session eval block: $@";
        printmsg($msg, 0);
        quit($msg, 1);
    }
    
    
    ## Unlink tmp files that we aren't archiving (or quarantining)
    if (!$self{'archive_message'}) {
        
        printmsg("DEBUG => Unlinking temporary files " . $self{'filename'} . '.eml' . ' and ' . $self{'filename'} . '.nfo', 1);
        
        ## Unlink (delete) both files
        unlink($archiveDir . '/' . $self{'filename'} . '.eml');
        unlink($archiveDir . '/' . $self{'filename'} . '.nfo');
    }
    ## Otherwise log the archived filename for future reference
    else {
        printmsg("message-id=" . $self{messageID} . ", archived_filename=" . $self{filename}, 0);
    }
    
}










## getline($socketRef)
sub getline {
    my ($socket) = @_;
    local ($/) = "\r\n";
    return readline *{$$socket};
}


## Receive a SMTP response from ($socketRef)
sub hear {
    my ($socket) = @_;
    my ($tmp, $reply);
    return undef unless defined($tmp = getline($socket));
    return("hear() socket is not open") unless ($$socket->opened);
    ## Keep reading lines if it's a multi-line response
    while ($tmp =~ /^\d{3}-/o) {
        $reply .= $tmp;
        return undef unless defined($tmp = getline($socket));
    }
    $reply .= $tmp;
    $reply =~ s/\r\n$//o;
    return $reply;
}




## ok($socketRef)
sub ok {
    my ($socket, @msg) = @_;
    @msg = ("250 ok.") unless @msg;
    return("ok() socket is not open") unless ($$socket->opened);
    print {$$socket} ("@msg\r\n") or return($!);
    return(0);
}



## fail($socketRef)
sub fail {
    my ($socket, @msg) = @_;
    @msg = ("550 no.") unless @msg;
    return("fail() socket is not open") unless ($$socket->opened);
    print {$$socket} ("@msg\r\n") or return($!);
    return(0);
}




## Sends a message to a socket postpending a CRLF
sub say {
    my ($socket, @msg) = @_;
    return("No arguments passed to say()") unless @msg;
    return("say() socket is not open") unless ($$socket->opened);
    print {$$socket} ("@msg", "\r\n") or return("write error: $!");
    return(0);
}






## Proxies a SMTP command from the listenerSocket to the relaySocket
## Returns the last command proxied
sub proxyCommand {
    my $command = getline($self{listenerSocket});
    return undef unless defined($command);
    
    ## Analize the command, saving important info into %self (to/from/data/etc)
    $command = processCommand($command);
    
    ## Don't proxy the data command, do it later
    unless ($command eq '.') {
        printmsg("DEBUG => proxying message:  '" . $command . "'", 2);
        
        ## Forward command to relayhost
        say($self{relaySocket}, $command);
        
        ## Read relayhost's response
        my $response = hear($self{relaySocket});
        printmsg("DEBUG => proxying response: '" . $response . "'", 2);
        
        ## Send relayhost's response to the "server"
        ok($self{listenerSocket}, $response);
    }
    
    # Restart the timeout alarm  
    alarm($networking{'timeout'});
    
    return($command);
}






## Sends the DATA from a filehandle to an SMTP server
## Returns the number of bytes actually written
## sendData($socket, $filehandle)
sub sendData {
    my ($socket, $filehandle) = (@_);
    local (*_);
    local ($/) = "\r\n";
    my $bytesSent = 0;
    
    ## Start the data session
    say($socket, 'DATA');
    my $response = hear($socket);
    if ($response !~ /^[23]\d{2} /om) {
        $self{'acceptance_speech'} = $response;
        $self{'status'} = 'error';
        return(0);
    }
    
    ## Use fewer writes (thanks to Sam Horrocks for the tip)
    $$socket->autoflush(0);
    while (readline *{$filehandle}) {
        ## Replcae a . at the beginning of a line with ..
        s/^\./../o;
        
        ## Send the message
        print {$$socket} ($_) or quit("write error while sending body DATA. $!", 40);
        
        ## Keep track of bytes sent
        $bytesSent += length($_);
    }
    ## restore unbuffered socket operation
    $$socket->autoflush(1);  
    
    ## Finish the session by sending a bare period.
    print {$$socket} (".\r\n") or quit("write error while ending body DATA. $!", 40);
    
    return($bytesSent);
}








##
## Processes an incoming smtp command and snarfs some important
## info, such as From/To addresses.  
## If the originating server sends a "DATA" command we receive the
## whole message body and store it in the $self{'data'} filehandle.
##
sub processCommand {
    my ($command) = @_;
    local(*_);
    
    ## Remove line ending characters
    $command =~ s/[\r\n]*$//o;
    $self{'state'} = $command;
    
    ## Command: [e]helo
    if ($command =~ s/^.?he?lo\s+//io) {  # mp: find helo|ehlo|lhlo
        # mp: determine protocol (for future use)
        if ( $command =~ /^L/io ) { 
            $self{'proto'} = "lmtp";
        } 
        elsif ( $command =~ /^E/io ) { 
            $self{'proto'} = "esmtp"; 
        } 
        else { 
            $self{'proto'} = "smtp"; 
        }
        $command =~ s/\s*$//o;
        $command =~ s/\s+/ /go;
        $self{'helo'} = $command;
    }
    
    ## Command: rset
    elsif ($command =~ s/^rset\s*//io) {
        delete $self{recipients};
    }
    
    ## Command: mail from
    elsif ($command =~ s/^mail\s+from:\s*//io) {
        ## We're starting a new email message, reset the nfo file.
        $self{nfo}->seek(0, 0) or quit("Can't rewind tmp .nfo file. $!", 34);
        $self{nfo}->truncate(0) or quit("Can't truncate tmp .nfo file. $!", 35);
        delete $self{recipients};
        ## Postfix puts a SIZE field on the RCPT TO, and I'm removing it here since the size
        ## will be changing when dspam updates the headers and I don't want to loose the end
        ## of the message or something crazy!
        $command =~ s/\s.*$//o;
        $self{from} = $command;
        $self{nfo}->print("MAIL FROM:$command\n") or quit("PF-ERROR => Error writing From address to .nfo file. $!", 27);
        $self{state} = "MAIL FROM:$command";
    }
    
    ## Command: rcpt to
    elsif ($command =~ s/^rcpt\s+to:\s*//io) {
        $command =~ s/\s.*$//o;  ## Remove ending whitespace (and any other kruft)
        $command =~ s/\s+/ /go;  ## Replace more than one space with one space
        push @{$self{recipients}}, $command;
        $self{nfo}->print("RCPT TO:$command\n") or quit("PF-ERROR => Error writing a To address to .nfo file. $!", 27);
    }
    
    ## Command: data
    ## We're ready to receive the DATA (actual email message)
    ## We store the message in the file at the $self{data} filehandle.
    elsif ($command =~ /^data/io) {
        $self{'data'}->seek(0,0) or quit("Can't rewind tmp message file. $!", 32);
        $self{'data'}->truncate(0) or quit("Can't truncate tmp message file. $!", 33);
        
        printmsg("DEBUG => received message: $command", 2);
        ## Tell the originating smtp server it's ok to send us the message
        ok($self{'listenerSocket'}, '354 End data with <CR><LF>.<CR><LF>');
        
        my $inHeader=1;
        while (defined($_ = getline($self{'listenerSocket'}))) {
            
            ## If we're at the end of the message set the file pointer to the beginning 
            ## of the file, get the file's size, and return a state of '.'
            if ($_ eq ".\r\n") {
                $self{'data'}->seek(0,0) or quit("Can't rewind tmp message file. $!", 34);
                ## Get filesize
                $self{orig_size} = (stat($self{data}))[7] or quit("Can't stat tmp message file: $!", 22);
                ## Set new_size to "unchanged" until we scan if (if we do)
                $self{'new_size'} = "(unchanged)";
                $self{'messageID'} = "(unknown)" unless $self{'messageID'};
                printmsg("DEBUG => successfully received email message", 1);
                return $self{'state'} = '.';
            }
            
            ## Replace two dots at the beginning of a line with just one as per RFC
            s/^\.\./\./o;
            
            ## Write each line to the tmp file
            $self{'data'}->print($_) or quit("write error saving data: $!", 26);
            
            if ($inHeader) {
                ## If we just hit the last line of headers, go on.
                if (/^\r?\n$/o) {
                    $inHeader = 0;
                }
                ## Find the Message-ID for logging
                elsif (/^Message-Id:\s+(.*?)\s*$/io) {
                    $self{'messageID'} = $1;
                }
                ## The Message-ID might be on a separate line
                elsif (/^Message-Id:\s*$/io) {
                    $_ = getline($self{'listenerSocket'}) or quit("PF-ERROR => getline failed while looking for message-id", 27);
                    if (/^\s+(.*)\s*$/) {
                        $self{'messageID'} = $1;
                    }
                }
                if ($self{'messageID'}) {
                    while($self{'messageID'} =~ s/\([^\(\)]*\)//o) {};    # remove comments and
                    $self{'messageID'} =~ s/^\s+|\s+$//go;                # leading and trailing spaces
                    $self{'messageID'} =~ s/\s.*$//o;                     # keep only the first token
                    
                    ## Pretend we're not in the header anymore, since we got what we were looking for
                    $inHeader = 0;
                }
            }
        }
    }
    
    return $self{'state'};
}









##
## DSPAM Module
##
## Returns 0 on success, text message on most errors.
##
sub module_dspam {
    
    ## Output lists with a , delimeter by default
    local ($") = ",";
    
    ## Make sure some variables are OK
    $dspam{'spamResult'} = '';
    if (!$dspam{'max-size'}) { $dspam{'max-size'} = 0; }
    if (!$dspam{'additional-arguments'}) { $dspam{'additional-arguments'} = ''; }
    if (!$dspam{'deliver'}) { $dspam{'deliver'} = 'all'; }
    if (!$dspam{'archive'}) { $dspam{'archive'} = 'none'; }
    if (!$dspam{'dspam-command'}) { $dspam{'dspam-command'} = `which dspam`; }
    if (!$dspam{'training-mode'}) { $dspam{'training-mode'} = 'tum'; }
    if (! -x $dspam{'dspam-command'}) { return("ERROR => The dspam binary couldn't be located or is not executable!"); }
    ## Decide what to use for the dspam-user field
    unless ($dspam{'dspam-user'}) {
        if (${$self{recipients}}[0]) {
            ## Use the first (only?) recepient as the user if a static one wasn't specified in the conf file
            $dspam{'dspam-user'} = ${$self{recipients}}[0];
            ## Remove angled arrows on addresses like: <caspian@dotconf.net>
            $dspam{'dspam-user'} =~ s/^<|>$//go;
        }
        else {
            $dspam{'dspam-user'} = "unknown";  ## Just to be safe ;)
        }
    }
    
    ## Only process message under max-size KB
    if ( ($dspam{'max-size'} != 0) and ($self{'orig_size'} > ($dspam{'max-size'} * 1024))) {
        printmsg("message-id=" . $self{'messageID'} . ", didn't dspam scan large message (". sprintf("%1.2f", $self{'orig_size'} / 1024) ." KB)", 0);
        $self{'new_size'} = "(unscanned)";
        $dspam{'spamResult'} = 'Unscanned';
    }
    
    ## Analyze everything else
    else {
        
        
        ## Setup the dspam command line to use
        my $command = 
            $dspam{'dspam-command'} . 
            " --mode=" . $dspam{'training-mode'} . 
            " --user '" . $dspam{'dspam-user'} . "'" . 
            " --deliver=innocent,spam" . 
            " --stdout" . 
            " --process" . 
            " " . $dspam{'additional-arguments'};
            
        printmsg("DEBUG => module_dspam() dspam command: $command", 2);
        
        ## Start a timer
        my $timeStart = time();
        
        ## Open a pipe to/from DSPAM
        my $readFH = gensym();
        my $writeFH = gensym();
        my $pid = open2($readFH, $writeFH, $command);
        
        ## Fixme, do we need an alarm to make sure dspam doesnt hang?
        ## Catch errors if launching dspam fails (permission denied)
        
        ##
        ## Pipe lines from file to DSPAM
        ##
        $self{data}->seek(0,0) or return("Can't rewind tmp message file. $!");
        printmsg("DEBUG => module_dspam() Piping message to dspam", 1);
        while (readline *{$self{data}}) {
            ## DSPAM doesn't like \r's or die "Can't print to message file: $!"; 
            $_ =~ s/\r//go;
            print {$writeFH} $_ or return("Can't print to DSPAM process. $!"); 
        }
        ## Close DSPAM's STDIN so it knows we're done talking to it
        close($writeFH);
        
        ##
        ## Read message from DSPAM, grabbing only the X-DSPAM headers
        ##
        my $inHeader=1;
        my $dspamHeaders = '';
        printmsg("DEBUG => module_dspam() Reading message from dspam", 2);
        while (readline *{$readFH}) {
            
            ## Make sure each line has a \r\n on it, have to follow RFC!
            chomp($_);
            $_ .= "\r\n";
            
            if ($inHeader) {
                ## If we just hit the last line of headers, stop reading from dspam and go on.
                if (/^\r\n$/o) { 
                    $inHeader = 0;
                    last;
                }
                ## Find the X-DSPAM-Result
                elsif (/^X-DSPAM-Result: (.*)\r\n$/o) {
                    $dspam{'spamResult'} = $1;
                }
                ## Find all X-DSPAM headers, and save them so we can post-pend them to the 
                ## the headers when delivering the message to relayhost.
                if (/^X-DSPAM-(Result|Probability|Signature|Confidence)/o) {
                    $dspamHeaders .= $_;
                }
            }
        }
        close($readFH);
        printmsg("DEBUG => module_dspam() Done reading message from dspam", 2);
        
        ## Calculate how long the content scan took
        my $timeTotal = sprintf("%1.2f", time() - $timeStart);
        
        ## Log weather it was innocent or spam
        printmsg("message-id=" . $self{messageID} . ", X-DSPAM-Result=" . $dspam{'spamResult'} . ", scan_time=" . $timeTotal);
        
        ## Now we have the fun job of copying the whole message into memory and 
        ## back into the filehandle with the DSPAM headers in place if the conf
        ## files says to write dspam headers.
        if ($dspam{'write-headers'}) {
            printmsg("DEBUG => module_dspam() Writing dspam headers into message", 1);
            $self{data}->seek(0,0) or return("Can't rewind tmp message file. $!");
            $inHeader = 1;
            my @lines = ();
            while (readline *{$self{data}}) {
                
                if ($inHeader) {
                    ## Postpend the DSPAM headers to the end of the headers.
                    if (/^\r\n$/) {
                        $inHeader = 0;
                        push(@lines, $dspamHeaders, $_);
                    }
                    ## Leave the rest of the headers unchanged, but drop incoming X-DSPAM headers.
                    else {
                        push(@lines, $_) unless (/^X-DSPAM-/o);
                    }
                }
                else {
                    ## Save the rest into an array
                    push(@lines, $_);
                }
            }
            
            ## Rewind and blank the file
            $self{data}->seek(0,0) or return("Can't rewind tmp message file. $!");
            $self{data}->truncate(0) or return("Can't truncate tmp message file. $!");
            ## Write the modified message to the file
            foreach (@lines) {
                $self{data}->print($_);
            }
        }
        
        ## Rewind the file
        $self{data}->seek(0,0) or return("Can't rewind tmp message file. $!");
        
        ## Stat the file again to get it's size
        $self{new_size} = (stat($self{data}))[7] or return("Can't stat tmp message file: $!");
        
        ## Check to see if the file got smaller, if it did log an error and send a 450 response back.
        if ($self{orig_size} > $self{new_size}) {
            return("Error, message appears to have gotten smaller after dspam.  orig_size: $self{orig_size}  new_size: $self{new_size}");
        }
    }
    
    
    ##
    ## Use configuration file options to make a few decisions about:
    ##   1. Do we stop delivery the message?
    ##   2. Do we mark the message for archiving?
    ##   3. Do we have a custom SMTP response to send to the originating smtp server?
    ##
    ## The default behavior is to deliver all messages, never archive a message, and
    ## use the SMTP response received from the "relayhost" smtp server.
    ##
    
    CASE: {
        
        ## Innocent (ham)
        ($dspam{'spamResult'} eq 'Innocent') && do {
            ## Do we deliver it?
            if ($dspam{'deliver'} =~ /^(spam|unscanned|none)$/io) { 
                $self{'deliver_message'} = 0;
                printmsg("DEBUG => module_dspam() Message will not be delivered.  (Delivery Mode: " . $dspam{'deliver'} . ")", 1);
            }
            ## Do we archive it?
            if ($dspam{'archive'} =~ /^(ham|all)$/io) {
                $self{'archive_message'} = 1;
                printmsg("DEBUG => module_dspam() Message marked for archiving.  (Archive Mode: " . $dspam{'archive'} . ")", 1);
            }
            ## Do we have a custom response?
            if ($dspam{'ham-custom-response'}) {
                $self{'acceptance_speech'} = $dspam{'ham-custom-response'};
                printmsg("DEBUG => module_dspam() " . $dspam{'spamResult'} . " message has custom SMTP response: " . $self{'acceptance_speech'}, 1);
            }
            
            last CASE;
        };
        
        ## Unscanned (mail larger than max-size)
        ($dspam{'spamResult'} eq 'Unscanned') && do {
            ## Do we deliver it?
            if ($dspam{'deliver'} =~ /^(spam|none)$/io) { 
                $self{'deliver_message'} = 0;
                printmsg("DEBUG => module_dspam() Message will not be delivered.  (Delivery Mode: " . $dspam{'deliver'} . ")", 1);
            }
            ## Do we archive it?
            if ($dspam{'archive'} =~ /^(ham|unscanned|all)$/io) {
                $self{'archive_message'} = 1;
                printmsg("DEBUG => module_dspam() Message marked for archiving.  (Archive Mode: " . $dspam{'archive'} . ")", 1);
            }
            ## Do we have a custom response?
            if ($dspam{'unscanned-custom-response'}) {
                $self{'acceptance_speech'} = $dspam{'unscanned-custom-response'};
                printmsg("DEBUG => module_dspam() " . $dspam{'spamResult'} . " message has custom SMTP response: " . $self{'acceptance_speech'}, 1);
            }
            
            last CASE;
        };
        
        ## Spam
        ($dspam{'spamResult'} eq 'Spam') && do {
            ## Do we deliver it?
            if ($dspam{'deliver'} =~ /^(ham|unscanned|none)$/io) { 
                $self{'deliver_message'} = 0;
                printmsg("DEBUG => module_dspam() Message will not be delivered.  (Delivery Mode: " . $dspam{'deliver'} . ")", 1);
            }
            ## Do we archive it?
            if ($dspam{'archive'} =~ /^(spam|all)$/io) {
                $self{'archive_message'} = 1;
                printmsg("DEBUG => module_dspam() Message marked for archiving.  (Archive Mode: " . $dspam{'archive'} . ")", 1);
            }
            ## Do we have a custom response?
            if ($dspam{'spam-custom-response'}) {
                $self{'acceptance_speech'} = $dspam{'spam-custom-response'};
                printmsg("DEBUG => module_dspam() " . $dspam{'spamResult'} . " message has custom SMTP response: " . $self{'acceptance_speech'}, 1);
            }
            
            last CASE;
        };
        
        
        ## None of the above matched, exit fake case statement.
        do {
            last CASE;
        };
    };
    
    
    ## Return 0 errors
    return(0);
}









##
## ClamAV Module
##
## Returns 0 on success, text message on most errors.
##
sub module_clamav {
    
    ## Output lists with a , delimeter by default
    local ($") = ",";
    
    ## Make sure some variables are OK
    $clamav{'scanResult'} = '';
    if (!$clamav{'max-size'}) { $clamav{'max-size'} = 0; }
    if (!$clamav{'deliver'}) { $clamav{'deliver'} = 'all'; }
    if (!$clamav{'archive'}) { $clamav{'archive'} = 'none'; }
    
    ## Only process message under max-size KB
    if ( ($clamav{'max-size'} != 0) and ($self{'orig_size'} > ($clamav{'max-size'} * 1024))) {
        printmsg("message-id=" . $self{'messageID'} . ", didn't clamav scan large message (". sprintf("%1.2f", $self{'orig_size'} / 1024) ." KB)", 0);
        $self{'new_size'} = "(unscanned)";
        $clamav{'scanResult'} = 'Unscanned';
    }
    
    ## Analyze everything else
    else {
        
        ## Fixme: We should read the clamd conf file and see how to connect to it
        
        ## Start a timer
        my $timeStart = time();
        
        ## Connect to the clamd server
        $SIG{'ALRM'} = sub { quit("ERROR => module_clamav() Timeout while connecting to localhost:3310  There was no response after $networking{'timeout'} seconds.", 1); };
        alarm($networking{'timeout'});
        my $SERVER = IO::Socket::INET->new( PeerAddr  => '127.0.0.1',
                                            PeerPort  => '3310',
                                            Proto     => 'tcp',
                                            Autoflush => 1,
                                            Blocking  => 1,
                                            timeout   => $networking{'timeout'},  ## FIXME should this be a separate timeout value?
        ) or return("ERROR => module_clamav() Connection attempt to localhost:3310 failed: $@", 1);
        alarm(0);
        
        ##
        ## Tell clamd to scan our file
        ##
        printmsg("DEBUG => module_clamav() telling clamd to scan " . $archiveDir . '/' . $self{'filename'} . '.eml', 1);
        print $SERVER 'CONTSCAN ' . $archiveDir . '/' . $self{'filename'} . '.eml';
        
        ##
        ## Read the result from clamd
        ##
        
        ## Read a response from the server
        printmsg("DEBUG => module_clamav() reading response from clamd", 3);
        $SIG{'ALRM'} = sub { $error = "alarm"; $SERVER->close(); };
        alarm($networking{'timeout'});
        my $result; 
        my $bytes = $SERVER->sysread($result, 1480);
        alarm(0);
        
        ## Generate an alert if we timed out
        if ($error eq "alarm") {
            $error = "ERROR => module_clamav() Timeout while reading from localhost:3310 There was no response after $networking{'timeout'} seconds.";
            return(1);
        }
        
        ## Make sure the server actually responded
        if ($bytes == 0) {
            $error = "ERROR => module_clamav() localhost:3310 returned a zero byte response to our query.";
            return(2);
        }
        
        ## Disconnect from the server
        close($SERVER);
        
        ## Calculate how long the content scan took
        my $timeTotal = sprintf("%1.2f", time() - $timeStart);
        
        ## Check the response for an OK or FOUND message, the message is Clean.
        my $clamavHeaders = "";
        if ($result =~ /.*\s+OK$/o) {
            ## Log that it was clean
            printmsg("message-id=" . $self{messageID} . ", X-CLAMAV-Result=Clean, scan_time=" . $timeTotal, 0);
            $clamavHeaders = "X-CLAMAV-Result: Clean\r\n";
            $clamav{'scanResult'} = "Clean";
        }
        
        ## Else if it was infected
        ## Sample text if infected: /tmp/message-1086813102.28732-2917.eml: Worm.SomeFool.AB FOUND
        elsif ($result =~ /^.*:\s+([a-zA-Z.\-=0-9]+)\s+FOUND$/o) {
            ## Log that it was infected
            printmsg("message-id=" . $self{messageID} . ", X-CLAMAV-Result=Infected, virus=$1, scan_time=" . $timeTotal, 0);
            $clamavHeaders = "X-CLAMAV-Result: Infected ($1)\r\n";
            $clamav{'scanResult'} = "Infected";
        }
        
        ## Otherwise something bad happened
        else {
            printmsg("message-id=" . $self{messageID} . ", X-CLAMAV-Result=UNKNOWN, scan_time=" . $timeTotal, 0);
            printmsg("message-id=" . $self{messageID} . ", ERROR while running clamav scan! Help!", 0);
            printmsg("message-id=" . $self{messageID} . ", Message from CLAMAV was: $result", 0);
            return("ERROR => module_clamav() ClamAV scan result did not look valid. Please investigate.");
        }
        
        ## Now we have the fun job of copying the whole message into memory and 
        ## back into the filehandle with the CLAMAV headers in place if the conf
        ## files says to write-headers.
        if ($clamav{'write-headers'}) {
            printmsg("DEBUG => module_clamav() Writing clamav headers into message", 1);
            $self{data}->seek(0,0) or return("Can't rewind tmp message file. $!");
            my $inHeader = 1;
            my @lines = ();
            while (readline *{$self{data}}) {
                
                if ($inHeader) {
                    ## Postpend the CLAMAV headers to the end of the headers.
                    if (/^\r\n$/) {
                        $inHeader = 0;
                        push(@lines, $clamavHeaders, $_);
                    }
                    else {
                        push(@lines, $_);
                    }
                }
                else {
                    ## Save the rest into an array
                    push(@lines, $_);
                }
            }
            
            ## Rewind and blank the file
            $self{data}->seek(0,0) or return("Can't rewind tmp message file. $!");
            $self{data}->truncate(0) or return("Can't truncate tmp message file. $!");
            ## Write the modified message to the file
            foreach (@lines) {
                $self{data}->print($_);
            }
        }
        
        ## Rewind the file
        $self{data}->seek(0,0) or return("Can't rewind tmp message file. $!");
        
        ## Stat the file again to get it's size
        $self{new_size} = (stat($self{data}))[7] or return("Can't stat tmp message file: $!");
        
        ## Check to see if the file got smaller, if it did log an error and send a 450 response back.
        if ($self{orig_size} > $self{new_size}) {
            return("ERROR => module_clamav() Message appears to have gotten smaller after clamav.  orig_size: $self{orig_size}  new_size: $self{new_size}");
        }
        
    }
    
    
    
    
    ##
    ## Use configuration file options to make a few decisions about:
    ##   1. Do we stop delivery the message?
    ##   2. Do we mark the message for archiving?
    ##   3. Do we have a custom SMTP response to send to the originating smtp server?
    ##
    ## The default behavior is to deliver all messages, never archive a message, and
    ## use the SMTP response received from the "relayhost" smtp server.
    ##
    
    CASE: {
        
        ## Clean (innocent)
        ($clamav{'scanResult'} eq 'Clean') && do {
            ## Do we deliver it?
            if ($clamav{'deliver'} =~ /^(infected|unscanned|none)$/io) { 
                $self{'deliver_message'} = 0;
                printmsg("DEBUG => module_clamav() Message will not be delivered.  (Delivery Mode: " . $clamav{'deliver'} . ")", 1);
            }
            ## Do we archive it?
            if ($clamav{'archive'} =~ /^(clean|all)$/io) {
                $self{'archive_message'} = 1;
                printmsg("DEBUG => module_clamav() Message marked for archiving.  (Archive Mode: " . $clamav{'archive'} . ")", 1);
            }
            ## Do we have a custom response?
            if ($clamav{'clean-custom-response'}) {
                $self{'acceptance_speech'} = $clamav{'clean-custom-response'};
                printmsg("DEBUG => module_clamav() " . $clamav{'scanResult'} . " message has custom SMTP response: " . $self{'acceptance_speech'}, 1);
            }
            
            last CASE;
        };
        
        ## Unscanned (mail larger than max-size)
        ($clamav{'scanResult'} eq 'Unscanned') && do {
            ## Do we deliver it?
            if ($clamav{'deliver'} =~ /^(infected|none)$/io) { 
                $self{'deliver_message'} = 0;
                printmsg("DEBUG => module_clamav() Message will not be delivered.  (Delivery Mode: " . $clamav{'deliver'} . ")", 1);
            }
            ## Do we archive it?
            if ($clamav{'archive'} =~ /^(clean|unscanned|all)$/io) {
                $self{'archive_message'} = 1;
                printmsg("DEBUG => module_clamav() Message marked for archiving.  (Archive Mode: " . $clamav{'archive'} . ")", 1);
            }
            ## Do we have a custom response?
            if ($clamav{'unscanned-custom-response'}) {
                $self{'acceptance_speech'} = $clamav{'unscanned-custom-response'};
                printmsg("DEBUG => module_clamav() " . $clamav{'scanResult'} . " message has custom SMTP response: " . $self{'acceptance_speech'}, 1);
            }
            
            last CASE;
        };
        
        ## Infected
        ($clamav{'scanResult'} eq 'Infected') && do {
            ## Do we deliver it?
            if ($clamav{'deliver'} =~ /^(clean|unscanned|none)$/io) { 
                $self{'deliver_message'} = 0;
                printmsg("DEBUG => module_clamav() Message will not be delivered.  (Delivery Mode: " . $clamav{'deliver'} . ")", 1);
            }
            ## Do we archive it?
            if ($clamav{'archive'} =~ /^(infected|all)$/io) {
                $self{'archive_message'} = 1;
                printmsg("DEBUG => module_clamav() Message marked for archiving.  (Archive Mode: " . $clamav{'archive'} . ")", 1);
            }
            ## Do we have a custom response?
            if ($clamav{'infected-custom-response'}) {
                $self{'acceptance_speech'} = $clamav{'infected-custom-response'};
                printmsg("DEBUG => module_clamav() " . $clamav{'scanResult'} . " message has custom SMTP response: " . $self{'acceptance_speech'}, 1);
            }
            
            last CASE;
        };
        
        
        ## None of the above matched, exit fake case statement.
        do {
            last CASE;
        };
    };
    
    
    
    ## Return 0 errors
    return(0);
    
}
































#############################
##
##      MAIN PROGRAM
##
#############################

## Initialize signal handlers and such
initialize();

## Process Command Line
processCommandLine();

## Validate the configuration file if that's our mode
if ($mode eq "validate") {
    print "\nSorry, this feature is not implemented yet!\n\n";
    quit("", 0);
    ## if (validateConfigurationFile($configurationFile)) {
    ##     printmsg($error, 0) if ($error);
    ##     ## Fixme: how should this work?
    ##     quit($error, 1);
    ## }
    ## else {
    ##     quit("Syntax OK.", 0);
    ## }
}

## Print a list of available commands if that's our mode
if ($mode eq "list") {            
    my @list = returnConfigurationFileSections($configurationFile);
    if (scalar(@list)) {
        print "Configuration file sections:\n";
        foreach (@list) { print "    $_\n"; }
        print "\n";
        quit("",0);
    }
    else {
        quit("There are no sections found in the configuration file!", 1);
    }
}

## Do all the other initialization stuff - the same as a HUP signal would do, so I just call that function.
handleHUP();




#########################
##                     ##
##  MAIN PROGRAM LOOP  ##
##                     ##
#########################


## Become deamon
if ($mode =~ /daemon/i) {
    
    if ( ($debug >= 1) or ($general{'nofork'}) or (fork() == 0) ) {
        
        ## Write the pidfile (or quit)
        if ($general{'pidFile'}) {
            if (openPidFile($general{'pidFile'})) { quit("ERROR => Opening the file [$general{'pidFile'}] returned the error: $!", 1); }
        }
        
        ## Open a network port and listen for incoming connections
        printmsg("DEBUG => Opening tcp port $networking{'listenHost'}:$networking{'listenPort'} and listening for up to $networking{'concurrentConnections'} connections.", 1);
        alarm($networking{'timeout'});
        my $listenSocket = IO::Socket::INET->new(  LocalAddr => $networking{'listenHost'},
                                                   LocalPort => $networking{'listenPort'},
                                                   Proto     => 'tcp',
                                                   Listen    => $networking{'concurrentConnections'},
                                                   Reuse     => 1,
                                                   Autoflush => 1,
                                                   Blocking  => 1,
        ) or quit("ERROR => bind to tcp port $networking{'listenHost'}:$networking{'listenPort'} failed. $!",1);
        alarm(0);
        $self{'listenSocket'} = \$listenSocket;
        
        ## Setup HUP handler function - this will re-open the log file, etc
        $SIG{'HUP'} = sub { handleHUP(); };
        
        ## Setup a SIGUSR1 handler, this will tell us to stop accepting new connections... 
        # i.e. in preparation for a service restart.
        $SIG{'USR1'} = sub { 
            printmsg("INFO => Received SIGUSR1, not accepting any new connections.");
            $self{'listenSocket'}->close(); 
        };
        
        ## Fixme: setup a SIGUSR2 handler that will make it start accepting connections again.
        ## Fixme: setup a signal that will tell a running dspampd to log some stats.
        
        ## Set the mode to running so that messages get logged rather than printed to the screen
        $mode = "running";
        
        ## Tell the user that we have started successfully
        printmsg("INFO => Daemon mode started successfully", 0);
        
        ## Forever
        while (1) {
            
            ##
            ## See if we're ready to accept a new connection, we don't want to have more than
            ## $maxChildren children running at once.
            ##
            ## Fixme
            ## This could be done with a simple socket in /tmp/ that the children write to when
            ## they are exiting.. could include stats like "innocent, processing took 0.24 seconds"
            ##
            
            ## Cleanup a few things in %self
            delete $self{'listenerSocket'};    ## The filehandle for the smtp server connection we are proxying from (i.e. this server connected to us)
            delete $self{'relaySocket'};       ## The filehandle for the smtp server connection we are proxying to
            
            ## Accept an incoming connection
            quit("ERROR => \$listenSocket is not defined! What happened to it!?", 1) if (!$listenSocket);
            printmsg("DEBUG => Accepting an incoming connection on $networking{'listenHost'}:$networking{'listenPort'}", 2);
            my $listenerSocket = $listenSocket->accept();
            $self{'listenerSocket'} = \$listenerSocket;
            
            ## We must have been interrupted while accepting a connection, try again.
            if (!$listenerSocket or !$listenerSocket->connected()) { next; }
            
            ## Fork sub-process for each new connection
            my $pid = fork();
            if (!$pid) {
                
                ## SIGHUP shouldn't do anything to a child process.
                $SIG{'HUP'}   = sub { printmsg("INFO => Child received SIG$_[0] but is ignoring it", 1); };
                
                ## Same for USR1
                $SIG{'USR1'}  = sub { printmsg("INFO => Child received SIG$_[0] but is ignoring it", 1); };
                
                ## SIGPIPE indicates that one of the connections has been severed, or DSPAM died.
                $SIG{'PIPE'}  = sub { printmsg("INFO => Child received SIG$_[0] but is ignoring it", 0); };
                
                ##  Drop permissions
                $> = $general{'user'} if ($general{'user'});
                $) = $general{'group'} if ($general{'group'});
                
                ## Fixme, how are we going to proxy for more than one domain?
                ## do we wait until we know the rcpt to: list before we connect
                ## to a remote server?
                
                ## Connect to $networking{'relayHost'}
                my $relaySocket = IO::Socket::INET->new(      PeerAddr  => $networking{'relayHost'},
                                                              PeerPort  => $networking{'relayPort'},
                                                              Proto     => 'tcp',
                                                              Autoflush => 1,
                                                              Blocking  => 1,
                ) or quit("WARNING => Child process exiting. Connect to $networking{'relayHost'}:$networking{'relayPort'} failed. Error was: $!",1);
                $self{'relaySocket'} = \$relaySocket;
                
                ## Process the SMTP session (this scans it and everything)
                ## We loop if the server sends us a rset at the end so we can support pipelining.
                $self{'state'} = 'rset';
                while ( $self{'state'} =~ /^rset/io ) {
                    ## Start a timer
                    my $timeStart = time();
                    
                    ## Proxy / scan one email message
                    process_session();
                    
                    ## Calculate how long the entire process took
                    my $timeTotal = sprintf("%1.2f", time() - $timeStart);
                    
                    ## Log weather it was innocent or spam
                    printmsg("DEBUG => Total time for process_session(): $timeTotal seconds", 1);
                }
                
                ## Cleanup and exit
                close $listenSocket;
                close $relaySocket;
                quit("",0);  ## This may change later if we want a child to handle more than one email
            
            }  ## End of forked process
            
            ## Parent closes this socket so the child can process it
            ## and the parent can accept a new connection.
            $listenerSocket->close() if ($listenerSocket and $listenerSocket->connected());
            
        }  ## End of main program loop
        
    }
    else {
        ## The original parent process exits here
        quit("",0);
    }
    
}

## Program should never get here, but just in case:
quit("ERROR => I shouldn't ever exit here!",1);

