#!/usr/bin/env php
<?php
	$root = substr(__DIR__, 0, strrpos(__DIR__, '/'));
	require_once( $root . '/dronebl.config.php');
	require_once( $frameworks_path . '/DroneBL/Database.framework');
	require_once( $frameworks_path . '/DroneBL/Validation.framework');
	require_once( $frameworks_path . '/DroneBL/Cron.framework');
	require_once( $frameworks_path . '/DroneBL/Logging.framework');

	chkprog('Entry Retester');
	$maxentries = 10;
	$found = 0;
	function delistEntry($ip, $type, $port)
	{
		global $found;
		$found += db_affected_rows(get_db_rows("UPDATE blacklist SET listed=0, ts_del=now()::abstime::int WHERE ip='".$ip."' AND type='".$type."' AND port='".$port."'"));
	}
	
	function updateEntry($ip, $type, $port, $active=0)
	{
		get_db_rows("UPDATE blacklist SET entrytest=now()::abstime::int, entryactive=".$active." WHERE ip='".$ip."' AND type='".$type."' AND port='".$port."'");
	}
	
	$workers = [];
	$mh = curl_multi_init();
	// curl_multi_setopt($mh, CURLMOPT_MAX_HOST_CONNECTIONS, 1);
	// curl_multi_setopt($mh, CURLMOPT_MAX_TOTAL_CONNECTIONS, 100);
	function createWorker($ip, $toscan, $port, $type)
	{
		global $workers, $mh;
		if (!$ip || !$port) return false;
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL, 'http://89.18.174.160/ptest');
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		// curl_setopt($ch, CURLOPT_VERBOSE, 1);
		switch($toscan)
		{
			case 'http':
			case 'https':
				curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP );
				break;
			case 'socks4':
				curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
				break;
			case 'socks5':
				curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
				break;
		}
		curl_setopt($ch, CURLOPT_PROXYPORT, $port);
		curl_setopt($ch, CURLOPT_PROXY, $ip);
		$workers[uniqid('', true)] = ['curl' => $ch, 'ip' => $ip, 'type' => $type, 'port' => $port];
		$res = curl_multi_add_handle($mh, $ch);
	}
	
	$cur = 1;
	$queue = [];
	$query = get_db_rows("SELECT id, ip, port, type FROM blacklist WHERE listed=1 AND (type=12 OR (type IN (8,9,10,11,14,18) AND port > 0)) ORDER BY entrytest ASC LIMIT ".$maxentries);
	$linecount = db_num_rows($query);
	conlog("Testing entries (".$linecount.")");
	while ($row = get_db_tuple($query))
	{
		progress($linecount, $found, 'database entries');
		
		$ip = $row['ip'];
		$type = intval($row['type']);
		$port = intval($row['port']);
		
		$toscan = false;
		$delist = false;
		$active = 0;
		
		switch($type)
		{
			case 8:
				if (!$port) break;
				$toscan = ['socks4', 'socks5'];
				break;
			case 9:
			case 11:
				if (!$port) break;
				$toscan = ['http', 'https'];
				break;
			case 12:
				$test = exec('dig +short test.openresolver.com TXT @'.$ip);
				if (!preg_match('/open-resolver-detected/', $test))
					$delist = true;
				else
					$active = 1;
				break;
			case 10:
			case 14:
				if (!$row['port']) break;
				$toscan = ['http', 'https', 'socks4', 'socks5'];
				break;
			case 18:
				$test = mb_strtolower(gethostbyaddr($ip));
				if ($test == mb_strtolower($ip))
					$delist = true;
				else
				{
					$matches = array('[^\.]+mail','mail','correo','smtp','mx','mta','news','ns','dns','ftp','www','web','imap');
					foreach ($matches AS $match)
					{
						if (preg_match('/^'.$match.'/', $test))
						{
							$active = 1;
							break;
						}
					}
					$delist = true;
				}
				break;
			default:
				continue;
		}
		if ($delist)
			delistEntry($ip, $type, $port);
		else if ($toscan)
		{
			if(isset($queue[$ip]['p'.$port]['t'.$type]))
				$toscan = array_unique(array_merge($queue[$ip]['p'.$port]['t'.$type], $toscan));
			$queue[$ip]['p'.$port]['t'.$type] = $toscan;
		}
		else
			updateEntry($ip, $type, $port, $active);
	}
	echo PHP_EOL;
	
	$cur = 1;
	foreach(array_keys($queue) AS $ip)
	{
		progress(count($queue), $found, 'remaining queue entries');
		foreach(array_keys($queue[$ip]) AS $port)
		{
			$port = substr($port,1);
			foreach(array_keys($queue[$ip]['p'.$port]) as $type)
				createWorker($ip, $queue[$ip]['p'.$port][$type], $port, intval(substr($type,1)));
		}
	}
	echo PHP_EOL;
	
	conlog(count($workers).' curl channels prepared...');

	$cur = 1;
	$running = 1;
	while ($running)
	{
		$mrc = curl_multi_exec($mh, $running);
		$cur = $running;
		progress(count($workers), $found, 'workers');
		if (curl_multi_select($mh) == -1)
		{
			usleep(1);
			continue;
		}
		while ($info = curl_multi_info_read($mh))
		{
			var_dump($info);
			if ($info === false) continue;
		
			$flag = false;
			$remove = false;
			$update = false;
			$active = 0;
			$info2 = curl_getinfo($info['handle']);
			var_dump($info2);
			switch($info['result'])
			{
				case 0:
					
					switch(intval($info2['http_code']))
					{
						case 200:
							$data = trim(curl_multi_getcontent($info['handle']));
							if ($data == 'GOTCHA')
							{
								echo ' active';
								$active = 1;
								$flag = true;
							}
							else
								echo ' received:'.$data.PHP_EOL;
							break;
						default:
							echo 'HTTP '.$info2['http_code'];
					}
					break;
				case 7:
				case 52:
				case 56:
					echo ' no longer active';
					$flag = true;
					$remove = true;
					break;
				case 28:
					echo ' timed out';
					$update = true;
					break;
				default:
					var_dump($info);
					echo PHP_EOL;
					continue;
			}
			
			if (!$update && !$flag && !$remove) continue;
			
			foreach (array_keys($workers) as $workid)
			{
				$worker = $workers[$workid];
				if ($worker['curl'] == $info['handle'])
				{
					echo ' '.$worker['ip'].':'.$worker['port'].' (type: '.$worker['type'].')'.PHP_EOL;
					if ($flag || $remove)
						curl_multi_remove_handle($mh, $info['handle']);
					updateEntry($worker['ip'], $worker['type'], $worker['port'], $active);
					
					if ($remove)
						delistEntry($worker['ip'], $worker['type'], $worker['port']);
					if ($flag)
						$workers[$workid]['active'] = 1;
				}
			}
		}
	}
	curl_multi_close($mh);
	echo PHP_EOL;	
	endprog();
?>
