#!/usr/bin/perl -w
# ftptrackd.pl - Michael Karr
# part of ftptrack
# ftp watcher daemon.

# Please send all errors/bugs/requests to mkarr@hostgator.com

use Proc::Daemon;
use Getopt::Long;
use File::Tail;
use Sys::Syslog;
use Sys::Hostname;
use LWP::UserAgent;
use POSIX qw(:signal_h :errno_h :sys_wait_h);
use Time::Local;
use LWP::Simple;
use IO::Socket;

# globals

my $ftplog = "/var/log/messages";
my $hostname = hostname;
my @downloads;
my @uploads;
my @regexlist;
my $start = undef;
my $stop = undef;
my $curuser;

if ( -e "/opt/hgmods/gatorftplist" ) {
	open(FILE, "/opt/hgmods/gatorftplist");
	@regexlist = <FILE>;
	close(FILE);
}
# begin main

$0 = "gatorftptrackd"; # set proc name

GetOptions ('start' => \$start,
            'stop' => \$stop);

my $daemon = Proc::Daemon->new(work_dir => "/var/run",
                               pid_file => "$0.pid");

chdir $daemon->{work_dir}; # change to working directory (bug in Proc::Daemon?, doesn't chdir when trying to use status methods)

if ($start) {
    if ($daemon->Status()) {
        print "gatorftptrackd seems to already be running. Maybe a stale PID file?\n";
    } else {
        print "Starting gatorftptrackd.\n";
        
        my $pid = $daemon->Init();
        
        if ($pid == 0) { # we are in the child proc, start watching
            my $living = 1;
            sigaction(SIGTERM, POSIX::SigAction->new(sub {$living = 0}, POSIX::SigSet->new(SIGTERM))); # trap SIGTERM so we can die cleanly
            
            messagelog ("Started successfully, beginning to watch.");
        
            # begin watching log
            
            $log = File::Tail->new($ftplog);
            my $curhour;
            my $symcount;
            while (defined(my $line = $log->read()) && $living) {
                chomp($line);
                $symcount = 0;
                #Oct 17 14:00:57 gator742 pure-ftpd: (?@125.25.9.122) [INFO] koirich is now logged in
                
                my ($month, $day, $time, $host, $service, $user, undef, $filename, $type, $size) = split(' ', $line);
    
                if (( $service eq "kernel:") && ($user eq "Illegal") ) { 
                    if (($line =~ /\.cpanel\/quickinstall/) || ($line =~ /tmp\/magick/)) { next; }
                    my $curhour = (split(':', $time))[0];
                    if ($hour != $curhour) {
                        $hour = $curhour; 
                        $symcount = 0; 
                    } else {
                        $symcount++;
                        if ($symcount < 1000) {
                            process_symlink($line, $symcount); 
                        }
                     
                    }
                    next;
                }
                $user =~ /([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})/;
                my $ip = $1;
                if ($line =~ /\?@([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\) \[WARNING\] Authentication failed for user \[(\S+)\]/ ) {
			my $msg = $1 . ':' . $2 . ':' . $hostname;
                        my $sock = IO::Socket::INET->new(Proto     => 'udp', PeerPort  => 2083, PeerAddr  => '192.185.178.101');
                        $sock->send($msg);
                        next;
                }
                if (!$size) { next; }
                $size =~ s/\(// ;

                if (!$ip) { next; }
                $ip =~ s/\)// ; 
                if ($type =~ /(downloaded|uploaded)/) {
                        $curtime = convert_to_epoch($month, $day, $time);
                        #processes download line
                        my @newarray;
                        #clear out old data and put into new array
                        foreach(@downloads) {
                                my($file, $timestamp, $size) = split(/;/, $_);
                                $timestamp = $timestamp + 60;
                                if (($curtime < $timestamp)) {
                                        push(@newarray, $_);
                                }
                        }
                        @downloads = @newarray;
                        undef @newarray;
                        foreach(@uploads) {
                                my ($user, $timestamp, $filediff) = split(/;/, $_);
                                $timestamp = $timestamp + 60;
                                if ( $curtime < $timestamp) { 
                                        push(@newarray, $_);
                                }
                        }
                        @uploads = @newarray;
                        if ( $filename !~ m/[\.php|\.htm]/ ) { next; }
                        if ($type eq "downloaded") {
                                
                                #prepare new download line
                                $curline = join(';', $filename, $curtime, $size);
                                push(@downloads, $curline);
                        }        
                        elsif ( $type eq "uploaded" ) 
                        {
                                $curuser = (split(/\//, $filename))[2];
				if (@regexlist) {
	                                foreach my $regex (@regexlist){
        	                            if ( $filename =~ /$regex/i )  {
                	                      messagelog("regex matched $filename");  
			                      my $owner = get_owner($curuser);
		                              send_notification($hostname, $curuser, $ip, $filename, $owner, $size);
                        	            }
                                        }
				}
                                #search for file in download array
                                foreach(@downloads) {
                                        my ($dlfile, $date, $dlsize) = split(/;/, $_);
                                        #if upload file matches a file already downloaded
                                        if ($dlfile eq $filename) {
                                                my $difference = $size - $dlsize;
						my $curline = join(';', $curuser, $curtime, $difference);
                                                push(@uploads, $curline);
                                        }
                                }
                                #get total count for the current user
                                foreach(@uploads) {
                                        my ($user, $timestamp, $filediff) = split(/;/, $_);
                                                if ( $user eq $curuser ) {
                                                $count++;
                                        }
                        }
                }
                        #send notification if count = 10
                        if ($count == 10 ) { 
                            my $owner = get_owner($curuser);
                            send_notification($hostname, $curuser, $ip, $filename, $owner, $size);
                        }


        }


            }
            
            unlink($daemon->{pid_file}); # it doesn't automatically get removed when we die
            
            messagelog ("Shutting down.");
        } elsif ( $pid < 0) {
            print "Failed to fork: ".$!;
            exit;
        } 
        print "Things seem to have gone well.\n";
    }
} elsif ($stop) {
    print "Trying to kill gatorftptrackd.\n";
    
    if (my $pid = $daemon->Status()) {
        my $procs = $daemon->Kill_Daemon($pid, 15); # send SIGTERM to request shutdown
        
        messagelog("Killing daemon."); # somewhat of a dirty trick, makes sure tail's read() returns something
        
        $| = 1; #turn on autoflush of stdout (allows progress code to work correctly)
        print "Waiting to die";
        
        my $timeout = 20;
        
        while ($daemon->Status($pid) && $timeout) {
            $timeout--;
            print ".";
            sleep 1;
        }
        
        if ($daemon->Status($pid)) {
            print "failed.\n";
            print "Speeding up the process. Murderkilling daemon.\n";
            my $procs = $daemon->Kill_Daemon();
            print "There were $procs processes killed.\n"
        } else {
            print "success.\n";
        }
    } else {
        print "gatorftptrackd does not appear to be running. Was the PID file removed without a proper shutdown?\n";
    }
} else {
    my $pid = $daemon->Status();
    
    if ($pid) {
        print "gatorftptrackd running as pid $pid.\n";
    } else {
        print "gatorftptrackd does not appear to be running.\n";
    }
}

exit;

# endmain

sub send_notification {
        my ($hostname, $curuser, $ip, $filename, $owner, $size) = @_;
	my $params = "hostname=" . $hostname . "&user=" . $curuser . "&ip=" . $ip . "&filename=" . $filename . "&owner=" . $owner . "&size=" . $size;
        system("/usr/bin/GET \"http://192.185.0.113/ftp/upload.cgi?$params \" ");
}

sub messagelog {
        my ($line) = @_;
        openlog("ftptrackd","","user");
        syslog('info', $line);
        closelog();
}
sub convert_to_epoch {
       my ($month, $day, $time) = @_;
        my ($hour, $min, $sec) = split(/:/, $time);
        %mon2num = qw(
          jan 0  feb 1  mar 2  apr 3  may 4  jun 5
          jul 6  aug 7  sep 8  oct 9 nov 10 dec 11
        );
        $mon = $mon2num{ lc substr($month, 0, 3) };
	my $year = ((localtime)[5]) + 1900;
        my $unixtime = timelocal($sec, $min, $hour, $day, $mon, $year);
        return $unixtime;
}

sub process_symlink {
    my $thisline = shift;
    my $count = shift;
    $thisline =~ /Illegal Symlink User ([0-9]+):[0-9]+ not allowed to symlink to (\/.*) due to ([0-9]+:[0-9]+)/;
    my $user = getpwuid($1);
    my $symlink = $2;
    my $perms = $3;
    if (($user) && ($symlink) && ($perms)) {
        my $owner = get_owner($user);
        my $params = "user=" . $user . "&owner=" . $owner ."&hostname=" . $hostname . "&symlink=" . $symlink . "&perms=" . $perms;
        system("/usr/bin/GET \"http://192.185.0.113/ftp/symlink.cgi?$params\" ");
        messagelog("processing symlink $symlink count $count");
    }
}

sub get_owner {
    my $user=shift;
    my $owner;
    open (USEROWNER,"<","/etc/trueuserowners");
    my @userowner = <USEROWNER>;
    close (USEROWNER);
    foreach(@userowner) { if ( $_ =~ /^$user: (.*)/ ) { $owner = $1; } }
    chomp($owner);
    if ((!$owner) || ($owner eq "root")) { $user = $owner; }
    return $owner;
}

    

