Skip to content

Commit 439437b

Browse files
committed
fix(http): prevent premature connection closure and ensure HTTP/1.1 compliance
1 parent fcb0f5e commit 439437b

3 files changed

Lines changed: 16 additions & 18 deletions

File tree

src/Net/Http/Server/Connection.php

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -182,22 +182,22 @@ public function start(Server $server): void
182182
try {
183183
$content = $this->stream->read(8192);
184184
if ($content === '' && $this->stream->eof()) {
185-
$this->disconnect();
186-
return;
185+
throw new ConnectionException();
187186
}
188187

189188
foreach ($this->processData($content) as $reqInfo) {
190189
$this->onRequest($reqInfo);
191190
}
192-
} catch (ConnectionException) {
193-
$this->disconnect();
194191
} catch (Throwable $err) {
195-
Stdin::println($err->getMessage());
196-
$this->disconnect();
192+
if (!$err instanceof ConnectionException) {
193+
Stdin::println($err->getMessage());
194+
}
195+
196+
$this->stream->close();
197197
}
198198
});
199199
} catch (ConnectionException) {
200-
$this->disconnect();
200+
$this->stream->close();
201201
}
202202
}
203203

@@ -209,14 +209,6 @@ public function isAlive(): bool
209209
return !$this->stream->isClosed();
210210
}
211211

212-
/**
213-
* @return void
214-
*/
215-
public function disconnect(): void
216-
{
217-
$this->stream->close();
218-
}
219-
220212
/**
221213
* 处理 HTTP 请求
222214
* @param array $reqInfo 请求信息
@@ -261,8 +253,6 @@ private function onRequest(array $reqInfo): void
261253
} catch (Throwable $exception) {
262254
$req->respond($exception->getMessage(), [], 500);
263255
$this->reset();
264-
} finally {
265-
($keepAlive || $isWebSocketUpgrade) || $this->disconnect();
266256
}
267257
}
268258

src/Net/Http/Server/Response.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
use function array_key_exists;
3131
use function is_int;
3232
use function is_file;
33+
use function strtolower;
3334

3435
/**
3536
* response entity
@@ -152,6 +153,13 @@ public function __invoke(Stream $stream): void
152153
throw new ConnectionException('The response content is illegal.');
153154
}
154155
}
156+
157+
$connectionHeader = $this->headers['Connection'] ?? '';
158+
$connectionValue = strtolower($connectionHeader);
159+
160+
if ($connectionValue === 'close') {
161+
$stream->close();
162+
}
155163
}
156164

157165
/**

src/Stream.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -690,7 +690,7 @@ public static function connect(string $address, int|float $timeout = 0, mixed $c
690690
{
691691
$address = str_replace('ssl://', 'tcp://', $address);
692692

693-
// 使用@抑制警告然后检查错误信息
693+
// 使用@抑制警告, 然后检查错误信息
694694
$connection = @stream_socket_client(
695695
$address,
696696
$errCode,

0 commit comments

Comments
 (0)