#!/usr/bin/perl

# ispCP ω (OMEGA) a Virtual Hosting Control Panel
# Copyright (C) 2001-2006 by moleSoftware GmbH - http://www.molesoftware.com
# Copyright (C) 2006-2010 by isp Control Panel - http://ispcp.net
#
# Version: $Id: ispcp-vrl-traff 3220 2010-08-22 21:56:20Z benedikt $
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is "VHCS - Virtual Hosting Control System".
#
# The Initial Developer of the Original Code is moleSoftware GmbH.
# Portions created by Initial Developer are Copyright (C) 2001-2006
# by moleSoftware GmbH. All Rights Reserved.
# Portions created by the ispCP Team are Copyright (C) 2006-2010 by
# isp Control Panel. All Rights Reserved.
#
# The ispCP ω Home Page is:
#
#    http://isp-control.net
#

use FindBin;
use lib "$FindBin::Bin/..";
require 'ispcp_common_code.pl';

use strict;
use warnings;
use File::Basename;
use Fcntl ":seek";

%main::ftp_traffic = ();
%main::smtp_traffic = ();
%main::po_traffic = ();
%main::sub_id_name= ();

sub zero_traffic_entries {
	push_el(\@main::el, 'zero_traffic_entries()', 'Starting...');

	my ($key, $value) = (undef, undef);

	while (($key, $value) = each %main::domain_name_id) {
		$main::ftp_traffic{$key} = 0;
		$main::smtp_traffic{$key} = 0;
		$main::po_traffic{$key} = 0;
	}

	while (($key, $value) = each %main::als_name_id) {
		$main::ftp_traffic{$key} = 0;
		$main::smtp_traffic{$key} = 0;
		$main::po_traffic{$key} = 0;
	}

	push_el(\@main::el, 'zero_traffic_entries()', 'Ending...');
	0;
}

sub gen_log_file {
	my ($fname, $src_dir, $dest_dir) = @_;
	push_el(\@main::el, 'gen_log_file()', "Starting for logfile $src_dir/$fname");

	my $rs = undef;
	$fname =~ s/\/*//i;
	my $src_file = "$src_dir/$fname";
	my $dest_file = "$dest_dir/" . basename($fname);

	if (! -e $src_file) {
		push_el(
			\@main::el, 
			'gen_log_file()', 
			"WARNING: File '$src_file' does not exist!"
		);
		return (0, '_no_');
	}

	# Log enhancement: use a small (file-based) database storing the previous
	# offset and first line of each processed logfile.
	my $logdb_file = "$dest_dir/logdb";
	my %logdb;
	my ($recPos, $recLine) = (0, '');

	# Creating the logdb file where the log position for each log reside if not 
	# already created
	if (! -e "$logdb_file") {
		$rs = sys_command("$main::cfg{'CMD_TOUCH'} $logdb_file");
		if ($rs != 0) {
			push_el(
				\@main::el, 
				'gen_log_file()', 
				"ERROR: Unable to create the lobdb file '$logdb_file'!"
			);
			return ($rs, '');
		}
	}

	# @TODO:
	# This is unefficient because gen_log_file is called once for every log file
	# to be processed. Therefore, the *whole* logdb file is read at each call, 
	# causing a lot of re-readings. Thus, logdb reading should be done once at 
	# the beggining of this script and, similarly, logdb writting should be done
	# just once at the end.
	push_el(
		\@main::el, 
		'gen_log_file()', 
		"Taking the domain log positions from '$logdb_file'..."
	);
	$rs = open (LOGDB,'<',"$logdb_file");
	if (!defined($rs)) {
		push_el(
			\@main::el, 
			'gen_log_file()', 
			"ERROR: Cannot open '$logdb_file' for reading !"
		);
		return (-1, '');
	}
	
	while (<LOGDB>) {
		chomp;
		my ($logdb_key,$logdb_val) = split(' ', $_, 2);
		$logdb{$logdb_key} = $logdb_val;
	}
	close(LOGDB);
	
 	if (exists($logdb{$fname})) {
		($recPos, $recLine) = split(' ', $logdb{$fname}, 2);
		$recLine = '' if (!defined($recLine)) ;
	}

	# Open the relevant files
	$rs = open(SRC_FILE, '<', $src_file);
	if (!defined($rs)) {
		push_el(
			\@main::el, 
			'gen_log_file()', 
			"ERROR: Cannot open '$src_file' for reading !"
		);
		return (-1, '');
	}
	
	# Retrieve the current first line
	my $curLine = <SRC_FILE> || '';
	$curLine =~ s/\n//;
	seek(SRC_FILE, 0, SEEK_SET);
	
	# If the line is empty, there's no data on the logfile so we can safely skip
	# it this time. Rotated logfiles will be detected later on, when there's 
	# data in the logfile.
	if (!$curLine) {
		push_el(
			\@main::el, 
			'gen_log_file', 
			"Logfile contains no data, so skip it for now."
		);
		close(SRC_FILE);
		return (0, '_no_');
	}

	# Open the destination file
	$rs = open(DST_FILE, '>', $dest_file);
	if (!defined($rs)) {
		push_el(
			\@main::el, 
			'gen_log_file()', 
			"ERROR: Cannot open '$dest_file' for writing !"
		);
		close(SRC_FILE);
		return (-1, '');
	}

	# Rotated log detection conditions:
	#   1. The current logfile is smaller than the previously recorded offset position
	#   2. The first line of the current log is different from the previously recorded first line
	# If one of these conditions is fullfilled, try to read from the rotated logfile first.
	if (-s $src_file < $recPos || $curLine ne $recLine) {
		my $old_src_file = "$src_file.1";

		if (-e $old_src_file) {
			push_el(
				\@main::el,
				'gen_log_file', 
				"Logfile has been rotated, parsing '$old_src_file' from position $recPos."
			);
			$rs = open(OLD_SRC_FILE, '<', $old_src_file);
			
			if (defined($rs)) {
				seek(OLD_SRC_FILE, $recPos, SEEK_SET);
				while(<OLD_SRC_FILE>) {
					print DST_FILE $_;
				}
				close(OLD_SRC_FILE);
			} else {
				push_el(
					\@main::el, 
					'gen_log_file',
					"WARNING: Cannot open '$old_src_file' for reading!"
				);
			}
		} else {
			push_el(
				\@main::el, 
				'gen_log_file',
				"Logfile has been rotated, but '$old_src_file' doesn't exist."
			);
		}
		$recPos = 0;
	}

	# Read the lines from the last position to the end
	seek(SRC_FILE, $recPos, SEEK_SET);
	while(<SRC_FILE>) {
		print DST_FILE $_;
	}

	$recPos = tell(SRC_FILE);
	close(SRC_FILE);
	close(DST_FILE);
 
	# Let's write the new position back to the log db
	$logdb{$fname} = "$recPos $curLine";
	push_el(
		\@main::el, 
		'gen_log_file()', 
		"Saving new domain log positions in '$logdb_file'..."
	);

	$rs = open (LOGDB,'>',"$logdb_file");
	if (!defined($rs)) {
		push_el(
			\@main::el,
			'gen_log_file()',
			"ERROR: Cannot open '$logdb_file' for writing !"
		);
		return (-1, '');
	}

	foreach my $logdb_key (keys %logdb) {
		print LOGDB "$logdb_key $logdb{$logdb_key}\n";
	}
	close LOGDB;

	push_el(\@main::el, 'gen_log_file()', 'Ending...');
	return (0, $dest_file);
}

sub collect_http_traffic_from_log {

	my ($key, $value) = @_;
	my ($rs, $rdata, $timestamp, $sum, $rows, $sql) = 
		(undef, undef, time(), 0, undef, undef);

	# timestamp has floor down for the last half'n our to make timestamps in
	# server_traffic and domain_traffic the same
	$timestamp = $timestamp - ($timestamp % 1800);

	my $domain_log = "$key-traf.log";

	($rs, $rdata) = gen_log_file($domain_log, $main::cfg{'APACHE_LOG_DIR'}, $main::cfg{'LOG_DIR'});
	return ($rs, '') if ($rs != 0);

	$sum = 0;

	if ($rdata ne '_no_') {
		my $res = open(F, '<', $rdata);

		if (!defined($res)) {
			push_el(
				\@main::el,
				'collect_http_traffic()',
				"ERROR: Cannot open '$rdata' for reading!"
			);
			return (-1, '');
		}

		while (<F>) {
			$sum += $1 if ($_ =~ /(\d+)\n$/);
		}
		close(F);

		$rs = del_file($rdata);
		return ($rs, '') if ($rs != 0);
	}

	if ($sum != 0) {
		$sql="
			SELECT
				COUNT(`domain_id`)
			FROM 
				`domain_traffic`
			WHERE 
				`domain_id` = '$value'
				AND
				`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
			;";

		($rs, $rows) = doSQL($sql);
		return $rs if ($rs != 0);

		if ($$rows[0][0] == 0) {
			$sql = "
				INSERT INTO
					`domain_traffic`
				(
					`domain_id`,
					`dtraff_time`,
					`dtraff_web`,
					`dtraff_ftp`,
					`dtraff_mail`,
					`dtraff_pop`
				) VALUES (
					'$value',
					'$timestamp',
					$sum,
					'0',
					'0',
					'0'
				);";
		} else {
			$sql = "
				UPDATE
					`domain_traffic`
				SET
					`dtraff_web` = `dtraff_web` + $sum,
					`dtraff_time` = '$timestamp'
				WHERE
					`domain_id` = '$value'
					AND
					`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
				LIMIT 1
			;";
		}

		($rs, $rdata) = doSQL($sql);
		return ($rs, '') if ($rs != 0);
	}
	
	return (0, $timestamp);
}

sub collect_http_traffic {

	my ($key, $value,$timestamp,$rs) = (undef, undef, time(),undef);

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

	while (($key,$value) = each(%main::domain_name_id)) {
		($rs, $timestamp) = collect_http_traffic_from_log($key,$value);
		return ($rs, '') if ($rs != 0);
	}

	while (($key,$value) = each(%main::als_name_id)) {
		($rs, $timestamp) = collect_http_traffic_from_log($key, $main::als_id_parentid{$value});
		return ($rs, '') if ($rs != 0);
	}

	while (($key,$value) = each(%main::sub_id_name)) {
		($rs, $timestamp) = collect_http_traffic_from_log(
				"$value.$main::domain_id_name{$main::sub_id_parentid{$key}}", 
				$main::sub_id_parentid{$key}
			);
		return ($rs, '') if ($rs != 0);
	}

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

	return (0, $timestamp);
}

sub collect_ftp_traffic {

	my ($timestamp) = @_;

	my ($key, $value, $id, $rdata, $traffic_size, $traffic_domain);

	my ($rs, $rlog) = gen_log_file(
		$main::cfg{'FTP_TRAFF_LOG'}, 
		$main::cfg{'TRAFF_LOG_DIR'}, 
		$main::cfg{'LOG_DIR'}
	);
	return $rs if ($rs != 0);

	if ($rlog ne '_no_') {
		my $res = open(F, '<', $rlog);

		if (!defined($res)) {
			push_el(
				\@main::el, 
				'collect_ftp_traffic()', 
				"ERROR: Cannot open '$rlog' for reading!"
			);
			return (-1, '');
		}

		while (<F>) {
			my $line = $_;

			if ($line =~ /^(\d+) [^\@]+\@([^\n]+)\n$/) {
				$traffic_size = $1;
				$traffic_domain = $2;

				if($traffic_domain =~ /(.*)(\.)(.*\.)(.*)$/ && 
					!exists $main::ftp_traffic{$traffic_domain}) {
					$main::ftp_traffic{$3.$4} += $traffic_size;
				} else {
					$main::ftp_traffic{$traffic_domain} += $traffic_size;
				}
			}
		}
		close(F);

		while (($key, $value) = each %main::ftp_traffic) {
			if ($id = $main::als_name_id{$key}) {
				$main::ftp_traffic{$main::domain_id_name {
						$main::als_id_parentid{$id}}} += $value;
			}
		}

		$rs = del_file($rlog);
		return $rs if ($rs != 0);
	}

	while (($key, $value) = each %main::ftp_traffic) {
		if ($id = $main::domain_name_id{$key}) {
			if ($value != 0) {
				my $sql = undef;

				$sql="
					SELECT
						COUNT(`domain_id`) 
					FROM
						`domain_traffic`
					WHERE 
						`domain_id` = '$id' 
					AND 
						`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
					;";

				my ($rs, $rows) = doSQL($sql);
				return $rs if ($rs != 0);

				if ($$rows[0][0] == 0) {
					$sql = "
						INSERT INTO
							`domain_traffic`
						(
							`domain_id`, `dtraff_time`, `dtraff_web`, 
							`dtraff_ftp`, `dtraff_mail`, `dtraff_pop`
						) VALUES (
							'$id', '$timestamp', '0', $value, '0', '0'
						)
					;";
				} else {
					$sql = "
						UPDATE
							`domain_traffic`
						SET
							`dtraff_ftp` = `dtraff_ftp` + $value,
							`dtraff_time` = '$timestamp'
						WHERE
							`domain_id`='$id'
							AND
							`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
						LIMIT 1
					;";
				}

				($rs, $rdata) = doSQL($sql);
				return $rs if ($rs != 0);
			}
		}
	}
}

sub collect_mail_traffic {

	my ($timestamp) = @_;

	my ($key, $value, $id, $rdata, $traffic_size, $traffic_domain, 
		$smtp_from_domain, $smtp_to_domain);

	my ($cat, $grep, $awk) = (
		$main::cfg{'CMD_CAT'}, 
		$main::cfg{'CMD_GREP'}, 
		$main::cfg{'CMD_AWK'}
	);
	my ($rs, $rlog) = gen_log_file(
		$main::cfg{'MAIL_TRAFF_LOG'}, 
		$main::cfg{'TRAFF_LOG_DIR'}, 
		$main::cfg{'LOG_DIR'}
	);
	return $rs if ($rs != 0);

	if ($rlog ne '_no_') {
		my $smtp_log = "$main::cfg{'LOG_DIR'}/smtp.log";
		my $smtp_delivery_log = "$main::cfg{'LOG_DIR'}/smtp_delivery.log";
		my $imap_log = "$main::cfg{'LOG_DIR'}/imap.log";
		my $pop3_log = "$main::cfg{'LOG_DIR'}/pop3.log";
		my $cmd = "$grep 'postfix' $rlog | $main::cfg{'CMD_PFLOGSUM'} standard 1>$smtp_delivery_log";

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

		if (exists $main::cfg{'MAIL_LOG_INC_AMAVIS'} && $main::cfg{'MAIL_LOG_INC_AMAVIS'}) {
			# Logs including AMAVIS/SPAMASSASSIN/CLAMAV entries
			$cmd = "$cat $smtp_delivery_log|$awk '{if ( \$10 != \"?\" && " .
				"!(\$5 ~ /localhost|127.0.0.1/ && \$6 ~ /localhost|127.0.0.1/)) " . 
				"print substr(\$3, index(\$3, \"@\")+1, length(\$3)), " .
				"substr(\$4, index(\$4, \"@\")+1, length(\$4)),\$10;}' 1>$smtp_log";
		} else {
			# Logs not including AMAVIS/SPAMASSASSIN/CLAMAV entries
 			$cmd = "$cat $smtp_delivery_log|$awk '{if ( \$10 != \"?\" && " .
 				"\$6 !~ /virtual/ && !(\$5 ~ /localhost|127.0.0.1/ &&" .
 				"\$6 ~ /localhost|127.0.0.1/)) " .
 				"print substr(\$3, index(\$3, \"@\")+1, length(\$3)), ".
 				"substr(\$4, index(\$4, \"@\")+1, length(\$4)),\$10;}' 1>$smtp_log";
		}

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

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

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

		if (!defined($res)) {
			push_el(
				\@main::el, 
				'collect_mail_traffic()', 
				"ERROR: Cannot open '$smtp_log' for reading !"
			);
			return (-1, '');
		}

		while (<F>) {
			my $line = $_;

			if ($line =~ /^([^\,]+)\ ([^\,]+)\ (\d+)\n$/) {
				$smtp_from_domain = $1;
				$smtp_to_domain = $2;
				$traffic_size = $3;

				if ($smtp_from_domain =~ /(.*)(\.)(.*\.)(.*)$/ && 
					!exists $main::smtp_traffic{$smtp_from_domain}) {
					$smtp_from_domain = $3.$4;
				}

				if ($smtp_to_domain =~ /(.*)(\.)(.*\.)(.*)$/ && 
					!exists $main::smtp_traffic{$smtp_to_domain}) {
					$smtp_to_domain = $3.$4;
				}

				if (exists $main::smtp_traffic{$smtp_from_domain}) {
					$main::smtp_traffic{$smtp_from_domain} += $traffic_size;
				} else {
					$main::smtp_traffic{$smtp_to_domain} += $traffic_size;
				}
			}
		}
		close(F);

		while (($key, $value) = each %main::smtp_traffic) {
			if ($id = $main::als_name_id{$key}) {
				$main::smtp_traffic{$main::domain_id_name{
					$main::als_id_parentid{$id}}} += $value;
			}

		}

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

		# IMAP accounting
		$rs = sys_command("$cat $rlog|$grep 'imap'|$grep 'user='|$grep 'body='|" . 
			"$grep -v 'ip=\\[::ffff:127.0.0.1\\]'|$awk '{print \$7,\$9," .
			"substr(\$10,1,length(\$10)-1);}' 1>$imap_log");
		return $rs if ($rs != 0);
		
		# IMAP accounting for Dovecot
		# This should not harm normal IMAP accounting in any way. If Dovecot is 
		# not used, nothing will be appended to imap_log.
		$rs = sys_command("$cat $rlog|$grep 'IMAP'|$grep 'Logged out bytes'|$awk '" .
			"/IMAP/ {split(\$10,result,\"=\"); split(result[2],oper,\"/\");" .
			"print \"user=\"substr(\$6,6,length(\$6)-7) \", headers=0, " .
			"body=\" oper[1]+oper[2]}'>>$imap_log"); 
		return $rs if ($rs != 0);

		$res = open(F, '<', $imap_log);

		if (!defined($res)) {
			push_el(
				\@main::el, 
				'collect_mail_traffic()', 
				"ERROR: Cannot open '$imap_log' for reading !"
			);
			return (-1, '');
		}

		while (<F>) {
			my $line = $_;

			if ($line =~ /^user=([^\,]+)\, headers=(\d+), body=(\d+)\n$/) {
				my ($ma, $sum) = ("$1\n", $2 + $3);

				$ma =~ /^([^\@]+)\@([^\n]+)\n$/;
				$traffic_domain = $2;

				if ($traffic_domain =~ /(.*)(\.)(.*\.)(.*)$/ 
					&& !exists $main::po_traffic{$traffic_domain}) {
					$main::po_traffic{$3.$4} += $sum;
				} else {
					$main::po_traffic{$traffic_domain} += $sum;
				}
			}
		}
		close(F);

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

		# IMAP-SSL accounting
		$rs = sys_command("$cat $rlog|$grep 'imapd-ssl'|$grep 'user='|" .
			"$grep -v 'ip=\\[::ffff:127.0.0.1\\]'|" .
			"$awk '{print \$7,\$9,substr(\$10,1,length(\$10)-1);}' 1>$imap_log");
		return $rs if ($rs != 0);

		$res = open(F, '<', $imap_log);

		if (!defined($res)) {
			push_el(
				\@main::el, 
				'collect_mail_traffic()',
				"ERROR: Cannot open '$imap_log' for reading !");
			return (-1, '');
		}

		while (<F>) {
			my $line = $_;

			if ($line =~ /^user=([^\,]+)\, headers=(\d+), body=(\d+)\n$/) {
				my ($ma, $sum) = ("$1\n", $2 + $3);

				$ma =~ /^([^\@]+)\@([^\n]+)\n$/;
				$traffic_domain = $2;

				if ($traffic_domain =~ /(.*)(\.)(.*\.)(.*)$/ && 
					!exists $main::po_traffic{$traffic_domain}) {
					$main::po_traffic{$3.$4} += $sum;
				} else {
					$main::po_traffic{$traffic_domain} += $sum;
				}
			}
		}
		close(F);

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

		# POP3 accounting
		# courierpop3login is for Debian. pop3d for Fedora.
		$rs = sys_command("$cat $rlog|$grep -E '(courierpop3login|pop3d).+user=.+top='|"
			."$grep -v 'ip=\\[::ffff:127.0.0.1\\]'|"
			."$awk '/courierpop3login/ {print \$7,\$9,substr(\$10,1,length(\$10)-1);} "
			."/pop3d/ {print \$7,\$10,substr(\$11,1,length(\$11)-1);}' "
			."1>>$pop3_log");
		return $rs if ($rs != 0);

		# POP3 accounting for Dovecot
		# This should not harm in any way. If Courier / Dovecot is not used, the
		# string will be empty and nothing will be written to the pop3_log.
		$rs = sys_command("$cat $rlog|$grep 'POP3'| $grep 'Disconnected: Logged out' |"
			."$awk '/POP3/ {split(\$10,array,\"\/\"); print \"user=\"substr(\$6,6,length(\$6)-7) "
			."\", top=\"substr(array[2],0,length(array[2])) \", "
			."retr=\"substr(\$11,index(\$11,\"/\")+1,length(\$11)-1) ;}' "
			."1>>$pop3_log");
		return $rs if ($rs != 0);

		$res = open(F, '<', $pop3_log);

		if (!defined($res)) {
			push_el(
				\@main::el, 
				'collect_mail_traffic()',
				"ERROR: Cannot open '$pop3_log' for reading !");
			return (-1, '');
		}

		while (<F>) {
			my $line = $_;

			if ($line =~ /^user=([^\,]+)\, top=(\d+), retr=(\d+),?\n$/) {
				my ($ma, $sum) = ("$1\n", $2 + $3);

				$ma =~ /^([^\@]+)\@([^\n]+)\n$/;
				$traffic_domain = $2;

				if ($traffic_domain =~ /(.*)(\.)(.*\.)(.*)$/ && 
					!exists $main::po_traffic{$traffic_domain}) {
					$main::po_traffic{$3.$4} += $sum;
				} else {
					$main::po_traffic{$traffic_domain} += $sum;
				}
			}
		}
		close(F);

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

		# POP3-SSL accounting
		$rs = sys_command("$cat $rlog|$grep 'pop3d-ssl'|$grep 'user='|" .
			"$grep 'retr='|$grep -v 'ip=\\[::ffff:127.0.0.1\\]'|$awk " .
			"'{print \$7,\$9,substr(\$10,1,length(\$10)-1);}' 1>$pop3_log");
		return $rs if ($rs != 0);
		
		$res = open(F, '<', $pop3_log);

		if (!defined($res)) {
			push_el(
				\@main::el, 
				'collect_mail_traffic()', 
				"ERROR: Cannot open '$pop3_log' for reading !");
			return (-1, '');
		}

		while (<F>) {
			my $line = $_;

			if ($line =~ /^user=([^\,]+)\, top=(\d+), retr=(\d+)\n$/) {
				my ($ma, $sum) = ("$1\n", $2 + $3);

				$ma =~ /^([^\@]+)\@([^\n]+)\n$/;
				$traffic_domain = $2;

				if($traffic_domain =~ /(.*)(\.)(.*\.)(.*)$/ 
					&& !exists $main::po_traffic{$traffic_domain}) {
					$main::po_traffic{$3.$4} += $sum;
				} else {
					$main::po_traffic{$traffic_domain} += $sum;
				}
			}
		}
		close(F);

		while (($key, $value) = each %main::po_traffic) {
			if ($id = $main::als_name_id{$key}) {
				$main::po_traffic {$main::domain_id_name {
					$main::als_id_parentid{$id}}} += $value;

			}
		}

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

		$rs = del_file($rlog);
		return $rs if ($rs != 0);
	}

	while (($key, $value) = each %main::smtp_traffic) {
		if ($id = $main::domain_name_id{$key}) {
			if ($value != 0) {
				my $sql = undef;

				$sql = "
						SELECT
							COUNT(`domain_id`) 
						FROM 
							`domain_traffic` 
						WHERE 
							`domain_id` = '$id' 
							AND 
							`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
						;";

				my ($rs, $rows) = doSQL($sql);
				return $rs if ($rs != 0);

				if ($$rows[0][0] == 0) {
					$sql = "
							INSERT INTO
								`domain_traffic`
							(
								`domain_id`, `dtraff_time`, `dtraff_web`,
								`dtraff_ftp`, `dtraff_mail`, `dtraff_pop`
							) VALUES (
								'$id', '$timestamp', '0', '0', $value, '0'
							)
							;";
				} else {
					$sql = "
							UPDATE
								`domain_traffic`
							SET
								`dtraff_mail` = `dtraff_mail` + $value,
								`dtraff_time`='$timestamp'
							WHERE
								`domain_id` = '$id' AND
								`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
							LIMIT 1
							;";
				}

				($rs, $rdata) = doSQL($sql);
				return $rs if ($rs != 0);
			}
		}
	}

	while (($key, $value) = each %main::po_traffic) {
		if ($id = $main::domain_name_id{$key}) {
			if ($value != 0) {
				my $sql = undef;

				$sql = "
						SELECT 
							COUNT(`domain_id`) 
						FROM 
							`domain_traffic`
						WHERE 
							`domain_id` = '$id' 
							AND
							`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
						;";

				my ($rs, $rows) = doSQL($sql);
				return $rs if ($rs != 0);

				if ($$rows[0][0] == 0) {
					$sql = "
							INSERT INTO
								`domain_traffic`
							(
								`domain_id`, `dtraff_time`, `dtraff_web`,
								`dtraff_ftp`, `dtraff_mail`, `dtraff_pop`
							) VALUES (
								'$id', '$timestamp', '0', '0', '0', $value
							)
							;";
				} else {
					$sql = "
							UPDATE
								`domain_traffic`
							SET
								`dtraff_pop` = `dtraff_pop` + $value,
								`dtraff_time` = '$timestamp'
							WHERE
								`domain_id` = '$id' AND
								`dtraff_time` >= UNIX_TIMESTAMP(CURRENT_DATE())
							LIMIT 1
							;";
				}

				($rs, $rdata) = doSQL($sql);
				return $rs if ($rs != 0);
			}
		}
	}

	0;
}


sub vrl_traff_start_up {
	my ($rs, $rdata) = (undef, undef);

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

	# Clear Execution Logs, if any
	if (-e $main::ispcp_vrl_traff_el) {
		$rs = del_file($main::ispcp_vrl_traff_el);
		return $rs if ($rs != 0);
	}

	# Get the config
	$rs = get_conf();
	return $rs if ($rs != 0);

	# Get the initial data
	my $sql = "
		SELECT
			`domain_id`,
			`domain_name`,
			`domain_gid`,
			`domain_uid`,
			`domain_admin_id`,
			`domain_created_id`,
			`domain_created`,
			`domain_last_modified`,
			`domain_mailacc_limit`,
			`domain_ftpacc_limit`,
			`domain_traffic_limit`,
			`domain_sqld_limit`,
			`domain_sqlu_limit`,
			`domain_status`,
			`domain_alias_limit`,
			`domain_ip_id`,
			`domain_disk_limit`,
			`domain_disk_usage`,
			`domain_php`,
			`domain_cgi`
		FROM
			`domain`
		;";

	($rs, $rdata) = doSQL($sql);
	return $rs if ($rs != 0);

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

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

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

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

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

	0;
}


sub vrl_traff_shut_down {

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

	0;
}

sub vrl_traff_engine {
	my ($rs, $timestamp) = (undef, undef);

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

	($rs, $timestamp) = collect_http_traffic();
	return $rs if ($rs != 0);

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

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

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

	0;
}

################################################################################
##                                    MAIN                                    ##
################################################################################

my $rs = undef;

$rs = vrl_traff_start_up();

if ($rs != 0) {
	dump_el(\@main::el, $main::ispcp_vrl_traff_el);
	vrl_traff_shut_down();
	exit 1;
}


$rs = vrl_traff_engine();

if ($rs != 0) {
	dump_el(\@main::el, 'stderr');
	exit 1;
}


$rs = vrl_traff_shut_down();

if ($rs != 0) {
	dump_el(\@main::el, $main::ispcp_vrl_traff_el);
	exit 1;
}

exit 0;
