/**
 * 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;
    }
}
Пример #2
1
 protected function _recv()
 {
     stream_set_timeout($this->_fp, 0, $this->_timeout_recv);
     $data = fread($this->_fp, 24);
     $info = stream_get_meta_data($this->_fp);
     if ($info['timed_out']) {
         return FALSE;
     }
     $array = $this->_show_request($data);
     if ($array['bodylength']) {
         $bodylength = $array['bodylength'];
         $data = '';
         while ($bodylength > 0) {
             $recv_data = fread($this->_fp, $bodylength);
             $bodylength -= strlen($recv_data);
             $data .= $recv_data;
         }
         if ($array['extralength']) {
             $extra_unpacked = unpack('Nint', substr($data, 0, $array['extralength']));
             $array['extra'] = $extra_unpacked['int'];
         }
         $array['key'] = substr($data, $array['extralength'], $array['keylength']);
         $array['body'] = substr($data, $array['extralength'] + $array['keylength']);
     }
     return $array;
 }
Пример #3
0
 public function connect($ip, $port)
 {
     $this->remoteip = $ip;
     $this->remoteport = $port;
     $errno = 0;
     $errstr = '';
     logger::debug("Connecting to %s:%d", $ip, $port);
     $this->state = SOCKSTATE_CONNECTING;
     $this->fsh = fsockopen($ip, $port, $errno, $errstr);
     if ($errno) {
         logger::warning("Socket error: %d %s (%s:%d)", $errno, $errstr, $ip, $port);
         $this->state = SOCKSTATE_ERROR;
         return false;
     } else {
         if (!$this->fsh) {
             $this->state = SOCKSTATE_ERROR;
             logger::warning("No socket handle returned but no error indicated");
             return false;
         }
         logger::debug("Socket connected to %s:%d", $ip, $port);
         stream_set_timeout($this->fsh, 0, 200);
         $this->state = SOCKSTATE_CONNECTED;
         return true;
     }
 }
Пример #4
0
 function connect()
 {
     $this->online_start = microtime(true);
     $this->main->log('Connecting to ' . $this->info['address'] . '...', __CLASS__);
     $this->socket = @fsockopen($this->info['address'], $this->info['port'], $erno, $errstr, 30);
     @stream_set_blocking($this->socket, false);
     @stream_set_timeout($this->socket, $this->listen_timeout);
     if ($this->state() == false) {
         $this->main->log('Could not connect to ' . $this->info['address'] . ': (' . $erno . ') ' . $errstr, __CLASS__);
         $this->reconnect();
     } else {
         $this->retry_count = 0;
         $this->main->log('Connection to IRC-server established', __CLASS__);
         //Connection stuff
         if (!empty($this->info['pass'])) {
             $this->main->log('Sending stored password', __CLASS__);
             $this->main->send_data('PASS ' . $this->info['pass'], IRCINE_PRIO_CRITICAL);
         }
         $this->main->log('Authenticating to IRC-server', __CLASS__);
         $this->nickname(Mootyconf::get_value('deerkins::nick'));
         $this->main->log('Sending ident info', __CLASS__);
         $this->main->send_data('USER ' . $this->info['ident'] . ' ' . $this->info['address'] . ' * :' . $this->info['realname'], IRCINE_PRIO_CRITICAL);
         // Idents with server
         $this->main->log('Connection to ' . $this->info['address'] . ' succeeded!', __CLASS__);
         $this->listen();
     }
 }
Пример #5
0
 /**
  * Initialize connection to JSON-RPC server.
  *
  * @throws Exception\JsonRPCException
  */
 function dial()
 {
     $conn = @fsockopen($this->host, $this->port, $errorNumber, $errorString, 5);
     if (!$conn) {
         throw new JsonRPCException(sprintf('An error appeared while connecting to RPC server: %s (%d)', $errorNumber, $errorString), $errorNumber);
     }
     $request = 'CONNECT ' . $this->path . ' HTTP/1.0' . "\n";
     if (array_key_exists('dial_headers', $this->options)) {
         foreach ($this->options['dial_headers'] as $header => $value) {
             $request .= $header . ': ' . $value . "\n";
         }
     }
     @fwrite($conn, $request . "\n");
     stream_set_timeout($conn, 0, 3000);
     do {
         $line = @fgets($conn);
     } while ($line !== false && empty($line));
     $success = 'HTTP/1.0 200 Connected';
     if ($line === false) {
         throw new JsonRPCException('An error appeared while reading from RPC server');
     } else {
         if (substr($line, 0, strlen($success)) != $success) {
             @fclose($conn);
             throw new JsonRPCException(sprintf('Unexpected HTTP response while connecting: %s', $line));
         }
     }
     $this->connection = $conn;
 }
Пример #6
0
 private function InitUrlSocket()
 {
     $i = $CreateCount = $ErrCount = 0;
     $errno = $errstr = 0;
     foreach ($this->Sockets as $Key => $UrlUnit) {
         $Urls = $UrlUnit['Urls'];
         $Port = empty($Urls['port']) ? '80' : $Urls['port'];
         $s = stream_socket_client($Urls['host'] . ':' . $Port, $errno, $errstr, $this->ConnectTimeout, STREAM_CLIENT_ASYNC_CONNECT | STREAM_CLIENT_CONNECT);
         if ($s) {
             stream_set_timeout($s, 0, $this->StreamTimeout);
             $this->Sockets[$Key]['Socket'] = $s;
             $this->Sockets[$Key]['Data'] = '';
             $this->Sockets[$Key]['Succ'] = false;
             $this->Sockets[$Key]['HttpStates'] = array();
             $this->Sockets[$Key]['State'] = 0;
             $this->Sockets[$Key]['Location'] = '';
             $this->Sockets[$Key]['DataLen'] = 0;
             $CreateCount++;
         } elseif ($ErrCount == 3) {
             exit('cannot connection internet');
         } else {
             unset($this->Sockets[$Key]);
             $ErrCount++;
         }
     }
     return $CreateCount;
 }
Пример #7
0
function http_send($_url, $_body)
{
    $errno = 0;
    $errstr = '';
    $timeout = 10;
    $fp = fsockopen(_IP_, _PORT_, $errno, $errstr, $timeout);
    if (!$fp) {
        return FALSE;
    }
    $_head = "POST /" . $_url . " HTTP/1.1\r\n";
    $_head .= "Host: " . _IP_ . ":" . _PORT_ . "\r\n";
    $_head .= "Content-Type: Text/plain\r\n";
    if (!$_body) {
        $body_len = 0;
    } else {
        $body_len = strlen($_body);
    }
    $send_pkg = $_head . "Content-Length:" . $body_len . "\r\n\r\n" . $_body;
    ilog(iLOG_INFO, "    -----> http_send url: " . $_url);
    ilog(iLOG_INFO, "    -----> http_send body: " . $_body);
    if (fputs($fp, $send_pkg) === FALSE) {
        return FALSE;
    }
    //设置3s超时
    stream_set_timeout($fp, 3);
    while (!feof($fp)) {
        ilog(iLOG_INFO, "    -----> rsp: " . fgets($fp, 128));
    }
    if ($fp) {
        fclose($fp);
    }
    return TRUE;
}
Пример #8
0
 public function setSocketTimeout($seconds)
 {
     $this->config['socket_timeout'] = $seconds;
     if (isset($this->connection) && $seconds > 0) {
         stream_set_timeout($this->connection, $seconds);
     }
 }
Пример #9
0
 /**
  * Connects and authenticates to SMTP server.
  * @return void
  */
 private function connect()
 {
     $this->connection = @fsockopen(($this->secure === 'ssl' ? 'ssl://' : '') . $this->host, $this->port, $errno, $error, $this->timeout);
     if (!$this->connection) {
         throw new SmtpException($error, $errno);
     }
     stream_set_timeout($this->connection, $this->timeout, 0);
     $this->read();
     // greeting
     $self = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost';
     $this->write("EHLO {$self}");
     if ((int) $this->read() !== 250) {
         $this->write("HELO {$self}", 250);
     }
     if ($this->secure === 'tls') {
         $this->write('STARTTLS', 220);
         if (!stream_socket_enable_crypto($this->connection, TRUE, STREAM_CRYPTO_METHOD_TLS_CLIENT)) {
             throw new SmtpException('Unable to connect via TLS.');
         }
         $this->write("EHLO {$self}", 250);
     }
     if ($this->username != NULL && $this->password != NULL) {
         $this->write('AUTH LOGIN', 334);
         $this->write(base64_encode($this->username), 334, 'username');
         $this->write(base64_encode($this->password), 235, 'password');
     }
 }
Пример #10
0
 /**
  * @param string $host
  * @param int $port
  * @param int $connectTimeout
  */
 public function __construct($host, $port, $connectTimeout)
 {
     if (!($this->_socket = @fsockopen($host, $port, $errno, $errstr, $connectTimeout))) {
         throw new Pheanstalk_Exception_ConnectionException($errno, $errstr);
     }
     stream_set_timeout($this->_socket, self::SOCKET_TIMEOUT);
 }
Пример #11
0
 public function open($host, $port, $transport = 'tcp')
 {
     // if a socket is current open then close it
     $this->close();
     if (($ip = filter_var($host, FILTER_VALIDATE_IP)) !== false) {
         $this->host = $ip;
     } elseif (($ip = gethostbyname($host)) != $host) {
         $this->host = $ip;
     } else {
         throw new Exception('Unable to resolve host: ' . $host);
     }
     $this->port = filter_var($port, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1, 'max_range' => 65535)));
     if (!$this->port) {
         throw new Exception('Invalid Port: ' . $port);
     }
     $err = 0;
     $msg = '';
     $this->stream = fsockopen("{$transport}://{$this->host}", $this->port, $err, $msg, $this->timeout);
     if (!$this->isOpen()) {
         throw new Exception("Unable to open socket: {$msg}", $err);
     }
     stream_set_timeout($this->stream, $this->timeout);
     stream_set_blocking($this->stream, $this->block);
     return $this;
 }
Пример #12
0
 function __construct($config)
 {
     if (extension_loaded("pcntl")) {
         //Add signal handlers to shut down the bot correctly if its getting killed
         pcntl_signal(SIGTERM, array($this, "signalHandler"));
         pcntl_signal(SIGINT, array($this, "signalHandler"));
     } else {
         //die("Please make sure the pcntl PHP extension is enabled.\n");
     }
     $this->config = $config;
     $this->startTime = time();
     $this->lastServerMessage = $this->startTime;
     ini_set("memory_limit", $this->config['memoryLimit'] . "M");
     if ($config['verifySSL']) {
         $this->socket = stream_socket_client("" . $config['server'] . ":" . $config['port']) or die("Connection error!");
     } else {
         $socketContext = stream_context_create(array("ssl" => array("verify_peer" => false, "verify_peer_name" => false)));
         $this->socket = stream_socket_client("" . $config['server'] . ":" . $config['port'], $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $socketContext) or die("Connection error!");
     }
     stream_set_blocking($this->socket, 0);
     stream_set_timeout($this->socket, 600);
     $this->login();
     $this->loadPlugins();
     $this->main($config);
 }
Пример #13
0
 public function scrape($url, $infohash)
 {
     if (!is_array($infohash)) {
         $infohash = array($infohash);
     }
     foreach ($infohash as $hash) {
         if (!preg_match('#^[a-f0-9]{40}$#i', $hash)) {
             throw new ScraperException('Invalid infohash: ' . $hash . '.');
         }
     }
     $url = trim($url);
     if (preg_match('%(http://.*?/)announce([^/]*)$%i', $url, $m)) {
         $url = $m[1] . 'scrape' . $m[2];
     } else {
         if (preg_match('%(http://.*?/)scrape([^/]*)$%i', $url, $m)) {
         } else {
             throw new ScraperException('Invalid tracker url.');
         }
     }
     $sep = preg_match('/\\?.{1,}?/i', $url) ? '&' : '?';
     $requesturl = $url;
     foreach ($infohash as $hash) {
         $requesturl .= $sep . 'info_hash=' . rawurlencode(pack('H*', $hash));
         $sep = '&';
     }
     ini_set('default_socket_timeout', $this->timeout);
     $rh = @fopen($requesturl, 'r');
     // var_dump($url);
     if (!$rh) {
         throw new ScraperException('Could not open HTTP connection.', 0, true);
     }
     stream_set_timeout($rh, $this->timeout);
     $return = '';
     $pos = 0;
     while (!feof($rh) && $pos < $this->maxreadsize) {
         $return .= fread($rh, 1024);
     }
     fclose($rh);
     if (!substr($return, 0, 1) == 'd') {
         throw new ScraperException('Invalid scrape response.');
     }
     $lightbenc = new lightbenc();
     $arr_scrape_data = $lightbenc->bdecode($return);
     $torrents = array();
     foreach ($infohash as $hash) {
         $ehash = pack('H*', $hash);
         if (isset($arr_scrape_data['files'][$ehash])) {
             if (array_key_exists('downloaded', $arr_scrape_data['files'][$ehash])) {
                 $completed = $arr_scrape_data['files'][$ehash]['downloaded'];
             } else {
                 $completed = "0";
             }
             $torrents[$hash] = array('infohash' => $hash, 'seeders' => (int) $arr_scrape_data['files'][$ehash]['complete'], 'completed' => (int) $completed, 'leechers' => (int) $arr_scrape_data['files'][$ehash]['incomplete']);
         } else {
             $torrents[$hash] = false;
         }
     }
     // var_dump($torrents);
     return $torrents;
 }
Пример #14
0
 public function connect($host, $port = false, $tval = 30)
 {
     if ($this->connected) {
         return true;
     }
     set_error_handler(array($this, 'catchWarning'));
     $this->pop_conn = fsockopen($host, $port, $errno, $errstr, $tval);
     restore_error_handler();
     if ($this->error && $this->do_debug >= 1) {
         $this->displayErrors();
     }
     if ($this->pop_conn == false) {
         $this->error = array('error' => "Failed to connect to server {$host} on port {$port}", 'errno' => $errno, 'errstr' => $errstr);
         if ($this->do_debug >= 1) {
             $this->displayErrors();
         }
         return false;
     }
     if (version_compare(phpversion(), '5.0.0', 'ge')) {
         stream_set_timeout($this->pop_conn, $tval, 0);
     } else {
         if (substr(PHP_OS, 0, 3) !== 'WIN') {
             socket_set_timeout($this->pop_conn, $tval, 0);
         }
     }
     $pop3_response = $this->getResponse();
     if ($this->checkResponse($pop3_response)) {
         $this->connected = true;
         return true;
     }
     return false;
 }
Пример #15
0
 /**
  * Send data through the socket and listen for a return
  * @param string $msg Data to send
  * @param string $type The type of data to return (array or string)
  * @return string|array
  */
 function send($msg, $type = '')
 {
     // Set a short timeout to prevent long hangs
     stream_set_timeout($this->handle, 2);
     // Send message over connection
     fwrite($this->handle, $msg);
     // Check what type is required
     if ($type == 'array') {
         // If array loop and create array
         $response = array();
         $line_num = 0;
         while (!feof($this->handle)) {
             if (($response[$line_num] = fgets($this->handle, 4096)) === false) {
                 break;
             } else {
                 $line_num++;
             }
         }
         // Return response as array
         return $response;
     } elseif ($type == 'string') {
         // If string, loop and create string
         $response = '';
         while (!feof($this->handle)) {
             $response .= fgets($this->handle, 4096);
         }
         // Return response as string
         return $response;
     } else {
         // If anything else, return nothing but a true
         return true;
     }
 }
Пример #16
0
 /**
  * Loads remote content using sockets.
  */
 public function getRemoteContents($url, $timeout = 10)
 {
     $result = "";
     $url = parse_url($url);
     if ($fs = @fsockopen($url['host'], 80)) {
         if (function_exists("socket_set_timeout")) {
             socket_set_timeout($fs, $timeout, 0);
         } else {
             if (function_exists("stream_set_timeout")) {
                 stream_set_timeout($fs, $timeout, 0);
             }
         }
         $http_get_cmd = "GET " . $url['path'] . "?" . $url['query'] . " HTTP/1.0\r\n" . "Host: " . $url['host'] . "\r\n" . "Connection: Close\r\n\r\n";
         fwrite($fs, $http_get_cmd);
         while (!feof($fs)) {
             $result .= @fread($fs, 40960);
         }
         fclose($fs);
         if (strpos($result, "404 Not Found")) {
             return FALSE;
         } else {
             list($headers, $body) = preg_split("/\r\n\r\n/s", $result, 2);
             // separate headers
             return $body;
         }
     } else {
         return FALSE;
     }
 }
Пример #17
0
function SendMsg2Daemon($ip, $port, $msg, $timeout = 15)
{
    if (!$ip || !$port || !$msg) {
        return array(false);
    }
    $errno;
    $errstr;
    $fp = @fsockopen($ip, $port, $errno, $errstr, $timeout);
    if (!$fp) {
        return array(false);
    }
    stream_set_blocking($fp, true);
    stream_set_timeout($fp, $timeout);
    @fwrite($fp, $msg . "\n");
    $status = stream_get_meta_data($fp);
    $ret;
    if (!$status['timed_out']) {
        $datas = 'data:';
        while (!feof($fp)) {
            $data = fread($fp, 4096);
            if ($data) {
                $datas = $datas . $data;
            }
        }
        return array(true, $datas);
    } else {
        $ret = array(false);
    }
    @fclose($fp);
    return ret;
}
Пример #18
0
function stardust_do_post_request($found) {
    $params = array('http' => array(
            'method' => 'POST',
            'content' => implode(',', $found)
            ));
    if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
    }
    $ctx = stream_context_create($params);
    $timeout = 15;
    $old = ini_set('default_socket_timeout', $timeout);
    $fp = @fopen(STARDUST_SERVICE_URL, 'rb', false, $ctx);
    ini_set('default_socket_timeout', $old);
    if ($fp) {
        stream_set_timeout($fp, $timeout);
        stream_set_blocking($fp, 3);
    } else
        //throw new Exception("Problem with " . STARDUST_SERVICE_URL . ", $php_errormsg");
        return false;
    $response = @stream_get_contents($fp);
    if ($response === false) {
        //throw new Exception("Problem reading data from " . STARDUST_SERVICE_URL . ", $php_errormsg");
    }
    return $response;
}
Пример #19
0
 /**
  * @param null $host - $host of socket server
  * @param null $port - port of socket server
  * @param string $action - action to execute in sockt server
  * @param null $data - message to socket server
  * @param string $address - addres of socket.io on socket server
  * @param string $transport - transport type
  * @return bool
  */
 public function send($host = null, $port = null, $action = "message", $data = null, $address = "/socket.io/?EIO=3", $transport = 'websocket')
 {
     $fd = fsockopen($host, $port, $errno, $errstr);
     if (!$fd) {
         return false;
     }
     //Can't connect tot server
     $key = $this->generateKey();
     $out = "GET {$address}&sessionid=&transport={$transport} HTTP/1.1\r\n";
     $out .= "Host: http://{$host}:{$port}\r\n";
     $out .= "Upgrade: WebSocket\r\n";
     $out .= "Connection: Upgrade\r\n";
     $out .= "Sec-WebSocket-Key: {$key}\r\n";
     $out .= "Sec-WebSocket-Version: 13\r\n";
     $out .= "Origin: *\r\n\r\n";
     stream_set_timeout($fd, 5);
     fwrite($fd, $out);
     // 101 switching protocols, see if echoes key
     $result = fread($fd, 10000);
     preg_match('#Sec-WebSocket-Accept:\\s(.*)$#mU', $result, $matches);
     $keyAccept = trim($matches[1]);
     $expectedResonse = base64_encode(pack('H*', sha1($key . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11')));
     $handshaked = $keyAccept === $expectedResonse ? true : false;
     if ($handshaked) {
         fwrite($fd, $this->hybi10Encode('42["' . $action . '", "' . addslashes($data) . '"]'));
         fread($fd, 1000000);
         sleep(2);
         fclose($fd);
         return true;
     } else {
         return false;
     }
 }
Пример #20
0
function call_async_fsockopen($script_path, $data = null)
{
    if (empty($data)) {
        $out = "GET {$script_path} HTTP/1.1\r\n";
        $out .= "Host: {$_SERVER['SERVER_NAME']}\r\n";
        $out .= 'User-Agent: ' . ME_USERAGENT . "\r\n";
        $out .= "Connection: Close\r\n";
    } else {
        $post = '';
        while (list($k, $v) = each($data)) {
            $post .= rawurlencode($k) . "=" . rawurlencode($v) . "&";
        }
        $len = strlen($post);
        $out = "POST {$script_path} HTTP/1.1\r\n";
        $out .= "Host: {$_SERVER['SERVER_NAME']}\r\n";
        $out .= 'User-Agent: ' . ME_USERAGENT . "\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded\r\n";
        $out .= "Connection: Close\r\n";
        $out .= "Content-Length: {$len}\r\n";
        $out .= "\r\n";
        $out .= $post . "\r\n";
    }
    $fp = @fsockopen('127.0.0.1', $_SERVER['SERVER_PORT'], $errno, $errstr, 3);
    if ($fp) {
        fwrite($fp, $out);
        stream_set_timeout($fp, 3);
        if ("HTTP/1.1 200 OK\r\n" === fgets($fp)) {
            fclose($fp);
            return 'ok';
        }
    }
    fclose($fp);
    return 'no';
}
Пример #21
0
 public function setTimeout($timeout)
 {
     $this->options['timeout'] = $timeout;
     if ($this->socket && get_resource_type($this->socket) === 'stream') {
         stream_set_timeout($this->socket, $timeout);
     }
 }
Пример #22
0
 public function connect()
 {
     $this->socket = stream_socket_client('tcp://' . $this->ip . ':' . $this->port, $errno, $errstr, 5);
     $this->Connected = true;
     stream_set_timeout($this->socket, 0);
     return $this;
 }
Пример #23
0
 /**
  * @return bool
  */
 public function Connect()
 {
     $sHost = $this->bUseSsl ? 'ssl://' . $this->sHost : $this->sHost;
     if ($this->IsConnected()) {
         CApi::Log('already connected[' . $sHost . ':' . $this->iPort . ']: result = false', ELogLevel::Error);
         $this->Disconnect();
         return false;
     }
     $sErrorStr = '';
     $iErrorNo = 0;
     CApi::Log('start connect to ' . $sHost . ':' . $this->iPort);
     $this->rConnect = @fsockopen($sHost, $this->iPort, $iErrorNo, $sErrorStr, $this->iConnectTimeOut);
     if (!$this->IsConnected()) {
         CApi::Log('connection error[' . $sHost . ':' . $this->iPort . ']: fsockopen = false (' . $iErrorNo . ': ' . $sErrorStr . ')', ELogLevel::Error);
         return false;
     } else {
         CApi::Log('connected');
     }
     if (\MailSo\Base\Utils::FunctionExistsAndEnabled('stream_set_timeout')) {
         @stream_set_timeout($this->rConnect, $this->iSocketTimeOut);
     }
     if (\MailSo\Base\Utils::FunctionExistsAndEnabled('@stream_set_blocking')) {
         @stream_set_blocking($this->rConnect, true);
     }
     return true;
 }
Пример #24
0
 /**
  * Sends packet to server.
  * 
  * @param OTS_Buffer $packet Buffer to send.
  * @return OTS_Buffer|null Respond buffer (null if server is offline).
  * @throws E_OTS_OutOfBuffer When there is read attemp after end of packet stream.
  */
 private function send(OTS_Buffer $packet)
 {
     // connects to server
     // gives maximum 5 seconds to connect
     $socket = fsockopen($this->server, $this->port, $error, $message, 5);
     // if connected then checking statistics
     if ($socket) {
         // sets 5 second timeout for reading and writing
         stream_set_timeout($socket, 5);
         // creates real packet
         $packet = $packet->getBuffer();
         $packet = pack('v', strlen($packet)) . $packet;
         // sends packet with request
         // 06 - length of packet, 255, 255 is the comamnd identifier, 'info' is a request
         fwrite($socket, $packet);
         // reads respond
         $data = stream_get_contents($socket);
         // closing connection to current server
         fclose($socket);
         // sometimes server returns empty info
         if (empty($data)) {
             // returns offline state
             return false;
         }
         return new OTS_Buffer($data);
     }
     return false;
 }
 /**
  * 
  * @access protected
  * @param resource $server 
  */
 protected function readStringFromSocket($socket)
 {
     $this->_logger->log(__METHOD__);
     stream_set_timeout($socket, 2);
     $i = 0;
     $content = '';
     //        stream_set_read_buffer ($socket, 20000);
     do {
         $content .= @fread($socket, 1024);
         $this->_logger->log(__METHOD__ . '$i' . $i);
         $this->_logger->log(__METHOD__ . 'len' . strlen($content));
     } while (($i += 1024) === strlen($content) && !@feof($socket));
     //        $content .= @fread($socket, 8096);
     //        if(!@feof($socket)) {
     //
     //            stream_set_blocking($socket, 0);
     //            do {
     //                sleep(1);
     //                $part = @fgets($socket, 124);
     //                $this->_logger->log(__METHOD__ . ': strlen($content): ' . strlen($content));
     //
     //                if ((strlen($content) != 0 && strlen($content) == strlen($content . $part)) || @feof($socket)) {
     //                    break;
     //                }
     //                $content .= $part;
     //            } while (1);
     //
     //            stream_set_blocking($socket, 1);
     //
     //            $this->_logger->log(__METHOD__ . ': $i ' . $i);
     //            $this->_logger->log(__METHOD__ . ': content length ' . strlen($content));
     //        }
     return $content;
 }
Пример #26
0
 /**
  * Connect to the remote server
  * 
  * Will try to connect to the proxy server. If no proxy was set, will
  * fall back to the target server (behave like regular Socket adapter)
  *
  * @param string  $host
  * @param int     $port
  * @param boolean $secure
  * @param int     $timeout
  */
 public function connect($host, $port = 80, $secure = false)
 {
     // If no proxy is set, fall back to Socket adapter
     if (!$this->config['proxy_host']) {
         return parent::connect($host, $port, $secure);
     }
     // Go through a proxy - the connection is actually to the proxy server
     $host = $this->config['proxy_host'];
     $port = $this->config['proxy_port'];
     // If we are connected to the wrong proxy, disconnect first
     if ($this->connected_to[0] != $host || $this->connected_to[1] != $port) {
         if (is_resource($this->socket)) {
             $this->close();
         }
     }
     // Now, if we are not connected, connect
     if (!is_resource($this->socket) || !$this->config['keepalive']) {
         $this->socket = @fsockopen($host, $port, $errno, $errstr, (int) $this->config['timeout']);
         if (!$this->socket) {
             $this->close();
             throw new Zend_Http_Client_Adapter_Exception('Unable to Connect to proxy server ' . $host . ':' . $port . '. Error #' . $errno . ': ' . $errstr);
         }
         // Set the stream timeout
         if (!stream_set_timeout($this->socket, (int) $this->config['timeout'])) {
             throw new Zend_Http_Client_Adapter_Exception('Unable to set the connection timeout');
         }
         // Update connected_to
         $this->connected_to = array($host, $port);
     }
 }
Пример #27
0
 /**
  * @param string $ip      IP of the MC server
  * @param int    $port    Port of the MC server
  * @param int    $timeout Timeout
  * @throws InvalidArgumentException
  */
 public function __construct($ip, $port = 25565, $timeout = 5)
 {
     $time = microtime(true);
     if (!is_int($timeout) || $timeout < 0) {
         throw new InvalidArgumentException('Timeout must be an integer.');
     }
     // Connect to the server
     $this->socket = @fsockopen('udp://' . $ip, (int) $port, $errorNumber, $errorString, $timeout);
     // Failure?
     if ($errorNumber || $this->socket === false) {
         $this->online = false;
         return;
     }
     stream_set_blocking($this->socket, true);
     stream_set_timeout($this->socket, (int) $timeout);
     try {
         $challenge = $this->fetchChallenge();
         $this->fetchStatus($challenge);
     } catch (MinecraftQueryException $e) {
         fclose($this->socket);
         $this->online = false;
         return;
     }
     fclose($this->socket);
     $this->duration = microtime(true) - $time;
 }
Пример #28
0
function kill_client($port, $remipp)
{
    global $g;
    //$tcpsrv = "tcp://127.0.0.1:{$port}";
    $tcpsrv = "unix://{$g['varetc_path']}/openvpn/{$port}.sock";
    $errval;
    $errstr;
    /* open a tcp connection to the management port of each server */
    $fp = @stream_socket_client($tcpsrv, $errval, $errstr, 1);
    $killed = -1;
    if ($fp) {
        stream_set_timeout($fp, 1);
        fputs($fp, "kill {$remipp}\n");
        while (!feof($fp)) {
            $line = fgets($fp, 1024);
            $info = stream_get_meta_data($fp);
            if ($info['timed_out']) {
                break;
            }
            /* parse header list line */
            if (strpos($line, "INFO:") !== false) {
                continue;
            }
            if (strpos($line, "SUCCESS") !== false) {
                $killed = 0;
            }
            break;
        }
        fclose($fp);
    }
    return $killed;
}
Пример #29
0
 function _Set_Timeout(&$res, $s, $m = 0)
 {
     if (version_compare(phpversion(), '4.3.0', '<')) {
         return socket_set_timeout($res, $s, $m);
     }
     return stream_set_timeout($res, $s, $m);
 }
Пример #30
0
 function SendSmtp(&$body, &$headers)
 {
     $crlf = "\r\n";
     if (($socket = @fsockopen($this->host, 25, $errno, $errstr, 10)) !== FALSE) {
         stream_set_timeout($socket, 30);
         $this->SmtpGetLines($socket);
         fwrite($socket, "HELO localhost{$crlf}");
         $this->SmtpGetLines($socket);
         fwrite($socket, "RSET{$crlf}");
         $this->SmtpGetLines($socket);
         fwrite($socket, "MAIL FROM: <{$this->from}>{$crlf}");
         $this->SmtpGetLines($socket);
         fwrite($socket, "RCPT TO: <{$this->to}>{$crlf}");
         $this->SmtpGetLines($socket);
         fwrite($socket, "DATA{$crlf}");
         $this->SmtpGetLines($socket);
         fwrite($socket, "{$headers}{$crlf}{$crlf}{$body}{$crlf}.{$crlf}");
         $this->SmtpGetLines($socket);
         fwrite($socket, "QUIT{$crlf}");
         $this->SmtpGetLines($socket);
         fclose($socket);
     } else {
         return FALSE;
     }
 }