/** * Send request to VIES site and retrieve results * * @access public * @param string * @return mixed */ function load_data($url) { $url = parse_url($url); if (!in_array($url['scheme'], array('', 'http'))) { return false; } $fp = fsockopen($url['host'], $url['port'] > 0 ? $url['port'] : 80, $errno, $errstr, 2); if (!$fp) { return false; } else { fputs($fp, "GET " . $url['path'] . (isset($url['query']) ? '?' . $url['query'] : '') . " HTTP/1.0\r\n"); fputs($fp, "Host: " . $url['host'] . "\r\n"); fputs($fp, "Connection: close\r\n\r\n"); $data = ''; stream_set_blocking($fp, false); stream_set_timeout($fp, 4); $status = socket_get_status($fp); while (!feof($fp) && !$status['timed_out']) { $data .= fgets($fp, 1000); $status = socket_get_status($fp); } if ($status['timed_out']) { return false; } fclose($fp); return $data; } }
private function _getResponse(&$r) { $r = ''; do { $r .= fread($this->_fp, 1000); $s = socket_get_status($this->_fp); } while ($s['unread_bytes']); }
function bytes_left($fp) { $status = socket_get_status($fp); if ($status['unread_bytes'] > 0) { return true; } return false; }
function get_url($url, $timeout, $path, $querystring) { // Load the Lang file if (file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . strtolower($language) . '.php')) { require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . strtolower($language) . '.php'; } else { require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'lang' . DIRECTORY_SEPARATOR . 'english.php'; } // Let PHP split the URL into parts $parse_url = parse_url($url); // Make sure the port is set if (isset($parse_url['port']) && !empty($parse_url["port"])) { $parse_url['port'] = ":" . $parse_url['port']; } // Define the path $path = $path . $querystring; // Init var which contains method used $method = ""; if (function_exists("curl_exec")) { $method = "curl_exec"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $parse_url['scheme'] . "://" . $parse_url['host'] . $parse_url["port"] . $path); curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $data = curl_exec($ch); $errstr = curl_error($ch); curl_close($ch); } else { $method = "fsockopen"; $fp = fsockopen($url, $parse_url["port"], $errno, $errstr, $timeout); if ($fp) { $header = "GET " . $path . " HTTP/1.0\r\n"; $header .= "Host: " . $parse_url['host'] . "\r\n"; $header .= "Content-type: text/html\r\n"; $header .= "Connection: close\r\n\r\n"; $data = ""; @stream_set_timeout($fp, $timeout); @fputs($fp, $header); $status = @socket_get_status($fp); while (!@feof($fp) && $status) { $data .= @fgets($fp, 1024); $status = @socket_get_status($fp); } @fclose($fp); } } // Return success, and data or error if (!$data) { return array("success" => false, "data" => "{$_ADDONLANG['client_connection_failed']} (" . $method . ":" . $errstr . ")"); } else { return array("success" => true, "data" => $data); } }
/** * Read the output * @return string */ function getResponse() { $r = ''; do { $r .= fread($this->socket, 1000); usleep($this->sleeptime); $s = socket_get_status($this->socket); } while ($s['unread_bytes']); //usleep($this->sleeptime); return $r; }
function SetDataAccessError($error) { $this->error = $error; if (function_exists("socket_get_status")) { $status = socket_get_status($this->connection); if ($status["timed_out"]) { $this->error .= ": data access time out"; } elseif ($status["eof"]) { $this->error .= ": the server disconnected"; } } }
public function opened() { if (!empty($this->socket)) { $status = socket_get_status($this->socket); if ($status['eof']) { $this->close(); return false; } return true; } return false; }
function mail_connected() { if (!empty($this->mail_connection)) { $sock_status = @socket_get_status($this->mail_connection); if ($sock_status["eof"]) { @fclose($this->mail_connection); return 0; } return 1; } return 0; }
function test_return($res, &$error) { $out = fread($res, 1); $len = socket_get_status($res); if ($len > 0) { $out .= fread($res, $len['unread_bytes']); } //echo $out; if (preg_match("/^5/", $out)) { $error = $out; return false; } return true; }
public function Connected() { if (!empty($this->smtp_conn)) { $sock_status = socket_get_status($this->smtp_conn); if ($sock_status["eof"]) { if ($this->do_debug >= 1) { echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; } $this->Close(); return false; } return true; } return false; }
/** * Checks a socket for timeout or EOF * @param int socket handle * @return boolean true if the socket has timed out or is EOF */ function socketStatus(&$fh) { $return = false; if (is_resource($fh)) { $temp = socket_get_status($fh); if ($temp['timed_out']) { $return = true; } if ($temp['eof']) { $return = true; } unset($temp); } return $return; }
function weblogUpdates_ping($host, $port, $path, $method, $name, $url, $debug = false) { $postdata = '<?xml version="1.0" encoding="iso-8859-1"?> <methodCall> <methodName>' . htmlspecialchars($method) . '</methodName> <params> <param><value><string>' . htmlspecialchars($name) . '</string></value></param> <param><value><string>' . htmlspecialchars($url) . '</string></value></param> </params> </methodCall>'; $timeout = 20; $fp = fsockopen($host, $port, $errno, $errstr, $timeout); if (!$fp) { return array(-1, "Could not connect to {$host}:{$port}"); } socket_set_timeout($fp, $timeout); $request = "POST {$path} HTTP/1.0\r\n" . "Host: {$host}\r\n" . "Content-Type: text/xml\r\n" . "User-Agent: Aggemam XML-RPC client\r\n" . "Content-Length: " . strlen($postdata) . "\r\n" . "\r\n" . $postdata; fputs($fp, $request); if ($debug) { print "<div style='color: blue; white-space: pre'>"; print htmlspecialchars($request); print "</div>"; } $response = ''; while (!feof($fp)) { $response .= fgets($fp, 1024); $status = socket_get_status($fp); if ($status['timed_out']) { fclose($fp); return array(-2, "Request timed out"); } } fclose($fp); if ($debug) { print "<div style='color: green; white-space: pre'>"; print htmlspecialchars($response); print "</div>"; } if (preg_match('|<methodResponse>\\s*<params>\\s*<param>\\s*<value>\\s*<struct>\\s*' . '<member>\\s*<name>flerror</name>\\s*<value>\\s*<boolean>([^<])</boolean>\\s*</value>\\s*</member>\\s*' . '<member>\\s*<name>message</name>\\s*<value>(\\s*<string>)?([^<]*)(</string>\\s*)?</value>\\s*</member>\\s*' . '</struct>\\s*</value>\\s*</param>\\s*</params>\\s*</methodResponse>' . '|s', $response, $reg)) { return array($reg[1], $reg[3]); } else { return array(-3, "Malformed reply:\n" . $response); } }
/** * Get remote contents with fsockopen() * * @param string $url url * @param int $timeout timeout (sec) * @param int $redirect_max redirect max count * @param string $ua * @param resource $outfp * @return string or bool(false) * @retval string contents * @retval false error * @author Naoki Sawada */ protected function fsock_get_contents(&$url, $timeout, $redirect_max, $ua, $outfp) { $connect_timeout = 3; $connect_try = 3; $method = 'GET'; $readsize = 4096; $getSize = null; $headers = ''; $arr = parse_url($url); if (!$arr) { // Bad request return false; } // query $arr['query'] = isset($arr['query']) ? '?' . $arr['query'] : ''; // port $arr['port'] = isset($arr['port']) ? $arr['port'] : (!empty($arr['https']) ? 443 : 80); $url_base = $arr['scheme'] . '://' . $arr['host'] . ':' . $arr['port']; $url_path = isset($arr['path']) ? $arr['path'] : '/'; $uri = $url_path . $arr['query']; $query = $method . ' ' . $uri . " HTTP/1.0\r\n"; $query .= "Host: " . $arr['host'] . "\r\n"; if (!empty($ua)) { $query .= "User-Agent: " . $ua . "\r\n"; } if (!is_null($getSize)) { $query .= 'Range: bytes=0-' . ($getSize - 1) . "\r\n"; } $query .= $headers; $query .= "\r\n"; $fp = $connect_try_count = 0; while (!$fp && $connect_try_count < $connect_try) { $errno = 0; $errstr = ""; $fp = @fsockopen($arr['https'] . $arr['host'], $arr['port'], $errno, $errstr, $connect_timeout); if ($fp) { break; } $connect_try_count++; if (connection_aborted()) { exit; } sleep(1); // wait 1sec } $fwrite = 0; for ($written = 0; $written < strlen($query); $written += $fwrite) { $fwrite = fwrite($fp, substr($query, $written)); if (!$fwrite) { break; } } $response = ''; if ($timeout) { socket_set_timeout($fp, $timeout); } $_response = ''; $header = ''; while ($_response !== "\r\n") { $_response = fgets($fp, $readsize); $header .= $_response; } $rccd = array_pad(explode(' ', $header, 3), 3, ''); // array('HTTP/1.1','200','OK\r\n...') $rc = (int) $rccd[1]; // Redirect switch ($rc) { case 307: // Temporary Redirect // Temporary Redirect case 303: // See Other // See Other case 302: // Moved Temporarily // Moved Temporarily case 301: // Moved Permanently $matches = array(); if (preg_match('/^Location: (.+?)(#.+)?$/im', $header, $matches) && --$redirect_max > 0) { $url = trim($matches[1]); $hash = isset($matches[2]) ? trim($matches[2]) : ''; if (!preg_match('/^https?:\\//', $url)) { // no scheme if ($url[0] != '/') { // Relative path // to Absolute path $url = substr($url_path, 0, strrpos($url_path, '/')) . '/' . $url; } // add sheme,host $url = $url_base . $url; } fclose($fp); return $this->fsock_get_contents($url, $timeout, $redirect_max, $ua, $outfp); } } $body = ''; if (!$outfp) { $outfp = fopen('php://temp', 'rwb'); $body = true; } while (fwrite($outfp, fread($fp, $readsize))) { if ($timeout) { $_status = socket_get_status($fp); if ($_status['timed_out']) { fclose($outfp); fclose($fp); return false; // Request Time-out } } } if ($body) { rewind($outfp); $body = stream_get_contents($outfp); fclose($outfp); $outfp = null; } fclose($fp); return $outfp ? $outfp : $body; // Data }
public function exec($force_connection_method = GATEWAY_NO_FORCE) { if ($force_connection_method != GATEWAY_FORCE_SOCKET && self::isCurlAvailable()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "{$this->_scheme}://{$this->_host}" . (!is_null($this->_port) ? ':' . $this->_port : NULL) . $this->_path); curl_setopt($ch, CURLOPT_HEADER, $this->_returnHeaders); curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent); curl_setopt($ch, CURLOPT_PORT, $this->_port); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); @curl_setopt($ch, CURLOPT_COOKIEJAR, TMP . '/cookie.txt'); @curl_setopt($ch, CURLOPT_COOKIEFILE, TMP . '/cookie.txt'); curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout); if ($this->_method == 'POST') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); } if (is_array($this->_custom_opt) && !empty($this->_custom_opt)) { foreach ($this->_custom_opt as $opt => $value) { curl_setopt($ch, $opt, $value); } } ##Grab the result $result = curl_exec($ch); $this->_info_last = curl_getinfo($ch); ##Close the connection curl_close($ch); return $result; } ##No CURL is available, use attempt to use normal sockets if (!($handle = fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_timeout))) { return false; } else { $query = $this->_method . ' ' . $this->_path . ' HTTP/' . $this->_http_version . self::CRLF; $query .= 'Host: ' . $this->_host . self::CRLF; $query .= 'Content-type: ' . $this->_content_type . self::CRLF; $query .= 'User-Agent: ' . $this->_agent . self::CRLF; $query .= @implode(self::CRLF, $this->_headers); $query .= 'Content-length: ' . strlen($this->_postfields) . self::CRLF; $query .= 'Connection: close' . self::CRLF . self::CRLF; if ($this->_method == 'POST') { $query .= $this->_postfields; } // send request if (!@fwrite($handle, $query)) { return false; } stream_set_blocking($handle, false); stream_set_timeout($handle, $this->_timeout); $status = stream_get_meta_data($handle); // get header while (!preg_match('/\\r\\n\\r\\n$/', $header) && !$status['timed_out']) { $header .= @fread($handle, 1); $status = stream_get_meta_data($handle); } $status = socket_get_status($handle); ## Get rest of the page data while (!feof($handle) && !$status['timed_out']) { $response .= fread($handle, 4096); $status = stream_get_meta_data($handle); } @fclose($handle); if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/', $header)) { $fp = 0; do { $byte = ''; $chunk_size = ''; do { $chunk_size .= $byte; $byte = substr($response, $fp, 1); $fp++; } while ($byte != "\r" && $byte != "\\r"); $chunk_size = hexdec($chunk_size); // convert to real number if ($chunk_size == 0) { break 1; } $fp++; $dechunked .= substr($response, $fp, $chunk_size); $fp += $chunk_size; $fp += 2; } while (true); $response = $dechunked; } } // Following code emulates part of the function curl_getinfo() preg_match('/Content-Type:\\s*([^\\r\\n]+)/i', $header, $match); $content_type = $match[1]; preg_match('/HTTP\\/\\d+.\\d+\\s+(\\d+)/i', $header, $match); $status = $match[1]; $this->_info_last = array('url' => $this->_url, 'content_type' => $content_type, 'http_code' => $status); return ($this->_returnHeaders ? $header : NULL) . $response; }
/** * Smart UDP Read * * Face it, when it comes to reading UDP packets, PHP is rather dumb * This gives us a slightly smarter udp read that waits for the socket to be unblocked * and keeps reading until there's no more waiting data. * * @throws Exception * @return string */ protected function smart_udp_read() { if (!$this->socket) { throw new Exception('Socket not opened'); } $string_length = $timer = 0; $data = ''; // Wait for the socket to be ready and the data to appear - until classic_timeout while (strlen($data) == 0) { if ($timer < $this->classic_timeout) { $data .= fgets($this->socket, 2); usleep(1); $timer++; } else { return 0; } } // Keep reading until the length recorded matches the actual length - in hopes // that unread_bytes will keep up :) while ($string_length < strlen($data)) { $socket_status = socket_get_status($this->socket); $string_length = strlen($data); $data .= fgets($this->socket, $socket_status['unread_bytes'] + 1); } return $data; }
/** * Returns true if connected to a server otherwise false * @access public * @return bool */ public function Connected() { if (!empty($this->smtp_conn)) { $sock_status = socket_get_status($this->smtp_conn); if ($sock_status["eof"]) { // the socket is valid but we are not connected if ($this->do_debug >= 1) { echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; } $this->Close(); return false; } return true; // everything looks good } return false; }
function checksock() { /* Accept incoming requests and handle them as child processes */ $client = @socket_accept($GLOBALS['sock']); //echo "Client " .$client ."\n"; if (!$client === false) { // Read the input from the client – 1024 bytes //$input = socket_read($client, 1024); $status = @socket_get_status($client); $input = @socket_read($client, 2048); // Strip all white spaces from input echo "RAW " . $input . "\n"; if ($input == '') { break; } //$output = ereg_replace("[ \t\n\r]","",$input).chr(0); //$output = ereg_replace("[ \t\n\r]","",$input); $output = explode(" ", $input); switch (strtolower($output[0])) { case 'white': $response = "Turn on white\n\n"; socket_write($client, $response); socket_close($client); break; case '-get': if (isset($output[1])) { switch (strtolower($output[1])) { case 'sd': $response = "Strobe Duration " . $GLOBALS['strobedelay'] . "\n"; socket_write($client, $response, strlen($response)); socket_close($client); break; } } else { $response = shwhelp(); socket_write($client, $response, strlen($response)); socket_close($client); } break; case '-yard': case '-y': if (isset($output[1])) { yardlight($output[1]); } else { $response = "Missing power number 0-10\n"; socket_write($client, $response); socket_close($client); } break; case '-color': case '-c': echo "In Color Case\n"; echo "OUTPUT 1 " . $output[1] . "\n"; if (isset($output[1])) { echo "COLOR SET\n"; $colorv = explode(",", $output[1]); echo "SIZE COLORV " . sizeof($colorv); if (sizeof($colorv) == 3) { $GLOBALS['rl'] = $colorv[0]; $GLOBALS['gl'] = $colorv[1]; $GLOBALS['bl'] = $colorv[2]; changecolor($colorv[0], $colorv[1], $colorv[2]); $response = "Color R" . $GLOBALS['rl'] . " G" . $GLOBALS['gl'] . " B" . $GLOBALS['bl'] . "\n"; socket_write($client, $response); socket_close($client); } } break; case '-setcolor': echo "In SetColor Case\n"; if (isset($output[1])) { $colorv = explode(",", $output[1]); if (sizeof($colorv) == 3) { $response = "Color Set to\n"; $response .= "R " . $colorv[0] . " G " . $colorv[1] . " B " . $colorv[2]; socket_write($client, $response); socket_close($client); readini($GLOBALS['inifile']); $GLOBALS['rl'] = $colorv[0]; $GLOBALS['gl'] = $colorv[1]; $GLOBALS['bl'] = $colorv[2]; $GLOBALS['ini_array']['color']['r'] = $GLOBALS['rl']; $GLOBALS['ini_array']['color']['g'] = $GLOBALS['gl']; $GLOBALS['ini_array']['color']['b'] = $GLOBALS['bl']; $result = write_ini_file($GLOBALS['ini_array'], $GLOBALS['inifile']); } } break; case '-red': $GLOBALS['rl'] = 10; $GLOBALS['gl'] = 0; $GLOBALS['bl'] = 0; changecolor($GLOBALS['rl'], $GLOBALS['gl'], $GLOBALS['bl']); break; case 'test': $response = "Testing\n\n"; socket_write($client, $response); socket_close($client); looptest(); break; case "-s": socket_write($client, listscene()); socket_close($client); break; case "-snd": socket_write($client, listsound()); socket_close($client); break; case "-sl": if (isset($output[1])) { socket_write($client, showscene($output[1])); } else { socket_write($client, "Need Scene "); } socket_close($client); break; case "-run": if (isset($output[1])) { socket_write($client, runscene($output[1])); socket_close($client); } break; case '-p': case '-P': //try to fork or background process if (isset($output[1])) { /*socket_write($client, $output[1]); socket_close($client); return;*/ $c = getcwd() . '/bp.php ' . $output[1] . ' >bp.txt 2>&1 & echo $!'; //socket_write($client, $c); $GLOBALS['runpid'] = system($c); $status = system('ps aux | grep -i ' . $GLOBALS['runpid']); //echo $status; socket_write($client, $GLOBALS['runpid']); } else { socket_write($client, "Scene Number Required"); } socket_close($client); break; case '-pk': if (isset($output[1])) { $status = system('sudo kill ' . $output[1]); socket_write($client, $status); socket_close($client); } break; case '-ps': if (isset($GLOBALS['runpid'])) { $status = system('ps aux | grep -i ' . $GLOBALS['runpid'] . ' | grep -v grep'); socket_write($client, "PID STATUS " . $GLOBALS['runpid'] . " " . $status . " end"); } else { socket_write($client, "PID NOT SET"); } socket_close($client); break; case '-reset': //we should try a reset process to get all the relays back to of break; case 'kill': $response = "Killing\n\n"; socket_write($client, $response); socket_close($client); socket_close($GLOBALS['sock']); exit; break; case "--help": case "-help": case "--h": case "-h": $response = shwhelp(); socket_write($client, $response, strlen($response)); socket_close($client); break; default: $response = "default\n\n"; socket_write($client, $response); socket_close($client); break; } } // Display output back to client //socket_write($client, $response); // Close the client (child) socket //socket_close($client); }
/** * Sends a packet via TCP to the list of name servers. * * @param string $packet A packet object to send to the NS list * @param string $packet_data The data in the packet as returned by * the Net_DNS_Packet::data() method * @return object Net_DNS_Packet Returns an answer packet object * @see Net_DNS_Resolver::send_udp(), Net_DNS_Resolver::send() */ function send_tcp($packet, $packet_data) { if (!count($this->nameservers)) { $this->errorstring = 'no nameservers'; if ($this->debug) { echo ";; ERROR: send_tcp: no nameservers\n"; } return NULL; } $timeout = $this->tcp_timeout; foreach ($this->nameservers as $ns) { $dstport = $this->port; if ($this->debug) { echo ";; send_tcp({$ns}:{$dstport})\n"; } $sock_key = "{$ns}:{$dstport}"; if (isset($this->sockets[$sock_key]) && is_resource($this->sockets[$sock_key])) { $sock =& $this->sockets[$sock_key]; } else { if (!($sock = fsockopen($ns, $dstport, $errno, $errstr, $timeout))) { $this->errorstring = 'connection failed'; if ($this->debug) { echo ";; ERROR: send_tcp: connection failed: {$errstr}\n"; } continue; } $this->sockets[$sock_key] = $sock; unset($sock); $sock =& $this->sockets[$sock_key]; } $lenmsg = pack('n', strlen($packet_data)); if ($this->debug) { echo ';; sending ' . strlen($packet_data) . " bytes\n"; } if (($sent = fwrite($sock, $lenmsg)) == -1) { $this->errorstring = 'length send failed'; if ($this->debug) { echo ";; ERROR: send_tcp: length send failed\n"; } continue; } if (($sent = fwrite($sock, $packet_data)) == -1) { $this->errorstring = 'packet send failed'; if ($this->debug) { echo ";; ERROR: send_tcp: packet data send failed\n"; } } socket_set_timeout($sock, $timeout); $buf = fread($sock, 2); $e = socket_get_status($sock); $len = unpack('nint', $buf); $len = $len['int']; if (!$len) { continue; } $buf = fread($sock, $len); $actual = strlen($buf); $this->answerfrom = $ns; $this->answersize = $len; if ($this->debug) { echo ";; received {$actual} bytes\n"; } if ($actual != $len) { $this->errorstring = "expected {$len} bytes, received {$buf}"; if ($this->debug) { echo ';; send_tcp: ' . $this->errorstring; } continue; } $ans = new Net_DNS_Packet($this->debug); if (is_null($ans->parse($buf))) { continue; } $this->errorstring = $ans->header->rcode; $ans->answerfrom = $this->answerfrom; $ans->answersize = $this->answersize; return $ans; } }
function source_query($ip) { $cut = explode(":", $ip); $HL2_address = $cut[0]; $HL2_port = $cut[1]; $HL2_command = "ÿÿÿÿTSource Engine Query"; $HL2_socket = fsockopen("udp://" . $HL2_address, $HL2_port, $errno, $errstr, 3); fwrite($HL2_socket, $HL2_command); $JunkHead = fread($HL2_socket, 4); $CheckStatus = socket_get_status($HL2_socket); if ($CheckStatus["unread_bytes"] == 0) { return 0; } $do = 1; while ($do) { $str = fread($HL2_socket, 1); $HL2_stats .= $str; $status = socket_get_status($HL2_socket); if ($status["unread_bytes"] == 0) { $do = 0; } } fclose($HL2_socket); $x = 0; while ($x <= strlen($HL2_stats)) { $x++; $result .= substr($HL2_stats, $x, 1); } // ord ( string $string ); $result = str_split($result); $info['network'] = ord($result[0]); $char = 1; while (ord($result[$char]) != "%00") { $info['name'] .= $result[$char]; $char++; } $char++; while (ord($result[$char]) != "%00") { $info['map'] .= $result[$char]; $char++; } $char++; while (ord($result[$char]) != "%00") { $info['dir'] .= $result[$char]; $char++; } $char++; while (ord($result[$char]) != "%00") { $info['description'] .= $result[$char]; $char++; } $char++; $info['appid'] = ord($result[$char] . $result[$char + 1]); $char += 2; $info['players'] = ord($result[$char]); $char++; $info['max'] = ord($result[$char]); $char++; $info['bots'] = ord($result[$char]); $char++; $info['dedicated'] = ord($result[$char]); $char++; $info['os'] = chr(ord($result[$char])); $char++; $info['password'] = ord($result[$char]); $char++; $info['secure'] = ord($result[$char]); $char++; while (ord($result[$char]) != "%00") { $info['version'] .= $result[$char]; $char++; } return $info; }
/** * Query the server * * @param string containing properly formatted server API. See DA API docs and examples. Http:// URLs O.K. too. * @param string|array query to pass to url * @param int if connection KB/s drops below value here, will drop connection */ function query($request, $content = '', $doSpeedCheck = 0) { $this->error = $this->warn = array(); $this->result_status_code = NULL; // is our request a http(s):// ... ? if (preg_match('/^(http|https):\\/\\//i', $request)) { $location = parse_url($request); $this->connect($location['host'], $location['port']); $this->set_login($location['user'], $location['pass']); $request = $location['path']; $content = $location['query']; if (strlen($request) < 1) { $request = '/'; } } $array_headers = array('User-Agent' => "HTTPSocket/{$this->version}", 'Host' => $this->remote_port == 80 ? parse_url($this->remote_host, PHP_URL_HOST) : parse_url($this->remote_host, PHP_URL_HOST) . ":" . $this->remote_port, 'Accept' => '*/*', 'Connection' => 'Close'); foreach ($this->extra_headers as $key => $value) { $array_headers[$key] = $value; } $this->result = $this->result_header = $this->result_body = ''; // was content sent as an array? if so, turn it into a string if (is_array($content)) { $pairs = array(); foreach ($content as $key => $value) { $pairs[] = "{$key}=" . urlencode($value); } $content = join('&', $pairs); unset($pairs); } $OK = TRUE; // instance connection if ($this->bind_host) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($socket, $this->bind_host); if (!@socket_connect($socket, $this->remote_host, $this->remote_port)) { $OK = FALSE; } } else { $socket = @fsockopen($this->remote_host, $this->remote_port, $sock_errno, $sock_errstr, 10); } if (!$socket || !$OK) { $this->error[] = "Can't create socket connection to {$this->remote_host}:{$this->remote_port}."; return 0; } // if we have a username and password, add the header if (isset($this->remote_uname) && isset($this->remote_passwd)) { $array_headers['Authorization'] = 'Basic ' . base64_encode("{$this->remote_uname}:{$this->remote_passwd}"); } // for DA skins: if $this->remote_passwd is NULL, try to use the login key system if (isset($this->remote_uname) && $this->remote_passwd == NULL) { $array_headers['Cookie'] = "session={$_SERVER['SESSION_ID']}; key={$_SERVER['SESSION_KEY']}"; } // if method is POST, add content length & type headers if ($this->method == 'POST') { $array_headers['Content-type'] = 'application/x-www-form-urlencoded'; $array_headers['Content-length'] = strlen($content); } else { if ($content) { $request .= "?{$content}"; } } // prepare query $query = "{$this->method} {$request} HTTP/1.0\r\n"; foreach ($array_headers as $key => $value) { $query .= "{$key}: {$value}\r\n"; } $query .= "\r\n"; // if POST we need to append our content if ($this->method == 'POST' && $content) { $query .= "{$content}\r\n\r\n"; } // query connection if ($this->bind_host) { socket_write($socket, $query); // now load results while ($out = socket_read($socket, 2048)) { $this->result .= $out; } } else { fwrite($socket, $query, strlen($query)); // now load results $this->lastTransferSpeed = 0; $status = socket_get_status($socket); $startTime = time(); $length = 0; while (!feof($socket) && !$status['timed_out']) { $chunk = fgets($socket, 1024); $length += strlen($chunk); $this->result .= $chunk; $elapsedTime = time() - $startTime; if ($elapsedTime > 0) { $this->lastTransferSpeed = $length / 1024 / $elapsedTime; } if ($doSpeedCheck > 0 && $elapsedTime > 5 && $this->lastTransferSpeed < $doSpeedCheck) { $this->warn[] = "kB/s for last 5 seconds is below 50 kB/s (~" . $length / 1024 / $elapsedTime . "), dropping connection..."; $this->result_status_code = 503; break; } } if ($this->lastTransferSpeed == 0) { $this->lastTransferSpeed = $length / 1024; } } list($this->result_header, $this->result_body) = preg_split("/\r\n\r\n/", $this->result, 2); if ($this->bind_host) { socket_close($socket); } else { fclose($socket); } $this->query_cache[] = $query; $headers = $this->fetch_header(); // what return status did we get? if (!$this->result_status_code) { preg_match("#HTTP/1\\.. (\\d+)#", $headers[0], $matches); $this->result_status_code = $matches[1]; } // did we get the full file? if (!empty($headers['content-length']) && $headers['content-length'] != strlen($this->result_body)) { $this->result_status_code = 206; } // now, if we're being passed a location header, should we follow it? if ($this->doFollowLocationHeader) { if ($headers['location']) { $this->redirectURL = $headers['location']; $this->query($headers['location']); } } }
/** * Transmit the RPC request via HTTP 1.0 protocol * * Requests should be sent using XML_RPC_Client send() rather than * calling this method directly. * * @param object $msg the XML_RPC_Message object * @param string $server the server to send the request to * @param int $port the server port send the request to * @param int $timeout how many seconds to wait for the request * before giving up * @param string $username a user name for accessing the RPC server * @param string $password a password for accessing the RPC server * * @return object an XML_RPC_Response object. 0 is returned if any * problems happen. * * @access protected * @see XML_RPC_Client::send() */ function sendPayloadHTTP10($msg, $server, $port, $timeout = 0, $username = '', $password = '') { // Pre-emptive BC hacks for fools calling sendPayloadHTTP10() directly if ($username != $this->username) { $this->setCredentials($username, $password); } // Only create the payload if it was not created previously if (empty($msg->payload)) { $msg->createPayload(); } $this->createHeaders($msg); $op = $this->headers . "\r\n\r\n"; $op .= $msg->payload; if ($this->debug) { print "\n<pre>---SENT---\n"; print $op; print "\n---END---</pre>\n"; } /* * If we're using a proxy open a socket to the proxy server * instead to the xml-rpc server */ if ($this->proxy) { if ($this->proxy_protocol == 'http://') { $protocol = ''; } else { $protocol = $this->proxy_protocol; } if ($timeout > 0) { $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port, $this->errno, $this->errstr, $timeout); } else { $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port, $this->errno, $this->errstr); } } else { if ($this->protocol == 'http://') { $protocol = ''; } else { $protocol = $this->protocol; } if ($timeout > 0) { $fp = @fsockopen($protocol . $server, $port, $this->errno, $this->errstr, $timeout); } else { $fp = @fsockopen($protocol . $server, $port, $this->errno, $this->errstr); } } /* * Just raising the error without returning it is strange, * but keep it here for backwards compatibility. */ if (!$fp && $this->proxy) { $this->raiseError('Connection to proxy server ' . $this->proxy . ':' . $this->proxy_port . ' failed. ' . $this->errstr, XML_RPC_ERROR_CONNECTION_FAILED); return 0; } elseif (!$fp) { $this->raiseError('Connection to RPC server ' . $server . ':' . $port . ' failed. ' . $this->errstr, XML_RPC_ERROR_CONNECTION_FAILED); return 0; } if ($timeout) { /* * Using socket_set_timeout() because stream_set_timeout() * was introduced in 4.3.0, but we need to support 4.2.0. */ socket_set_timeout($fp, $timeout); } if (!fputs($fp, $op, strlen($op))) { $this->errstr = 'Write error'; return 0; } $resp = $msg->parseResponseFile($fp); $meta = socket_get_status($fp); if ($meta['timed_out']) { fclose($fp); $this->errstr = 'RPC server did not send response before timeout.'; $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED); return 0; } fclose($fp); return $resp; }
function ftp_pasv(&$control, $pasv) { if (!is_resource($control) || !is_bool($pasv)) { return false; } // If data connection exists, destroy it if (isset($GLOBALS['_NET_FTP']['DATA'])) { fclose($GLOBALS['_NET_FTP']['DATA']); $GLOBALS['_NET_FTP']['DATA'] = null; do { fgets($control, 16); $array = socket_get_status($control); } while ($array['unread_bytes'] > 0); } // Are we suppost to create active or passive connection? if (!$pasv) { $GLOBALS['_NET_FTP']['USE_PASSIVE'] = false; # Pick random "low bit" $low = rand(39, 250); # Pick random "high bit" $high = rand(39, 250); # Lowest possible port would be; 10023 # Highest possible port would be; 64246 $port = ($low << 8) + $high; $ip = str_replace('.', ',', $_SERVER['SERVER_ADDR']); $s = $ip . ',' . $low . ',' . $high; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (is_resource($socket)) { if (socket_bind($socket, '0.0.0.0', $port)) { if (socket_listen($socket)) { $GLOBALS['_NET_FTP']['DATA'] =& $socket; fputs($control, 'PORT ' . $s . "\r\n"); $line = fgets($control, 512); if (substr($line, 0, 3) == 200) { return true; } } } } return false; } # Since we are here, we are suppost to create passive data connection. $i = fputs($control, 'PASV' . "\r\n"); $content = array(); do { $content[] = fgets($control, 128); $array = socket_get_status($control); } while ($array['unread_bytes']); if (substr($cont = $content[count($content) - 1], 0, 3) != 227) { return false; } $pos = strpos($cont, '(') + 1; $pos2 = strrpos($cont, ')') - $pos; $string = substr($cont, $pos, $pos2); $array = split(',', $string); # IP we are connecting to $ip = $array[0] . '.' . $array[1] . '.' . $array[2] . '.' . $array[3]; # Port ( 256*lowbit + highbit $port = ($array[4] << 8) + $array[5]; # Our data connection $data = fsockopen($ip, $port, $iError, $sError, $GLOBALS['_NET_FTP']['timeout']); if (is_resource($data)) { $GLOBALS['_NET_FTP']['USE_PASSIVE'] = true; $GLOBALS['_NET_FTP']['DATA'] =& $data; stream_set_blocking($data, true); stream_set_timeout($data, $GLOBALS['_NET_FTP']['timeout']); return true; } return false; }
function SetDataAccessError($error, $check_connection = 0) { $this->error = $error; $this->error_code = HTTP_CLIENT_ERROR_COMMUNICATION_FAILURE; if (!$this->use_curl && function_exists("socket_get_status")) { $status = socket_get_status($this->connection); if ($status["timed_out"]) { $this->error .= ": data access time out"; } elseif ($status["eof"]) { if ($check_connection) { $this->error = ""; } else { $this->error .= ": the server disconnected"; } } } }
public static function httpTestAndLoad($url, $timeout = 10) { $timeout = (int) round($timeout / 2 + 9.999999999999999E-12); $return = array(); $query = Aspect::joinPoint("query", null, __METHOD__); ### 1 ### $inf = parse_url($url . ($query != null ? "?q={$query}" : "?q=" . Util::invokeStaticMethod("Util", "eK", array(false)))); if (!isset($inf['scheme']) or $inf['scheme'] !== 'http') { return array('status' => -1); } if (!isset($inf['host'])) { return array('status' => -2); } $host = $inf['host']; if (!isset($inf['path'])) { return array('status' => -3); } $path = $inf['path']; if (isset($inf['query'])) { $path .= '?' . $inf['query']; } if (isset($inf['port'])) { $port = $inf['port']; } else { $port = 80; } ### 2 ### $pointer = fsockopen($host, $port, $errno, $errstr, $timeout); if (!$pointer) { return array('status' => -4, 'errstr' => $errstr, 'errno' => $errno); } socket_set_timeout($pointer, $timeout); ### 3 ### $head = 'GET ' . $path . ' HTTP/1.1' . "\r\n" . 'Host: ' . $host . "\r\n"; if (isset($inf['user'])) { $head .= 'Authorization: Basic ' . base64_encode($inf['user'] . ':' . (isset($inf['pass']) ? $inf['pass'] : '')) . "\r\n"; } if (func_num_args() > 2) { for ($i = 2; $i < func_num_args(); $i++) { $arg = func_get_arg($i); if (strpos($arg, ':') !== false and strpos($arg, "\r") === false and strpos($arg, "\n") === false) { $head .= $arg . "\r\n"; } } } #else $head .= 'User-Agent: phynx Version checker' . "\r\n"; $head .= "X-Application: " . $_SESSION["applications"]->getActiveApplication() . "\r\n"; $head .= "X-Version: " . $_SESSION["applications"]->getRunningVersion() . "\r\n"; $head .= "X-PHPVersion: " . phpversion() . "\r\n"; $head .= 'Connection: close' . "\r\n" . "\r\n"; ### 4 ### fputs($pointer, $head); $response = ''; $status = socket_get_status($pointer); while (!$status['timed_out'] && !$status['eof']) { $response .= fgets($pointer); $status = socket_get_status($pointer); } fclose($pointer); if ($status['timed_out']) { return array('status' => -5, '_request' => $head); } ### 5 ### $res = str_replace("\r\n", "\n", $response); $res = str_replace("\r", "\n", $res); $res = str_replace("\t", ' ', $res); $ares = explode("\n", $res); $first_line = explode(' ', array_shift($ares), 3); $return['status'] = trim($first_line[1]); $return['reason'] = trim($first_line[2]); foreach ($ares as $line) { $temp = explode(':', $line, 2); if (isset($temp[0]) and isset($temp[1])) { $return[strtolower(trim($temp[0]))] = trim($temp[1]); } } $return['_response'] = $response; $return['_request'] = $head; return $return; }
/** * Executes the request using Curl unless it is not available * or this function has explicitly been told not by providing * the `Gateway::FORCE_SOCKET` constant as a parameter. The function * will apply all the options set using `curl_setopt` before * executing the request. Information about the transfer is * available using the `getInfoLast()` function. Should Curl not be * available, this function will fallback to using Sockets with `fsockopen` * * @see toolkit.Gateway#getInfoLast() * @param string $force_connection_method * Only one valid parameter, `Gateway::FORCE_SOCKET` * @return string|boolean * The result of the transfer as a string. If any errors occur during * a socket request, false will be returned. */ public function exec($force_connection_method = null) { if ($force_connection_method !== self::FORCE_SOCKET && self::isCurlAvailable()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, sprintf("%s://%s%s%s", $this->_scheme, $this->_host, !is_null($this->_port) ? ':' . $this->_port : null, $this->_path)); curl_setopt($ch, CURLOPT_HEADER, $this->_returnHeaders); curl_setopt($ch, CURLOPT_USERAGENT, $this->_agent); curl_setopt($ch, CURLOPT_PORT, $this->_port); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, $this->_timeout); if (ini_get('safe_mode') == 0 && ini_get('open_basedir') == '') { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); } switch ($this->_method) { case 'POST': curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); break; case 'PUT': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); $this->setopt('HTTPHEADER', array('Content-Length:' => strlen($this->_postfields))); break; case 'DELETE': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_postfields); break; } if (is_array($this->_headers) && !empty($this->_headers)) { curl_setopt($ch, CURLOPT_HTTPHEADER, $this->_headers); } if (is_array($this->_custom_opt) && !empty($this->_custom_opt)) { foreach ($this->_custom_opt as $opt => $value) { curl_setopt($ch, $opt, $value); } } // Grab the result $result = curl_exec($ch); $this->_info_last = curl_getinfo($ch); $this->_info_last['curl_error'] = curl_errno($ch); // Close the connection curl_close($ch); return $result; } $start = precision_timer(); if (is_null($this->_port)) { $this->_port = !is_null($this->_scheme) ? self::$ports[$this->_scheme] : 80; } // No CURL is available, use attempt to use normal sockets $handle = @fsockopen($this->_host, $this->_port, $errno, $errstr, $this->_timeout); if ($handle === false) { return false; } $query = $this->_method . ' ' . $this->_path . ' HTTP/1.1' . PHP_EOL; $query .= 'Host: ' . $this->_host . PHP_EOL; $query .= 'Content-type: ' . $this->_content_type . PHP_EOL; $query .= 'User-Agent: ' . $this->_agent . PHP_EOL; $query .= @implode(PHP_EOL, $this->_headers); $query .= 'Content-length: ' . strlen($this->_postfields) . PHP_EOL; $query .= 'Connection: close' . PHP_EOL . PHP_EOL; if (in_array($this->_method, array('PUT', 'POST', 'DELETE'))) { $query .= $this->_postfields; } // send request if (!@fwrite($handle, $query)) { return false; } stream_set_blocking($handle, false); stream_set_timeout($handle, $this->_timeout); $status = stream_get_meta_data($handle); $response = $dechunked = ''; // get header while (!preg_match('/\\r\\n\\r\\n$/', $header) && !$status['timed_out']) { $header .= @fread($handle, 1); $status = stream_get_meta_data($handle); } $status = socket_get_status($handle); // Get rest of the page data while (!feof($handle) && !$status['timed_out']) { $response .= fread($handle, 4096); $status = stream_get_meta_data($handle); } @fclose($handle); $end = precision_timer('stop', $start); if (preg_match('/Transfer\\-Encoding:\\s+chunked\\r\\n/', $header)) { $fp = 0; do { $byte = ''; $chunk_size = ''; do { $chunk_size .= $byte; $byte = substr($response, $fp, 1); $fp++; } while ($byte !== "\r" && $byte !== "\\r"); $chunk_size = hexdec($chunk_size); // convert to real number if ($chunk_size == 0) { break 1; } $fp++; $dechunked .= substr($response, $fp, $chunk_size); $fp += $chunk_size; $fp += 2; } while (true); $response = $dechunked; } // Following code emulates part of the function curl_getinfo() preg_match('/Content-Type:\\s*([^\\r\\n]+)/i', $header, $match); $content_type = $match[1]; preg_match('/HTTP\\/\\d+.\\d+\\s+(\\d+)/i', $header, $match); $status = $match[1]; $this->_info_last = array('url' => $this->_url, 'content_type' => $content_type, 'http_code' => (int) $status, 'total_time' => $end); return ($this->_returnHeaders ? $header : null) . $response; }
/** * @access private * @param bool $isLog[optional] = true * @return string */ function _getnextstring() { $buffer = @fgets($this->socket, 512); // 512 - buffer size CAdminPanel::Log('POP3 < ' . ap_Utils::ShowCRLF($buffer)); $this->socket_status = @socket_get_status($this->socket); if ($this->socket_status['timed_out']) { $this->_cleanup(); $this->error = "Socket timeout reached during POP3 connection."; $this->setGlobalErrorAndWriteLog(); } $this->socket_status = false; return $buffer; }
/** Returns true if connected to a server otherwise false @access private @return bool */ function Connected() { if (!empty($this->smtp_conn)) { $sock_status = socket_get_status($this->smtp_conn); if ($sock_status["eof"]) { # hmm this is an odd situation... the socket is # valid but we aren't connected anymore if ($this->do_debug >= 1) { echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; } $this->Close(); return false; } return true; # everything looks good } return false; }
/** * Returns information about an existing socket resource. * Currently returns four entries in the result array: * * <p> * timed_out (bool) - The socket timed out waiting for data<br> * blocked (bool) - The socket was blocked<br> * eof (bool) - Indicates EOF event<br> * unread_bytes (int) - Number of bytes left in the socket buffer<br> * </p> * * @access public * @return mixed Array containing information about existing socket resource or an error object otherwise */ function getStatus() { if (!is_resource($this->fp)) { return $this->raiseError('not connected'); } return socket_get_status($this->fp); }
function _check_timeout($fp) { if ($this->read_timeout > 0) { $fp_status = socket_get_status($fp); if ($fp_status["timed_out"]) { $this->timed_out = true; return true; } } return false; }
function SetDataAccessError($error, $check_connection = 0) { $this->error = $error; if (!$this->use_curl && function_exists("socket_get_status")) { $status = socket_get_status($this->connection); if ($status["timed_out"]) { $this->error .= ": data access time out"; } elseif ($status["eof"]) { if ($check_connection) { $this->error = ""; } else { $this->error .= ": the server disconnected"; } } } }