From f04f605f48dbed8fe5c80a0f3246cac29cb8ab87 Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sun, 22 Nov 2026 20:27:21 +0300 Subject: [PATCH 1/3] fix: bound incremental HTTP parsing resources --- README.md | 8 +- README.ru.md | 9 +- src/Gateway/HttpBodyTracker.php | 29 +++++-- src/Protocols/Http.php | 143 ++++++++++++++++++++------------ src/Protocols/Http/Request.php | 11 ++- tests/gateway_smoke.php | 27 ++++++ tests/smoke.php | 76 +++++++++++++++++ 7 files changed, 234 insertions(+), 69 deletions(-) diff --git a/README.md b/README.md index 7e6e75d..8d497b7 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ High-performance event-driven server runtime for PHP with TCP, UDP, HTTP/1.1, WebSocket, timers, long-lived connections and multi-process workers. -The current stable release is 7.2.1. It provides process supervision, HTTP/1.x and WebSocket protocols, and a bounded +The current stable release is 7.2.2. It provides process supervision, HTTP/1.x and WebSocket protocols, and a bounded L4/L7 gateway. Packages from version 4.x have a different public API; see the [compatibility guide](https://server.localzet.com/current/compatibility) for the changes and migration notes. @@ -204,12 +204,16 @@ HTTP request limits are configurable globally when an application needs stricter ```php use localzet\Server\Protocols\Http; +use localzet\Server\Protocols\Http\Request; Http::maxHeaderLength(16 * 1024); Http::maxHeaderCount(100); +Request::$maxMultipartParts = 256; ``` -The parser also handles `Expect: 100-continue`, validates HTTP/1.1 `Host`, rejects ambiguous request framing and accepts +Multipart parsing is limited to 1,024 parts per request by default. Lower `Request::$maxMultipartParts` for the +application; exceeding the configured limit throws `LengthException` when the request body is first parsed. The parser +also handles `Expect: 100-continue`, validates HTTP/1.1 `Host`, rejects ambiguous request framing and accepts standards-compliant extension methods such as WebDAV verbs rather than using a fixed method whitelist. ## Gateway diff --git a/README.ru.md b/README.ru.md index 5f64bdc..c06bace 100644 --- a/README.ru.md +++ b/README.ru.md @@ -4,7 +4,7 @@ Событийный серверный runtime на PHP: TCP, UDP, HTTP/1.1, WebSocket, таймеры, долгоживущие соединения и многопроцессные воркеры. -Текущая стабильная версия — 7.2.1. В ней есть управление процессами, HTTP/1.x, WebSocket и ограниченный шлюз L4/L7. У версий 4.x другой публичный API; различия и порядок перехода описаны в [руководстве по совместимости](https://server.localzet.com/current/compatibility). +Текущая стабильная версия — 7.2.2. В ней есть управление процессами, HTTP/1.x, WebSocket и ограниченный шлюз L4/L7. У версий 4.x другой публичный API; различия и порядок перехода описаны в [руководстве по совместимости](https://server.localzet.com/current/compatibility). ## Требования @@ -166,12 +166,17 @@ $connection->send( ```php use localzet\Server\Protocols\Http; +use localzet\Server\Protocols\Http\Request; Http::maxHeaderLength(16 * 1024); Http::maxHeaderCount(100); +Request::$maxMultipartParts = 256; ``` -Парсер обрабатывает `Expect: 100-continue`, проверяет HTTP/1.1 `Host`, отклоняет неоднозначный framing и принимает корректные дополнительные методы, включая WebDAV. +По умолчанию multipart-запрос может содержать не более 1 024 частей. Уменьшите `Request::$maxMultipartParts` под +потребности приложения; превышение лимита вызывает `LengthException` при первом разборе тела запроса. Парсер также +обрабатывает `Expect: 100-continue`, проверяет HTTP/1.1 `Host`, отклоняет неоднозначный framing и принимает корректные +дополнительные методы, включая WebDAV. ## Gateway diff --git a/src/Gateway/HttpBodyTracker.php b/src/Gateway/HttpBodyTracker.php index 0fe5662..b32496e 100644 --- a/src/Gateway/HttpBodyTracker.php +++ b/src/Gateway/HttpBodyTracker.php @@ -175,7 +175,7 @@ private function consumeChunked(string $data): int while (!$this->complete) { if ($this->readingTrailers) { - // Пустые trailers заканчиваются одиночным CRLF; непустые — CRLFCRLF. + // Empty trailers end with one CRLF; non-empty trailers use CRLFCRLF. if (str_starts_with(substr($this->chunkBuffer, $offset), "\r\n")) { $offset += 2; $this->complete = true; @@ -212,19 +212,32 @@ private function consumeChunked(string $data): int if ($sizeToken === '' || !ctype_xdigit($sizeToken)) { throw new RuntimeException('Invalid chunk size in proxied HTTP message.'); } - $this->chunkRemaining = hexdec($sizeToken); + $size = hexdec($sizeToken); + if (!is_int($size) || $size < 0) { + throw new RuntimeException('Invalid chunk size in proxied HTTP message.'); + } + $this->chunkRemaining = $size; $offset = $lineEnd + 2; - if ($this->chunkRemaining === 0) { + if ($size === 0) { $this->readingTrailers = true; $this->chunkRemaining = null; } continue; } - if (strlen($this->chunkBuffer) - $offset < $this->chunkRemaining + 2) { + $available = strlen($this->chunkBuffer) - $offset; + if ($this->chunkRemaining > 0) { + $payloadBytes = min($available, $this->chunkRemaining); + $offset += $payloadBytes; + $this->chunkRemaining -= $payloadBytes; + if ($this->chunkRemaining > 0) { + break; + } + } + + if (strlen($this->chunkBuffer) - $offset < 2) { break; } - $offset += $this->chunkRemaining; if (substr($this->chunkBuffer, $offset, 2) !== "\r\n") { throw new RuntimeException('Invalid chunk terminator in proxied HTTP message.'); } @@ -236,14 +249,12 @@ private function consumeChunked(string $data): int $this->chunkBuffer = (string)substr($this->chunkBuffer, $offset); } - // Пока terminal zero-chunk не найден, вся новая порция однозначно - // принадлежит текущему body и может немедленно стримиться upstream. + // Stream body bytes immediately; keep only incomplete framing bytes. if (!$this->complete) { return strlen($data); } - // После terminal chunk возвращаем только часть новой порции до границы - // message. Остаток уже может быть началом следующего HTTP сообщения. + // Bytes after the terminal chunk may start the next HTTP message. $consumed = max(0, min(strlen($data), $offset - $before)); $this->chunkBuffer = ''; return $consumed; diff --git a/src/Protocols/Http.php b/src/Protocols/Http.php index d1f0ac6..ca26da8 100644 --- a/src/Protocols/Http.php +++ b/src/Protocols/Http.php @@ -220,6 +220,7 @@ public static function decode(string $buffer, ConnectionInterface $connection): $trailers = []; if (($connection->context->httpChunked ?? false) === true) { unset($connection->context->httpChunked); + unset($connection->context->httpChunkedParserState); [$buffer, $trailers] = static::decodeChunked($buffer); } @@ -415,80 +416,111 @@ protected static function validPort(string $port): bool protected static function inputChunked(string $buffer, TcpConnection $connection, int $headerLength): int { $connection->context->httpChunked = true; - $pos = $headerLength; $bufferLength = strlen($buffer); + $state = $connection->context->httpChunkedParserState ?? null; + if (!is_array($state) || ($state['headerLength'] ?? null) !== $headerLength) { + $state = [ + 'headerLength' => $headerLength, + 'mode' => 'size', + 'pos' => $headerLength, + 'scanOffset' => $headerLength, + 'chunkSize' => 0, + 'trailerCount' => 0, + 'trailerBytes' => 0, + ]; + } while (true) { - $lineEnd = strpos($buffer, "\r\n", $pos); - if ($lineEnd === false) { - return 0; + if ($state['mode'] === 'size') { + $lineEnd = strpos($buffer, "\r\n", $state['scanOffset']); + if ($lineEnd === false) { + $state['scanOffset'] = max($state['pos'], $bufferLength - 1); + $connection->context->httpChunkedParserState = $state; + return 0; + } + + $sizeLine = substr($buffer, $state['pos'], $lineEnd - $state['pos']); + $semicolon = strpos($sizeLine, ';'); + $hex = $semicolon === false ? $sizeLine : substr($sizeLine, 0, $semicolon); + if ($hex === '' || strlen($hex) > 16 || !ctype_xdigit($hex)) { + static::reject($connection, static::HTTP_400); + return 0; + } + + $size = hexdec($hex); + if (!is_int($size)) { + static::reject($connection, static::HTTP_400); + return 0; + } + $state['pos'] = $lineEnd + 2; + + if ($size === 0) { + $state['mode'] = 'trailers'; + $state['scanOffset'] = $state['pos']; + $state['trailerCount'] = 0; + $state['trailerBytes'] = 0; + continue; + } + + if ($size > $connection->maxPackageSize || $state['pos'] + $size + 2 > $connection->maxPackageSize) { + static::reject($connection, static::HTTP_413); + return 0; + } + $state['chunkSize'] = $size; + $state['mode'] = 'data'; + continue; } - $sizeLine = substr($buffer, $pos, $lineEnd - $pos); - $semicolon = strpos($sizeLine, ';'); - $hex = $semicolon === false ? $sizeLine : substr($sizeLine, 0, $semicolon); - if ($hex === '' || strlen($hex) > 16 || !ctype_xdigit($hex)) { - static::reject($connection, static::HTTP_400); - return 0; + if ($state['mode'] === 'data') { + $dataEnd = $state['pos'] + $state['chunkSize']; + if ($dataEnd + 2 > $bufferLength) { + $connection->context->httpChunkedParserState = $state; + return 0; + } + if (substr($buffer, $dataEnd, 2) !== "\r\n") { + static::reject($connection, static::HTTP_400); + return 0; + } + $state['pos'] = $dataEnd + 2; + $state['scanOffset'] = $state['pos']; + $state['mode'] = 'size'; + continue; } - $size = hexdec($hex); - if (!is_int($size)) { - static::reject($connection, static::HTTP_400); + $trailerEnd = strpos($buffer, "\r\n", $state['scanOffset']); + if ($trailerEnd === false) { + $state['scanOffset'] = max($state['pos'], $bufferLength - 1); + $connection->context->httpChunkedParserState = $state; return 0; } - $pos = $lineEnd + 2; - - if ($size === 0) { - // После zero chunk допускаются trailers, заканчивающиеся пустой строкой. - // Они входят в те же защитные limits, что и обычные headers. - $trailerCount = 0; - $trailerBytes = 0; - while (true) { - $trailerEnd = strpos($buffer, "\r\n", $pos); - if ($trailerEnd === false) { - return 0; - } - if ($trailerEnd === $pos) { - $total = $pos + 2; - if ($total > $connection->maxPackageSize) { - static::reject($connection, static::HTTP_413); - return 0; - } - return $total; - } - $trailerLine = substr($buffer, $pos, $trailerEnd - $pos); - $trailerCount++; - $trailerBytes += strlen($trailerLine) + 2; - if ($trailerCount > static::$maxHeaderCount || $trailerBytes > static::$maxHeaderLength) { - static::reject($connection, static::HTTP_431); - return 0; - } - if (!preg_match("/^[!#$%&'*+.^_`|~0-9A-Za-z-]+:[^\r\n]*$/D", $trailerLine)) { - static::reject($connection, static::HTTP_400); - return 0; - } - [$trailerName] = explode(':', $trailerLine, 2); - if (static::forbiddenTrailerField(strtolower($trailerName))) { - static::reject($connection, static::HTTP_400); - return 0; - } - $pos = $trailerEnd + 2; + if ($trailerEnd === $state['pos']) { + $total = $state['pos'] + 2; + if ($total > $connection->maxPackageSize) { + static::reject($connection, static::HTTP_413); + return 0; } + unset($connection->context->httpChunkedParserState); + return $total; } - if ($size > $connection->maxPackageSize || $pos + $size + 2 > $connection->maxPackageSize) { - static::reject($connection, static::HTTP_413); + $trailerLine = substr($buffer, $state['pos'], $trailerEnd - $state['pos']); + $state['trailerCount']++; + $state['trailerBytes'] += strlen($trailerLine) + 2; + if ($state['trailerCount'] > static::$maxHeaderCount || $state['trailerBytes'] > static::$maxHeaderLength) { + static::reject($connection, static::HTTP_431); return 0; } - if ($pos + $size + 2 > $bufferLength) { + if (!preg_match("/^[!#$%&'*+.^_`|~0-9A-Za-z-]+:[^\\r\\n]*$/D", $trailerLine)) { + static::reject($connection, static::HTTP_400); return 0; } - if (substr($buffer, $pos + $size, 2) !== "\r\n") { + [$trailerName] = explode(':', $trailerLine, 2); + if (static::forbiddenTrailerField(strtolower($trailerName))) { static::reject($connection, static::HTTP_400); return 0; } - $pos += $size + 2; + $state['pos'] = $trailerEnd + 2; + $state['scanOffset'] = $state['pos']; } } @@ -731,6 +763,7 @@ protected static function encodeFile(Response $response, TcpConnection $connecti protected static function reject(TcpConnection $connection, string $response): void { + unset($connection->context->httpChunkedParserState); $connection->close($response, true); } } diff --git a/src/Protocols/Http/Request.php b/src/Protocols/Http/Request.php index 75cedb5..042d7ab 100644 --- a/src/Protocols/Http/Request.php +++ b/src/Protocols/Http/Request.php @@ -46,6 +46,7 @@ class Request implements Stringable public const MAX_CACHE_SIZE = 256; public static int $maxFileUploads = 1024; + public static int $maxMultipartParts = 1024; /** * Список доверенных reverse proxy. Пока peer не входит в этот список, @@ -629,8 +630,16 @@ protected function parseMultipart(string $contentType): void $files = []; $uploadCount = 0; $fileToken = 0; + $maxParts = static::$maxMultipartParts; + if ($maxParts < 1) { + throw new \LengthException('Multipart part limit must be greater than zero.'); + } + $parts = explode('--' . $boundary, $this->rawBody(), $maxParts + 3); + if (count($parts) > $maxParts + 2) { + throw new \LengthException('Multipart request contains too many parts.'); + } - foreach (explode('--' . $boundary, $this->rawBody()) as $part) { + foreach ($parts as $part) { $part = ltrim($part, "\r\n"); if ($part === '' || $part === '--\r\n' || $part === '--' || !str_contains($part, "\r\n\r\n")) { continue; diff --git a/tests/gateway_smoke.php b/tests/gateway_smoke.php index 45b67c4..d63e958 100644 --- a/tests/gateway_smoke.php +++ b/tests/gateway_smoke.php @@ -92,6 +92,24 @@ function gatewayOk(bool $condition, string $message): void $consumed = $chunked->consume($tail); gatewayOk($consumed === strlen("ki\r\n0\r\n\r\n") && $chunked->isComplete(), 'chunked terminal boundary'); +$largeChunkSize = 1024 * 1024; +$largeChunk = HttpBodyTracker::forRequest(['transfer-encoding' => ['chunked']]); +$chunkBufferProperty = new ReflectionProperty(HttpBodyTracker::class, 'chunkBuffer'); +$chunkRemainingProperty = new ReflectionProperty(HttpBodyTracker::class, 'chunkRemaining'); +$fragmentSize = 64 * 1024; +$largeBodyRetained = $largeChunk->consume("100000\r\n" . str_repeat('a', $fragmentSize)) === 8 + $fragmentSize + && strlen($chunkBufferProperty->getValue($largeChunk)) <= 2; +for ($remaining = $largeChunkSize - $fragmentSize; $remaining > 0; $remaining -= $fragmentSize) { + $largeBodyRetained = $largeChunk->consume(str_repeat('a', $fragmentSize)) === $fragmentSize + && strlen($chunkBufferProperty->getValue($largeChunk)) <= 2 + && $chunkRemainingProperty->getValue($largeChunk) === $remaining - $fragmentSize + && $largeBodyRetained; +} +gatewayOk($largeBodyRetained, 'chunked gateway streams payload without retaining it'); +$largeChunkTail = "\r\n0\r\n\r\nNEXT"; +gatewayOk($largeChunk->consume($largeChunkTail) === strlen("\r\n0\r\n\r\n") + && $largeChunk->isComplete(), 'chunked gateway preserves boundary after streamed payload'); + $oversizedChunkLine = HttpBodyTracker::forRequest(['transfer-encoding' => ['chunked']]); $rejected = false; try { @@ -102,6 +120,15 @@ function gatewayOk(bool $condition, string $message): void } gatewayOk($rejected, 'oversized fragmented chunk-size line rejected'); +$oversizedChunkLength = HttpBodyTracker::forRequest(['transfer-encoding' => ['chunked']]); +$rejected = false; +try { + $oversizedChunkLength->consume("FFFFFFFFFFFFFFFF\r\n"); +} catch (RuntimeException) { + $rejected = true; +} +gatewayOk($rejected, 'chunk size exceeding integer range rejected'); + $oversizedTrailers = HttpBodyTracker::forRequest(['transfer-encoding' => ['chunked']]); $rejected = false; try { diff --git a/tests/smoke.php b/tests/smoke.php index ca06161..1cc7912 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -125,6 +125,38 @@ function connectionPair(): array ok($request->post('a') === '1' && $request->post('b') === '2', 'HTTP chunked body decode'); ok($request->trailer('x-trace') === 'done', 'HTTP chunked trailers'); +[$chunkedServer, $chunkedPeer] = connectionPair(); +$chunkedConnection = new TcpConnection(new Select(), $chunkedServer, '127.0.0.1:12345'); +$chunkedConnection->protocol = Http::class; +$incrementalHeader = "POST /incremental HTTP/1.1\r\nHost: example.test\r\nTransfer-Encoding: chunked\r\n\r\n"; +$incrementalBuffer = $incrementalHeader; +ok(Http::input($incrementalBuffer, $chunkedConnection) === 0, 'HTTP chunked parser waits for body'); +$incrementalBuffer .= "2\r\nx"; +ok(Http::input($incrementalBuffer, $chunkedConnection) === 0 + && $chunkedConnection->context->httpChunkedParserState['mode'] === 'data', + 'HTTP chunked parser retains partial payload state'); +$incrementalBuffer .= "y\r\n"; +ok(Http::input($incrementalBuffer, $chunkedConnection) === 0, 'HTTP chunked parser resumes partial payload'); +$cursorAdvanced = true; +for ($index = 0; $index < 64; $index++) { + $incrementalBuffer .= "1\r\nx\r\n"; + $cursorAdvanced = Http::input($incrementalBuffer, $chunkedConnection) === 0 + && $chunkedConnection->context->httpChunkedParserState['pos'] === strlen($incrementalBuffer) + && $cursorAdvanced; +} +ok($cursorAdvanced, 'HTTP chunked parser advances its cursor'); +$incrementalBuffer .= "0\r\nX-Trace: done\r"; +ok(Http::input($incrementalBuffer, $chunkedConnection) === 0, 'HTTP chunked parser waits for trailer terminator'); +$incrementalBuffer .= "\n\r\n"; +ok(Http::input($incrementalBuffer, $chunkedConnection) === strlen($incrementalBuffer), 'HTTP chunked parser completes incremental frame'); +$incrementalRequest = Http::decode($incrementalBuffer, $chunkedConnection); +ok($incrementalRequest->rawBody() === 'xy' . str_repeat('x', 64) + && $incrementalRequest->trailer('x-trace') === 'done', + 'HTTP chunked incremental body and trailers decode'); +$incrementalRequest->destroy(); +$chunkedConnection->destroy(); +fclose($chunkedPeer); + // Multipart parser keeps ordinary fields and upload metadata separate and owns // the temporary file lifecycle through Request::destroy(). $boundary = '----localzet-smoke-boundary'; @@ -152,6 +184,50 @@ function connectionPair(): array $multipartRequest->destroy(); ok(!is_file($uploadTmp), 'HTTP multipart temp file cleanup'); +$multipartLimit = Request::$maxMultipartParts; +$uploadDir = sys_get_temp_dir() . '/localzet-multipart-limit-' . bin2hex(random_bytes(4)); +mkdir($uploadDir); +$previousUploadDir = Http::uploadTmpDir(); +Http::uploadTmpDir($uploadDir); +Request::$maxMultipartParts = 2; +$limitedBoundary = '----localzet-limited-multipart'; +$limitedMultipartBody = "--{$limitedBoundary}\r\n" + . "Content-Disposition: form-data; name=\"first\"\r\n\r\none\r\n" + . "--{$limitedBoundary}\r\n" + . "Content-Disposition: form-data; name=\"upload\"; filename=\"blocked.txt\"\r\n\r\nfile\r\n" + . "--{$limitedBoundary}\r\n" + . "Content-Disposition: form-data; name=\"third\"\r\n\r\nthree\r\n" + . "--{$limitedBoundary}--\r\n"; +$limitedMultipartRaw = "POST /upload HTTP/1.1\r\nHost: example.test\r\n" + . "Content-Type: multipart/form-data; boundary={$limitedBoundary}\r\n" + . 'Content-Length: ' . strlen($limitedMultipartBody) . "\r\n\r\n" + . $limitedMultipartBody; +$limitedMultipart = new Request($limitedMultipartRaw); +$partLimitRejected = false; +try { + $limitedMultipart->post(); +} catch (LengthException) { + $partLimitRejected = true; +} +ok($partLimitRejected && (glob($uploadDir . '/localzet-upload-*') ?: []) === [], + 'HTTP multipart part limit rejects before creating upload files'); +$limitedMultipart->destroy(); +$atLimitBody = "--{$limitedBoundary}\r\n" + . "Content-Disposition: form-data; name=\"first\"\r\n\r\none\r\n" + . "--{$limitedBoundary}\r\n" + . "Content-Disposition: form-data; name=\"second\"\r\n\r\ntwo\r\n" + . "--{$limitedBoundary}--\r\n"; +$atLimitRaw = "POST /upload HTTP/1.1\r\nHost: example.test\r\n" + . "Content-Type: multipart/form-data; boundary={$limitedBoundary}\r\n" + . 'Content-Length: ' . strlen($atLimitBody) . "\r\n\r\n" + . $atLimitBody; +$atLimitRequest = new Request($atLimitRaw); +ok($atLimitRequest->post('second') === 'two', 'HTTP multipart request at configured part limit parses'); +$atLimitRequest->destroy(); +Request::$maxMultipartParts = $multipartLimit; +Http::uploadTmpDir($previousUploadDir); +@rmdir($uploadDir); + // Response: header injection не проходит. $response = new Response(200, ['X-Test' => "safe\r\nInjected: yes"], 'body'); $encoded = (string)$response; From aff91da556736f088973d321e1fb31b0b145d368 Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:28:12 +0000 Subject: [PATCH 2/3] style: format code with PHP CS Fixer This commit fixes the style issues introduced in f04f605 according to the output from PHP CS Fixer. Details: https://github.com/localzet/Server/pull/32 --- src/Protocols/Http/Request.php | 68 +++++++++++++++++++++-------- tests/gateway_smoke.php | 4 +- tests/smoke.php | 80 +++++++++++++++++++++++----------- 3 files changed, 109 insertions(+), 43 deletions(-) diff --git a/src/Protocols/Http/Request.php b/src/Protocols/Http/Request.php index 042d7ab..557de55 100644 --- a/src/Protocols/Http/Request.php +++ b/src/Protocols/Http/Request.php @@ -428,12 +428,24 @@ protected function setSidCookie(string $sessionName, string $sid, array $params) } $cookie = rawurlencode($sessionName) . '=' . rawurlencode($sid); - if (!empty($params['domain'])) $cookie .= '; Domain=' . str_replace(["\r", "\n"], '', (string)$params['domain']); - if (!empty($params['lifetime'])) $cookie .= '; Max-Age=' . max(0, (int)$params['lifetime']); - if (!empty($params['path'])) $cookie .= '; Path=' . str_replace(["\r", "\n"], '', (string)$params['path']); - if (!empty($params['samesite'])) $cookie .= '; SameSite=' . str_replace(["\r", "\n"], '', (string)$params['samesite']); - if (($params['secure'] ?? false) === true) $cookie .= '; Secure'; - if (($params['httponly'] ?? true) === true) $cookie .= '; HttpOnly'; + if (!empty($params['domain'])) { + $cookie .= '; Domain=' . str_replace(["\r", "\n"], '', (string)$params['domain']); + } + if (!empty($params['lifetime'])) { + $cookie .= '; Max-Age=' . max(0, (int)$params['lifetime']); + } + if (!empty($params['path'])) { + $cookie .= '; Path=' . str_replace(["\r", "\n"], '', (string)$params['path']); + } + if (!empty($params['samesite'])) { + $cookie .= '; SameSite=' . str_replace(["\r", "\n"], '', (string)$params['samesite']); + } + if (($params['secure'] ?? false) === true) { + $cookie .= '; Secure'; + } + if (($params['httponly'] ?? true) === true) { + $cookie .= '; HttpOnly'; + } $this->connection->headers['Set-Cookie'][] = $cookie; } @@ -484,15 +496,21 @@ public function getRequestIp(): ?string $forwarded = (string)$this->header('forwarded', ''); if ($forwarded !== '' && preg_match('/(?:^|[;,])\s*for=(?:"?\[?)([^\]";,]+)(?:\]?"?)/i', $forwarded, $match)) { $candidate = static::normalizeForwardedIp($match[1]); - if ($candidate !== null) return $candidate; + if ($candidate !== null) { + return $candidate; + } } foreach (['x-forwarded-for', 'x-real-ip', 'client-ip', 'x-client-ip'] as $header) { $value = $this->header($header); - if (!is_string($value) || $value === '') continue; + if (!is_string($value) || $value === '') { + continue; + } foreach (explode(',', $value) as $candidate) { $ip = static::normalizeForwardedIp($candidate); - if ($ip !== null) return $ip; + if ($ip !== null) { + return $ip; + } } } return $peer; @@ -577,7 +595,9 @@ protected function parseHeaders(): array $lines = explode("\r\n", $this->rawHead()); array_shift($lines); foreach ($lines as $line) { - if ($line === '' || !str_contains($line, ':')) continue; + if ($line === '' || !str_contains($line, ':')) { + continue; + } [$name, $value] = explode(':', $line, 2); $key = strtolower(trim($name)); $value = trim($value, " \t"); @@ -588,7 +608,9 @@ protected function parseHeaders(): array protected function parseQuery(string $query): array { - if ($query === '') return []; + if ($query === '') { + return []; + } parse_str($query, $result); return $this->sanitizeInput($result); } @@ -653,7 +675,9 @@ protected function parseMultipart(string $contentType): void $name = $match[1]; $filename = $match[2] ?? null; - if ($name === '') continue; + if ($name === '') { + continue; + } if ($filename === null || $filename === '') { $postPairs[] = rawurlencode($name) . '=' . rawurlencode($body); @@ -666,7 +690,9 @@ protected function parseMultipart(string $contentType): void $tmpDir = \localzet\Server\Protocols\Http::uploadTmpDir(); $tmp = tempnam($tmpDir, 'localzet-upload-'); if ($tmp === false || file_put_contents($tmp, $body, LOCK_EX) === false) { - if (is_string($tmp) && is_file($tmp)) @unlink($tmp); + if (is_string($tmp) && is_file($tmp)) { + @unlink($tmp); + } continue; } preg_match('/^Content-Type:\s*([^\r\n]+)/mi', $head, $typeMatch); @@ -718,7 +744,9 @@ protected static function isTrustedProxy(string $ip): bool protected static function ipMatchesCidr(string $ip, string $cidr): bool { - if (!str_contains($cidr, '/')) return false; + if (!str_contains($cidr, '/')) { + return false; + } [$network, $prefix] = explode('/', $cidr, 2); $ipBinary = @inet_pton($ip); $networkBinary = @inet_pton($network); @@ -727,11 +755,17 @@ protected static function ipMatchesCidr(string $ip, string $cidr): bool } $bits = (int)$prefix; $maxBits = strlen($ipBinary) * 8; - if ($bits < 0 || $bits > $maxBits) return false; + if ($bits < 0 || $bits > $maxBits) { + return false; + } $bytes = intdiv($bits, 8); $remaining = $bits % 8; - if ($bytes > 0 && substr($ipBinary, 0, $bytes) !== substr($networkBinary, 0, $bytes)) return false; - if ($remaining === 0) return true; + if ($bytes > 0 && substr($ipBinary, 0, $bytes) !== substr($networkBinary, 0, $bytes)) { + return false; + } + if ($remaining === 0) { + return true; + } $mask = (0xff << (8 - $remaining)) & 0xff; return (ord($ipBinary[$bytes]) & $mask) === (ord($networkBinary[$bytes]) & $mask); } diff --git a/tests/gateway_smoke.php b/tests/gateway_smoke.php index d63e958..5cc178b 100644 --- a/tests/gateway_smoke.php +++ b/tests/gateway_smoke.php @@ -19,7 +19,9 @@ $prefix = 'localzet\\Server\\'; if (str_starts_with($class, $prefix)) { $file = $root . '/src/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php'; - if (is_file($file)) require_once $file; + if (is_file($file)) { + require_once $file; + } } }); require_once $root . '/Helpers.php'; diff --git a/tests/smoke.php b/tests/smoke.php index 1cc7912..5b71ce4 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -20,7 +20,9 @@ if (str_starts_with($class, $prefix)) { $relative = substr($class, strlen($prefix)); $file = $root . '/src/' . str_replace('\\', '/', $relative) . '.php'; - if (is_file($file)) require_once $file; + if (is_file($file)) { + require_once $file; + } } }); require_once $root . '/Helpers.php'; @@ -75,7 +77,9 @@ function ok(bool $condition, string $message): void function connectionPair(): array { $pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); - if ($pair === false) throw new RuntimeException('stream_socket_pair failed'); + if ($pair === false) { + throw new RuntimeException('stream_socket_pair failed'); + } return $pair; } @@ -132,9 +136,11 @@ function connectionPair(): array $incrementalBuffer = $incrementalHeader; ok(Http::input($incrementalBuffer, $chunkedConnection) === 0, 'HTTP chunked parser waits for body'); $incrementalBuffer .= "2\r\nx"; -ok(Http::input($incrementalBuffer, $chunkedConnection) === 0 +ok( + Http::input($incrementalBuffer, $chunkedConnection) === 0 && $chunkedConnection->context->httpChunkedParserState['mode'] === 'data', - 'HTTP chunked parser retains partial payload state'); + 'HTTP chunked parser retains partial payload state' +); $incrementalBuffer .= "y\r\n"; ok(Http::input($incrementalBuffer, $chunkedConnection) === 0, 'HTTP chunked parser resumes partial payload'); $cursorAdvanced = true; @@ -150,9 +156,11 @@ function connectionPair(): array $incrementalBuffer .= "\n\r\n"; ok(Http::input($incrementalBuffer, $chunkedConnection) === strlen($incrementalBuffer), 'HTTP chunked parser completes incremental frame'); $incrementalRequest = Http::decode($incrementalBuffer, $chunkedConnection); -ok($incrementalRequest->rawBody() === 'xy' . str_repeat('x', 64) +ok( + $incrementalRequest->rawBody() === 'xy' . str_repeat('x', 64) && $incrementalRequest->trailer('x-trace') === 'done', - 'HTTP chunked incremental body and trailers decode'); + 'HTTP chunked incremental body and trailers decode' +); $incrementalRequest->destroy(); $chunkedConnection->destroy(); fclose($chunkedPeer); @@ -174,12 +182,14 @@ function connectionPair(): array . $multipartBody; $multipartRequest = new Request($multipartRaw); $upload = $multipartRequest->file('upload'); -ok($multipartRequest->post('title') === 'demo' +ok( + $multipartRequest->post('title') === 'demo' && is_array($upload) && ($upload['name'] ?? '') === 'note.txt' && is_file((string)($upload['tmp_name'] ?? '')) && file_get_contents((string)$upload['tmp_name']) === 'hello upload', - 'HTTP multipart field and upload parsing'); + 'HTTP multipart field and upload parsing' +); $uploadTmp = (string)$upload['tmp_name']; $multipartRequest->destroy(); ok(!is_file($uploadTmp), 'HTTP multipart temp file cleanup'); @@ -209,8 +219,10 @@ function connectionPair(): array } catch (LengthException) { $partLimitRejected = true; } -ok($partLimitRejected && (glob($uploadDir . '/localzet-upload-*') ?: []) === [], - 'HTTP multipart part limit rejects before creating upload files'); +ok( + $partLimitRejected && (glob($uploadDir . '/localzet-upload-*') ?: []) === [], + 'HTTP multipart part limit rejects before creating upload files' +); $limitedMultipart->destroy(); $atLimitBody = "--{$limitedBoundary}\r\n" . "Content-Disposition: form-data; name=\"first\"\r\n\r\none\r\n" @@ -240,12 +252,16 @@ function connectionPair(): array $compressedResponse = (new Response(200, ['Content-Type' => 'text/plain'], $compressible)) ->withCompressionForRequest($compressRequest, 128); $compressedBody = $compressedResponse->rawBody(); - ok($compressedResponse->getHeader('Content-Encoding') === 'gzip' + ok( + $compressedResponse->getHeader('Content-Encoding') === 'gzip' && is_string($compressedBody) && gzdecode($compressedBody) === $compressible, - 'HTTP opt-in gzip compression'); - ok(stripos((string)$compressedResponse->getHeader('Vary'), 'Accept-Encoding') !== false, - 'HTTP gzip Vary header'); + 'HTTP opt-in gzip compression' + ); + ok( + stripos((string)$compressedResponse->getHeader('Vary'), 'Accept-Encoding') !== false, + 'HTTP gzip Vary header' + ); $gzipRejected = new Request("GET /gzip HTTP/1.1\r\nHost: example.test\r\nAccept-Encoding: gzip;q=0, *;q=1\r\n\r\n"); $notCompressed = (new Response(200, [], $compressible))->withCompressionForRequest($gzipRejected, 128); @@ -254,15 +270,19 @@ function connectionPair(): array $headRequest = new Request("HEAD /gzip HTTP/1.1\r\nHost: example.test\r\nAccept-Encoding: gzip\r\n\r\n"); $headResponse = (new Response(200, [], $compressible))->withCompressionForRequest($headRequest, 128); $headEncoded = (string)$headResponse; - ok($headResponse->getHeader('Content-Encoding') === 'gzip' + ok( + $headResponse->getHeader('Content-Encoding') === 'gzip' && str_ends_with($headEncoded, "\r\n\r\n"), - 'HTTP gzip HEAD suppresses body'); + 'HTTP gzip HEAD suppresses body' + ); } ok((string)new Chunk('abc') === "3\r\nabc\r\n", 'HTTP chunk serialization'); $sse = (string)new ServerSentEvents("line1\nline2", 'update', '42', 1500); -ok(str_contains($sse, "event: update\n") && str_contains($sse, "data: line2\n") && str_ends_with($sse, "\n\n"), - 'Server-Sent Events serialization'); +ok( + str_contains($sse, "event: update\n") && str_contains($sse, "data: line2\n") && str_ends_with($sse, "\n\n"), + 'Server-Sent Events serialization' +); // HTTP framing: ambiguous / malformed requests must be rejected before application decode. @@ -372,7 +392,7 @@ function connectionPair(): array $idleLoop = new Select(); $idleConnection = new TcpConnection($idleLoop, $idleServer, '127.0.0.1:12345'); $idleConnection->setIdleTimeout(0.01); -$idleLoop->delay(0.04, static fn() => $idleLoop->stop()); +$idleLoop->delay(0.04, static fn () => $idleLoop->stop()); $idleLoop->run(); ok($idleConnection->getStatus() === TcpConnection::STATUS_CLOSED, 'TCP idle timeout'); fclose($idlePeer); @@ -408,7 +428,9 @@ function connectionPair(): array // Async UDP: application scheme должен кодироваться поверх UDP, а не становиться transport scheme. $udpServer = stream_socket_server('udp://127.0.0.1:0', $udpErrno, $udpError, STREAM_SERVER_BIND); -if ($udpServer === false) throw new RuntimeException("Unable to create UDP fixture: $udpError"); +if ($udpServer === false) { + throw new RuntimeException("Unable to create UDP fixture: $udpError"); +} $udpAddress = (string)stream_socket_get_name($udpServer, false); [, $udpPort] = explode(':', $udpAddress, 2); $udpClient = new AsyncUdpConnection('text://127.0.0.1:' . $udpPort, [], new Select()); @@ -475,7 +497,9 @@ function connectionPair(): array $payload = 'hello'; $mask = "\x01\x02\x03\x04"; $masked = $payload; -for ($i = 0; $i < strlen($masked); $i++) $masked[$i] = $masked[$i] ^ $mask[$i & 3]; +for ($i = 0; $i < strlen($masked); $i++) { + $masked[$i] = $masked[$i] ^ $mask[$i & 3]; +} $clientFrame = chr(0x81) . chr(0x80 | strlen($payload)) . $mask . $masked; ok(Websocket::input($clientFrame, $conn) === strlen($clientFrame), 'WebSocket masked frame length'); ok(Websocket::decode($clientFrame, $conn) === 'hello', 'WebSocket masked frame decode'); @@ -506,8 +530,10 @@ function connectionPair(): array Websocket::decode($partOne, $limitedWs); ok(Websocket::input($partTwo, $limitedWs) === strlen($partTwo), 'WebSocket limited continuation frame accepted'); Websocket::decode($partTwo, $limitedWs); -ok(in_array($limitedWs->getStatus(), [TcpConnection::STATUS_ENDING, TcpConnection::STATUS_CLOSING, TcpConnection::STATUS_CLOSED], true), - 'WebSocket aggregate fragmented message limit'); +ok( + in_array($limitedWs->getStatus(), [TcpConnection::STATUS_ENDING, TcpConnection::STATUS_CLOSING, TcpConnection::STATUS_CLOSED], true), + 'WebSocket aggregate fragmented message limit' +); $limitedWs->destroy(); fclose($limitedWsPeer); @@ -518,7 +544,9 @@ function connectionPair(): array $logBase = sys_get_temp_dir() . '/localzet-log-smoke-' . getmypid() . '.log'; @unlink($logBase); @unlink($logBase . '.lock'); -foreach (glob($logBase . '.*.*') ?: [] as $archive) @unlink($archive); +foreach (glob($logBase . '.*.*') ?: [] as $archive) { + @unlink($archive); +} Server::$logFile = $logBase; Server::$logFileMaxSize = 32; Server::$daemonize = true; @@ -531,7 +559,9 @@ function connectionPair(): array Server::$daemonize = $oldDaemonize; @unlink($logBase); @unlink($logBase . '.lock'); -foreach ($archives as $archive) @unlink($archive); +foreach ($archives as $archive) { + @unlink($archive); +} // Event loop timer. $fired = false; From 7328f705cd09f61ebfc79a45f99b438542b2419e Mon Sep 17 00:00:00 2001 From: Ivan Zorin Date: Sun, 22 Nov 2026 20:45:25 +0300 Subject: [PATCH 3/3] refactor: reduce HTTP parser complexity --- src/Gateway/HttpBodyTracker.php | 135 ++++++++++++--------- src/Protocols/Http.php | 208 +++++++++++++++++++------------- src/Protocols/Http/Request.php | 144 ++++++++++++++-------- tests/smoke.php | 35 ++++-- 4 files changed, 324 insertions(+), 198 deletions(-) diff --git a/src/Gateway/HttpBodyTracker.php b/src/Gateway/HttpBodyTracker.php index b32496e..dfdd93e 100644 --- a/src/Gateway/HttpBodyTracker.php +++ b/src/Gateway/HttpBodyTracker.php @@ -175,74 +175,24 @@ private function consumeChunked(string $data): int while (!$this->complete) { if ($this->readingTrailers) { - // Empty trailers end with one CRLF; non-empty trailers use CRLFCRLF. - if (str_starts_with(substr($this->chunkBuffer, $offset), "\r\n")) { - $offset += 2; - $this->complete = true; + $nextOffset = $this->consumeChunkedTrailers($offset); + if ($nextOffset === null) { break; } - $end = strpos($this->chunkBuffer, "\r\n\r\n", $offset); - if ($end === false) { - if (strlen($this->chunkBuffer) - $offset > self::MAX_TRAILER_BYTES) { - throw new RuntimeException('Trailers are too large in proxied HTTP message.'); - } - break; - } - if ($end + 4 - $offset > self::MAX_TRAILER_BYTES) { - throw new RuntimeException('Trailers are too large in proxied HTTP message.'); - } - $offset = $end + 4; - $this->complete = true; + $offset = $nextOffset; break; } if ($this->chunkRemaining === null) { - $lineEnd = strpos($this->chunkBuffer, "\r\n", $offset); - if ($lineEnd === false) { - if (strlen($this->chunkBuffer) - $offset > self::MAX_CHUNK_LINE_BYTES) { - throw new RuntimeException('Chunk size line is too large in proxied HTTP message.'); - } + if (!$this->readChunkedSize($offset)) { break; } - if ($lineEnd - $offset > self::MAX_CHUNK_LINE_BYTES) { - throw new RuntimeException('Chunk size line is too large in proxied HTTP message.'); - } - $line = substr($this->chunkBuffer, $offset, $lineEnd - $offset); - $sizeToken = trim(explode(';', $line, 2)[0]); - if ($sizeToken === '' || !ctype_xdigit($sizeToken)) { - throw new RuntimeException('Invalid chunk size in proxied HTTP message.'); - } - $size = hexdec($sizeToken); - if (!is_int($size) || $size < 0) { - throw new RuntimeException('Invalid chunk size in proxied HTTP message.'); - } - $this->chunkRemaining = $size; - $offset = $lineEnd + 2; - if ($size === 0) { - $this->readingTrailers = true; - $this->chunkRemaining = null; - } continue; } - $available = strlen($this->chunkBuffer) - $offset; - if ($this->chunkRemaining > 0) { - $payloadBytes = min($available, $this->chunkRemaining); - $offset += $payloadBytes; - $this->chunkRemaining -= $payloadBytes; - if ($this->chunkRemaining > 0) { - break; - } - } - - if (strlen($this->chunkBuffer) - $offset < 2) { + if (!$this->consumeChunkedPayload($offset)) { break; } - if (substr($this->chunkBuffer, $offset, 2) !== "\r\n") { - throw new RuntimeException('Invalid chunk terminator in proxied HTTP message.'); - } - $offset += 2; - $this->chunkRemaining = null; } if ($offset > 0) { @@ -259,4 +209,79 @@ private function consumeChunked(string $data): int $this->chunkBuffer = ''; return $consumed; } + + private function consumeChunkedTrailers(int $offset): ?int + { + if (str_starts_with(substr($this->chunkBuffer, $offset), "\r\n")) { + $this->complete = true; + return $offset + 2; + } + + $end = strpos($this->chunkBuffer, "\r\n\r\n", $offset); + if ($end === false) { + if (strlen($this->chunkBuffer) - $offset > self::MAX_TRAILER_BYTES) { + throw new RuntimeException('Trailers are too large in proxied HTTP message.'); + } + return null; + } + if ($end + 4 - $offset > self::MAX_TRAILER_BYTES) { + throw new RuntimeException('Trailers are too large in proxied HTTP message.'); + } + + $this->complete = true; + return $end + 4; + } + + private function readChunkedSize(int &$offset): bool + { + $lineEnd = strpos($this->chunkBuffer, "\r\n", $offset); + if ($lineEnd === false || $lineEnd - $offset > self::MAX_CHUNK_LINE_BYTES) { + if (strlen($this->chunkBuffer) - $offset > self::MAX_CHUNK_LINE_BYTES) { + throw new RuntimeException('Chunk size line is too large in proxied HTTP message.'); + } + return false; + } + + $line = substr($this->chunkBuffer, $offset, $lineEnd - $offset); + $sizeToken = trim(explode(';', $line, 2)[0]); + if ($sizeToken === '' || !ctype_xdigit($sizeToken)) { + throw new RuntimeException('Invalid chunk size in proxied HTTP message.'); + } + $size = hexdec($sizeToken); + if (!is_int($size) || $size < 0) { + throw new RuntimeException('Invalid chunk size in proxied HTTP message.'); + } + + $this->chunkRemaining = $size; + $offset = $lineEnd + 2; + if ($size === 0) { + $this->readingTrailers = true; + $this->chunkRemaining = null; + } + return true; + } + + private function consumeChunkedPayload(int &$offset): bool + { + $available = strlen($this->chunkBuffer) - $offset; + if ($this->chunkRemaining > 0) { + $payloadBytes = min($available, $this->chunkRemaining); + $offset += $payloadBytes; + $this->chunkRemaining -= $payloadBytes; + if ($this->chunkRemaining > 0) { + return false; + } + } + + if (strlen($this->chunkBuffer) - $offset < 2) { + return false; + } + if (substr($this->chunkBuffer, $offset, 2) !== "\r\n") { + throw new RuntimeException('Invalid chunk terminator in proxied HTTP message.'); + } + + $offset += 2; + $this->chunkRemaining = null; + return true; + } } diff --git a/src/Protocols/Http.php b/src/Protocols/Http.php index ca26da8..f79c6a9 100644 --- a/src/Protocols/Http.php +++ b/src/Protocols/Http.php @@ -419,109 +419,153 @@ protected static function inputChunked(string $buffer, TcpConnection $connection $bufferLength = strlen($buffer); $state = $connection->context->httpChunkedParserState ?? null; if (!is_array($state) || ($state['headerLength'] ?? null) !== $headerLength) { - $state = [ - 'headerLength' => $headerLength, - 'mode' => 'size', - 'pos' => $headerLength, - 'scanOffset' => $headerLength, - 'chunkSize' => 0, - 'trailerCount' => 0, - 'trailerBytes' => 0, - ]; + $state = static::newChunkedParserState($headerLength); } while (true) { if ($state['mode'] === 'size') { - $lineEnd = strpos($buffer, "\r\n", $state['scanOffset']); - if ($lineEnd === false) { - $state['scanOffset'] = max($state['pos'], $bufferLength - 1); - $connection->context->httpChunkedParserState = $state; + if (!static::readChunkedSizeLine($buffer, $connection, $state, $bufferLength)) { return 0; } - - $sizeLine = substr($buffer, $state['pos'], $lineEnd - $state['pos']); - $semicolon = strpos($sizeLine, ';'); - $hex = $semicolon === false ? $sizeLine : substr($sizeLine, 0, $semicolon); - if ($hex === '' || strlen($hex) > 16 || !ctype_xdigit($hex)) { - static::reject($connection, static::HTTP_400); - return 0; - } - - $size = hexdec($hex); - if (!is_int($size)) { - static::reject($connection, static::HTTP_400); - return 0; - } - $state['pos'] = $lineEnd + 2; - - if ($size === 0) { - $state['mode'] = 'trailers'; - $state['scanOffset'] = $state['pos']; - $state['trailerCount'] = 0; - $state['trailerBytes'] = 0; - continue; - } - - if ($size > $connection->maxPackageSize || $state['pos'] + $size + 2 > $connection->maxPackageSize) { - static::reject($connection, static::HTTP_413); - return 0; - } - $state['chunkSize'] = $size; - $state['mode'] = 'data'; continue; } if ($state['mode'] === 'data') { - $dataEnd = $state['pos'] + $state['chunkSize']; - if ($dataEnd + 2 > $bufferLength) { - $connection->context->httpChunkedParserState = $state; - return 0; - } - if (substr($buffer, $dataEnd, 2) !== "\r\n") { - static::reject($connection, static::HTTP_400); + if (!static::readChunkedData($buffer, $connection, $state, $bufferLength)) { return 0; } - $state['pos'] = $dataEnd + 2; - $state['scanOffset'] = $state['pos']; - $state['mode'] = 'size'; continue; } - $trailerEnd = strpos($buffer, "\r\n", $state['scanOffset']); - if ($trailerEnd === false) { - $state['scanOffset'] = max($state['pos'], $bufferLength - 1); - $connection->context->httpChunkedParserState = $state; + $completeLength = null; + if (!static::readChunkedTrailer($buffer, $connection, $state, $bufferLength, $completeLength)) { return 0; } - if ($trailerEnd === $state['pos']) { - $total = $state['pos'] + 2; - if ($total > $connection->maxPackageSize) { - static::reject($connection, static::HTTP_413); - return 0; - } - unset($connection->context->httpChunkedParserState); - return $total; + if ($completeLength !== null) { + return $completeLength; } + } + } - $trailerLine = substr($buffer, $state['pos'], $trailerEnd - $state['pos']); - $state['trailerCount']++; - $state['trailerBytes'] += strlen($trailerLine) + 2; - if ($state['trailerCount'] > static::$maxHeaderCount || $state['trailerBytes'] > static::$maxHeaderLength) { - static::reject($connection, static::HTTP_431); - return 0; - } - if (!preg_match("/^[!#$%&'*+.^_`|~0-9A-Za-z-]+:[^\\r\\n]*$/D", $trailerLine)) { - static::reject($connection, static::HTTP_400); - return 0; - } - [$trailerName] = explode(':', $trailerLine, 2); - if (static::forbiddenTrailerField(strtolower($trailerName))) { - static::reject($connection, static::HTTP_400); - return 0; - } - $state['pos'] = $trailerEnd + 2; + /** @return array{headerLength: int, mode: string, pos: int, scanOffset: int, chunkSize: int, trailerCount: int, trailerBytes: int} */ + private static function newChunkedParserState(int $headerLength): array + { + return [ + 'headerLength' => $headerLength, + 'mode' => 'size', + 'pos' => $headerLength, + 'scanOffset' => $headerLength, + 'chunkSize' => 0, + 'trailerCount' => 0, + 'trailerBytes' => 0, + ]; + } + + /** @param array $state */ + private static function readChunkedSizeLine(string $buffer, TcpConnection $connection, array &$state, int $bufferLength): bool + { + $lineEnd = strpos($buffer, "\r\n", $state['scanOffset']); + if ($lineEnd === false) { + $state['scanOffset'] = max($state['pos'], $bufferLength - 1); + $connection->context->httpChunkedParserState = $state; + return false; + } + + $sizeLine = substr($buffer, $state['pos'], $lineEnd - $state['pos']); + $semicolon = strpos($sizeLine, ';'); + $hex = $semicolon === false ? $sizeLine : substr($sizeLine, 0, $semicolon); + if ($hex === '' || strlen($hex) > 16 || !ctype_xdigit($hex)) { + static::reject($connection, static::HTTP_400); + return false; + } + + $size = hexdec($hex); + if (!is_int($size)) { + static::reject($connection, static::HTTP_400); + return false; + } + $state['pos'] = $lineEnd + 2; + + if ($size === 0) { + $state['mode'] = 'trailers'; $state['scanOffset'] = $state['pos']; + $state['trailerCount'] = 0; + $state['trailerBytes'] = 0; + return true; + } + + if ($size > $connection->maxPackageSize || $state['pos'] + $size + 2 > $connection->maxPackageSize) { + static::reject($connection, static::HTTP_413); + return false; + } + $state['chunkSize'] = $size; + $state['mode'] = 'data'; + return true; + } + + /** @param array $state */ + private static function readChunkedData(string $buffer, TcpConnection $connection, array &$state, int $bufferLength): bool + { + $dataEnd = $state['pos'] + $state['chunkSize']; + if ($dataEnd + 2 > $bufferLength) { + $connection->context->httpChunkedParserState = $state; + return false; + } + if (substr($buffer, $dataEnd, 2) !== "\r\n") { + static::reject($connection, static::HTTP_400); + return false; + } + + $state['pos'] = $dataEnd + 2; + $state['scanOffset'] = $state['pos']; + $state['mode'] = 'size'; + return true; + } + + /** @param array $state */ + private static function readChunkedTrailer( + string $buffer, + TcpConnection $connection, + array &$state, + int $bufferLength, + ?int &$completeLength + ): bool { + $trailerEnd = strpos($buffer, "\r\n", $state['scanOffset']); + if ($trailerEnd === false) { + $state['scanOffset'] = max($state['pos'], $bufferLength - 1); + $connection->context->httpChunkedParserState = $state; + return false; + } + if ($trailerEnd === $state['pos']) { + $completeLength = $state['pos'] + 2; + if ($completeLength > $connection->maxPackageSize) { + static::reject($connection, static::HTTP_413); + return false; + } + unset($connection->context->httpChunkedParserState); + return true; + } + + $trailerLine = substr($buffer, $state['pos'], $trailerEnd - $state['pos']); + $state['trailerCount']++; + $state['trailerBytes'] += strlen($trailerLine) + 2; + if ($state['trailerCount'] > static::$maxHeaderCount || $state['trailerBytes'] > static::$maxHeaderLength) { + static::reject($connection, static::HTTP_431); + return false; + } + if (!preg_match("/^[!#$%&'*+.^_`|~0-9A-Za-z-]+:[^\\r\\n]*$/D", $trailerLine)) { + static::reject($connection, static::HTTP_400); + return false; + } + + [$trailerName] = explode(':', $trailerLine, 2); + if (static::forbiddenTrailerField(strtolower($trailerName))) { + static::reject($connection, static::HTTP_400); + return false; } + $state['pos'] = $trailerEnd + 2; + $state['scanOffset'] = $state['pos']; + return true; } /** diff --git a/src/Protocols/Http/Request.php b/src/Protocols/Http/Request.php index 557de55..38be83f 100644 --- a/src/Protocols/Http/Request.php +++ b/src/Protocols/Http/Request.php @@ -639,19 +639,10 @@ protected function parsePost(): void protected function parseMultipart(string $contentType): void { - if (!preg_match('/boundary=(?:"([^"]+)"|([^;\s]+))/i', $contentType, $matches)) { - return; - } - $boundary = $matches[1] !== '' ? $matches[1] : ($matches[2] ?? ''); - if ($boundary === '' || strlen($boundary) > 200) { + $boundary = $this->multipartBoundary($contentType); + if ($boundary === null) { return; } - - $postPairs = []; - $filePairs = []; - $files = []; - $uploadCount = 0; - $fileToken = 0; $maxParts = static::$maxMultipartParts; if ($maxParts < 1) { throw new \LengthException('Multipart part limit must be greater than zero.'); @@ -661,52 +652,107 @@ protected function parseMultipart(string $contentType): void throw new \LengthException('Multipart request contains too many parts.'); } + $postPairs = []; + $filePairs = []; + $files = []; + $uploadCount = 0; + $fileToken = 0; foreach ($parts as $part) { - $part = ltrim($part, "\r\n"); - if ($part === '' || $part === '--\r\n' || $part === '--' || !str_contains($part, "\r\n\r\n")) { - continue; - } - // Boundary delimiter contributes CRLF before the next part; it is not file content. - $part = preg_replace('/\r\n$/D', '', $part, 1) ?? $part; - [$head, $body] = explode("\r\n\r\n", $part, 2); - if (!preg_match('/^Content-Disposition:\s*form-data;[^\r\n]*\bname="([^"]*)"(?:;\s*filename="([^"]*)")?/mi', $head, $match)) { - continue; + if (!$this->collectMultipartPart($part, $postPairs, $filePairs, $files, $uploadCount, $fileToken)) { + break; } + } - $name = $match[1]; - $filename = $match[2] ?? null; - if ($name === '') { - continue; - } + $this->storeMultipartFields($postPairs, $filePairs, $files); + } - if ($filename === null || $filename === '') { - $postPairs[] = rawurlencode($name) . '=' . rawurlencode($body); - continue; - } - if (++$uploadCount > static::$maxFileUploads) { - break; - } + private function multipartBoundary(string $contentType): ?string + { + if (!preg_match('/boundary=(?:"([^"]+)"|([^;\s]+))/i', $contentType, $matches)) { + return null; + } + $boundary = $matches[1] !== '' ? $matches[1] : ($matches[2] ?? ''); + return $boundary !== '' && strlen($boundary) <= 200 ? $boundary : null; + } + + /** @param list $postPairs @param list $filePairs @param array> $files */ + private function collectMultipartPart( + string $part, + array &$postPairs, + array &$filePairs, + array &$files, + int &$uploadCount, + int &$fileToken + ): bool { + $fields = $this->parseMultipartPart($part); + if ($fields === null) { + return true; + } + [$head, $body, $name, $filename] = $fields; + if ($filename === null || $filename === '') { + $postPairs[] = rawurlencode($name) . '=' . rawurlencode($body); + return true; + } + if (++$uploadCount > static::$maxFileUploads) { + return false; + } - $tmpDir = \localzet\Server\Protocols\Http::uploadTmpDir(); - $tmp = tempnam($tmpDir, 'localzet-upload-'); - if ($tmp === false || file_put_contents($tmp, $body, LOCK_EX) === false) { - if (is_string($tmp) && is_file($tmp)) { - @unlink($tmp); - } - continue; + $upload = $this->createMultipartUpload($head, $body, $filename); + if ($upload === null) { + return true; + } + + $token = (string)++$fileToken; + $files[$token] = $upload; + $filePairs[] = rawurlencode($name) . '=' . rawurlencode($token); + return true; + } + + /** @return array{string, string, string, ?string}|null */ + private function parseMultipartPart(string $part): ?array + { + $part = ltrim($part, "\r\n"); + if ($part === '' || $part === "--\r\n" || $part === '--' || !str_contains($part, "\r\n\r\n")) { + return null; + } + // Boundary delimiter contributes CRLF before the next part; it is not file content. + $part = preg_replace('/\r\n$/D', '', $part, 1) ?? $part; + [$head, $body] = explode("\r\n\r\n", $part, 2); + if (!preg_match('/^Content-Disposition:\s*form-data;[^\r\n]*\bname="([^"]*)"(?:;\s*filename="([^"]*)")?/mi', $head, $match)) { + return null; + } + + $name = $match[1]; + if ($name === '') { + return null; + } + return [$head, $body, $name, $match[2] ?? null]; + } + + /** @return array|null */ + private function createMultipartUpload(string $head, string $body, string $filename): ?array + { + $tmp = tempnam(\localzet\Server\Protocols\Http::uploadTmpDir(), 'localzet-upload-'); + if ($tmp === false || file_put_contents($tmp, $body, LOCK_EX) === false) { + if (is_string($tmp) && is_file($tmp)) { + unlink($tmp); } - preg_match('/^Content-Type:\s*([^\r\n]+)/mi', $head, $typeMatch); - $token = (string)++$fileToken; - $files[$token] = [ - 'name' => basename(str_replace('\\', '/', $filename)), - 'tmp_name' => $tmp, - 'size' => strlen($body), - 'error' => UPLOAD_ERR_OK, - 'type' => trim($typeMatch[1] ?? 'application/octet-stream'), - ]; - $filePairs[] = rawurlencode($name) . '=' . rawurlencode($token); + return null; } + preg_match('/^Content-Type:\s*([^\r\n]+)/mi', $head, $typeMatch); + return [ + 'name' => basename(str_replace('\\', '/', $filename)), + 'tmp_name' => $tmp, + 'size' => strlen($body), + 'error' => UPLOAD_ERR_OK, + 'type' => trim($typeMatch[1] ?? 'application/octet-stream'), + ]; + } + + /** @param list $postPairs @param list $filePairs @param array> $files */ + private function storeMultipartFields(array $postPairs, array $filePairs, array $files): void + { if ($postPairs) { parse_str(implode('&', $postPairs), $post); $this->data['post'] = $this->sanitizeInput($post); diff --git a/tests/smoke.php b/tests/smoke.php index 5b71ce4..861e2e9 100644 --- a/tests/smoke.php +++ b/tests/smoke.php @@ -74,6 +74,17 @@ function ok(bool $condition, string $message): void fwrite(STDOUT, "OK: {$message}\n"); } +function removeSmokeFixture(string $path): void +{ + if (is_dir($path) && !is_link($path)) { + rmdir($path); + return; + } + if (file_exists($path) || is_link($path)) { + unlink($path); + } +} + function connectionPair(): array { $pair = stream_socket_pair(STREAM_PF_UNIX, STREAM_SOCK_STREAM, STREAM_IPPROTO_IP); @@ -95,8 +106,8 @@ function connectionPair(): array PidFileSmokeServer::writePidForTest($pidFixture, 12345); ok(file_get_contents($pidFixture . '.target') === (string)getmypid(), 'atomic PID write does not follow symlink target'); ok(!is_link($pidFixture) && trim((string)file_get_contents($pidFixture)) === '12345', 'atomic PID write replaces symlink itself'); - @unlink($pidFixture); - @unlink($pidFixture . '.target'); + removeSmokeFixture($pidFixture); + removeSmokeFixture($pidFixture . '.target'); } else { ok(true, 'PID symlink regression skipped on unsupported filesystem'); } @@ -196,7 +207,7 @@ function connectionPair(): array $multipartLimit = Request::$maxMultipartParts; $uploadDir = sys_get_temp_dir() . '/localzet-multipart-limit-' . bin2hex(random_bytes(4)); -mkdir($uploadDir); +mkdir($uploadDir, 0700); $previousUploadDir = Http::uploadTmpDir(); Http::uploadTmpDir($uploadDir); Request::$maxMultipartParts = 2; @@ -238,7 +249,7 @@ function connectionPair(): array $atLimitRequest->destroy(); Request::$maxMultipartParts = $multipartLimit; Http::uploadTmpDir($previousUploadDir); -@rmdir($uploadDir); +removeSmokeFixture($uploadDir); // Response: header injection не проходит. $response = new Response(200, ['X-Test' => "safe\r\nInjected: yes"], 'body'); @@ -330,7 +341,7 @@ function connectionPair(): array $reloaded->save(); $empty = new Session($sessionId); ok($empty->all() === [], 'HTTP session flush'); -@rmdir($sessionDir); +removeSmokeFixture($sessionDir); // HTTP/1.1 chunked response must never emit conflicting Content-Length. $chunkedHead = (string)(new Response(200))->withChunkedTransfer(); @@ -370,7 +381,7 @@ function connectionPair(): array $unmodifiedRequest = new Request("GET /asset HTTP/1.1\r\nHost: example.test\r\nIf-Unmodified-Since: {$oldDate}\r\n\r\n"); $unmodifiedEncoded = Http::encode((new Response())->withFileForRequest($unmodifiedRequest, $fileFixture), $conn); ok(str_starts_with($unmodifiedEncoded, 'HTTP/1.1 412'), 'HTTP If-Unmodified-Since precondition'); -@unlink($fileFixture); +removeSmokeFixture($fileFixture); // Expect: 100-continue отправляется один раз до получения body. [$continueServer, $continuePeer] = connectionPair(); @@ -542,10 +553,10 @@ function connectionPair(): array $oldLogMax = Server::$logFileMaxSize; $oldDaemonize = Server::$daemonize; $logBase = sys_get_temp_dir() . '/localzet-log-smoke-' . getmypid() . '.log'; -@unlink($logBase); -@unlink($logBase . '.lock'); +removeSmokeFixture($logBase); +removeSmokeFixture($logBase . '.lock'); foreach (glob($logBase . '.*.*') ?: [] as $archive) { - @unlink($archive); + removeSmokeFixture($archive); } Server::$logFile = $logBase; Server::$logFileMaxSize = 32; @@ -557,10 +568,10 @@ function connectionPair(): array Server::$logFile = $oldLogFile; Server::$logFileMaxSize = $oldLogMax; Server::$daemonize = $oldDaemonize; -@unlink($logBase); -@unlink($logBase . '.lock'); +removeSmokeFixture($logBase); +removeSmokeFixture($logBase . '.lock'); foreach ($archives as $archive) { - @unlink($archive); + removeSmokeFixture($archive); } // Event loop timer.