Skip to content

Commit 58dafe3

Browse files
author
何平
committed
适配http2
1 parent fa096b7 commit 58dafe3

File tree

4 files changed

+70
-65
lines changed

4 files changed

+70
-65
lines changed

cloud-admin/Http2/Parser/Http2Driver.php

+38-37
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ public function send(int $id, Response $response, Request $request)
149149
return;
150150
}
151151
$this->sendBody($id, $response, $request);
152-
if (! empty($pushStream)) {
152+
if (!empty($pushStream)) {
153153
foreach ($pushStream as $push) {// 发送推送帧
154154
$this->send(...$push);
155155
}
@@ -168,7 +168,7 @@ public function send(int $id, Response $response, Request $request)
168168

169169
public function sendBody(int $id, Response $response, Request $request): void
170170
{
171-
if (! in_array($request->path(), $this->streamUrl)) {
171+
if (!in_array($request->path(), $this->streamUrl)) {
172172
if (is_callable($this->onWriteBody)) {
173173
// 服务端流模式在此处不停的发送帧
174174
$response->http2Driver = $this;
@@ -177,10 +177,10 @@ public function sendBody(int $id, Response $response, Request $request): void
177177
}
178178
}
179179
$body = $response->getBody();
180-
if (strlen((string) $body)) {
180+
if (strlen((string)$body)) {
181181
$this->writeData($body, $id);
182182
}
183-
if (! isset($this->streams[$id])) {
183+
if (!isset($this->streams[$id])) {
184184
return;
185185
}
186186
$trailers = $response->getTrailers();
@@ -249,7 +249,7 @@ public function sendHeader(int $id, Response $response, Request $request): void
249249
*/
250250
public function writeData(string $data, int $id): void
251251
{
252-
if (! isset($this->streams[$id])) {
252+
if (!isset($this->streams[$id])) {
253253
var_dump('The stream was closed');
254254
return;
255255
}
@@ -264,7 +264,7 @@ public function writeFrame(string $data, int $type, int $flags, int $stream = 0)
264264

265265
public function handlePing(string $data): void
266266
{
267-
if (! $this->pinged) { // 没有ping过就更新
267+
if (!$this->pinged) { // 没有ping过就更新
268268
$this->http2Connection->updateExpirationTime(
269269
max($this->http2Connection->getExpirationTime(), time() + 5)
270270
);
@@ -282,7 +282,7 @@ public function handleStreamWindowIncrement(int $streamId, int $windowSize): voi
282282
if ($streamId > $this->remoteStreamId) {
283283
throw new Http2ConnectionException('Stream ID does not exist', Http2Parser::PROTOCOL_ERROR);
284284
}
285-
if (! isset($this->streams[$streamId])) {
285+
if (!isset($this->streams[$streamId])) {
286286
return;
287287
}
288288
$stream = $this->streams[$streamId];
@@ -329,7 +329,7 @@ public function handleConnectionWindowIncrement(int $windowSize): void
329329
public function handleHeaders(int $streamId, array $pseudo, array $headers, bool $ended): void
330330
{
331331
foreach ($pseudo as $name => $value) {
332-
if (! isset(Http2Parser::KNOWN_REQUEST_PSEUDO_HEADERS[$name])) {
332+
if (!isset(Http2Parser::KNOWN_REQUEST_PSEUDO_HEADERS[$name])) {
333333
throw new Http2StreamException('Invalid pseudo header', $streamId, Http2Parser::PROTOCOL_ERROR);
334334
}
335335
}
@@ -339,7 +339,7 @@ public function handleHeaders(int $streamId, array $pseudo, array $headers, bool
339339
throw new Http2StreamException('Stream remote closed', $streamId, Http2Parser::STREAM_CLOSED);
340340
}
341341
} else {
342-
if (! ($streamId & 1) || $this->remainingStreams-- <= 0 || $streamId <= $this->remoteStreamId) {
342+
if (!($streamId & 1) || $this->remainingStreams-- <= 0 || $streamId <= $this->remoteStreamId) {
343343
throw new Http2ConnectionException("Invalid stream ID {$streamId}", Http2Parser::PROTOCOL_ERROR);
344344
}
345345
$stream = $this->streams[$streamId] = new Http2Stream(Options::getBodySizeLimit(), $this->initialWindowSize);
@@ -350,7 +350,7 @@ public function handleHeaders(int $streamId, array $pseudo, array $headers, bool
350350
throw new Http2StreamException('Stream already reserved', $streamId, Http2Parser::PROTOCOL_ERROR);
351351
}
352352
$stream->state |= Http2Stream::RESERVED;
353-
if (! isset($pseudo[':method'], $pseudo[':path'], $pseudo[':scheme'], $pseudo[':authority'])
353+
if (!isset($pseudo[':method'], $pseudo[':path'], $pseudo[':scheme'], $pseudo[':authority'])
354354
|| isset($headers['connection'])
355355
|| $pseudo[':path'] === ''
356356
|| (isset($headers['te']) && implode('', $headers['te']) !== 'trailers')
@@ -362,17 +362,17 @@ public function handleHeaders(int $streamId, array $pseudo, array $headers, bool
362362
$scheme = $pseudo[':scheme'];
363363
$host = $pseudo[':authority'];
364364
$query = null;
365-
if (! preg_match('#^([A-Z\\d\\.\\-]+|\\[[\\d:]+\\])(?::([1-9]\\d*))?$#i', (string) $host, $matches)) {
365+
if (!preg_match('#^([A-Z\\d\\.\\-]+|\\[[\\d:]+\\])(?::([1-9]\\d*))?$#i', (string)$host, $matches)) {
366366
throw new Http2StreamException('Invalid authority (host) name', $streamId, Http2Parser::PROTOCOL_ERROR);
367367
}
368368
$host = $matches[1];
369-
$port = isset($matches[2]) ? (int) $matches[2] : $this->http2Connect->getPort();
370-
if ($position = strpos((string) $target, '#')) {
371-
$target = substr((string) $target, 0, $position);
369+
$port = isset($matches[2]) ? (int)$matches[2] : $this->http2Connection->getPort();
370+
if ($position = strpos((string)$target, '#')) {
371+
$target = substr((string)$target, 0, $position);
372372
}
373-
if ($position = strpos((string) $target, '?')) {
374-
$query = substr((string) $target, $position + 1);
375-
$target = substr((string) $target, 0, $position);
373+
if ($position = strpos((string)$target, '?')) {
374+
$query = substr((string)$target, $position + 1);
375+
$target = substr((string)$target, 0, $position);
376376
}
377377
$headers = array_merge($headers, ['scheme' => $scheme, 'host' => $host, 'port' => $port, 'path' => $target, 'query' => $query, 'method' => $method]);
378378
$this->pinged = 0;
@@ -392,17 +392,17 @@ public function handleHeaders(int $streamId, array $pseudo, array $headers, bool
392392
throw new Http2StreamException('Received multiple content-length headers', $streamId, Http2Parser::PROTOCOL_ERROR);
393393
}
394394
$contentLength = $headers['content-length'][0];
395-
if (! preg_match('/^0|[1-9][0-9]*$/', (string) $contentLength)) {
395+
if (!preg_match('/^0|[1-9][0-9]*$/', (string)$contentLength)) {
396396
throw new Http2StreamException('Invalid content-length header value', $streamId, Http2Parser::PROTOCOL_ERROR);
397397
}
398-
$stream->expectedLength = (int) $contentLength;
398+
$stream->expectedLength = (int)$contentLength;
399399
}
400400
$request = new Request($streamId, $this->http2Connection, $headers);
401401
$this->streamIdRequestMap[$streamId] = $request;
402402
// 如果是客户端流模式,这里应该给前端返回头响应
403403
if (in_array($request->path(), $this->streamUrl)) {
404404
if (is_callable($this->onRequest)) {
405-
$response = ($this->onRequest)($request);
405+
$response = ($this->onRequest)($request,$this->http2Connection);
406406
} else {
407407
$response = new Response(200, ['content-type' => 'text/html'], '');
408408
}
@@ -425,7 +425,7 @@ public function handleData(int $streamId, string $data): void
425425
if ($stream->state & Http2Stream::REMOTE_CLOSED) {
426426
throw new Http2StreamException('Stream remote closed', $streamId, Http2Parser::PROTOCOL_ERROR);
427427
}
428-
if (! $length) {
428+
if (!$length) {
429429
return;
430430
}
431431
$this->serverWindow -= $length;
@@ -457,7 +457,7 @@ public function handleData(int $streamId, string $data): void
457457
$request->appendData($data);
458458
}
459459
if ($stream->serverWindow <= self::MINIMUM_WINDOW) {
460-
if (! isset($this->streams[$streamId])) {
460+
if (!isset($this->streams[$streamId])) {
461461
return;
462462
}
463463
$stream = $this->streams[$streamId];
@@ -478,7 +478,7 @@ public function handleData(int $streamId, string $data): void
478478
*/
479479
public function handleStreamEnd(int $streamId): void
480480
{
481-
if (! isset($this->streams[$streamId])) {
481+
if (!isset($this->streams[$streamId])) {
482482
return;
483483
}
484484
$stream = $this->streams[$streamId];
@@ -488,16 +488,16 @@ public function handleStreamEnd(int $streamId): void
488488
}
489489
/** @var Request $request */
490490
$request = $this->streamIdRequestMap[$streamId];
491-
if (! in_array($request->getMethod(), Options::getAllowedMethods())) {
491+
if (!in_array($request->getMethod(), Options::getAllowedMethods())) {
492492
$response = new Response(405); // METHOD_NOT_ALLOWED
493493
} else {
494-
$response = $this->streamIdResponseMap[$streamId];
495-
if (! $response instanceof Response) {
494+
$response = $this->streamIdResponseMap[$streamId] ?? null;
495+
if (!$response instanceof Response) {
496496
if (is_callable($this->onRequest)) {
497-
$response = ($this->onRequest)($request);
497+
$response = ($this->onRequest)($request,$this->http2Connection);
498498
}
499499
}
500-
if (! $response instanceof Response) {
500+
if (!$response instanceof Response) {
501501
$response = new Response(404, ['content-type' => 'text/html'], '');
502502
}
503503
}
@@ -529,7 +529,7 @@ public function handlePushPromise(int $streamId, int $pushId, array $pseudo, arr
529529
*/
530530
public function handlePriority(int $streamId, int $parentId, int $weight): void
531531
{
532-
if (! isset($this->streams[$streamId])) {// 为将来的流设置优先级
532+
if (!isset($this->streams[$streamId])) {// 为将来的流设置优先级
533533
// if ($streamId === 0 || !($streamId & 1) || $this->remainingStreams-- <= 0) {
534534
if ($streamId === 0 || $this->remainingStreams-- <= 0) { // chrome居然发送了偶数帧过来
535535
throw new Http2ConnectionException("Invalid stream ID {$streamId}", Http2Parser::PROTOCOL_ERROR);
@@ -625,6 +625,7 @@ public function handleConnectionException(Http2ConnectionException $exception):
625625
}
626626

627627
// http1.1升级h2c
628+
628629
/**
629630
* @throws Http2StreamException
630631
*/
@@ -651,7 +652,7 @@ private function sendPushPromise(Request $request, int $streamId, array $push):
651652
$id = $this->localStreamId += 2;
652653
// $this->remoteStreamId = \max($id, $this->remoteStreamId);
653654
$headers = array_merge(['scheme' => 'https', 'host' => '', 'port' => 443, 'path' => '/', 'query' => '', 'method' => 'GET'], $push['uri'], $mergedHeaders);
654-
$request = new Request($this->http2Connection, $this->http2Connection, $headers);
655+
$request = new Request($streamId, $this->http2Connection, $headers);
655656
$this->streams[$id] = new Http2Stream(0, $this->initialWindowSize, Http2Stream::RESERVED | Http2Stream::REMOTE_CLOSED);
656657
$this->streamIdRequestMap[$id] = $request;
657658
foreach ($mergedHeaders as $k => $v) {
@@ -680,9 +681,9 @@ private function sendPushPromise(Request $request, int $streamId, array $push):
680681
}
681682
$response = null;
682683
if (is_callable($this->onRequest)) {
683-
$response = ($this->onRequest)($request);
684+
$response = ($this->onRequest)($request,$this->http2Connection);
684685
}
685-
if (! $response instanceof Response) {
686+
if (!$response instanceof Response) {
686687
$response = new Response(404, ['content-type' => 'text/html'], '');
687688
}
688689
$this->streams[$id]->state |= Http2Stream::LOCAL_CLOSED;
@@ -703,7 +704,7 @@ private function sendBufferedData(): void
703704
if ($this->clientWindow <= 0) {
704705
return;
705706
}
706-
if (! strlen($stream->buffer) || $stream->clientWindow <= 0) {
707+
if (!strlen($stream->buffer) || $stream->clientWindow <= 0) {
707708
continue;
708709
}
709710
$this->writeBufferedData($id);
@@ -752,9 +753,9 @@ private function encodeHeaders(array $headers): string
752753
{
753754
$input = [];
754755
foreach ($headers as $field => $values) {
755-
$values = (array) $values;
756+
$values = (array)$values;
756757
foreach ($values as $value) {
757-
$input[] = [(string) $field, (string) $value];
758+
$input[] = [(string)$field, (string)$value];
758759
}
759760
}
760761
return $this->hPack->encode($input);
@@ -765,7 +766,7 @@ private function shutdown(?int $lastId = null, ?Throwable $reason = null): void
765766
$code = $reason ? $reason->getCode() : Http2Parser::GRACEFUL_SHUTDOWN;
766767
$lastId ??= $id ?? 0;
767768
$this->writeFrame(pack('NN', $lastId, $code), Http2Parser::GOAWAY, Http2Parser::NO_FLAG);
768-
if (! empty($this->streams)) {
769+
if (!empty($this->streams)) {
769770
if (empty($reason)) {
770771
$exception = new ClientException('', 0, $reason);
771772
} else {
@@ -783,7 +784,7 @@ private function shutdown(?int $lastId = null, ?Throwable $reason = null): void
783784
*/
784785
private function releaseStream(int $id, ClientException $exception = null): void
785786
{
786-
if (! isset($this->streams[$id])) {
787+
if (!isset($this->streams[$id])) {
787788
return;
788789
}
789790
unset($this->streams[$id]);

cloud-admin/Http2/Parser/Request.php

+13-11
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212
namespace CloudAdmin\Http2\Parser;
1313

14-
use Swow\Psr7\Server\ServerConnection;
1514
use function explode;
1615
use function file_put_contents;
1716
use function is_array;
@@ -78,8 +77,11 @@ public function get($name = null, $default = null): array
7877
*/
7978
public function post($name = null, $default = null): mixed
8079
{
81-
if (! isset($this->data['post'])) {
82-
$this->parsePost();
80+
if (!isset($this->data['post'])) {
81+
try {
82+
$this->parsePost();
83+
} catch (\JsonException $e) {
84+
}
8385
}
8486
if ($name === null) {
8587
return $this->data['post'] ?? [];
@@ -93,7 +95,7 @@ public function post($name = null, $default = null): mixed
9395
*/
9496
public function file($name = null): mixed
9597
{
96-
if (! isset($this->data['files'])) {
98+
if (!isset($this->data['files'])) {
9799
$this->parsePost();
98100
}
99101
if ($name === null) {
@@ -104,7 +106,7 @@ public function file($name = null): mixed
104106

105107
public function ip(): string
106108
{
107-
return $this->client->getPeerAddress();
109+
return $this->client->getLocalAddress();
108110
}
109111

110112
public function host(): string
@@ -155,7 +157,7 @@ public function header(string $name = null, mixed $default = null): null|array|s
155157

156158
protected function parsePost(): void
157159
{
158-
if (! $this->rawBody) {
160+
if (!$this->rawBody) {
159161
return;
160162
}
161163
$this->data['post'] = $this->data['files'] = [];
@@ -166,7 +168,7 @@ protected function parsePost(): void
166168
return;
167169
}
168170
if (preg_match('/\bjson\b/i', $content_type)) {
169-
$this->data['post'] = (array) json_decode($this->rawBody, true, 512, JSON_THROW_ON_ERROR);
171+
$this->data['post'] = (array)json_decode($this->rawBody, true, 512, JSON_THROW_ON_ERROR);
170172
} else {
171173
parse_str($this->rawBody, $this->data['post']);
172174
}
@@ -202,15 +204,15 @@ protected function parseUploadFiles(string $http_post_boundary): void
202204
$tmp_file = '';
203205
$size = strlen($boundary_value);
204206
$tmp_upload_dir = './temp/';
205-
if (! $tmp_upload_dir) {
207+
if (!$tmp_upload_dir) {
206208
$error = UPLOAD_ERR_NO_TMP_DIR;
207209
} else {
208210
$tmp_file = tempnam($tmp_upload_dir, 'workerman.upload.');
209-
if ($tmp_file === false || ! file_put_contents($tmp_file, $boundary_value)) {
211+
if ($tmp_file === false || !file_put_contents($tmp_file, $boundary_value)) {
210212
$error = UPLOAD_ERR_CANT_WRITE;
211213
}
212214
}
213-
if (! isset($files[$key])) {
215+
if (!isset($files[$key])) {
214216
$files[$key] = [];
215217
}
216218
// Parse upload files.
@@ -232,7 +234,7 @@ protected function parseUploadFiles(string $http_post_boundary): void
232234
break;
233235
case 'content-type':
234236
// add file_type
235-
if (! isset($files[$key])) {
237+
if (!isset($files[$key])) {
236238
$files[$key] = [];
237239
}
238240
$files[$key]['type'] = trim($header_value);

cloud-admin/Http2/Parser/Response.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ public function getPushes(): array
113113
return $this->push;
114114
}
115115

116-
public function push(string $url, array $header = [])
116+
public function push(string $url, array $header = []): void
117117
{
118118
$urlInfo = parse_url($url);
119119
if (is_array($urlInfo)) {

0 commit comments

Comments
 (0)