*/ private array $jobs = []; private int $next = 0; /** tests: any address (the fakes listen on 127.0.0.1, which is private anyway) */ public bool $anyAddress = false; /** * @param array $headers * @param \Closure(?array{status: int, headers: array, body: string}, string): void $done the answer, or null + why */ public function request(string $method, string $url, string $body, array $headers, float $timeout, \Closure $done): void { $p = parse_url($url); $host = (string)($p['host'] ?? ''); if (($p['scheme'] ?? '') !== 'http' || $host === '') { $done(null, 'adresse non prise en charge'); return; } $ip = trim($host, '[]'); if (!$this->anyAddress && (!filter_var($ip, FILTER_VALIDATE_IP) || !HttpServer::isPrivateAddress($ip))) { $done(null, 'adresse hors du réseau local refusée'); return; } $port = (int)($p['port'] ?? 80); $path = ($p['path'] ?? '/') . (isset($p['query']) ? '?' . $p['query'] : ''); $socket = @stream_socket_client('tcp://' . (str_contains($ip, ':') ? "[$ip]" : $ip) . ':' . $port, $errno, $error, 0, STREAM_CLIENT_CONNECT | STREAM_CLIENT_ASYNC_CONNECT); if ($socket === false) { $done(null, 'connexion impossible (' . ($error ?: 'réseau') . ')'); return; } stream_set_blocking($socket, false); $head = "$method $path HTTP/1.1\r\nHost: $host" . (isset($p['port']) ? ':' . $port : '') . "\r\nConnection: close\r\n" . 'Content-Length: ' . strlen($body) . "\r\n"; foreach ($headers as $name => $value) { $head .= $name . ': ' . str_replace(["\r", "\n"], '', $value) . "\r\n"; } $this->jobs[$this->next++] = ['socket' => $socket, 'url' => $url, 'out' => $head . "\r\n" . $body, 'in' => '', 'until' => microtime(true) + $timeout, 'done' => $done, 'connected' => false]; } public function busy(): bool { return $this->jobs !== []; } public function poll(): void { foreach (array_keys($this->jobs) as $id) { $this->step($id); } } private function step(int $id): void { $job = &$this->jobs[$id]; $socket = $job['socket']; if (microtime(true) > $job['until']) { unset($job); $this->finish($id, null, 'pas de réponse (délai dépassé)'); return; } if (!$job['connected']) { $r = null; $w = [$socket]; $e = null; if (@stream_select($r, $w, $e, 0) !== 1) { return; } if (@stream_socket_get_name($socket, true) === false) { unset($job); $this->finish($id, null, 'connexion refusée'); return; } $job['connected'] = true; } if ($job['out'] !== '') { $written = @fwrite($socket, $job['out']); if ($written === false) { unset($job); $this->finish($id, null, 'connexion coupée'); return; } $job['out'] = (string)substr($job['out'], $written); if ($job['out'] !== '') { return; } } for ($n = 0; $n < 32; $n++) { $chunk = @fread($socket, 65536); if (!is_string($chunk) || $chunk === '') { break; } $job['in'] .= $chunk; if (strlen($job['in']) > self::MAX_BODY) { unset($job); $this->finish($id, null, 'réponse trop grande'); return; } } $response = self::parse($job['in'], feof($socket)); if ($response !== null) { unset($job); $this->finish($id, $response, ''); } elseif (feof($socket)) { unset($job); $this->finish($id, null, 'réponse incomplète'); } } private function finish(int $id, ?array $response, string $error): void { $job = $this->jobs[$id]; unset($this->jobs[$id]); if (is_resource($job['socket'])) { @fclose($job['socket']); } try { ($job['done'])($response, $error); } catch (\Throwable $e) { error_log('[LanHttp] ' . $e->getMessage()); } } /** * A whole answer in $raw (Content-Length, chunked, or up to the end of the connection), null while it is not. * @return array{status: int, headers: array, body: string}|null */ public static function parse(string $raw, bool $ended): ?array { $end = strpos($raw, "\r\n\r\n"); if ($end === false) { return null; } $lines = explode("\r\n", substr($raw, 0, $end)); if (!preg_match('#^HTTP/\d\.\d (\d{3})#', (string)array_shift($lines), $m)) { return ['status' => 0, 'headers' => [], 'body' => '']; } $headers = []; foreach ($lines as $line) { $colon = strpos($line, ':'); if ($colon !== false) { $headers[strtolower(trim(substr($line, 0, $colon)))] = trim(substr($line, $colon + 1)); } } $body = (string)substr($raw, $end + 4); if (stripos($headers['transfer-encoding'] ?? '', 'chunked') !== false) { $out = ''; $i = 0; while (true) { $eol = strpos($body, "\r\n", $i); if ($eol === false) { return $ended ? ['status' => (int)$m[1], 'headers' => $headers, 'body' => $out] : null; } $size = hexdec(trim((string)strtok(substr($body, $i, $eol - $i), ';'))); if ($size === 0) { return ['status' => (int)$m[1], 'headers' => $headers, 'body' => $out]; } if (strlen($body) < $eol + 2 + $size + 2) { return $ended ? ['status' => (int)$m[1], 'headers' => $headers, 'body' => $out] : null; } $out .= substr($body, $eol + 2, (int)$size); $i = $eol + 2 + (int)$size + 2; } } if (isset($headers['content-length'])) { $length = (int)$headers['content-length']; return strlen($body) >= $length ? ['status' => (int)$m[1], 'headers' => $headers, 'body' => substr($body, 0, $length)] : null; } return $ended ? ['status' => (int)$m[1], 'headers' => $headers, 'body' => $body] : null; } public function close(): void { foreach ($this->jobs as $job) { if (is_resource($job['socket'])) { @fclose($job['socket']); } } $this->jobs = []; } }