protected function connectToAddress(string $address, float $timeout, bool $encrypt) { $url = \sprintf('%s://%s', $this->protocol, $address); $errno = null; $errstr = null; $context = \stream_context_create(\array_replace_recursive($this->options, ['socket' => ['connect' => $address]])); $socket = @\stream_socket_client($url, $errno, $errstr, $timeout ?: null, \STREAM_CLIENT_CONNECT | \STREAM_CLIENT_ASYNC_CONNECT, $context); if (!\is_resource($socket)) { throw new SocketException(\sprintf('Could not connect to "%s" (%s): [%s] %s', $url, $this->peer, $errno, \trim($errstr))); } try { \stream_set_blocking($socket, false); \stream_set_read_buffer($socket, 0); \stream_set_write_buffer($socket, 0); if ($this->tcpNoDelay) { Socket::setTcpNoDelay($socket, true); } if ($encrypt) { yield from $this->encryptSocketClient($socket, $timeout); } else { (yield new AwaitWrite($socket, $timeout)); } return $socket; } catch (\Throwable $e) { Socket::shutdown($socket); throw $e; } }
/** * Generates random bytes as a string of given length. * * <code> * echo Txp::get('\Textpattern\Password\Random')->generate(196); * </code> * * @param int $length The length of the generated value * @return string The value */ public function generate($length) { $bytes = (int) ceil($length / 2); if (function_exists('mcrypt_create_iv') && version_compare(PHP_VERSION, '5.3.0') >= 0) { $random = mcrypt_create_iv($bytes, MCRYPT_DEV_URANDOM); if ($random && strlen($random) === $bytes) { return substr(bin2hex($random), 0, $length); } } if (IS_WIN === false && file_exists('/dev/urandom') && is_readable('/dev/urandom') && ($fp = fopen('/dev/urandom', 'rb')) !== false) { if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($fp, 0); } $random = fread($fp, $bytes); fclose($fp); if ($random && strlen($random) === $bytes) { return substr(bin2hex($random), 0, $length); } } if (IS_WIN === false && function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4') >= 0) { $random = openssl_random_pseudo_bytes($bytes, $strong); if ($random && $strong === true && strlen($random) === $bytes) { return substr(bin2hex($random), 0, $length); } } return parent::generate($length); }
function dmx_connect() { global $debug, $dmx, $read_buffer; $r = trim(`ls -1 /dev/serial/by-id 2>/dev/null |grep "DMX"`); if ($r == '') { logformat("No USB DMX Interface appears to be connected!\n"); exit(1); } $t = explode("-", $r); if (isset($t[1])) { logformat(sprintf("Found a %s\n", $t[1])); } $interface = "/dev/serial/by-id/" . $r; `stty -F {$interface} 230400 raw -echo`; if ($dmx = fopen($interface, 'w+')) { stream_set_blocking($dmx, 0); stream_set_read_buffer($dmx, 2048); $data = ''; dmx_set_levels($data); dmx_set_dmx_receive_mode(SEND_ON_CHANGE_ONLY); sleep(1); while ($b = fread($dmx, 2048)) { } //empty the buffer $data = "Hello World!"; dmx_set_parameters(27, 4, 40, $data); if (!($c = dmx_request_parameters($read_buffer))) { dmx_close(); return 0; } return $c; } return 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(); }
function get_random_bytes($count) { $output = ''; if (@is_readable('/dev/urandom') && ($fh = @fopen('/dev/urandom', 'rb'))) { if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($fh, 0); } $output = fread($fh, $count); fclose($fh); } elseif (function_exists('openssl_random_pseudo_bytes')) { $output = openssl_random_pseudo_bytes($count, $orpb_secure); if ($orpb_secure != true) { $output = ''; } } elseif (defined('MCRYPT_DEV_URANDOM')) { $output = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM); } if (strlen($output) < $count) { $output = ''; for ($i = 0; $i < $count; $i += 16) { $this->random_state = md5(microtime() . $this->random_state); $output .= pack('H*', md5($this->random_state)); } $output = substr($output, 0, $count); } return $output; }
/** * Generate a random string by using openssl, dev/urandom or random * @param int $length optional length of the string * @return string random string * @author Benjamin BALET <*****@*****.**> */ private function generateRandomString($length = 10) { if (function_exists('openssl_random_pseudo_bytes')) { $rnd = openssl_random_pseudo_bytes($length, $strong); if ($strong === TRUE) { return base64_encode($rnd); } } $sha = ''; $rnd = ''; if (file_exists('/dev/urandom')) { $fp = fopen('/dev/urandom', 'rb'); if ($fp) { if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($fp, 0); } $sha = fread($fp, $length); fclose($fp); } } for ($i = 0; $i < $length; $i++) { $sha = hash('sha256', $sha . mt_rand()); $char = mt_rand(0, 62); $rnd .= chr(hexdec($sha[$char] . $sha[$char + 1])); } return base64_encode($rnd); }
/** * Use /dev/arandom or /dev/urandom for random numbers * * @ref http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers * * @param int $bytes * @return string */ function random_bytes($bytes) { static $fp = null; if ($fp === null) { if (is_readable('/dev/arandom')) { $fp = fopen('/dev/arandom', 'rb'); } else { $fp = fopen('/dev/urandom', 'rb'); } } if ($fp !== false) { $streamset = stream_set_read_buffer($fp, 0); if ($streamset === 0) { $remaining = $bytes; do { $read = fread($fp, $remaining); if ($read === false) { // We cannot safely read from urandom. $buf = false; break; } // Decrease the number of bytes returned from remaining $remaining -= RandomCompat_strlen($read); $buf .= $read; } while ($remaining > 0); if ($buf !== false) { if (RandomCompat_strlen($buf) === $bytes) { return $buf; } } } } throw new Exception('PHP failed to generate random data.'); }
/** * @param resource $resource * @param bool $autoClose * @throws InvalidArgumentException */ public function __construct($resource, $autoClose = true) { parent::__construct($resource, $autoClose); $this->readable = true; $this->bufferSize = 4096; if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($this->resource, 0); } }
private function readFromStatus() { stream_set_blocking($this->pipeHandles[3], 0); stream_set_read_buffer($this->pipeHandles[3], 0); $status = ''; while (!feof($this->pipeHandles[3])) { $status .= fread($this->pipeHandles[3], 1); } return $status; }
/** * Wrapper around the stream. * Provides async and non async write access required for threads * @param ForkableLoopInterface $loop * @param resource $connection */ public function __construct(ForkableLoopInterface $loop, $connection) { $this->loop = $loop; $this->connection = $connection; $this->buffer = new BinaryBuffer(); $this->ThrowOnConnectionInvalid(); if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($this->connection, 0); } $this->attachReadStream(); }
/** * @param resource $resource * @param LoopInterface $loop * @param bool $autoClose * @throws InvalidArgumentException */ public function __construct($resource, LoopInterface $loop, $autoClose = true) { parent::__construct($resource, $autoClose); if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($this->resource, 0); } $this->loop = $loop; $this->listening = false; $this->paused = true; $this->resume(); }
/** * @param resource $resource Stream resource. * @param bool $autoClose True to close the resource on destruct, false to leave it open. */ public function __construct($resource, bool $autoClose = true) { parent::__construct($resource, $autoClose); stream_set_read_buffer($resource, 0); stream_set_chunk_size($resource, self::CHUNK_SIZE); $this->queue = new \SplQueue(); $this->poll = $this->createPoll($resource, $this->queue); $this->onCancelled = function () { $this->poll->cancel(); $this->queue->shift(); }; }
/** * Returns the pointer to the random source. * @return resource The pointer to the random source. */ private function getPointer() { if (!isset($this->pointer)) { $this->pointer = fopen($this->source, 'r'); // File read buffering is not supported on HHVM if (!defined('HHVM_VERSION')) { stream_set_chunk_size($this->pointer, 32); stream_set_read_buffer($this->pointer, 32); } } return $this->pointer; }
/** * Connect to Kafka via socket * * @return void */ public function connect() { if (!is_resource($this->conn)) { $this->conn = stream_socket_client('tcp://' . $this->host . ':' . $this->port, $errno, $errstr); if (!$this->conn) { throw new RuntimeException($errstr, $errno); } stream_set_timeout($this->conn, $this->socketTimeout); stream_set_read_buffer($this->conn, $this->socketBufferSize); stream_set_write_buffer($this->conn, $this->socketBufferSize); //echo "\nConnected to ".$this->host.":".$this->port."\n"; } }
private function init() { $connection = @stream_socket_client('tcp://' . $this->host . ':' . $this->port); stream_set_write_buffer($connection, 0); stream_set_read_buffer($connection, 0); if (!$connection) { throw new \Exception('No SyncDaemon available.'); } $data = trim(fgets($connection)); if ($data != self::ACCEPT) { throw new \Exception('Connection faild. Wrong answer: ' . $data); } $this->connection = $connection; }
/** Returns a random binary string * */ function bytes($n) { if (!is_int($n) || $n < 0) { throw new InvalidArgumentException("Argument must be non-negative integer: got {$n}"); } if ($this->fp === null) { if (defined('MCRYPT_DEV_URANDOM')) { $bytes = mcrypt_create_iv($n, MCRYPT_DEV_URANDOM); if ($bytes === FALSE || strlen($bytes) != $n) { throw new RuntimeException("mcrypt_create_iv failed!"); } return $bytes; } $this->fp = fopen('/dev/urandom', 'rb'); if ($this->fp === FALSE) { $this->fp = null; throw new RuntimeException("fopen of /dev/urandom failed"); } // by default PHP reads 4096 of bytes // http://stackoverflow.com/questions/4296932/does-phps-fread-always-read-at-least-4096-bytes // With php >= 5.3.3, we might be able to speed this up: // http://php.net/manual/en/function.stream-set-read-buffer.php if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($this->fp, 0); } } $bits = ''; $count = 0; $itermax = 10; // possible some weird IO problem is preventing reading of bytes // make sure infinite loop doesn't happen. Not sure how PHP // handles E_AGAIN signal under load. while ($count < $itermax) { $len = strlen($bits); if ($len === $n) { break; } $count++; $tmp = fread($this->fp, $n - $len); if ($tmp === FALSE) { continue; } $bits .= $tmp; } if ($count === $itermax) { throw new RuntimeException("After {$itermax} iterations, only got {$len} bytes, requested {$n}"); } return $bits; }
public function __construct() { if (self::$eio === null) { \eio_init(); $eio = @\eio_get_event_stream(); \stream_set_blocking($eio, false); \stream_set_read_buffer($eio, 0); self::$eio = $eio; self::$callback = function () { while (\eio_npending()) { \eio_poll(); } }; } }
/** * {@inheritdoc} */ public function connect() { if ($this->sock) { return; } $this->sock = stream_socket_client($this->uri, $errno, $errstr, $this->timeout); if (!$this->sock) { throw new \RuntimeException("Can't connect to the server at '{$this->uri}' ({$errno}: {$errstr})"); } stream_set_timeout($this->sock, $this->timeout); stream_set_blocking($this->sock, $this->blocking); stream_set_read_buffer($this->sock, 0); // 64k stream_set_write_buffer($this->sock, 0); }
/** * Transport constructor. * @param $socket * @param LoopInterface $loop */ public function __construct($socket, LoopInterface $loop) { $this->socket = $socket; $this->loop = $loop; stream_set_blocking($this->socket, 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->socket, 0); } }
public function __construct($host, $port, $connection_timeout, $read_write_timeout = null, $context = null, $blocking = false) { $errstr = $errno = null; $this->sock = null; if ($context) { $remote = sprintf('tls://%s:%s', $host, $port); $this->sock = @stream_socket_client($remote, $errno, $errstr, $connection_timeout, STREAM_CLIENT_CONNECT, $context); } else { $remote = sprintf('tcp://%s:%s', $host, $port); $this->sock = @stream_socket_client($remote, $errno, $errstr, $connection_timeout, STREAM_CLIENT_CONNECT); } if (!$this->sock) { throw new RuntimeException("Error Connecting to server({$errno}): {$errstr} "); } if (null !== $read_write_timeout) { if (!stream_set_timeout($this->sock, $read_write_timeout)) { throw new \Exception("Timeout (stream_set_timeout) could not be set"); } } /** * Manually set blocking & write buffer settings and make sure they are successfuly set * Use non-blocking as we dont want to stuck waiting for socket data while fread() w/o timeout */ if (!stream_set_blocking($this->sock, $blocking)) { throw new \Exception("Blocking could not be set"); } $rbuff = stream_set_read_buffer($this->sock, 0); if (!(0 === $rbuff)) { throw new \Exception("Read buffer could not be set"); } /** * ! this is not reliably returns success (0) * ! but default buffer is pretty high (few Kb), so will not affect sending single small pushes * * Output using fwrite() is normally buffered at 8K. * This means that if there are two processes wanting to write to the same output stream (a file), * each is paused after 8K of data to allow the other to write. * * Ensures that all writes with fwrite() are completed * before other processes are allowed to write to that output stream */ stream_set_write_buffer($this->sock, 0); /** * Set small chunk size (default=4096/8192) * Setting this to small values (100bytes) still does NOT help detecting feof() */ stream_set_chunk_size($this->sock, 1024); }
/** * Generate a random string of the specified size * * @param int $size The size of the requested random string * * @return string A string of the requested size */ public function generate($size) { if ($size == 0) { return static::emptyValue($size); } $file = fopen(static::$file, 'rb'); if (!$file) { return static::emptyValue($size); } if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($file, 0); } $result = fread($file, $size); fclose($file); return $result; }
/** * Generate a random string of the specified size * * @param int $size The size of the requested random string * * @return string A string of the requested size */ public function generate($size) { if ($size == 0 || !file_exists($this->file)) { return str_repeat(chr(0), $size); } $file = fopen($this->file, 'rb'); if (!$file) { return str_repeat(chr(0), $size); } if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($file, 0); } $result = fread($file, $size); fclose($file); return $result; }
public static function connect(string $url, $workerId) : IpcClient { $errno = null; $errstr = null; $socket = @\stream_socket_client($url, $errno, $errstr, 5); if ($socket === false) { throw new \RuntimeException(\sprintf('Failed to connecto to IPC server "%s": [%s] %s', $url, $errno, $errstr)); } \stream_set_read_buffer($socket, 0); \stream_set_write_buffer($socket, 0); $socket = new SocketStream($socket); $transmitter = new SocketTransmitter($socket); // Perform a blocking handshake. $transmitter->sendSync($workerId, SocketTransmitter::TYPE_HANDSHAKE); return new IpcClient($workerId, $socket, $transmitter); }
/** * @inheritdoc */ public function getPseudoRandomString($length) { $this->validateLength($length); $stream = fopen('/dev/urandom', 'rb'); if (!is_resource($stream)) { throw new FacebookSDKException(static::ERROR_MESSAGE . 'Unable to open stream to /dev/urandom.'); } if (!defined('HHVM_VERSION')) { stream_set_read_buffer($stream, 0); } $binaryString = fread($stream, $length); fclose($stream); if (!$binaryString) { throw new FacebookSDKException(static::ERROR_MESSAGE . 'Stream to /dev/urandom returned no data.'); } return $this->binToHex($binaryString, $length); }
/** * {@inheritdoc} */ public function connect($address) { if (!($this->stream = @stream_socket_client($address, $errno, $errstr, 1.0, STREAM_CLIENT_CONNECT))) { throw new SocketException(sprintf('Connection to %s failed: %s', $address, $errstr)); } stream_set_blocking($this->stream, 1); // 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); } return $this; }
public function execute(...$args) : Command { $spec = [['pipe', 'r']]; $command = $this->command; $options = []; $cwd = $this->dir ?? \getcwd(); $env = \array_merge(\array_filter($_SERVER, 'is_scalar'), $this->env ?? []); if (\DIRECTORY_SEPARATOR === '\\') { $options['bypass_shell'] = true; } for ($i = 0; $i < 2; $i++) { $spec[] = ['pipe', $i ? 'a' : 'w']; } foreach ($this->options as $k => $v) { if (\strlen($k) === 1) { $command .= ' -' . $k; } else { $command .= ' --' . $k; } if ($v !== null) { $command .= ' ' . \escapeshellarg($v); } } foreach ($args as $arg) { if ($arg instanceof RawArg) { $command .= ' ' . $arg; } else { $command .= ' ' . \escapeshellarg($arg); } } $pipes = []; $process = @\proc_open($command, $spec, $pipes, $cwd, $env, $options); if ($process === false) { throw new \RuntimeException(\sprintf('Failed to execute command: "%s"', $command)); } foreach ($pipes as &$pipe) { \stream_set_blocking($pipe, false); \stream_set_read_buffer($pipe, 0); \stream_set_write_buffer($pipe, 0); } $close = $this->stderr ? 1 : 2; @fclose($pipes[$close]); unset($pipes[$close]); return new Command($process, ...\array_values($pipes)); }
public function __construct(LevelProvider $level, $regionX, $regionZ) { $this->x = $regionX; $this->z = $regionZ; $this->levelProvider = $level; $this->filePath = $this->levelProvider->getPath() . "region/r.{$regionX}.{$regionZ}.mca"; $exists = file_exists($this->filePath); touch($this->filePath); $this->filePointer = fopen($this->filePath, "r+b"); stream_set_read_buffer($this->filePointer, 1024 * 16); //16KB stream_set_write_buffer($this->filePointer, 1024 * 16); //16KB if (!$exists) { $this->createBlank(); } else { $this->loadLocationTable(); } }
/** * @param int $length * * @return string */ public function getByte($length) { if (function_exists('random_bytes')) { return random_bytes($length); } elseif (function_exists('openssl_random_pseudo_bytes')) { return openssl_random_pseudo_bytes($length); } elseif (file_exists('/dev/urandom')) { $handle = fopen('/dev/urandom', 'rb'); stream_set_read_buffer($handle, 0); $r = fread($handle, $length); fclose($handle); return $r; } else { $r = ''; do { $r .= pack('L', mt_rand()); } while (strlen($r) < $length); return substr($r, 0, $length); } }
/** * @param string $host * @param int $port * @param int $timeout * @throws TransportException */ private function connect($host, $port, $timeout) { $this->socket = @fsockopen($host, $port, $errno, $errstr, $timeout); if (!$this->socket) { throw new TransportException('Cannot open socket', TransportException::NOT_INITIALIZED); } stream_set_read_buffer($this->socket, 0); stream_set_write_buffer($this->socket, 0); // handshake $header = $this->read(15); if ($header === false) { $this->onIoFailure(sprintf('during handshake (%s)', socket_strerror(socket_last_error($this->socket)))); } extract(unpack('Vsize/a*protocol', $header)); /** @var $size int */ /** @var $protocol string */ if ($size != 11 || $protocol != 'GBXRemote 2') { throw new TransportException('Wrong protocol header', TransportException::WRONG_PROTOCOL); } $this->lastNetworkActivity = time(); }
function get_random_bytes($count) { $output = ''; if (@is_readable('/dev/urandom') && ($fh = @fopen('/dev/urandom', 'rb'))) { if (function_exists('stream_set_read_buffer')) { stream_set_read_buffer($fh, 0); } $output = fread($fh, $count); fclose($fh); } elseif (function_exists('openssl_random_pseudo_bytes')) { $output = openssl_random_pseudo_bytes($count); } if (strlen($output) < $count) { $output = ''; for ($i = 0; $i < $count; $i += 16) { $this->random_state = md5(microtime() . $this->random_state); $output .= pack('H*', md5($this->random_state)); } $output = substr($output, 0, $count); } return $output; }