| 
| aka_kludge | Дата: Четверг, 29.10.2009, 22:31 | Сообщение # 1 |  |  Admin Группа: Администраторы Сообщений: 1058 Награды: 2 Репутация: 25 Статус: Offline | Code <?php /*
 ********************************************************************************
 *
 *  Library features:
 *  ~ multi-threaded work
 *  ~ overflow safety
 *  ~ high speed
 *  ~ zlib compression support
 *  ~ proxy to proxy
 *
 *  Requirements:
 *   Not work with non-unix! You have to compile the CGI or CLI version of PHP highest v.4.1.0
 *   with these config options: ./configure '--enable-sockets' '--enable-pcntl' '--enable-sigchild'
 *   '--with-zlib=[DIR]'
 *
 *  Date: 10.09.2005
 *
 *  Coded by n0 [CyberLords]
 *
 *  Copyright ї n0 2002-2005
 *
 ********************************************************************************
 */
 
 // no time limit
 set_time_limit(0);
 
 // no error reporting
 error_reporting(0);
 
 declare (ticks = 1);
 
 /*========================================================================*/
 // Signal handler function
 /*========================================================================*/
 
 function sig_handler($signo)
 {
 switch($signo)
 {
 case SIGTERM:
 // handle shutdown tasks
 die();
 break;
 default:
 // handle all other signals
 }
 }
 
 // Setup signal handlers
 pcntl_signal(SIGTERM, "sig_handler");
 
 /*========================================================================*/
 // Deamon class
 /*========================================================================*/
 
 class DMN
 {
 // Server status variables
 var $onLineF             = 0;
 var $onLineD             = 0;
 
 // Deamon version
 var $_VERSION            = 'v.0.39b';
 
 // IP & PORT
 var $_SERVER_IP          = '1.2.3.4';  // server ip
 var $_SERVER_PORT        = '3128'; // server port
 
 // Sockets variables
 var $_CREAT_SOCKET;
 var $_REMOTE_HOST_SOCK;
 var $_BILI;
 var $_SOCK_ACCEPT;
 
 // Query settings & variables
 var $_HTTP_DEFAULT_PORT  = 80;
 var $_HTTP_REMOTE_HOST   = '';
 var $_HTTP_REMOTE_PORT   = '';
 
 // -> && <- variables
 var $_QUERY_VAR;
 var $_REQUEST_VAR;
 var $_RESPONSE_VAR;
 var $_RESPONSE_DATA;
 
 // Connections settings
 var $_FM                 = 5000;
 var $_FN                 = 0;
 
 // Compression variables
 var $_GZ                 = 0; // TRUE = compression ON;  FALSE = COMPRESSION OFF
 var $compressed_level    = 0; // 3 recomended
 
 // Proxy to Proxy
 var $_PTP                = 0; // TRUE = PTP ON;  FALSE = PTP OFF
 var $_PROXY_IP           = '5.6.7.8';
 var $_PROXY_PORT         = '3128';
 
 // Logs
 var $logwd               = '/full/path/to/proxy_deamon_access_log'; // Example: /home/myhomepage/logs/proxy_deamon_logs
 
 // Time options
 var $_TO                 = 40; // timout for all connections
 
 /*========================================================================*/
 // Start Deamon
 /*========================================================================*/
 
 function start_deamon()
 {
 $onError = 0;
 print "\n  Starting deamon->\n\n  * Creating Socket: ";
 $this->_CREAT_SOCKET = socket_create(AF_INET, SOCK_STREAM, 0);
 if ($this->_CREAT_SOCKET) {print "Ok\n";} else {print "Faild\n";$onError++;}
 print "  * Set options: ";
 if (socket_set_option($this->_CREAT_SOCKET, SOL_SOCKET, SO_REUSEADDR, 1))  {print "Ok\n";} else {print "Faild\n";$onError++;}
 print "  * Binding port: ";
 if ($this->BILI = socket_bind($this->_CREAT_SOCKET, $this->_SERVER_IP, $this->_SERVER_PORT)) {print "Ok\n";} else {print "Faild\n";$onError++;}
 print "  * Listening: ";
 if ($this->BILI = socket_listen($this->_CREAT_SOCKET, 0)) {print "Ok\n\n";} else {print "Faild\n";$onError++;}
 if($onError == 0) {print "~~~~~~~~~~~~~~~~~~~~~~~~~\n\n + Deamon successful started on $this->_SERVER_IP".":"."$this->_SERVER_PORT with PID ".posix_getpid()."\n\n + Server ready\n\n + Waiting for connections.....\n\n"; return TRUE;} else {print "~~~~~~~~~~~~~~~~~~~~~~~~~\n\n - Starting Deamon Faild\n\n\n"; return FALSE;
 }
 }
 
 /*========================================================================*/
 // Stop Deamon
 /*========================================================================*/
 
 function stop_deamon()
 {
 if ($this->_CREAT_SOCKET)
 {
 $this->onLineF = 0;
 $this->onLineD = 0;
 if (is_writable($this->logwd))
 {
 $ft = fopen ($this->logwd, "a+");
 if (flock($ft, LOCK_EX)) // do an exclusive lock
 {
 fwrite ($ft, "[".date("d.m.y H:i:s")."] - PHP_PROXY_DEAMON ".$this->_VERSION." Written by n0 [CyberLords] // Successful terminated\n");
 flock($ft, LOCK_UN); // release the lock
 }
 fclose($ft);
 }
 print "\n  Stop deamon->\n\n  * Deamon successful terminated\n\n  Press 'Ctrl+C' for exit\n\n";sleep(120);exit();
 }
 else
 {
 print "\n\n!!!!Deamon is Shut down now!!!!\n\n";
 }
 }
 
 /*========================================================================*/
 // Parse request
 /*========================================================================*/
 
 function parse_request($_this_request)
 { // Split query into header sections
 list($_request_headers, $_request_body) = explode("\r\n\r\n", $_this_request, 2);
 $_request_header_lines = explode("\r\n", $_request_headers);
 
 // First line of headers is the HTTP quering method
 $_http_request_line = array_shift($_request_header_lines);
 if (preg_match('!([^ ]+) ([^ ]+) ([^/]+)/([^]+) ([^ ]+)!', $_http_request_line, $_matches))
 {
 $_request_method = $_matches[1];
 $_request_url= $_matches[2];
 $_request_http_version = $_matches[4];
 }
 
 // Parse url
 $_url_parse = parse_url($_matches[2]);
 $_http_host = $_url_parse["host"];
 $_http_port = $_url_parse["port"];
 
 // put the rest of the headers in an array
 $_request_header_array = array();
 
 foreach($_request_header_lines as $_header_line)
 {
 list($_header,$_value) = explode(': ', $_header_line, 2);
 $_request_header_array[$_header] .= $_value."\n";
 }
 // Return all in array
 return array("host" => $_http_host, "port" => $_http_port, "url" => $_request_url, "header" => $_request_header_lines, "header_array" => $_request_header_array);
 }
 
 /*========================================================================*/
 // Parse response
 /*========================================================================*/
 
 function parse_response($_this_response)
 { // Split response into header and body sections
 list($_response_headers, $_response_body) = explode("\r\n\r\n", $_this_response, 2);
 $_response_header_lines = explode("\r\n", $_response_headers);
 
 // Main response hedaer code
 $_response_code = $_response_header_lines[0];
 
 // put the rest of the headers in an array
 $_response_header_array = array();
 
 foreach($_response_header_lines as $_header_line)
 {
 list($_header,$_value) = explode(': ', $_header_line, 2);
 $_response_header_array[$_header] .= $_value."\n";
 }
 return array("code" => $_response_code, "header_array" => $_response_header_array, "header" => $_response_headers, "body" => $_response_body);
 }
 
 /*========================================================================*/
 // Prepare contents of the output buffer.
 /*========================================================================*/
 
 function create_output($_this_output)
 {
 if($this->_GZ)
 {
 if(strlen($_this_output) > 8192) // Compress the data into a new var. Don't compress any less than 1024 bytes as it's not worth the overhead at either side.
 {
 $response_array = $this->parse_response($_this_output);
 
 // Prepare output
 if(empty($response_array["header_array"]["Content-Encoding"]))
 {
 // Compress output
 $compressed_out = gzcompress($response_array["body"], $this->compressed_level);
 
 // Compression info
 print "Compression info: Before: ".strlen($response_array["body"])." & After: ".strlen($compressed_out)."\n";
 
 $_output = $response_array["code"]."\r\nAccept-Ranges: bytes\r\nContent-Encoding: gzip\r\nVary: Accept-Encoding\r\n"; // Tell the browser the content is compressed with gzip
 if(!empty($response_array["header_array"]["Content-Type"]))
 {
 $_output .= "Content-Type: ".$response_array["header_array"]["Content-Type"]."\r\n";
 }
 else
 {
 $_output .= "Content-Type: text/html\r\n\r\n";
 }
 $_output .= "\x1f\x8b\x08\x00\x00\x00\x00\x00";
 $_output .= $compressed_out;
 
 socket_write($this->_SOCK_ACCEPT, $_output, strlen($_output));
 }
 else
 {
 socket_write($this->_SOCK_ACCEPT, $_this_output, strlen($_this_output));
 }
 }
 else
 { // No compression
 socket_write($this->_SOCK_ACCEPT, $_this_output, strlen($_this_output));
 }
 }
 else
 {
 socket_write($this->_SOCK_ACCEPT, $_this_output, strlen($_this_output));
 }
 }
 
 /*========================================================================*/
 // Main function:
 //  new proc; get query; send query; get response; send response; kill proc;
 /*========================================================================*/
 
 function transfer()
 {
 while($this->onLineF)
 {
 while($this->_FN >= $this->_FM)
 {
 print "!!!! Maximum fork..... sleeping..... !!!!\n";
 sleep($this->_TO);
 $this->_FN = 0;
 }
 print "Forks created now: ".$this->_FN++."\n";
 if (($this->_SOCK_ACCEPT = socket_accept($this->_CREAT_SOCKET)) < 0)
 {
 echo "socket_accept() failed: reason: " .socket_strerror($this->_SOCK_ACCEPT) . "\n"; break;
 }
 $cpid = pcntl_fork();
 if ( $cpid == -1 )
 {
 die( "error\n" );
 }
 elseif ( $cpid  == 0) {}
 else
 {
 $this->_REMOTE_HOST_SOCK = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
 
 if ($this->_REMOTE_HOST_SOCK < 0)
 {
 print $log = "[".date("d.m.y H:i:s")."] - Connection ABORTED\n";break;
 }
 else
 {
 print $log = "[".date("d.m.y H:i:s")."] - New Connection... Process PID: ".$cpid."\n";
 }
 $this->_QUERY_VAR = socket_recv($this->_SOCK_ACCEPT,$this->_REQUEST_VAR,2048,0);
 
 // Parse request and get array with results
 $_request_array = $this->parse_request($this->_REQUEST_VAR);
 
 // Request print and write into log
 print $log .= "[".date("d.m.y H:i:s")."] - Requesting: ".$_request_array["url"]."\n";
 
 // Proxy connection check
 if(!$this->_PTP)
 {
 // HOST:PORT
 $this->_HTTP_REMOTE_HOST = $_request_array["host"];
 $this->_HTTP_REMOTE_PORT = $_request_array["port"];
 
 if (empty($this->_HTTP_REMOTE_PORT))
 {
 $this->_HTTP_REMOTE_PORT = $this->_HTTP_DEFAULT_PORT; // :80 - default port
 }
 }
 else
 {
 $this->_HTTP_REMOTE_HOST = $this->_PROXY_IP;
 $this->_HTTP_REMOTE_PORT = $this->_PROXY_PORT;
 }
 $fp = socket_connect($this->_REMOTE_HOST_SOCK,$this->_HTTP_REMOTE_HOST,$this->_HTTP_REMOTE_PORT);
 if ($fp < 0)
 {
 print $log .= "[".date("d.m.y H:i:s")."] - Connection to remote host (".$this->_HTTP_REMOTE_HOST.":".$this->_HTTP_REMOTE_PORT."): Faild...\n";break;
 }
 else
 {
 print $log .= "[".date("d.m.y H:i:s")."] - Connection to remote host (".$this->_HTTP_REMOTE_HOST.":".$this->_HTTP_REMOTE_PORT."): Ok...\n";
 
 if (socket_write($this->_REMOTE_HOST_SOCK, $this->_REQUEST_VAR, strlen($this->_REQUEST_VAR)))
 {
 print $log .= "[".date("d.m.y H:i:s")."] - Sending query: Ok...\n";
 
 while ($this->_RESPONSE_VAR =  socket_recv($this->_REMOTE_HOST_SOCK,$_tmp_DATA,4096,0))
 {
 $this->_RESPONSE_DATA .= $_tmp_DATA;
 }
 
 // Checking client browser about GZIP support if gzib-compression ON
 if($this->_GZ)
 {
 if(!ereg("gzip",$_request_array["header_array"]["Accept-Encoding"]))
 {
 $this->_GZ = 0;
 print $log .= "[".date("d.m.y H:i:s")."] - GZIP compression for process with PID ".posix_getpid().": OFF (GZIP not Supported)\n";
 }
 else
 {
 print $log .= "[".date("d.m.y H:i:s")."] - GZIP compression for process with PID ".posix_getpid().": ON (GZIP Supported)\n";
 }
 }
 // Send response to client
 $this->create_output($this->_RESPONSE_DATA);
 
 if (!$this->_RESPONSE_VAR)
 {
 print $log .= "[".date("d.m.y H:i:s")."] - Reading response from ".$this->_HTTP_REMOTE_HOST.":".$this->_HTTP_REMOTE_PORT.": Ok...\n";
 }
 else
 {
 print $log .= "[".date("d.m.y H:i:s")."] - Reading response from ".$this->_HTTP_REMOTE_HOST.":".$this->_HTTP_REMOTE_PORT.": Faild...\n";break;
 }
 }
 else
 {
 print $log .= "[".date("d.m.y H:i:s")."] - Sending query: Faild...\n";break;
 }
 }
 if (is_writable($this->logwd))
 {
 $fw = fopen ($this->logwd, "a+");
 if (flock($fw, LOCK_EX))
 { // do an exclusive lock
 fwrite ($fw, $log);
 flock($fw, LOCK_UN); // release the lock
 }
 fclose($fw);
 }
 @socket_close($this->_REMOTE_HOST_SOCK);
 posix_kill(posix_getpid(), SIGTERM);
 }
 }
 }
 }
 
 
 /*========================================================================*/
 // Keyboard class
 /*========================================================================*/
 
 class DCM
 {
 var $_DIN_READ       = '';
 var $_CMD            = '';
 
 /*========================================================================*/
 // Read command
 /*========================================================================*/
 
 function din_read()
 {
 global $_DMN;
 print "\nChose command:\n\n   - Start deamon #: 1 (BIND: ".$_DMN->_SERVER_IP.":".$_DMN->_SERVER_PORT.")";
 if($_DMN->_GZ) {print "\n\n     *Compression: ON (Compression level: ".$_DMN->compressed_level.")";} else {print "\n\n     *Compression: OFF";}
 if($_DMN->_PTP) {print "\n\n     *ProxToProxy: ON (Proxy ADDR: ".$_DMN->_PROXY_IP.":".$_DMN->_PROXY_PORT.")";} else {print "\n\n     *ProxToProxy: OFF";}
 print "\n\n   - Stop deamon #: 2\n\n";
 if (file_exists($_DMN->logwd)) {print "   - Show logs #: 3 (".substr(((filesize($_DMN->logwd)/1048576*100)/100),0,6)." Mb)\n\n";}
 print " *For back to main menu press 'ENTER'\n\n";
 print "Command #: ";
 $this->_DIN_READ = fopen('php://stdin','r');
 $this->_CMD = fgets($this->_DIN_READ, 2);
 fclose($this->_DIN_READ);
 return $this->_CMD;
 }
 }
 
 // Cheking OS type
 if (ereg("win", strtolower(PHP_OS))) {die("\nCannot run in Windows OS. This deamon only for Unix OS\n\n");}
 
 // Cheking PHP version
 if (str_replace(".",NULL,phpversion()) < 410) {die("\nWarning! You should update PHP to 4.1.0. Current version ".phpversion()."\n\n");}
 
 /*========================================================================*/
 // Extension checking function
 /*========================================================================*/
 
 function extension_checking($ext)
 {
 if (!extension_loaded($ext))
 {
 dl($ext.".so");
 if (!extension_loaded($ext))
 {
 die("\n - $ext extension: needed!\n\n");
 }
 }
 else
 {
 print  "\n + $ext extension: loaded";
 }
 }
 print "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nExtensions checking: \n";
 
 // Zlib extension loading
 extension_checking("zlib");
 
 // Sockets extension loading
 extension_checking("sockets");
 
 print "\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
 
 /*========================================================================*/
 // Permissions class
 /*========================================================================*/
 
 class SPM
 {
 var $_GID    =   10;
 var $_UID    =   10;
 
 /*========================================================================*/
 // Set permissions for current process
 /*========================================================================*/
 
 function set_permissions()
 {
 print "\nTrying set UID and GID for this process\n";
 if ((posix_setgid($this->_GID)) && (posix_setuid($this->_UID)))
 {
 print "\nGID ".$this->_GID." and UID ".$this->_UID." set for current process successful\n\n"; return TRUE;
 }
 else
 {
 print "\nSetting GID ".$this->_GID." and UID ".$this->_UID." is faild for current process\n\nYou don`t have permissions\n\n"; return FALSE;
 }
 }
 }
 
 // Main variables
 $_DMN = new DMN;
 $_DCM = new DCM;
 $_SPM = new SPM;
 
 // Welcome message
 print "\n\nWellcome to PHP_PROXY_SERVER ".$_DMN->_VERSION."\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWritten by n0 [CyberLords]\n\nUIN#: 899125\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n";
 print "Server info: ".php_uname()." as [".get_current_user()."]\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; // OS
 
 // main
 if ($_SPM->set_permissions()) // if your uid & gid 0 -> TRUE
 {
 while(TRUE)
 {
 $_DCM->CMD = $_DCM->din_read(); // read command from keyboard
 switch($_DCM->CMD) { // switch command
 // Start deamon
 case 1:
 unset($_DCM->CMD);
 if(!$_DMN->onLineF)
 {
 $_DMN->onLineF = TRUE;
 }
 if ($_DMN->onLineD) {print "\nAlready runing with PID ".posix_getpid()."\n";} elseif (!$_DMN->onLineD)
 {
 $_DMN->onLineD = TRUE;
 if ($_DMN->start_deamon()) // if deamon started -> get_send .....
 {
 if (is_writable($_DMN->logwd))
 {
 $fs = fopen ($_DMN->logwd, "a+");
 if (flock($fs, LOCK_EX)) // do an exclusive lock
 {
 fwrite ($fs, "[".date("d.m.y H:i:s")."] - PHP_PROXY_DEAMON ".$_DMN->_VERSION." Written by n0 [CyberLords] // Successful started (PTP: ".$_DMN->_PTP."  Compression: ".$_DMN->_GZ.")\n");
 flock($fs, LOCK_UN); // release the lock
 }
 fclose($fs);
 }
 $pid = pcntl_fork();
 if ($pid == -1) {die( "error\n" );} elseif ($pid  == 0) {$_DMN->transfer();} else {}
 }
 else
 {
 if (is_writable($_DMN->logwd))
 {
 $fs = fopen ($_DMN->logwd, "a+");
 if (flock($fs, LOCK_EX))
 {
 fwrite ($fs, "[".date("d.m.y H:i:s")."] - PHP_PROXY_DEAMON ".$_DMN->_VERSION." Written by n0 [CyberLords] // Starting aborted\n");
 flock($fs, LOCK_UN); // release the lock
 }
 fclose($fs);
 }
 exit(0); // if deamon not started -> exit
 }
 }
 break;
 // Stop deamon
 case 2:
 $_DMN->stop_deamon(); // deamon terminated
 break;
 case 3:
 unset($_DCM->CMD);
 if (filesize($_DMN->logwd) > 0)
 {
 include($_DMN->logwd);
 }
 else
 {
 print "\nLog file empty\n";
 }
 break;
 // Other command
 default:
 print "\n\nWarning!!!!! Unknown command\n\n";
 break;
 }
 }
 }
 else
 {
 exit();
 }
 ?>
 |  |  |  |  |