-
-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathHttp2Driver.php
More file actions
1479 lines (1198 loc) · 49.3 KB
/
Copy pathHttp2Driver.php
File metadata and controls
1479 lines (1198 loc) · 49.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php declare(strict_types=1);
namespace Amp\Http\Server\Driver;
use Amp\ByteStream\ReadableIterableStream;
use Amp\ByteStream\ReadableStream;
use Amp\ByteStream\StreamException;
use Amp\ByteStream\WritableStream;
use Amp\Cancellation;
use Amp\CancelledException;
use Amp\DeferredFuture;
use Amp\Future;
use Amp\Http\HPack;
use Amp\Http\Http2\Http2ConnectionException;
use Amp\Http\Http2\Http2Parser;
use Amp\Http\Http2\Http2Processor;
use Amp\Http\Http2\Http2StreamException;
use Amp\Http\HttpStatus;
use Amp\Http\InvalidHeaderException;
use Amp\Http\Server\ClientException;
use Amp\Http\Server\Driver\Internal\AbstractHttpDriver;
use Amp\Http\Server\Driver\Internal\Http2Stream;
use Amp\Http\Server\Driver\Internal\StreamTimeoutTracker;
use Amp\Http\Server\ErrorHandler;
use Amp\Http\Server\Push;
use Amp\Http\Server\Request;
use Amp\Http\Server\RequestBody;
use Amp\Http\Server\RequestHandler;
use Amp\Http\Server\Response;
use Amp\Http\Server\Trailers;
use Amp\Pipeline\Queue;
use Amp\Socket\InternetAddress;
use League\Uri;
use Psr\Log\LoggerInterface as PsrLogger;
use Revolt\EventLoop;
use function Amp\async;
use function Amp\Http\formatDateHeader;
final class Http2Driver extends AbstractHttpDriver implements Http2Processor
{
public const DEFAULT_CONCURRENT_STREAM_LIMIT = 100;
/** Stream behavior window interval in seconds. */
private const STREAM_BEHAVIOR_WINDOW = 10;
/** Ratio of normally released streams to exceptionally released which must be exceeded to automatically
* disconnect the client.*/
private const RESET_STREAM_RATIO = 0.25;
/** Number of streams released within the behavior window for the reset ratio to be applicable. */
private const STREAM_BEHAVIOR_THRESHOLD = 10;
public const DEFAULT_MAX_FRAME_SIZE = 1 << 14;
public const DEFAULT_WINDOW_SIZE = (1 << 16) - 1;
private const MINIMUM_WINDOW = (1 << 15) - 1;
private const MAX_INCREMENT = (1 << 16) - 1;
// Headers to take over from original request if present
private const PUSH_PROMISE_INTERSECT = [
"accept" => true,
"accept-charset" => true,
"accept-encoding" => true,
"accept-language" => true,
"authorization" => true,
"cache-control" => true,
"cookie" => true,
"date" => true,
"host" => true,
"user-agent" => true,
"via" => true,
];
private Client $client;
private ReadableStream $readableStream;
private WritableStream $writableStream;
private StreamTimeoutTracker $timeoutTracker;
private int $serverWindow = self::DEFAULT_WINDOW_SIZE;
private int $clientWindow = self::DEFAULT_WINDOW_SIZE;
private int $initialWindowSize = self::DEFAULT_WINDOW_SIZE;
/** @var positive-int */
private int $maxFrameSize = self::DEFAULT_MAX_FRAME_SIZE;
private bool $allowsPush;
/** @var non-negative-int Last used local stream ID. */
private int $localStreamId = 0;
/** @var non-negative-int Last used remote stream ID. */
private int $remoteStreamId = 0;
/** @var array<int, Http2Stream> */
private array $streams = [];
/** @var \WeakMap<Request, int> Map of Request objects to stream IDs. */
private \WeakMap $streamIdMap;
/** @var array<int, int> Release timestamps of the last {@see STREAM_BEHAVIOR_WINDOW} released streams. */
private array $releasedStreams = [];
/** @var array<int, int> Release timestamps of the last {@see STREAM_BEHAVIOR_WINDOW} streams released due to
* an exception (such as the client resetting the stream or sending an invalid frame).
*/
private array $exceptionalStreams = [];
/** @var array<string, int> Map of URLs pushed on this connection. */
private array $pushCache = [];
/** @var array<int, DeferredFuture> */
private array $trailerDeferreds = [];
/** @var array<int, Queue> */
private array $bodyQueues = [];
/** @var int Number of streams that may be opened. */
private int $remainingStreams;
private bool $stopping = false;
private int $pinged = 0;
private readonly HPack $hpack;
public function __construct(
RequestHandler $requestHandler,
ErrorHandler $errorHandler,
PsrLogger $logger,
private readonly int $streamTimeout = self::DEFAULT_STREAM_TIMEOUT,
private readonly int $connectionTimeout = self::DEFAULT_CONNECTION_TIMEOUT,
private readonly int $headerSizeLimit = self::DEFAULT_HEADER_SIZE_LIMIT,
private readonly int $bodySizeLimit = self::DEFAULT_BODY_SIZE_LIMIT,
private readonly int $concurrentStreamLimit = self::DEFAULT_CONCURRENT_STREAM_LIMIT,
private readonly bool $pushEnabled = true,
private readonly ?string $settings = null,
) {
parent::__construct($requestHandler, $errorHandler, $logger);
$this->remainingStreams = $concurrentStreamLimit;
$this->allowsPush = $pushEnabled;
$this->hpack = new HPack();
/** @var \WeakMap<Request, int> */
$this->streamIdMap = new \WeakMap();
}
#[\Override]
public function handleClient(
Client $client,
ReadableStream $readableStream,
WritableStream $writableStream,
): void {
/** @psalm-suppress RedundantPropertyInitializationCheck */
\assert(!isset($this->client), "The driver has already been setup");
$this->client = $client;
$this->readableStream = $readableStream;
$this->writableStream = $writableStream;
$this->timeoutTracker = new StreamTimeoutTracker(
$this->client,
self::getTimeoutQueue(),
$this->connectionTimeout,
$this->streamTimeout,
fn () => $this->shutdown(new ClientException($this->client, 'Shutting down connection due to inactivity')),
);
$this->processClientInput();
}
/**
* Provide separate functions for Http2Driver initialization:
* The Http1Driver may still be in process of reading a possible request body.
* As we want to be able to already start sending HTTP/2 frames before the whole request body has been read,
* we need to initialize writing early. Hence, we need a separate function for starting reading on the stream.
*/
public function initializeWriting(
Client $client,
WritableStream $writableStream,
): void {
/** @psalm-suppress RedundantPropertyInitializationCheck */
\assert(!isset($this->client), "The driver has already been setup");
$this->client = $client;
$this->writableStream = $writableStream;
$this->timeoutTracker = new StreamTimeoutTracker(
$this->client,
self::getTimeoutQueue(),
$this->connectionTimeout,
$this->streamTimeout,
fn () => $this->shutdown(new ClientException($this->client, 'Shutting down connection due to inactivity')),
);
if ($this->settings !== null) {
// Upgraded connections automatically assume an initial stream with ID 1.
// No data will be incoming on this stream, so body size of 0.
$this->createStream(1, 0, Http2Stream::RESERVED | Http2Stream::REMOTE_CLOSED);
$this->remoteStreamId = \max(1, $this->remoteStreamId);
$this->remainingStreams--;
// Initial settings frame, sent immediately for upgraded connections.
$this->writeFrame(
\pack(
"nNnNnNnN",
Http2Parser::INITIAL_WINDOW_SIZE,
self::DEFAULT_WINDOW_SIZE,
Http2Parser::MAX_CONCURRENT_STREAMS,
$this->concurrentStreamLimit,
Http2Parser::MAX_HEADER_LIST_SIZE,
$this->headerSizeLimit,
Http2Parser::MAX_FRAME_SIZE,
self::DEFAULT_MAX_FRAME_SIZE
),
Http2Parser::SETTINGS,
Http2Parser::NO_FLAG
);
}
}
public function handleClientWithBuffer(string $buffer, ReadableStream $readableStream): void
{
/** @psalm-suppress RedundantPropertyInitializationCheck */
\assert(isset($this->client), "The driver has not been setup");
$this->readableStream = $readableStream;
$this->processClientInput($buffer);
}
private function processClientInput(?string $chunk = null): void
{
/** @psalm-suppress RedundantCondition */
\assert($this->logger->debug(\sprintf(
"Handling requests from %s #%d using HTTP/2 driver",
$this->client->getRemoteAddress()->toString(),
$this->client->getId(),
)) || true);
$parser = new Http2Parser($this, $this->hpack, $this->settings);
try {
$parser->push($chunk ?? $this->readPreface());
while (null !== $chunk = $this->readableStream->read()) {
$parser->push($chunk);
}
$this->shutdown();
} catch (StreamException|Http2ConnectionException $exception) {
$this->shutdown(new ClientException(
$this->client,
"Exception thrown when reading client input: " . $exception->getMessage(),
$exception->getCode(),
$exception,
));
} finally {
$parser->cancel();
}
}
#[\Override]
protected function write(Request $request, Response $response): void
{
/** @psalm-suppress RedundantPropertyInitializationCheck */
\assert(isset($this->client), "The driver has not been setup");
$streamId = $this->streamIdMap[$request] ?? 1; // Default ID of 1 for upgrade requests.
/** @psalm-suppress RedundantCondition */
\assert((bool) $streamId); // For Psalm.
if (!isset($this->streams[$streamId])) {
return; // Client closed the stream or connection.
}
$stream = $this->streams[$streamId];
if ($streamId & 1) {
$this->timeoutTracker->update($streamId);
}
$deferred = new DeferredFuture;
$stream->pendingWrite = $deferred->getFuture();
$cancellation = $stream->deferredCancellation->getCancellation();
try {
$this->send($streamId, $response, $request, $cancellation);
} finally {
$deferred->complete();
}
}
#[\Override]
public function stop(): void
{
$this->shutdown();
}
#[\Override]
public function getPendingRequestCount(): int
{
return \count($this->bodyQueues);
}
private function send(int $id, Response $response, Request $request, Cancellation $cancellation): void
{
$chunk = ""; // Required for the finally, not directly overwritten, even if your IDE says otherwise.
$need = $response->getHeader("content-length");
$wrote = 0;
try {
$status = $response->getStatus();
if ($status < HttpStatus::OK) {
$response->setStatus(HttpStatus::HTTP_VERSION_NOT_SUPPORTED);
throw new ClientException(
$this->client,
"1xx response codes are not supported in HTTP/2",
Http2Parser::HTTP_1_1_REQUIRED
);
}
if ($status === HttpStatus::HTTP_VERSION_NOT_SUPPORTED && $response->getHeader("upgrade")) {
throw new ClientException(
$this->client,
"Upgrade requests require HTTP/1.1",
Http2Parser::HTTP_1_1_REQUIRED
);
}
$headers = [
':status' => [$status],
...$response->getHeaders(),
'date' => [formatDateHeader()],
];
// Remove headers that are obsolete in HTTP/2.
unset($headers["connection"], $headers["keep-alive"], $headers["transfer-encoding"]);
$trailers = $response->getTrailers();
if ($trailers !== null && !isset($headers["trailer"]) && ($fields = $trailers->getFields())) {
$headers["trailer"] = [\implode(", ", $fields)];
}
foreach ($response->getPushes() as $push) {
$headers["link"][] = "<{$push->getUri()}>; rel=preload";
if ($this->allowsPush) {
$this->sendPushPromise($request, $id, $push);
}
}
$this->writeHeaders($this->encodeHeaders($headers), Http2Parser::HEADERS, 0, $id);
if ($request->getMethod() === "HEAD") {
$this->streams[$id]->state |= Http2Stream::LOCAL_CLOSED;
$this->writeData("", $id);
return;
}
$body = $response->getBody();
$chunk = $body->read($cancellation);
while ($chunk !== null) {
// Stream may have been closed while waiting for body data.
if (!isset($this->streams[$id])) {
return;
}
$wrote += \strlen($chunk);
$this->writeData($chunk, $id);
$chunk = $body->read($cancellation);
}
// Stream may have been closed while waiting for body data.
if (!isset($this->streams[$id])) {
return;
}
$this->streams[$id]->state |= Http2Stream::LOCAL_CLOSED;
if ($trailers === null) {
$this->writeData("", $id);
} else {
$trailers = $trailers->await($cancellation);
// Stream may have been closed while writing final body chunk or headers.
if (!isset($this->streams[$id])) {
return;
}
$this->writeHeaders(
$this->encodeHeaders($trailers->getHeaders()),
Http2Parser::HEADERS,
Http2Parser::END_STREAM,
$id,
);
}
} catch (ClientException $exception) {
$error = $exception->getCode() ?? Http2Parser::CANCEL; // Set error code to be used below.
} catch (StreamException|CancelledException) {
// Body stream threw or client disconnected, ignore and proceed to clean up below.
$chunk = null;
} catch (\Throwable $throwable) {
// Will be rethrown after cleanup below.
}
// Cleanup outside finally block since the fiber may suspend to write RST_STREAM frame.
try {
/** @psalm-suppress ParadoxicalCondition Stream may be unset while awaiting above */
if (!isset($this->streams[$id])) {
return;
}
if ($chunk !== null || ($need !== null && $wrote !== (int) $need)) {
$error ??= Http2Parser::INTERNAL_ERROR;
$this->writeFrame(\pack("N", $error), Http2Parser::RST_STREAM, Http2Parser::NO_FLAG, $id);
$this->releaseStream($id, $exception ?? new ClientException($this->client, "Stream error", $error));
return;
}
if ($this->streams[$id]->state & Http2Stream::REMOTE_CLOSED) {
$this->releaseStream($id);
}
} finally {
if (isset($throwable)) {
throw $throwable;
}
}
}
private function shutdown(?ClientException $reason = null): void
{
if ($this->stopping) {
return;
}
$this->stopping = true;
$previous = $reason?->getPrevious();
$previous = $previous instanceof Http2ConnectionException ? $previous : null;
$code = $previous?->getCode() ?? Http2Parser::GRACEFUL_SHUTDOWN;
try {
$futures = [];
foreach ($this->streams as $id => $stream) {
if ($id > $this->remoteStreamId) {
break;
}
if ($stream->pendingResponse) {
$futures[] = $stream->pendingResponse;
}
}
$message = match ($code) {
Http2Parser::PROTOCOL_ERROR,
Http2Parser::FLOW_CONTROL_ERROR,
Http2Parser::FRAME_SIZE_ERROR,
Http2Parser::COMPRESSION_ERROR,
Http2Parser::SETTINGS_TIMEOUT,
Http2Parser::ENHANCE_YOUR_CALM => $previous?->getMessage(),
default => null,
};
$this->writeFrame(
\pack("NN", $this->remoteStreamId, $code) . $message,
Http2Parser::GOAWAY,
Http2Parser::NO_FLAG,
);
/** @psalm-suppress RedundantCondition */
\assert($this->logger->debug(\sprintf(
"Shutting down HTTP/2 client @ %s #%d; last-id: %d; reason: %s",
$this->client->getRemoteAddress()->toString(),
$this->client->getId(),
$this->remoteStreamId,
$reason?->getMessage() ?? "undefined",
)) || true);
Future\await($futures);
$futures = [];
foreach ($this->streams as $id => $stream) {
if ($id > $this->remoteStreamId) {
break;
}
if ($stream->pendingWrite) {
$futures[] = $stream->pendingWrite;
}
}
Future\await($futures);
} catch (StreamException) {
// ignore if no longer writable
} finally {
if (!empty($this->streams)) {
$reason ??= new ClientException($this->client, "Connection closed unexpectedly", Http2Parser::CANCEL);
foreach ($this->streams as $id => $_stream) {
$this->releaseStream($id, $reason);
}
}
$this->client->close();
$this->readableStream->close();
$this->writableStream->close();
}
}
private function sendPushPromise(Request $request, int $streamId, Push $push): void
{
$requestUri = $request->getUri();
$pushUri = $push->getUri();
$path = $pushUri->getPath();
if (($path[0] ?? "/") !== "/") { // Relative Path
$pushUri = $requestUri // Base push URI from original request URI.
->withPath($requestUri->getPath() . "/" . $path)
->withQuery($pushUri->getQuery());
}
if ($pushUri->getAuthority() === '') {
$pushUri = $pushUri // If push URI did not provide a host, use original request URI.
->withHost($requestUri->getHost())
->withPort($requestUri->getPort());
}
$url = (string) $pushUri;
if (isset($this->pushCache[$url])) {
return; // Resource already pushed to this client.
}
$this->pushCache[$url] = $streamId;
$path = $pushUri->getPath();
if ($query = $pushUri->getQuery()) {
$path .= "?" . $query;
}
$headers = [
...\array_intersect_key($request->getHeaders(), self::PUSH_PROMISE_INTERSECT), // Uses only select headers
...$push->getHeaders() // Overwrites request headers with those defined in push.
];
// $id is the new stream ID for the pushed response, $streamId is the original request stream ID.
$id = $this->localStreamId += 2; // Server initiated stream IDs must be even.
$request = new Request($this->client, "GET", $pushUri, $headers, "", "2");
// No data will be incoming on this stream.
$stream = $this->createStream($id, 0, Http2Stream::RESERVED | Http2Stream::REMOTE_CLOSED);
$this->streamIdMap[$request] = $id;
$headers = [
":authority" => [$pushUri->getAuthority()],
":scheme" => [$pushUri->getScheme()],
":path" => [$path],
":method" => ["GET"],
...$headers,
];
$this->writeHeaders(
\pack("N", $id) . $this->encodeHeaders($headers),
Http2Parser::PUSH_PROMISE,
0,
$streamId
);
$stream->pendingResponse = async($this->handleRequest(...), $request);
}
private function writeFrame(string $data, int $type, int $flags, int $stream = 0): void
{
$this->writableStream->write(Http2Parser::compileFrame($data, $type, $flags, $stream));
}
private function writeData(string $data, int $id): void
{
\assert(isset($this->streams[$id]), "The stream was closed");
$this->streams[$id]->buffer .= $data;
$this->writeBufferedData($id);
}
private function writeBufferedData(int $streamId): void
{
\assert(isset($this->streams[$streamId]), "The stream was closed");
$stream = $this->streams[$streamId];
$delta = \min($this->clientWindow, $stream->clientWindow);
$length = \strlen($stream->buffer);
if ($streamId & 1) {
$this->timeoutTracker->update($streamId);
}
if ($delta >= $length) {
$this->clientWindow -= $length;
$stream->clientWindow -= $length;
// Clear the buffer BEFORE the suspending writeFrame() call.
// sendBufferedData() can be invoked via EventLoop::defer while
// we are suspended on the socket write (any incoming
// WINDOW_UPDATE schedules it). If the buffer is still
// populated at that point, the deferred callback re-enters
// writeBufferedData() and emits the same DATA frame again.
$bufferToWrite = $stream->buffer;
$stream->buffer = "";
if ($length > $this->maxFrameSize) {
$split = \str_split($bufferToWrite, $this->maxFrameSize);
$bufferToWrite = \array_pop($split);
foreach ($split as $part) {
$this->writeFrame($part, Http2Parser::DATA, Http2Parser::NO_FLAG, $streamId);
}
}
if ($stream->state & Http2Stream::LOCAL_CLOSED) {
$this->writeFrame($bufferToWrite, Http2Parser::DATA, Http2Parser::END_STREAM, $streamId);
} else {
$this->writeFrame($bufferToWrite, Http2Parser::DATA, Http2Parser::NO_FLAG, $streamId);
}
if ($stream->deferredFuture) {
$stream->deferredFuture->complete();
$stream->deferredFuture = null;
}
return;
}
if ($delta > 0) {
$data = $stream->buffer;
$end = $delta - $this->maxFrameSize;
$stream->clientWindow -= $delta;
$this->clientWindow -= $delta;
for ($off = 0; $off < $end; $off += $this->maxFrameSize) {
$this->writeFrame(
\substr($data, $off, $this->maxFrameSize),
Http2Parser::DATA,
Http2Parser::NO_FLAG,
$streamId
);
}
$this->writeFrame(\substr($data, $off, $delta - $off), Http2Parser::DATA, Http2Parser::NO_FLAG, $streamId);
$stream->buffer = \substr($data, $delta);
}
$stream->deferredFuture ??= new DeferredFuture;
$stream->deferredFuture->getFuture()->await();
}
private function writeHeaders(string $headers, int $type, int $flags, int $id): void
{
$flags |= Http2Parser::END_HEADERS;
if (\strlen($headers) > $this->maxFrameSize) {
// Header frames must be sent as one contiguous block without frames from any other stream being
// interleaved between due to HPack. See https://datatracker.ietf.org/doc/html/rfc7540#section-4.3
$split = \str_split($headers, $this->maxFrameSize);
$headers = \array_pop($split);
$writeFrame = $this->writeFrame(...);
foreach ($split as $part) {
async($writeFrame, $part, $type, Http2Parser::NO_FLAG, $id)->ignore();
$type = Http2Parser::CONTINUATION;
}
async($writeFrame, $headers, $type, $flags, $id)->await();
return;
}
$this->writeFrame($headers, $type, $flags, $id);
}
private function createStream(int $id, int $bodySizeLimit, int $flags = Http2Stream::OPEN): Http2Stream
{
\assert(!isset($this->streams[$id]));
if ($id & 1) {
$this->timeoutTracker->insert(
$id,
fn (int $id) => $this->releaseStream(
$id,
new ClientException($this->client, "Closing stream due to inactivity"),
),
);
}
return $this->streams[$id] = new Http2Stream(
$bodySizeLimit,
$this->initialWindowSize,
$this->initialWindowSize,
$flags,
);
}
private function releaseStream(int $id, ?ClientException $exception = null): void
{
\assert(isset($this->streams[$id]), "Tried to release a non-existent stream");
$exceptional = $exception !== null;
$this->streams[$id]->deferredCancellation->cancel();
$clientInitiated = $id & 1;
if ($clientInitiated) {
$this->timeoutTracker->remove($id);
}
($this->bodyQueues[$id] ?? null)?->error(
$exception ??= new ClientException($this->client, "Client disconnected", Http2Parser::CANCEL)
);
($this->trailerDeferreds[$id] ?? null)?->error(
$exception ?? new ClientException($this->client, "Client disconnected", Http2Parser::CANCEL)
);
unset($this->streams[$id], $this->bodyQueues[$id], $this->trailerDeferreds[$id]);
if (!$clientInitiated) {
return; // Additional checks unnecessary for server-initiated streams.
}
$this->remainingStreams++;
$now = \time();
$filterCallback = fn (int $releasedAt) => $releasedAt > $now - self::STREAM_BEHAVIOR_WINDOW;
$this->releasedStreams = \array_filter($this->releasedStreams, $filterCallback);
$this->releasedStreams[$id] = $now;
if ($exceptional) {
$this->exceptionalStreams = \array_filter($this->exceptionalStreams, $filterCallback);
$this->exceptionalStreams[$id] = $now;
$releasedStreamCount = \count($this->releasedStreams);
$exceptionalStreamCount = \count($this->exceptionalStreams);
if ($releasedStreamCount >= self::STREAM_BEHAVIOR_THRESHOLD
&& $exceptionalStreamCount / $releasedStreamCount > self::RESET_STREAM_RATIO
) {
$this->handleConnectionException(new Http2ConnectionException(
'Too many reset streams',
Http2Parser::ENHANCE_YOUR_CALM,
));
}
}
}
private function readPreface(): string
{
$buffer = $this->readableStream->read();
if ($buffer === null) {
throw new Http2ConnectionException("Invalid preface", Http2Parser::PROTOCOL_ERROR);
}
while (\strlen($buffer) < \strlen(Http2Parser::PREFACE)) {
$chunk = $this->readableStream->read();
if ($chunk === null) {
throw new Http2ConnectionException("Invalid preface", Http2Parser::PROTOCOL_ERROR);
}
$buffer .= $chunk;
}
if (!\str_starts_with($buffer, Http2Parser::PREFACE)) {
throw new Http2ConnectionException("Invalid preface", Http2Parser::PROTOCOL_ERROR);
}
$buffer = \substr($buffer, \strlen(Http2Parser::PREFACE));
if ($this->settings === null) {
// Initial settings frame, delayed until after the preface is read for non-upgraded connections.
$this->writeFrame(
\pack(
"nNnNnNnN",
Http2Parser::INITIAL_WINDOW_SIZE,
self::DEFAULT_WINDOW_SIZE,
Http2Parser::MAX_CONCURRENT_STREAMS,
$this->concurrentStreamLimit,
Http2Parser::MAX_HEADER_LIST_SIZE,
$this->headerSizeLimit,
Http2Parser::MAX_FRAME_SIZE,
self::DEFAULT_MAX_FRAME_SIZE
),
Http2Parser::SETTINGS,
Http2Parser::NO_FLAG
);
}
return $buffer;
}
private function sendBufferedData(): void
{
foreach ($this->streams as $id => $stream) {
if ($this->clientWindow <= 0) {
return;
}
if ($stream->buffer === '' || $stream->clientWindow <= 0) {
continue;
}
try {
$this->writeBufferedData($id);
} catch (StreamException) {
return; // Socket closed while writing buffered data.
}
}
}
private function encodeHeaders(array $headers): string
{
$input = [];
foreach ($headers as $field => $values) {
$values = (array) $values;
foreach ($values as $value) {
$input[] = [(string) $field, (string) $value];
}
}
return $this->hpack->encode($input);
}
#[\Override]
public function handlePong(string $data): void
{
// Ignored
}
#[\Override]
public function handlePing(string $data): void
{
if (!$this->pinged) {
// Ensure there are a few extra seconds for request after first ping.
$this->timeoutTracker->ping(5);
}
$this->pinged++;
if ($this->pinged > 5) {
$this->handleConnectionException(
new Http2ConnectionException('Too many pings', Http2Parser::ENHANCE_YOUR_CALM)
);
} else {
$this->writeFrame($data, Http2Parser::PING, Http2Parser::ACK);
}
}
#[\Override]
public function handleShutdown(int $lastId, int $error, string $message): void
{
$message = \sprintf(
"Received GOAWAY frame from %s with error code %d and message '%s'",
$this->client->getRemoteAddress()->toString(),
$error,
$message,
);
if ($error !== Http2Parser::GRACEFUL_SHUTDOWN) {
$this->logger->notice($message);
}
$this->shutdown(new ClientException(
$this->client,
"Client closed HTTP/2 connection",
$error,
new Http2ConnectionException($message, $error),
));
}
#[\Override]
public function handleStreamWindowIncrement(int $streamId, int $windowSize): void
{
if ($streamId > $this->remoteStreamId) {
throw new Http2ConnectionException(
"Stream ID does not exist",
Http2Parser::PROTOCOL_ERROR
);
}
if (!isset($this->streams[$streamId])) {
return;
}
$stream = $this->streams[$streamId];
if ($stream->clientWindow + $windowSize > 2147483647) {
throw new Http2StreamException(
"Current window size plus new window exceeds maximum size",
$streamId,
Http2Parser::FLOW_CONTROL_ERROR
);
}
$stream->clientWindow += $windowSize;
EventLoop::defer($this->sendBufferedData(...));
}
#[\Override]
public function handleConnectionWindowIncrement(int $windowSize): void
{
if ($this->clientWindow + $windowSize > 2147483647) {
throw new Http2ConnectionException(
"Current window size plus new window exceeds maximum size",
Http2Parser::FLOW_CONTROL_ERROR
);
}
$this->clientWindow += $windowSize;
EventLoop::defer($this->sendBufferedData(...));
}
#[\Override]
public function handleHeaders(int $streamId, array $pseudo, array $headers, bool $streamEnded): void
{
foreach ($pseudo as $name => $_value) {
if (!isset(Http2Parser::KNOWN_REQUEST_PSEUDO_HEADERS[$name])) {
throw new Http2StreamException(
"Invalid pseudo header",
$streamId,
Http2Parser::PROTOCOL_ERROR
);
}
}
if (isset($this->streams[$streamId])) {
$stream = $this->streams[$streamId];
if ($stream->state & Http2Stream::REMOTE_CLOSED) {
throw new Http2StreamException(
"Stream remote closed",
$streamId,
Http2Parser::STREAM_CLOSED
);
}
} else {
if (!($streamId & 1) || $streamId <= $this->remoteStreamId) {
throw new Http2ConnectionException(
"Invalid stream ID",
Http2Parser::PROTOCOL_ERROR
);
}
if ($this->remainingStreams-- <= 0) {
throw new Http2ConnectionException(
"Concurrent stream limit exceeded",
Http2Parser::PROTOCOL_ERROR
);
}
$stream = $this->createStream($streamId, $this->bodySizeLimit);
}
// Header frames can be received on previously opened streams (trailer headers).
$this->remoteStreamId = \max($streamId, $this->remoteStreamId);
if (isset($this->trailerDeferreds[$streamId]) && $stream->state & Http2Stream::RESERVED) {
if (!$streamEnded) {
throw new Http2ConnectionException(
"Trailers must end the stream",
Http2Parser::PROTOCOL_ERROR
);
}
// Trailers must not contain pseudo-headers.
if (!empty($pseudo)) {
throw new Http2StreamException(
"Trailers must not contain pseudo headers",
$streamId,
Http2Parser::PROTOCOL_ERROR
);
}
// Trailers must not contain any disallowed fields.
if (\array_intersect_key($headers, Trailers::DISALLOWED_TRAILERS)) {
throw new Http2StreamException(
"Disallowed trailer field name",