#!/usr/bin/perl

# VHCS(tm) - Virtual Hosting Control System
# Copyright (c) 2001-2004 by moleSoftware GmbH
# http://www.molesoftware.com
#
#
# License:
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the MPL Mozilla Public License
#    as published by the Free Software Foundation; either version 1.1
#    of the License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    MPL Mozilla Public License for more details.
#
#    You may have received a copy of the MPL Mozilla Public License
#    along with this program.
#
#    An on-line copy of the MPL Mozilla Public License can be found
#    http://www.mozilla.org/MPL/MPL-1.1.html
#
#
# The VHCS Home Page is at:
#
#    http://www.vhcs.net

#
# common code: BEGIN
#

BEGIN {

    my @needed = (strict,
                  warnings,
                  IO::Socket,
                  DBI,
                  DBD::mysql,
                  MIME::Entity,
                  MIME::Parser,
                  Crypt::CBC,
                  Crypt::Blowfish,
                  MIME::Base64,
                  Mail::Address,
                  Term::ReadPassword);

    my ($mod, $mod_err, $mod_missing) = ('', '_off_', '');

    for $mod (@needed) {

        if (eval "require $mod") {

            $mod -> import();

        } else {

            print STDERR "\nCRITICAL ERROR: Module [$mod] WAS NOT FOUND !\n" ;

            $mod_err = '_on_';

            if ($mod_missing eq '') {

                $mod_missing .= $mod;

            } else {

                $mod_missing .= ", $mod";

            }
        }

    }

    if ($mod_err eq '_on_') {

        print STDERR "\nModules [$mod_missing] WAS NOT FOUND in your system...\n";

        exit 1;

    } else {

        $| = 1;

    }
}

$main::el_sep = "\t#\t";

@main::el = ();

sub push_el {

    my ($el, $sub_name, $msgDebug) = @_;

    push @$el, "$sub_name".$main::el_sep."$msgDebug";

    if (defined($main::engine_debug)) {

		print STDOUT "push_el() sub_name: $sub_name, msg: $msgDebug\n";

    }

}

sub pop_el {

    my ($el) = @_;

    my $data = pop @$el;

    if (!defined($data)) {

        if (defined($main::engine_debug)) {

			print  STDOUT "DEBUG: pop_el() Empty 'EL' Stack !\n";

        }

        return undef;
    }

    my ($sub_name, $msgDebug) = split(/$main::el_sep/, $data);

    if (defined($main::engine_debug)) {

		print STDOUT "DEBUG: pop_el() sub_name: $sub_name, msg: $msgDebug\n";

	}

    return $data;

}


sub dump_el {

    my ($el, $fname) = @_;

	my $res = undef;

    if ($fname ne 'stdout') {

        $res = open(FP, ">>", $fname);

        if (!defined($res)) {

            return 0;

        }

    }

    my $el_data = undef;

    #
    #if ($fname eq 'stdout') {
    #
    #    print STDOUT "%-20s | %s\n",  ' function', 'message';
    #
    #    print STDOUT "---------------------|---------------------------------------------------------------\n";
    #
    #} else {
    #
    #    print FP "%-20s | %s\n",  ' function', 'message';
    #
    #    print FP "---------------------|---------------------------------------------------------------\n";
    #
    #}
    #

    while (defined($el_data = pop_el(\@main::el))) {

        my ($sub_name, $msgDebug) = split(/$main::el_sep/, $el_data);

        if ($fname eq 'stdout') {

            printf STDOUT "%-30s | %s\n",  $sub_name, $msgDebug;

        } else {

            printf FP "%-30s | %s\n",  $sub_name, $msgDebug;

        }

    }

    close(FP);

}

# Global variables;

$main::db_host = undef;

$main::db_user = undef;

$main::db_pwd = undef;

$main::db_name = undef;

@main::db_connect = ();

$main::db = undef;

#

sub doSQL {

    my ($sql) = @_;

    my $qr = undef;

    push_el(\@main::el, 'doSQL()', 'Starting...');

    if (!defined($sql) || ($sql eq '')) {

        push_el(\@main::el, 'doSQL()', 'ERROR: Undefined SQL query !');

        return (-1, '');

    }

    if (!defined($main::db) || !ref($main::db)) {

        $main::db = DBI -> connect(@main::db_connect, {PrintError => 0});

        if ( !defined($main::db) ) {

            push_el(
                    \@main::el,
                    'doSQL()',
                    'ERROR: Unable to connect SQL server !'
                   );

            return (-1, '');

        }
    }

    if ($sql =~ /select/i) {

        $qr = $main::db -> selectall_arrayref($sql);

    } else {

        $qr = $main::db -> do($sql);

    }

    if (defined($qr)) {

        push_el(\@main::el, 'doSQL()', 'Ending...');

        return (0, $qr);

    } else {

        push_el(\@main::el, 'doSQL()', 'ERROR: Incrrect SQL Query -> '.$main::db -> errstr);

        return (-1, '');

    }


}

sub get_file {

    my ($fname) = @_;

    push_el(\@main::el, 'get_file()', 'Starting...');

    if (!defined($fname) || ($fname eq '')) {

        push_el(
                \@main::el,
                'get_file()',
                "ERROR: Undefined input data, fname: |$fname| !"
               );

        return (-1, '');

    }

    if (! -e $fname) {

        push_el(
                \@main::el,
                'get_file()',
                "ERROR: File '$fname' does not exist !"
               );

        return (-1, '');

    }

    my $res = open(F, '<', $fname);

    if (!defined($res)) {

        push_el(
                \@main::el,
                'get_file()',
                "ERROR: Can't open '$fname' for reading !"
               );

        return (-1, '');

    }

    my @fdata = <F>;

    close(F);

    my $line = join('', @fdata);

    push_el(\@main::el, 'get_file()', 'Ending...');

    return (0, $line);

}

sub del_file {

    my ($fname) = @_;

    push_el(\@main::el, 'del_file()', 'Starting...');

    if (!defined($fname) || ($fname eq '')) {

        push_el(
                \@main::el,
                'del_file()',
                "ERROR: Undefined input data, fname: |$fname| !"
               );

        return -1;

    }

    if (! -e $fname) {

        push_el(
                \@main::el,
                'del_file()',
                "ERROR: File '$fname' does not exist !"
               );

        return -1;

    }

    my $res = unlink ($fname);

    if ($res != 1) {

        push_el(
                \@main::el,
                'del_file()',
                "ERROR: Can't unlink '$fname' !"
               );

        return -1;

    }

    push_el(\@main::el, 'del_file()', 'Ending...');

    return 0;

}

# Global variables

%main::cfg = ();

$main::cfg_file = '/etc/vhcs2/vhcs2.conf';

$main::cfg_re = '^([\_A-Za-z0-9]+) *= *([^\n\r]*)[\n\r]';

use FindBin;
use lib "$FindBin::Bin/";
require 'vhcs2-db-keys.pl';

sub encrypt_db_password {

    my ($pass) = @_;

    push_el(\@main::el, 'encrypt_db_password()', 'Starting...');

    if (!defined($pass) || $pass eq '') {

        push_el(\@main::el, 'encrypt_db_password()', 'ERROR: Undefined input data ($pass)...');

        return (1, '');

    }

    my $cipher = Crypt::CBC -> new(
                                    {
                                        'key'             => $main::db_pass_key,
										'keysize' 		  => 32,
                                        'cipher'          => 'Blowfish',
                                        'iv'              => $main::db_pass_iv,
                                        'regenerate_key'  => 0,
                                        'padding'         => 'space',
                                        'prepend_iv'      => 0
                                    }
                                  );

    my $ciphertext = $cipher->encrypt($pass);

    my $encoded = encode_base64($ciphertext); chop($encoded);

    push_el(\@main::el, 'encrypt_db_password()', 'Ending...');

    return (0, $encoded);

}

sub decrypt_db_password {

    my ($pass) = @_;

    push_el(\@main::el, 'decrypt_db_password()', 'Starting...');

    if (!defined($pass) || $pass eq '') {

        push_el(\@main::el, 'decrypt_db_password()', 'ERROR: Undefined input data ($pass)...');

        return (1, '');

    }

    my $cipher = Crypt::CBC -> new(
                                    {
                                        'key'             => $main::db_pass_key,
										'keysize' 		  => 32,
                                        'cipher'          => 'Blowfish',
                                        'iv'              => $main::db_pass_iv,
                                        'regenerate_key'  => 0,
                                        'padding'         => 'space',
                                        'prepend_iv'      => 0
                                    }
                                  );

    my $decoded = decode_base64("$pass\n");

    my $plaintext = $cipher -> decrypt($decoded);


    push_el(\@main::el, 'decrypt_db_password()', 'Ending...');

    return (0, $plaintext);

}

sub setup_main_vars {

    push_el(\@main::el, 'setup_main_vars()', 'Starting...');

    #
    # Database backend vars;
    #

    $main::db_host = $main::cfg{'DATABASE_HOST'};

    $main::db_user = $main::cfg{'DATABASE_USER'};

    $main::db_pwd = $main::cfg{'DATABASE_PASSWORD'};

    if ($main::db_pwd ne '') {

        my $rs = undef;

        ($rs, $main::db_pwd) = decrypt_db_password($main::db_pwd);

    }



    $main::db_name = $main::cfg{'DATABASE_NAME'};

    @main::db_connect = (
                         "DBI:mysql:$main::db_name:$main::db_host",
                         $main::db_user,
                         $main::db_pwd
                        );

    push_el(\@main::el, 'setup_main_vars()', 'Ending...');

    return 0;
}

sub get_conf {

    push_el(\@main::el, 'get_conf()', 'Starting...');

    my ($rs, $fline) = get_file($main::cfg_file);

    return -1 if ($rs != 0);

    my @frows = split(/\n/, $fline);

    my $i = '';

    for ($i = 0; $i < scalar(@frows); $i++) {

        $frows[$i] = "$frows[$i]\n";

        if ($frows[$i] =~ /$main::cfg_re/) {

            $main::cfg{$1} = $2;

        }

    }

    return -1 if (setup_main_vars() != 0);

    push_el(\@main::el, 'get_conf()', 'Ending...');

    return 0;

}

my $rs = get_conf();

if ($rs != 0) {
	if( -d "/var/log/vhcs2/vhcs2-arpl-msgr/") {
		$main::vhcs2_arpl_msgr_el = "/var/log/vhcs2/vhcs2-arpl-msgr/vhcs2-arpl-msgr.el";
		$main::vhcs2_arpl_msgr_stdout = "/var/log/vhcs2/vhcs2-arpl-msgr/vhcs2-arpl-msgr.stdout";
		$main::vhcs2_arpl_msgr_stderr = "/var/log/vhcs2/vhcs2-arpl-msgr/vhcs2-arpl-msgr.stderr";
		open(STDOUT, ">", $main::vhcs2_arpl_msgr_stdout) || die "Can't redirect stdout";
		open(STDERR, ">", $main::vhcs2_arpl_msgr_stderr) || die "Can't redirect stderr";
	}
	print STDERR "\nCRITICAL ERROR: Failed open /etc/vhcs2/vhcs2.conf! Maybe wrong permissions?\n" ;
	exit 0;
}

#$main::engine_debug = '_on_';

# debug dump files;
$main::log_dir = $main::cfg{'LOG_DIR'};

$main::vhcs2_arpl_msgr_el = "$main::log_dir/vhcs2-arpl-msgr/vhcs2-arpl-msgr.el";
$main::vhcs2_arpl_msgr_stdout = "$main::log_dir/vhcs2-arpl-msgr/vhcs2-arpl-msgr.stdout";
$main::vhcs2_arpl_msgr_stderr = "$main::log_dir/vhcs2-arpl-msgr/vhcs2-arpl-msgr.stderr";

open(STDOUT, ">", $main::vhcs2_arpl_msgr_stdout) || die "Can't redirect stdout";
open(STDERR, ">", $main::vhcs2_arpl_msgr_stderr) || die "Can't redirect stderr";

#
# common code: END
#

use strict;

use warnings;

my @msg_rows = <STDIN>;

my $msg = join('', @msg_rows);

sub arpl_msgr_start_up {

    my ($rs, $rdata) = (undef, undef);

    push_el(\@main::el, 'arpl_msgr_start_up()', 'Starting...');

    # Let's clear Execution Logs, if any.

    if (-e $main::vhcs2_arpl_msgr_el) {

        $rs = del_file($main::vhcs2_arpl_msgr_el);

        return $rs if ($rs != 0);

    }

    # config check;

    $rs = get_conf();

    return $rs if ($rs != 0);

    # sql check;

    #
    # getting initial data also must be done here;
    #

    my $sql = "select * from domain;";

    ($rs, $rdata) = doSQL($sql);

    return $rs if ($rs != 0);

    push_el(\@main::el, 'arpl_msgr_start_up()', 'Ending...');

    return 0;

}

sub arpl_msgr_shut_down {

    my $rs = undef;

    push_el(\@main::el, 'arpl_msgr_shut_down()', 'Starting...');

	$main::db -> disconnect();

	if (!defined($main::engine_debug)) {

		$rs = del_file($main::vhcs2_arpl_msgr_stdout);

        return $rs if ($rs != 0);

		$rs = del_file($main::vhcs2_arpl_msgr_stderr);

        return $rs if ($rs != 0);

		push_el(\@main::el, 'arpl_msgr_shut_down()', "delete debugfiles.");

	}

    push_el(\@main::el, 'arpl_msgr_shut_down()', 'Ending...');

    return 0;

}

sub arpl_msgr_engine {

	push_el(\@main::el, 'arpl_msgr_engine()', 'Starting...');

	my ($sql, $rs) = (undef, undef);

	my $msg_parser = new MIME::Parser;

	$msg_parser -> output_to_core(1);

    my $msg_entity = $msg_parser -> parse_data($msg);

    my $head = $msg_entity -> head();

	my @from_ma = Mail::Address->parse($head -> get('From'));

	my @to_addrs = Mail::Address->parse($head -> get('X-Original-To'));

	my $buffer = "0";

	my $edmn = undef;

	my @edmn = @_;

	my $name = undef;

	my $mail_to = undef;

	my $to_ma = undef;

	my ($mailHeaderCheck1, $mailHeaderCheck2, $mailHeaderCheck3) = (1, 1, 1);

	if($head -> get('X-Mailer')) { if($head -> get('X-Mailer') =~ m/Autoreply Manager/i) { $mailHeaderCheck1 = 0; } }
	if($head -> get('Auto-Submitted')) { if($head -> get('Auto-Submitted') =~ m/auto-replied/i) { $mailHeaderCheck2 = 0; } }
	if($head -> get('Sender')) { if($head -> get('Sender')=~ m/autoresponder/i) { $mailHeaderCheck3 = 0; } }

	if(	$mailHeaderCheck1 && $mailHeaderCheck2 && $mailHeaderCheck3 && !$head -> get('X-Autoresponse-From')) {

		foreach $to_ma (@to_addrs) {

			if($to_ma->address =~ m/@/i && $to_ma->address !~ m/"/g) {

				if($buffer) {
					$name = $buffer;
					$buffer = "0";
				}
				else {
					if($to_ma->phrase) { $name = $to_ma->phrase; }
					else { $name = ""; }
				}

    			push_el(\@main::el, 'arpl_msgr_engine()', ">>> From: |".$from_ma[0]->address."|, To: |".$to_ma->address."|");

    	    	push_el(\@main::el, 'arpl_msgr_engine()', "loop!");

				my $ma = $to_ma->address."\n";

        		return 0 if (!($ma =~ /^([^\@]+)\@([^\n]+)\n$/));

	        	my ($user, $dmn) = ($1, $2);

    	    	my ($ref, $dmn_id, $sub_id, $pt) = (undef, undef, undef, undef, undef, undef);

       		 	my ($domainformsubdomain, $subformsubdomain) = (undef, undef);

       		 	#@edmn = split(/\./,$2,2);

       		 	#$edmn = $edmn[1];
       		 	
       		 	$edmn = $2;

        		$sql = "select count(domain_id) as cnt from domain where domain_name = '$edmn'";

	        	($rs, $ref) = doSQL($sql);

    	    	return $rs if ($rs != 0);

        		$ref = @$ref[0];

        		if (@$ref[0] == 1) {

            		$pt = 1;

	        	} else {

        		$sql = "select count(alias_id) as cnt from domain_aliasses where alias_name = '$edmn'";

	        	($rs, $ref) = doSQL($sql);

    	    	return $rs if ($rs != 0);

        		$ref = @$ref[0];

        		if (@$ref[0] == 1) {

	        	$pt = 2;

        		}
        		else {

        		$pt = 3;

        		}

        		}

        		if ($pt == 1) {

	            				$sql = "select mail_auto_respond from mail_users LEFT JOIN domain ON mail_users.domain_id=domain.domain_id where mail_acc = '$user' and domain_name = '$edmn' and sub_id=0;";

	    	    	}
			elsif ($pt == 2) {

						$sql = "select mail_auto_respond from mail_users LEFT JOIN domain_aliasses ON mail_users.sub_id=domain_aliasses.alias_id where mail_acc = '$user' and alias_name = '$edmn';";

	       	}

		       elsif ($pt == 3) {

						$sql = "select mail_auto_respond from mail_users LEFT JOIN subdomain ON mail_users.sub_id=subdomain.subdomain_id LEFT JOIN domain ON subdomain.domain_id=domain.domain_id where mail_acc = '$user' and (CONCAT(subdomain_name,'.',domain_name) = '$edmn');";

		       }

    			push_el(\@main::el, 'arpl_msgr_engine()', "sql: |".$sql."|");

	    	    ($rs, $ref) = doSQL($sql);

	        	return $rs if ($rs != 0);


		        $ref = @$ref[0]; my $auto_message = @$ref[0];

				if($auto_message ne '_no_') {

					if($name) { $mail_to = "\"".$name."\" "."<".$to_ma->address.">"; }

					else{ $mail_to = $to_ma->address; }


			        my $out = new MIME::Entity;

            		$mail_to=~s/\@vhcs2-arpl./\@/;

					$out -> build(
    		    	              From => $mail_to,
        		    	          To => $head -> get('From'),
            		    	      Subject => "[Autoreply] ".$head -> get('Subject'),
                		    	  Type => "multipart/mixed",
								  'X-Autoresponse-From' => $mail_to,
	                    		  'X-Mailer' => "VHCS $main::cfg{'VersionH'} Autoreply Manager"
								);


					$out -> attach(
	                    		  Type => "text/plain",
    	                		  Encoding => "7bit",
        	            		  Description => "Mail User Autoreply Message",
            	        		  Data => $auto_message
								);

					$out -> attach(
    	                		  Type => "message/rfc822",
        	            		  Description => "Original Message",
            	        		  Data => $msg
								);

					open MAIL, "| /usr/sbin/sendmail -t -oi";

					$out -> print(\*MAIL);

					close MAIL;
				}

		    	push_el(\@main::el, 'arpl_msgr_engine()', 'Ending...');

			}
			else
			{
				$buffer = $to_ma->address;
				$buffer =~ s/"//g;
			}

		}

	}

	return 0;

}

$rs = undef;

$rs = arpl_msgr_start_up();

if ($rs != 0) {

    dump_el(\@main::el, $main::vhcs2_arpl_msgr_el);

    arpl_msgr_shut_down();

    exit 1;

}

$rs = arpl_msgr_engine();

if ($rs != 0) {

    dump_el(\@main::el, $main::vhcs2_arpl_msgr_el);

    arpl_msgr_shut_down();

    exit 1;

}

$rs = arpl_msgr_shut_down();

if ($rs != 0) {

    dump_el(\@main::el, $main::vhcs2_arpl_msgr_el);

    exit 1;

}

exit 0;
