#!/usr/bin/perl -I/server/phexproxy/PhexProxy

use lib "/server/phexproxy/PhexProxy";

my $ServicePriority = "-1";				
system("renice $ServicePriority $$");
system("clear");

use DB_File;
use strict; no strict 'subs';
use PhexProxy::IO;
use PhexProxy::Time;
use PhexProxy::CryptoLibrary;
use IO::Socket;
use LWP::UserAgent;
use HTTP::Request;



my @ReadFromClient				= ();
my @ParisHosts					= ();
my $ServerSocket;
my $ReadFromClient;

# suche nach Sex -mp3 -midi
my $SendString					= "9b76071ab53c08ec4e5a6530371557c9##0123456789abcdef0123456789abcdef##4fbe1d281a7df21beccb587a152f9bad09eaf06e6968a86896da24f67f9bef09dadda7e587095f2a961eed93f477c93b96522b7ae9bf7451616e36b5b0754d04bf0e26344d657fe47fbc7ab9813c363fb61564adc3d401feaa543bc767f4dff822a2c48466a92c9186aefe0a90bc7e8be45e84606d7fdb58605127359e18c67d";
my $FakeMD5String				= "9b76071ab53c08ec4e5a6530371557c9";
my $PrivateKey					= "0123456789abcdef0123456789abcdef";
my $SleepTime					= 10;
my @ReadFromClient				= split('##', $SendString );
my %CurrentSearchRequests		= ();

###########
my @admin_sms_deliver			= ('0041789354830');	# diese handynr sollen error sms bekommen
my $MaxFileSizeOfWebDocument	= (5 * 1024 * 1024);	# 5mb
my $MaxRedirectRequests			= 0;
my $AuthorEmail					= 'test@cpan.org';
my $Timeout						= 5;
my $CrawlDelay					= int(rand(3));
my $SMS_DB						= "/server/phexproxy/tmp/ProxyCheck.db";		unlink $SMS_DB || system("/bin/rm -rf $SMS_DB");
my $SendSmsDelay				= 300;	# nur alle 300 sekundn soll eine sms gesendet werden
###########


# Abschnitt Entschlüsselung Handynachricht
####################### crypto api implementatione #####################
#	$IOReadFromClient[0] = MD5 Wert der Verschlüsselten Nachricht
#	$IOReadFromClient[1] = der public schlüssel 
#	$IOReadFromClient[2] = die verschlüsselte nachricht
	
my $PrivateCryptoKey		= PhexProxy::CryptoLibrary->GetPrivateCryptoKeyFromDatabase( $ReadFromClient[1] );



my %ParisHosts				= (
	"81.169.137.179"		=> "23072",					# bitjoepartner.com server - 81.169.137.179	
	"77.247.178.21"			=> "9923",	# sql server - 77.247.178.21
	"87.106.134.107"		=> "23071",					# 1und1 phex server - 87.106.134.107
);



while( my ($host,$port) = each(%ParisHosts)){
	# print "Connect to: '$host' und '$port' " . PhexProxy::Time->MySQLDateTime() . " \n";
	
	$ServerSocket				= ProxyConnect($host,$port);
	print $ServerSocket "$SendString\r\n";
	binmode($ServerSocket);
	my $content					= <$ServerSocket>;
	close($ServerSocket);
	chomp($content);

	my ($clientID,undef,undef)	= split("##",$content);
	my $resultstring			= "result##sex##$clientID##26db8cc2f5a107eedccd43cf66b2cc0c##4469097bf50e597b814664da2ef63a85##1.0.0.proxy";
	my $CryptText				= PhexProxy::CryptoLibrary->Encrypt( $PrivateCryptoKey, $resultstring );

	sleep $SleepTime; # schlafe 10 sekunden
	
	$ServerSocket				= ProxyConnect($host,$port);
	print $ServerSocket "$FakeMD5String##$PrivateKey##$CryptText\r\n";
	binmode($ServerSocket);
	my $contentback				= readSocket($ServerSocket);
	chomp($contentback);

	my (@SOURCES)				= split("\r", $contentback );
	my (@RESULTS)				= split("\r\n", $contentback );

	my $Results					= @RESULTS;
	my $Sources					= @SOURCES;

	if ( $Results == 0 || $Sources == 0 ) {
		SendStatusSMS("ERROR: [" .PhexProxy::Time->MySQLDateTime(). "] Server '$host:$port' giving '$Results' Results with '$Sources' Sources!\n");
	}

	print "[" .PhexProxy::Time->MySQLDateTime(). "] Server '$host:$port' giving '$Results' Results with '$Sources' overall Sources for 'sex -mp3 -midi'\n";	# ."('".length($contentback)."')
	close($ServerSocket);

}; # while( my ($host,$ports) = each(%ParisHosts)){


sub SendStatusSMS(){

	my $errormsg	= shift;
	my $sendfrom	= '004916023777337';	# diese rufnummer ist auf meinem handy unter dem namen 'Service Alive' eingetragen
	my $password	= "84c9293acd49fc6e4f22a53ffa25c195";
	my $LastSmsSend = RequestCounterRead();

	foreach my $smsto (@admin_sms_deliver) {

		my $MessageURI	= "http://www.sms-revolution.ch/API/httpsms.php?user=delicious&password=$password&text=$errormsg&to=$smsto&typ=3";
		
		if ( time() > $LastSmsSend + $SendSmsDelay ) {
			my ($status,$desc) = &Get($MessageURI);
			#	print "SMS Sending - Status: '$status' - Return: '$desc' \n";
			&RequestCounterWrite();
		}; # if ( time() > $LastSmsSend + $SendSmsDelay ) {
		
	}; # foreach my $smsto (@admin_sms_deliver) {

	return 1;

}; # sub SendStatusSMS(){


sub Get() {
		
	#my $self	= shift;
	my $url		= shift;
	my $referer	= $url;
	
	my $UA		= LWP::UserAgent->new( keep_alive => 1 );
	
	$UA->agent("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; YPC 3.0.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
	$UA->timeout( $Timeout );
	$UA->max_size( $MaxFileSizeOfWebDocument );
	$UA->from( $AuthorEmail );
	$UA->max_redirect( $MaxRedirectRequests );
	$UA->parse_head( 1 );
	$UA->protocols_allowed( [ 'http', 'https', 'ftp', 'ed2k'] );
	$UA->protocols_forbidden( [ 'file', 'mailto'] );
	$UA->requests_redirectable( [ 'HEAD', 'GET', 'POST'] );

	my $req = HTTP::Request->new( GET => $url );
	$req->referer($referer);

	my $res = $UA->request($req);

	if ( $res->is_success ) {

		#$StatusHashRef->{ 'OBJ' } = $res; 
		return $res->content; 
		
	}; # if ($res->is_success) {

	return 0;

}; # sub GET() {


sub RequestCounterWrite(){

	tie(%CurrentSearchRequests, 'DB_File', $SMS_DB ) || warn "can't open $SMS_DB: $!";
	flock(%CurrentSearchRequests,LOCK_EX);
		$CurrentSearchRequests{'LASTACCESS'} = time();
	flock(%CurrentSearchRequests, LOCK_UN);
	untie(%CurrentSearchRequests);

	return;
	
};	# sub NoResultDatabaseManager(){


sub RequestCounterRead(){

	tie(%CurrentSearchRequests, 'DB_File', $SMS_DB ) || warn "can't open $SMS_DB: $!";
		if ( length($CurrentSearchRequests{'LASTACCESS'}) > 0 ) {
			return $CurrentSearchRequests{'LASTACCESS'};
		} else {
			return 0;
		}
	untie(%CurrentSearchRequests);
		
};	# sub NoResultDatabaseManager(){


# result##sex##$clientID##26db8cc2f5a107eedccd43cf66b2cc0c##4469097bf50e597b814664da2ef63a85##1.0.0.proxy
# find##sex##m100100000000000000##26db8cc2f5a107eedccd43cf66b2cc0c##4469097bf50e597b814664da2ef63a85##1.0.0.proxy

# "result"+"##"+
#  to_search+"##"+
#  id+"##"+
#  Constant.UP_MD5+"##"+
#  Constant.SEC_MD5+"##"+
#  Constant.VERSION+
#  Constant.CRLF;

sub readSocket() {

	my $socket	= shift;
	
	my $IO;
	my $STREAM;
	my $StreamCount = 0;

	while (sysread($socket , $IO, 1) == 1) {
				
		$STREAM = $STREAM . $IO;
		$StreamCount++;

    }; # while (sysread($socket , $IO, 1) == 1) {}

	return $STREAM;

}; # sub _readSocket() {


sub ProxyConnect(){

	my $host = shift;
	my $port = shift;

	my $Connection	= IO::Socket::INET->new( 
		PeerAddr	=> $host,	
		PeerPort	=> $port,	
		Proto		=> 'tcp',
		Timeout		=> 5,
		Reuse		=> 1 ) or die "Peerconnection to $host und $port failed!\n";	# later sms benachrichtigung

	return $Connection;

}# sub ProxyConnect(){