/**
 * 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;
    }
}
 /**
  * Connects the TCP socket to the host with the given IP address and port
  * number
  *
  * Depending on whether PHP's sockets extension is loaded, this uses either
  * <var>socket_create</var>/<var>socket_connect</var> or
  * <var>fsockopen</var>.
  *
  * @param string $ipAddress The IP address to connect to
  * @param int $portNumber The TCP port to connect to
  * @param int $timeout The timeout in milliseconds
  * @throws SocketException if an error occurs during connecting the socket
  */
 public function connect($ipAddress, $portNumber, $timeout)
 {
     $this->ipAddress = $ipAddress;
     $this->portNumber = $portNumber;
     if ($this->socketsEnabled) {
         if (!($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) {
             throw new SocketException(socket_last_error($this->socket));
         }
         socket_set_nonblock($this->socket);
         @socket_connect($this->socket, $ipAddress, $portNumber);
         $write = array($this->socket);
         $read = $except = array();
         $sec = floor($timeout / 1000);
         $usec = $timeout % 1000;
         if (!socket_select($read, $write, $except, $sec, $usec)) {
             $errorCode = socket_last_error($this->socket);
         } else {
             $errorCode = socket_get_option($this->socket, SOL_SOCKET, SO_ERROR);
         }
         if ($errorCode) {
             throw new SocketException($errorCode);
         }
         socket_set_block($this->socket);
     } else {
         if (!($this->socket = @fsockopen("tcp://{$ipAddress}", $portNumber, $socketErrno, $socketErrstr, $timeout / 1000))) {
             throw new SocketException($socketErrstr);
         }
         stream_set_blocking($this->socket, true);
     }
 }
Example #3
1
function sshiconn($cmd, $pass, $ip, $sshp = 22)
{
    $ip = $_REQUEST['ip'];
    $pass = $_REQUEST['pass'];
    $sshp = $_REQUEST['sshp'];
    if (!isset($_REQUEST['sshp'])) {
        $sshp = '22';
    }
    $connection = ssh2_connect($ip, $sshp);
    if (!$connection) {
        throw new Exception("fail: unable to establish connection\nPlease IP or if server is on and connected");
    }
    $pass_success = ssh2_auth_password($connection, 'root', $pass);
    if (!$pass_success) {
        throw new Exception("fail: unable to establish connection\nPlease Check your password");
    }
    $stream = ssh2_exec($connection, $cmd);
    $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
    stream_set_blocking($errorStream, true);
    stream_set_blocking($stream, true);
    print_r($cmd);
    $output = stream_get_contents($stream);
    fclose($stream);
    fclose($errorStream);
    ssh2_exec($connection, 'exit');
    unset($connection);
    return $output;
}
 public function connect()
 {
     $nick = $this->getConfig('nick', 'phabot');
     $server = $this->getConfig('server');
     $port = $this->getConfig('port', 6667);
     $pass = $this->getConfig('pass');
     $ssl = $this->getConfig('ssl', false);
     $user = $this->getConfig('user', $nick);
     if (!preg_match('/^[A-Za-z0-9_`[{}^|\\]\\-]+$/', $nick)) {
         throw new Exception(pht("Nickname '%s' is invalid!", $nick));
     }
     $errno = null;
     $error = null;
     if (!$ssl) {
         $socket = fsockopen($server, $port, $errno, $error);
     } else {
         $socket = fsockopen('ssl://' . $server, $port, $errno, $error);
     }
     if (!$socket) {
         throw new Exception(pht('Failed to connect, #%d: %s', $errno, $error));
     }
     $ok = stream_set_blocking($socket, false);
     if (!$ok) {
         throw new Exception(pht('Failed to set stream nonblocking.'));
     }
     $this->socket = $socket;
     if ($pass) {
         $this->write("PASS {$pass}");
     }
     $this->write("NICK {$nick}");
     $this->write("USER {$user} 0 * :{$user}");
 }
Example #5
0
 /**
  * Initialize a new stream listener
  */
 public function __construct($stream)
 {
     $this->stream = $stream;
     stream_set_blocking($this->stream, 0);
     $meta = stream_get_meta_data($this->stream);
     if (substr($meta['mode'], -1) === '+') {
         $this->writable = true;
         $this->readable = true;
     } else {
         if (strpos($meta['mode'], 'r') !== false) {
             $this->readable = true;
         }
         if (strpos($meta['mode'], 'w') !== false) {
             $this->writable = true;
         }
     }
     if ($this->readable) {
         $this->ev_read = event_new();
         event_set($this->ev_read, $this->stream, EV_READ | EV_PERSIST, array($this, '_read'));
         Loop::attachEvent($this->ev_read);
     }
     if ($this->writable) {
         $this->ev_write = event_new();
         event_set($this->ev_write, $this->stream, EV_WRITE | EV_PERSIST, array($this, '_write'));
         Loop::attachEvent($this->ev_write);
     }
 }
Example #6
0
 public function send($socket)
 {
     $deferred = new Deferred();
     stream_set_blocking($socket, false);
     $data = $this->getRequest();
     \Amp\onWritable($socket, function ($writer, $socket) use($deferred, &$data) {
         if ($bytes = fwrite($socket, $data)) {
             if ($bytes < \strlen($data)) {
                 $data = substr($data, $bytes);
                 return;
             }
             $size = 8192;
             \Amp\onReadable($socket, function ($reader, $socket) use($deferred, &$size) {
                 /* make attention to not read too much data */
                 $data = stream_socket_recvfrom($socket, $size, STREAM_PEEK);
                 if (false === ($pos = strpos($data, "\r\n\r\n"))) {
                     if (\strlen($data) == $size) {
                         $size *= 2;
                         // unbounded??
                     }
                     return;
                 }
                 \Amp\cancel($reader);
                 $deferred->succeed($this->parseResponse(fread($socket, $pos + 4)));
             });
         } else {
             $deferred->succeed(null);
         }
         \Amp\cancel($writer);
     });
     return $deferred->promise();
 }
Example #7
0
 /**
  * Initialize connection
  *
  * @return Connection
  */
 public function create()
 {
     $this->socketClientFlags = STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT;
     parent::create();
     stream_set_blocking($this->resource, 0);
     return $this;
 }
Example #8
0
 /**
  * 
  */
 public function execute()
 {
     $this->process = proc_open($this->command, array(array("pipe", "r"), array("pipe", "w"), array("pipe", "w")), $pipes);
     stream_set_blocking($pipes[1], 0);
     stream_set_blocking($pipes[2], 0);
     $this->pipes = $pipes;
 }
 private function connect($device_ids, $message)
 {
     if (is_string($device_ids)) {
         $device_ids = (array) $device_ids;
     }
     $streamContext = stream_context_create();
     @stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->config);
     $fp = @stream_socket_client($this->url_service, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $streamContext);
     @stream_set_blocking($fp, 0);
     if (!$fp) {
         return false;
     }
     if ($device_ids[0] != "test") {
         $load = array('aps' => array('alert' => $message, 'badge' => 1, 'sound' => 'chime'));
         $payload = json_encode($load);
         $apnsMessage = null;
         foreach ($device_ids as $token) {
             @($apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $token)) . pack('n', strlen($payload)) . $payload);
         }
         fwrite($fp, $apnsMessage);
         usleep(500000);
         $ivalidToken = $this->pullMessage($fp);
         fclose($fp);
         return $ivalidToken;
     }
     return true;
 }
 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);
 }
Example #11
0
 public function callMinerd($cmd = false)
 {
     if (!($fp = @fsockopen("127.0.0.1", 4028, $errno, $errstr, 3))) {
         return array("error" => true, "msg" => $errstr);
     }
     stream_set_blocking($fp, false);
     if (!$cmd) {
         $in = json_encode(array("get" => "stats")) . "\n";
     } else {
         $in = json_encode($cmd) . "\n";
     }
     log_message("error", "Called Minerd with command: " . $in);
     fwrite($fp, $in);
     usleep(150000);
     $out = false;
     /*
     // Many thanks to Sandor111
     */
     $die = 0;
     while (!feof($fp) && !($str = fgets($fp, 2048))) {
         usleep(10000);
     }
     $out .= $str;
     while (!feof($fp) && $die < 10) {
         if (!($str = fgets($fp, 1024))) {
             $die++;
             usleep(10000);
             continue;
         }
         $die = 0;
         $out .= $str;
     }
     fclose($fp);
     return json_decode($out);
 }
Example #12
0
 private function getSocket($uriInfo)
 {
     $socket = stream_socket_client("tcp://" . $uriInfo["host"] . $this->getPort($uriInfo), $errno, $errstr, 1, STREAM_CLIENT_ASYNC_CONNECT);
     //STREAM_CLIENT_PERSISTENT
     stream_set_blocking($socket, 1);
     return $socket;
 }
function execute($cmd, &$output, &$error, &$returnCode)
{
    $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
    $process = proc_open($cmd, $descriptorspec, $pipes);
    if (!is_resource($process)) {
        throw new RuntimeException("Unable to execute the command. [{$cmd}]");
    }
    stream_set_blocking($pipes[1], false);
    stream_set_blocking($pipes[2], false);
    $output = $error = '';
    foreach ($pipes as $key => $pipe) {
        while (!feof($pipe)) {
            if (!($line = fread($pipe, 128))) {
                continue;
            }
            if (1 == $key) {
                $output .= $line;
                // stdout
            } else {
                $error .= $line;
                // stderr
            }
        }
        fclose($pipe);
    }
    $returnCode = proc_close($process);
}
/**
 * this function defines the asterisk client
 */
function asteriskClient()
{
    global $app_strings, $current_user;
    global $adb, $log;
    $data = getAsteriskInfo($adb);
    $server = $data['server'];
    $port = $data['port'];
    $username = $data['username'];
    $password = $data['password'];
    $version = $data['version'];
    $errno = $errstr = NULL;
    $sock = @fsockopen($server, $port, $errno, $errstr, 1);
    stream_set_blocking($sock, false);
    if ($sock === false) {
        echo "Socket cannot be created due to error: {$errno}:  {$errstr}\n";
        $log->debug("Socket cannot be created due to error:   {$errno}:  {$errstr}\n");
        exit(0);
    } else {
        echo "Date: " . date("d-m-Y") . "\n";
        echo "Connecting to asterisk server.....\n";
        $log->debug("Connecting to asterisk server.....\n");
    }
    echo "Connected successfully\n\n\n";
    $asterisk = new Asterisk($sock, $server, $port);
    authorizeUser($username, $password, $asterisk);
    //keep looping continuosly to check if there are any calls
    while (true) {
        //check for incoming calls and insert in the database
        sleep(2);
        $incoming = handleIncomingCalls($asterisk, $adb, $version);
    }
    fclose($sock);
    unset($sock);
}
function main__asteriskClient()
{
    global $app_strings, $current_user;
    global $adb, $log;
    $data = getAsteriskInfo($adb);
    $errno = $errstr = null;
    $sock = @fsockopen($data['server'], $data['port'], $errno, $errstr, 1);
    stream_set_blocking($sock, false);
    if ($sock === false) {
        echo "Socket cannot be created due to errno [{$errno}] - {$errstr}";
        $log->debug("Socket cannot be created due to errno [{$errno}] - {$errstr}");
        exit(0);
    }
    echo "Connecting to asterisk server @ " . date("Y-m-d H:i:s") . "\n";
    $log->debug("Connecting to asterisk server @ " . date("Y-m-d H:i:s"));
    echo "Connected successfully\n\n";
    $asterisk = new Asterisk($sock, $data['server'], $data['port']);
    # authorize user first
    authorizeUser($data['username'], $data['password'], $asterisk);
    // Keep looping to poll the asterisk events
    while (true) {
        // Give some break to avoid server hanging
        sleep(1);
        try {
            $incoming = asterisk_handleEvents($asterisk, $adb, $data['version']);
            asterisk_IncomingEventCleanup($adb);
        } catch (Exception $ex) {
            echo "EXCEPTION: " . $ex->getMessage() . "\n";
        }
    }
    fclose($sock);
    unset($sock);
}
 protected function acceptSocket()
 {
     $connection = stream_socket_accept($this->socket, 0);
     stream_set_blocking($this->socket, 0);
     self::log('Socket', 'accepted');
     return $connection;
 }
Example #17
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $output->writeln('Starting server on port 5000');
     $descriptorspec = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
     $port = $input->getOption('port');
     // Start server process
     $process = proc_open("php -S localhost:{$port} -t public/ " . getcwd() . "/scripts/normal-server/router.php", $descriptorspec, $pipes, getcwd(), $_ENV);
     if (!is_resource($process)) {
         throw new Exception("popen error");
     }
     stream_set_blocking($pipes[0], 0);
     stream_set_blocking($pipes[1], 0);
     stream_set_blocking($pipes[2], 0);
     // Redirect all output
     while (!feof($pipes[1])) {
         foreach ($pipes as $pipe) {
             $line = fread($pipe, 128);
             if ($line) {
                 $output->writeln($line);
             }
         }
         sleep(0.5);
     }
     foreach ($pipes as $pipe) {
         fclose($pipe);
     }
 }
Example #18
0
 /**
  * @param $command
  * @param bool $display
  * @return array
  * @throws \Exception
  */
 public function exec($command, $display = true)
 {
     $outStream = ssh2_exec($this->stream, $command);
     $errStream = ssh2_fetch_stream($outStream, SSH2_STREAM_STDERR);
     stream_set_blocking($outStream, true);
     stream_set_blocking($errStream, true);
     $err = $this->removeEmptyLines(explode("\n", stream_get_contents($errStream)));
     if (count($err)) {
         if (strpos($err[0], 'Cloning into') === false) {
             // throw new \Exception(implode("\n", $err));
         }
     }
     $out = $this->removeEmptyLines(explode("\n", stream_get_contents($outStream)));
     fclose($outStream);
     fclose($errStream);
     if ($display) {
         if (!$this->output instanceof OutputInterface) {
             throw new \LogicException('You should set output first');
         }
         foreach ($out as $line) {
             $this->output->writeln(sprintf('<info>%s</info>', $line));
         }
     }
     return $out;
 }
Example #19
0
 function _sock($url)
 {
     $host = parse_url($url, PHP_URL_HOST);
     $port = parse_url($url, PHP_URL_PORT);
     $port = $port ? $port : 80;
     $scheme = parse_url($url, PHP_URL_SCHEME);
     $path = parse_url($url, PHP_URL_PATH);
     $query = parse_url($url, PHP_URL_QUERY);
     if ($query) {
         $path .= '?' . $query;
     }
     if ($scheme == 'https') {
         $host = 'ssl://' . $host;
     }
     if ($fp = @fsockopen($host, $port, $error_code, $error_msg, 5)) {
         stream_set_blocking($fp, 0);
         //开启了手册上说的非阻塞模式
         $header = "GET {$path} HTTP/1.1\r\n";
         $header .= "Host: {$host}\r\n";
         $header .= "Connection: Close\r\n\r\n";
         //长连接关闭
         fwrite($fp, $header);
         fclose($fp);
     }
     return array($error_code, $error_msg);
 }
Example #20
0
 /**
  *
  * @param  string            $host Host to connect to. Default is localhost (127.0.0.1).
  * @param  int               $port Port to connect to. Default is 8080.
  * @return boolean           True on success
  * @throws \RuntimeException
  */
 protected function connect($host, $port)
 {
     $key1 = $this->generateRandomString(32);
     $key2 = $this->generateRandomString(32);
     $key3 = $this->generateRandomString(8, false, true);
     $header = "GET /echo HTTP/1.1\r\n";
     $header .= "Upgrade: WebSocket\r\n";
     $header .= "Connection: Upgrade\r\n";
     $header .= "Host: " . $host . ":" . $port . "\r\n";
     $header .= "Sec-WebSocket-Key1: " . $key1 . "\r\n";
     $header .= "Sec-WebSocket-Key2: " . $key2 . "\r\n";
     $header .= "\r\n";
     $header .= $key3;
     $this->socket = @stream_socket_client('tcp://' . $host . ':' . $port, $errno, $errstr, self::SOCKET_TIMEOUT);
     if (!$this->socket) {
         throw new \RuntimeException(sprintf('WebSocket connection error (%u): %s', $errno, $errstr));
     }
     stream_set_blocking($this->socket, false);
     // do a handshake
     if (!fwrite($this->socket, $header)) {
         throw new \RuntimeException('WebSocket write error');
     }
     /**
      * @todo: check response here. Currently not implemented cause "2 key handshake" is already deprecated.
      * See: http://en.wikipedia.org/wiki/WebSocket#WebSocket_Protocol_Handshake
      */
     // $response = fread($this->socket, 2000);
     return true;
 }
Example #21
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;
 }
Example #22
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;
}
Example #23
0
 public function ssh()
 {
     if (!function_exists("ssh2_connect")) {
         die("function ssh2_connect doesn't exist");
     }
     // log in at server1.example.com on port 22
     if (!($con = ssh2_connect("nao.local", 22))) {
         echo "fail: unable to establish connection\n";
     } else {
         //try to authenticate with username root, password secretpassword
         if (!ssh2_auth_password($con, "nao", "nao")) {
             echo "fail: unable to authenticate\n";
         } else {
             // allright, we're in!
             echo "okay: logged in...\n";
             // execute a command
             if (!($stream = ssh2_exec($con, "ls -al"))) {
                 echo "fail: unable to execute command\n";
             } else {
                 // collect returning data from command
                 stream_set_blocking($stream, true);
                 $data = "";
                 while ($buf = fread($stream, 4096)) {
                     $data .= $buf;
                 }
                 fclose($stream);
             }
         }
     }
 }
Example #24
0
 public function __construct($stream, LoopInterface $loop)
 {
     $this->stream = $stream;
     if (!is_resource($this->stream) || get_resource_type($this->stream) !== "stream") {
         throw new InvalidArgumentException('First parameter must be a valid stream resource');
     }
     stream_set_blocking($this->stream, 0);
     // Use unbuffered read operations on the underlying stream resource.
     // Reading chunks from the stream may otherwise leave unread bytes in
     // PHP's stream buffers which some event loop implementations do not
     // trigger events on (edge triggered).
     // This does not affect the default event loop implementation (level
     // triggered), so we can ignore platforms not supporting this (HHVM).
     if (function_exists('stream_set_read_buffer')) {
         stream_set_read_buffer($this->stream, 0);
     }
     $this->loop = $loop;
     $this->buffer = new Buffer($this->stream, $this->loop);
     $that = $this;
     $this->buffer->on('error', function ($error) use($that) {
         $that->emit('error', array($error, $that));
         $that->close();
     });
     $this->buffer->on('drain', function () use($that) {
         $that->emit('drain', array($that));
     });
     $this->resume();
 }
Example #25
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;
 }
Example #26
0
 /**
  * Read everything from standard input
  *
  * @param callable $lineCallback An operation to perform on each line read
  * @param callable $doneCallback An operation to perform when the end has been reached
  * @throws \RuntimeException if a timeout occurs
  * @link http://www.gregfreeman.org/2013/processing-data-with-php-using-stdin-and-piping/
  *       Based on "Processing data with PHP using STDIN and Piping" by Greg Freeman
  */
 public function read(callable $lineCallback, callable $doneCallback = null)
 {
     stream_set_blocking(STDIN, 0);
     $timeoutStarted = false;
     $timeout = null;
     while (1) {
         // I'm getting something...
         while (false !== ($line = fgets(STDIN))) {
             $lineCallback($line);
             if ($timeoutStarted) {
                 $timeoutStarted = false;
                 $timeout = null;
             }
         }
         // End of input
         if (feof(STDIN)) {
             if ($doneCallback) {
                 $doneCallback();
             }
             break;
         }
         // Wait a spell
         if (null === $timeout) {
             $timeout = time();
             $timeoutStarted = true;
             continue;
         }
         // Timeout
         if (time() > $timeout + $this->wait) {
             throw new \RuntimeException('Timeout reached while reading STDIN');
             return;
         }
     }
 }
 /**
  * @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;
 }
Example #28
0
 public function run()
 {
     $this->buffer = new \Threaded();
     $opts = getopt("", ["disable-readline"]);
     if (extension_loaded("readline") and $this->stream === "php://stdin" and !isset($opts["disable-readline"])) {
         $this->readline = true;
     } else {
         $this->readline = false;
         $this->fp = fopen($this->stream, "r");
         stream_set_blocking($this->fp, 1);
         //Non-blocking STDIN won't work on Windows
     }
     $lastLine = microtime(true);
     while (true) {
         if (($line = $this->readLine()) !== "") {
             $this->buffer->synchronized(function (\Threaded $buffer, $line) {
                 $buffer[] = preg_replace("#\\x1b\\x5b([^\\x1b]*\\x7e|[\\x40-\\x50])#", "", $line);
             }, $this->buffer, $line);
             $lastLine = microtime(true);
         } elseif (microtime(true) - $lastLine <= 0.1) {
             //Non blocking! Sleep to save CPU
             usleep(40000);
         }
     }
 }
 /**
  * @param bool $blocking
  */
 public function setBlocking($blocking)
 {
     $this->blocking = (bool) $blocking;
     foreach ($this->pipes as $pipe) {
         stream_set_blocking($pipe, $this->blocking);
     }
 }
Example #30
-1
    /**
     * Connect to server.
     * @param string $server
     * @param int $port
     */
    public function connect($server, $port = 5222)
    {
        $this->logger = \Logger::getLogger(__CLASS__);
        $this->server = $server;
        $this->port = $port;
        $connect = <<<CONNECT
<?xml version="1.0"?>
<stream:stream to="{$server}" xmlns="jabber:client" xmlns:stream="http://etherx.jabber.org/streams" version="1.0">
CONNECT;
        $type = 'tcp';
        if (5223 == $port) {
            $type = 'ssl';
        }
        $this->socket = \stream_socket_client("{$type}://{$server}:{$port}", $errno, $errstr, $this->timeout);
        if (false === $this->socket) {
            throw new \Exception($errstr, $errno);
            // TODO
        }
        \stream_set_blocking($this->socket, 0);
        // None blocking TODO CHeck error
        $this->stanzaParser = new StanzaParser();
        $this->sendRaw($connect);
        $readBytes = $this->read('stream:features');
        $this->logger->debug($this->stanzaParser->stanzas[0]->name);
        // TODO Error failed connection
    }