Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down
9 changes: 7 additions & 2 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

## Требования

Expand Down Expand Up @@ -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

Expand Down
128 changes: 82 additions & 46 deletions src/Gateway/HttpBodyTracker.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,77 +175,113 @@ private function consumeChunked(string $data): int

while (!$this->complete) {
if ($this->readingTrailers) {
// Пустые trailers заканчиваются одиночным CRLF; непустые — 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.');
}
$this->chunkRemaining = hexdec($sizeToken);
$offset = $lineEnd + 2;
if ($this->chunkRemaining === 0) {
$this->readingTrailers = true;
$this->chunkRemaining = null;
}
continue;
}

if (strlen($this->chunkBuffer) - $offset < $this->chunkRemaining + 2) {
if (!$this->consumeChunkedPayload($offset)) {
break;
}
$offset += $this->chunkRemaining;
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) {
$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;
}

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;
}
}
Loading