Throws an exception if stream timed out

@return void

@throws Net_Notifier_Socket_TimeoutException
328012
protected function checkTimeout()
    {
        $info = stream_get_meta_data($this->socket);
        if ($info['timed_out'] || $this->deadline && time() > $this->deadline) {
            $reason = $this->deadline
                ? "after {$this->timeout} second(s)"
                : 'due to default_socket_timeout php.ini setting';

            throw new Net_Notifier_Socket_TimeoutException(
                "Request timed out {$reason}"
            );
        }
    }
745416
public function disconnect()
    {
        try {
            if ($this->stream) {
                $this->stream->close();
                $this->stream = null;
            }
        } catch (\Throwable $e) {
            \danog\MadelineProto\Logger::log('Got exception while closing stream: '.$e->getMessage());
        } catch (\Exception $e) {
            \danog\MadelineProto\Logger::log('Got exception while closing stream: '.$e->getMessage());
        }
    }
279951
public function shutdown()
    {
        $exceptions = $this->client_holder->shutdown();

        if ($this->hasLogger()) {
            foreach ($exceptions as $exception) {
                printf(
                    "Exception caught during shutdown: %s\n",
                    (string) $exception
                );
            }

            $this->logger = null;
        }

        $this->client_poolers = [];
        $this->connection->close();
        $this->is_shutdown = true;
    }
231199
protected function connect()
    {
        $host = "{$this->socketProtocol}://{$this->hostname}";
        if ($this->socketPort) {
            $host .= ":{$this->socketPort}";
        }
        $socketStream = @stream_socket_client($host, $errorNumber, $errorMessage, $this->socketOptions['connectionTimeout']);
        if (!is_resource($socketStream)) {
            throw new \Exception("{$errorNumber}: Error connecting to socket: [{$errorMessage}]");
        }
        stream_set_timeout($socketStream, $this->socketOptions['streamTimeout']);
        stream_set_blocking($socketStream, true);
        $this->socketResource = $socketStream;
        return $this;
    }
912693
public void setTimeout(int pTimeout) {
        if (pTimeout < 0) {  // Must be positive
            throw new IllegalArgumentException("Timeout must be positive.");
        }
        timeout = pTimeout;
        if (socket != null) {
            try {
                socket.setSoTimeout(pTimeout);
            }
            catch (SocketException se) {
                // Not much to do about that...
            }
        }
    }
782630
public function selectAndProcess(): void
    {
        $read = $this->resources;
        $unused_write = null;
        $unsued_exception = null;

        stream_select(
            $read,
            $unused_write,
            $unused_exception,
            $this->options['timeout_select'],
            $this->options['timeout_select_microsec']
        );

        foreach ($read as $socket) {
            if ($socket == $this->socket->getResource()) {
                $this->processMasterSocket();
            } else {
                $this->processClientSocket($socket);
            }
        }
    }
678025
public function start(int $timeout_ms = 3000): void
    {
        $port = $this->config->getPort();

        $this->logger->notice("Starting standalone server on port $port.");

        if ($this->isStarted()) {
            $this->logger->notice('Standalone server already running, skipping start.');

            return;
        }

        if (!$this->portTester->isAvailable('localhost', $port, 'http')) {
            $msg = "Cannot start server on port '$port', it's already in use.";
            $this->logger->error("Start failed: $msg");
            throw new Exception\PortUnavailableException($msg);
        }

        $command = $this->getCommand();

        $log_file = $this->config->getLogFile();
        $pid_file = $this->config->getPidFile();
        $cmd = sprintf('%s > %s 2>&1 & echo $! > %s', $command, $log_file, $pid_file);

        $this->logger->debug("Start server with: $cmd");
        exec($cmd);

        if (!file_exists($pid_file)) {
            $msg = "Server not started, pid file was not created in '$pid_file'";
            $this->logger->error("Start failed: $msg");
            throw new Exception\RuntimeException($msg);
        }
        if (!file_exists($log_file)) {
            $msg = "Server not started, log file was not created in '$log_file'";
            $this->logger->error("Start failed: $msg");
            throw new Exception\RuntimeException($msg);
        }

        // Loop for waiting correct start of phpjavabridge
        $started = false;
        $iterations = 0;
        $refresh_us = 100 * 1000; // 100ms
        $timeout_us = $timeout_ms * 1000;
        $max_iterations = ceil($timeout_us / min([$refresh_us, $timeout_us]));

        while (!$started || $iterations > $max_iterations) {
            usleep($refresh_us);
            $log_file_content = file_get_contents($log_file);
            if (preg_match('/Exception/', $log_file_content)) {
                $msg = "Cannot start standalone server on port '$port', reason:\n";
                $msg .= $log_file_content;
                $this->logger->error("Start failed: $msg");
                throw new Exception\RuntimeException($msg);
            }

            $log_file_content = file_get_contents($log_file);
            if (preg_match('/JavaBridgeRunner started on/', $log_file_content)) {
                $started = true;
            }
            ++$iterations;
        }
        if (!$started) {
            $msg = "Standalone server probably not started, timeout '$timeout_ms' reached before getting output";
            $this->logger->error("Start failed: $msg");
            throw new Exception\RuntimeException($msg);
        }
        $this->started = true;
    }
808830
public function setStreamTimeout($value)
    {
        if ($value < 1) {
            $value = self::DEFAULT_STREAM_TIMEOUT;
        }

        $this->streamTimeout = (int) $value;
        if ($this->handle !== null) {
            stream_set_timeout($this->handle, 0, $this->getStreamTimeout());
        }
    }
139165
private function emitSocketError()
    {
        $errno = socket_last_error();
        $errstr = socket_strerror($errno);

        $this->disconnect();

        $this->onConnectionError(trim($errstr), $errno);
    }
1181056
protected function processMasterSocket(): void
    {
        $new = null;

        try {
            $new = $this->socket->accept();
        } catch (Exception $e) {
            $this->logger->error('Socket error: {exception}', [
                'exception' => $e,
            ]);
            return;
        }

        $connection = $this->createConnection($new);
        $this->server->notify(Server::EVENT_SOCKET_CONNECT, [$new, $connection]);
    }
923960
public synchronized void setTimeout(int timeout) {
        try {
            this.timeout = timeout;
            if (socket != null) {
                socket.setSoTimeout(timeout);
            }
        }
        catch (IOException ex) {
            logger.warn("Could not set timeout to value " + timeout, ex);
        }
    }
743678
public synchronized void start() throws SocketException {

        if (!isRunning()) {
            socket.set(new DatagramSocket(ANNOUNCEMENT_PORT));
            startTime.set(System.currentTimeMillis());
            deliverLifecycleAnnouncement(logger, true);

            final byte[] buffer = new byte[512];
            final DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            Thread receiver = new Thread(null, new Runnable() {
                @Override
                public void run() {
                    boolean received;
                    while (isRunning()) {
                        try {
                            if (getCurrentDevices().isEmpty()) {
                                socket.get().setSoTimeout(60000);  // We have no devices to check for timeout; block for a whole minute to check for shutdown
                            } else {
                                socket.get().setSoTimeout(1000);  // Check every second to see if a device has vanished
                            }
                            socket.get().receive(packet);
                            received = !ignoredAddresses.contains(packet.getAddress());
                        } catch (SocketTimeoutException ste) {
                            received = false;
                        } catch (IOException e) {
                            // Don't log a warning if the exception was due to the socket closing at shutdown.
                            if (isRunning()) {
                                // We did not expect to have a problem; log a warning and shut down.
                                logger.warn("Problem reading from DeviceAnnouncement socket, stopping", e);
                                stop();
                            }
                            received = false;
                        }
                        try {
                            if (received && (packet.getLength() == 54)) {
                                final Util.PacketType kind = Util.validateHeader(packet, ANNOUNCEMENT_PORT);
                                if (kind == Util.PacketType.DEVICE_KEEP_ALIVE) {
                                    // Looks like the kind of packet we need
                                    if (packet.getLength() < 54) {
                                        logger.warn("Ignoring too-short " + kind.name + " packet; expected 54 bytes, but only got " +
                                                packet.getLength() + ".");
                                    } else {
                                        if (packet.getLength() > 54) {
                                            logger.warn("Processing too-long " + kind.name + " packet; expected 54 bytes, but got " +
                                                    packet.getLength() + ".");
                                        }
                                        DeviceAnnouncement announcement = new DeviceAnnouncement(packet);
                                        final boolean foundNewDevice = isDeviceNew(announcement);
                                        updateDevices(announcement);
                                        if (foundNewDevice) {
                                            deliverFoundAnnouncement(announcement);
                                        }
                                    }
                                }
                            }
                            expireDevices();
                        } catch (Throwable t) {
                            logger.warn("Problem processing DeviceAnnouncement packet", t);
                        }
                    }
                }
            }, "beat-link DeviceFinder receiver");
            receiver.setDaemon(true);
            receiver.start();
        }
    }
922764
public function stream_close() {
    assert(isset($this->client));
    $this->client->close();
    $this->client = null;
  }
228529
public void setReadTimeout(int timeout) {
		Assert.isTrue(timeout >= 0, "Timeout must be a non-negative value");
		getHttpClient().getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
	}
150717
protected function _ensureSocketCreated() {
        // Already ready!
        if (is_resource($this->socket_)) {
            return TRUE;
        }

        $sockaddr = $this->scheme_ . '://' . $this->host_;
        $port = $this->port_;

        // Ignore the Thrift specified timeout ($this->timeout_) and use the
        // socket-specific timeout set in this file.
        $timeout = self::DEFAULT_CONNECT_TIMEOUT_SECS;

        for ($retry = 0; $retry < self::MAX_SOCKET_OPEN_RETRIES; $retry++) {
            try {
                // Suppress connection error logs
                $fd = @pfsockopen($sockaddr, $port, $errno, $errstr, $timeout);
                if ($errno == 0 && is_resource($fd)) {
                    // Connection okay - break out of the retry loop
                    stream_set_blocking($fd, 0);
                    stream_set_timeout($fd, 0, self::DEFAULT_STREAM_TIMEOUT_MICROS);
                    $this->socket_ = $fd;
                    break;
                }
            } catch (Exception $e) {
                // Ignore the exception and retry
            }
        }

        return is_resource($this->socket_);
    }
22405
public function connect()
    {
        if ($this->connection) {
            $this->disconnect();
        }

        $hasProtocol = strpos($this->_config['host'], '://') !== false;
        if ($hasProtocol) {
            list($this->_config['protocol'], $this->_config['host']) = explode('://', $this->_config['host']);
        }
        $scheme = null;
        if (!empty($this->_config['protocol'])) {
            $scheme = $this->_config['protocol'] . '://';
        }

        $this->_setSslContext($this->_config['host']);
        if (!empty($this->_config['context'])) {
            $context = stream_context_create($this->_config['context']);
        } else {
            $context = stream_context_create();
        }

        $connectAs = STREAM_CLIENT_CONNECT;
        if ($this->_config['persistent']) {
            $connectAs |= STREAM_CLIENT_PERSISTENT;
        }

        set_error_handler([$this, '_connectionErrorHandler']);
        $this->connection = stream_socket_client(
            $scheme . $this->_config['host'] . ':' . $this->_config['port'],
            $errNum,
            $errStr,
            $this->_config['timeout'],
            $connectAs,
            $context
        );
        restore_error_handler();

        if (!empty($errNum) || !empty($errStr)) {
            $this->setLastError($errNum, $errStr);
            throw new SocketException($errStr, $errNum);
        }

        if (!$this->connection && $this->_connectionErrors) {
            $message = implode("\n", $this->_connectionErrors);
            throw new SocketException($message, E_WARNING);
        }

        $this->connected = is_resource($this->connection);
        if ($this->connected) {
            stream_set_timeout($this->connection, $this->_config['timeout']);
        }

        return $this->connected;
    }
1220502
protected function fill()
    {
        if (count($this) <= 0) {
            return;
        }

        $read = $this->sockets;
        $write = null;
        $except = null;
        $time = count($this->results) > 0 ? 0 : $this->timeout;

        if (stream_select($read, $write, $except, $time) > 0) {
            foreach ($read as $socket) {
                try {
                    $result = $this->read($socket);
                } catch (\RuntimeException $e) {
                    continue;
                }
                $this->results->enqueue($result);
                $this->remain--;
            }
        }
    }