Blocking call that waits for response to specific request

@param Integer $requestId
@param Integer $timeoutMs [optional] the number of milliseconds to wait. Defaults to the ReadWriteTimeout value set.
@return string  response body
357730
public function wait_for_response($requestId, $timeoutMs = 0) {

        if (!isset($this->_requests[$requestId])) {
            throw new \Exception('Invalid request id given');
        }

        // If we already read the response during an earlier call for different id, just return it
        if ($this->_requests[$requestId]['state'] == self::REQ_STATE_OK
            || $this->_requests[$requestId]['state'] == self::REQ_STATE_ERR
            ) {
            return $this->_requests[$requestId]['response'];
        }

        if ($timeoutMs > 0) {
            // Reset timeout on socket for now
            $this->set_ms_timeout($timeoutMs);
        } else {
            $timeoutMs = $this->_readWriteTimeout;
        }

        // Need to manually check since we might do several reads none of which timeout themselves
        // but still not get the response requested
        $startTime = microtime(true);

        do {
            $resp = $this->readPacket();

            if ($resp['type'] == self::STDOUT || $resp['type'] == self::STDERR) {
                if ($resp['type'] == self::STDERR) {
                    $this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_ERR;
                }
                $this->_requests[$resp['requestId']]['response'] .= $resp['content'];
            }
            if ($resp['type'] == self::END_REQUEST) {
                $this->_requests[$resp['requestId']]['state'] = self::REQ_STATE_OK;
                if ($resp['requestId'] == $requestId) { 
                    break;
                }
            }
            if (microtime(true) - $startTime >= ($timeoutMs * 1000)) {
                // Reset
                $this->set_ms_timeout($this->_readWriteTimeout);
                throw new \Exception('Timed out');
            }
        } while ($resp);

        if (!is_array($resp)) {
            $info = stream_get_meta_data($this->_sock);

            // We must reset timeout but it must be AFTER we get info
            $this->set_ms_timeout($this->_readWriteTimeout);

            if ($info['timed_out']) {
                throw new TimedOutException('Read timed out');
            }

            if ($info['unread_bytes'] == 0
                    && $info['blocked']
                    && $info['eof']) {
                throw new ForbiddenException('Not in white list. Check listen.allowed_clients.');
            }

            throw new \Exception('Read failed');
        }

        // Reset timeout
        $this->set_ms_timeout($this->_readWriteTimeout);

        switch (ord($resp['content']{4})) {
            case self::CANT_MPX_CONN:
                throw new \Exception('This app can\'t multiplex [CANT_MPX_CONN]');
                break;
            case self::OVERLOADED:
                throw new \Exception('New request rejected; too busy [OVERLOADED]');
                break;
            case self::UNKNOWN_ROLE:
                throw new \Exception('Role value not known [UNKNOWN_ROLE]');
                break;
            case self::REQUEST_COMPLETE:
                return $this->_requests[$requestId]['response'];
        }
    }
134587
public function getUpdates(int $offset = null, int $limit = null, int $timeout = 10)
    {
        $response = $this->request(
            'getUpdates',
            [
                'offset'  => $offset,
                'limit'   => $limit,
                'timeout' => $timeout,
            ]
        );

        $updates = [];
        foreach ($response->result as $update_data) {
            $updates[] = new Update(new Unstructured($update_data));
        }

        return $updates;
    }
424909
public function handleRequest($requestUri = null, $requestMethod = null)
    {
        if (!$this->isConfigConsistent() && false) {
            throw new \LogicException('The client configuration is not consistent');
        }

        $pathInfo = $requestUri;

        if (false !== $pos = strpos($pathInfo, '?')) {
            $pathInfo = substr($pathInfo, 0, $pos);
        }

        $pathInfo = rawurldecode($pathInfo);

        $info = $this->getDispatcher()->dispatch($requestMethod, $pathInfo);

        if ($info[0] == Dispatcher::FOUND) {
            try {
                $response = $info[1]($this);

                if ($response instanceof ResponseInterface) {
                    $this->setResponse($response);
                }
            } catch (ResponseExceptionInterface $e) {
                $this->setResponse($e->getResponse());
            }
        } elseif (!$this->isAuthenticated()) {
            if (strtoupper($requestMethod) == 'GET') {
                $_SESSION[self::class][$this->getConfig()->getEntityID()]['targeted_path'] = $requestUri;
            }

            $request = $this->getSaml()->buildAuthnRequest();
            $_SESSION[self::class][$this->getConfig()->getEntityID()]['SAML_RelayState'] = $request->getRelayState();

            $this->setResponse($this->getSaml()->getHttpRedirectBindingResponse($request));
        }

        return $this;
    }
629536
protected function _receive($timeout = null)
    {
        $this->checkConnection();

        if ($timeout !== null) {
            stream_set_timeout($this->_connection, $timeout);
        }

        $response = fgets($this->_connection, 1024);
        $info = stream_get_meta_data($this->_connection);

        if (!empty($info['timed_out'])) {
            throw new SMTPException(__('%s has timed out', array($this->_host)));
        } elseif ($response === false) {
            throw new SMTPException(__('Could not read from %s', array($this->_host)));
        }

        return $response;
    }
1210765
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final Object data) {
        return requestTimeout(delay, unit, null, data);
    }
335020
private function set_ms_timeout($timeoutMs) {
        if (!$this->_sock) {
            return false;
        }
        return stream_set_timeout($this->_sock, floor($timeoutMs / 1000), ($timeoutMs % 1000) * 1000);
    }
137696
public static function setTimeout($timeout = 60) {
        if (!is_int($timeout) || $timeout < 0) {
            return false;
        }

        self::$timeout = $timeout;
        return true;
    }
1362585
function(callback, timeInMs) {
    var timeout = makeTimeout(function() {
      setTriggerTime(timeout, timeout.timeInMs);
      s_timeoutsToInsert.push(timeout);
      callback();
    });
    timeout.timeInMs = timeInMs;
    s_timeoutsToInsert.push(timeout);
    return timeout.id;
  }
177229
protected T _getResultWithTimeout(final long timeout) throws TimeoutException {
        if(timeout <= 0)
            cond.waitFor(this::hasResult);
        else if(!cond.waitFor(this::hasResult, timeout, TimeUnit.MILLISECONDS))
            throw new TimeoutException();
        return result;
    }
502139
protected TimeoutId requestTimeout(final long delay, final TimeUnit unit, @Nullable final String name) {
        return requestTimeout(delay, unit, name, null);
    }
150759
private function readNameValuePair(int $requestId, ?string &$buffer): void
    {
        $nameLength  = $this->readFieldLength($buffer);
        $valueLength = $this->readFieldLength($buffer);

        $contentFormat = (
            'a'.$nameLength.'name/'.
            'a'.$valueLength.'value/'
        );

        $content = unpack($contentFormat, $buffer);
        $this->requests[$requestId]['params'][$content['name']] = $content['value'];

        $buffer = substr($buffer, $nameLength + $valueLength);
    }
721199
private function receiveResponse(float $timeout): Response
    {
        $start = microtime(true);
        $data = '';
        $size = null;

        do {
            $nextByte = $this->serialInterface->readByte();

            if ($nextByte !== false) {
                $data .= $nextByte;
                $dataLength = strlen($data);

                if ($dataLength == 3 && $data !== $this->expectedPreamble) {
                    throw new \RuntimeException('Invalid preamble ' . $data . ' received. Expected: ' . $this->expectedPreamble);
                } elseif ($dataLength == 4) {
                    $size = unpack('C', $nextByte)[1];
                } elseif ($size != null && $dataLength >= ($size + 6)) {
                    return $this->responseFactory->create($data);
                }
            } else {
                usleep($this->sleepTime);
            }
        } while ((microtime(true) - $start) <= $timeout);

        throw new TimeoutException('Unable to receive response within ' . $timeout . ' seconds. (Received data: <' . $data . '>)');
    }
1371105
function set_timeout($timeout) {
        if (!is_integer($timeout)) {
            if (is_numeric($timeout)) {
                $this->timeout = (integer)$timeout;
                return true;
            }
            return false;
        }
        $this->timeout = $timeout;
        return true;
    }
342473
public function processResponse($requestId = null)
    {
        $this->_errors = array();
        $this->_errorReason = null;
        if (isset($_POST) && isset($_POST['SAMLResponse'])) {
            // AuthnResponse -- HTTP_POST Binding
            $response = new OneLogin_Saml2_Response($this->_settings, $_POST['SAMLResponse']);
            $this->_lastResponse = $response->getXMLDocument();

            if ($response->isValid($requestId)) {
                $this->_attributes = $response->getAttributes();
                $this->_attributesWithFriendlyName = $response->getAttributesWithFriendlyName();
                $this->_nameid = $response->getNameId();
                $this->_nameidFormat = $response->getNameIdFormat();
                $this->_nameidNameQualifier = $response->getNameIdNameQualifier();
                $this->_authenticated = true;
                $this->_sessionIndex = $response->getSessionIndex();
                $this->_sessionExpiration = $response->getSessionNotOnOrAfter();
                $this->_lastMessageId = $response->getId();
                $this->_lastAssertionId = $response->getAssertionId();
                $this->_lastAssertionNotOnOrAfter = $response->getAssertionNotOnOrAfter();
            } else {
                $this->_errors[] = 'invalid_response';
                $this->_errorReason = $response->getError();
            }
        } else {
            $this->_errors[] = 'invalid_binding';
            throw new OneLogin_Saml2_Error(
                'SAML Response not found, Only supported HTTP_POST Binding',
                OneLogin_Saml2_Error::SAML_RESPONSE_NOT_FOUND
            );
        }
    }
644274
public static function setTimeout($id, $timeout = null)
    {
        if (isset(self::$list[$id])) {
            self::$list[$id]->timeout($timeout);
            return true;
        }
        return false;
    }
1327635
public function wait($timeout = 60)
    {
        $timeoutMicro = $timeout !== null ? microtime(true) + (float)$timeout : null;
        while ($this->isRunning()) {
            if ($timeout !== null && microtime(true) >= $timeoutMicro) {
                return null;
            }
            usleep(1000);
        }

        return $this->getExitCode();
    }
827507
private function responseHandler($requestMethod, $requestPath, array $clientResponse)
    {
        $statusCode = (int) $clientResponse[0];
        $responseString = (string) $clientResponse[1];

        try {
            $responseData = Json::decode($responseString);
            $this->validateClientResponse($requestMethod, $requestPath, $statusCode, $responseData);

            if (400 <= $statusCode) {
                // either we sent an incorrect request, or there is a server error
                throw new HttpClientException(sprintf('[%d] %s "%s/%s": %s', $statusCode, $requestMethod, $this->baseUri, $requestPath, $responseData['error']));
            }

            // the request was correct, and there was not a server error
            if ($responseData[$requestPath]['ok']) {
                // our request was handled correctly
                if (!\array_key_exists('data', $responseData[$requestPath])) {
                    return null;
                }

                return $responseData[$requestPath]['data'];
            }

            // our request was not handled correctly, something went wrong...
            throw new ApiException($responseData[$requestPath]['error']);
        } catch (JsonException $e) {
            // unable to parse the JSON
            throw new HttpClientException(sprintf('[%d] %s "%s/%s": %s', $statusCode, $requestMethod, $this->baseUri, $requestPath, $e->getMessage()));
        }
    }