-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttp2Parser.php
705 lines (541 loc) · 21.8 KB
/
Http2Parser.php
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
<?php
/** @noinspection PhpUnusedPrivateFieldInspection */
/** @noinspection PhpDocSignatureInspection */
/** @noinspection PhpUnhandledExceptionInspection */
namespace Amp\Http\Http2;
use Amp\Http\HPack;
final class Http2Parser
{
public const PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n";
private const DEFAULT_MAX_FRAME_SIZE = 1 << 14;
private const HEADER_NAME_REGEX = '/^[\x21-\x40\x5b-\x7e]+$/';
public const KNOWN_RESPONSE_PSEUDO_HEADERS = [
":status" => true,
];
public const KNOWN_REQUEST_PSEUDO_HEADERS = [
":method" => true,
":authority" => true,
":path" => true,
":scheme" => true,
];
// SETTINGS Flags - https://http2.github.io/http2-spec/#rfc.section.6.5
public const ACK = 0x01;
// HEADERS Flags - https://http2.github.io/http2-spec/#rfc.section.6.2
public const NO_FLAG = 0x00;
public const END_STREAM = 0x01;
public const END_HEADERS = 0x04;
public const PADDED = 0x08;
public const PRIORITY_FLAG = 0x20;
// Frame Types - https://http2.github.io/http2-spec/#rfc.section.11.2
public const DATA = 0x00;
public const HEADERS = 0x01;
public const PRIORITY = 0x02;
public const RST_STREAM = 0x03;
public const SETTINGS = 0x04;
public const PUSH_PROMISE = 0x05;
public const PING = 0x06;
public const GOAWAY = 0x07;
public const WINDOW_UPDATE = 0x08;
public const CONTINUATION = 0x09;
// Settings
public const HEADER_TABLE_SIZE = 0x1; // 1 << 12
public const ENABLE_PUSH = 0x2; // 1
public const MAX_CONCURRENT_STREAMS = 0x3; // INF
public const INITIAL_WINDOW_SIZE = 0x4; // 1 << 16 - 1
public const MAX_FRAME_SIZE = 0x5; // 1 << 14
public const MAX_HEADER_LIST_SIZE = 0x6; // INF
// Error codes
public const GRACEFUL_SHUTDOWN = 0x0;
public const PROTOCOL_ERROR = 0x1;
public const INTERNAL_ERROR = 0x2;
public const FLOW_CONTROL_ERROR = 0x3;
public const SETTINGS_TIMEOUT = 0x4;
public const STREAM_CLOSED = 0x5;
public const FRAME_SIZE_ERROR = 0x6;
public const REFUSED_STREAM = 0x7;
public const CANCEL = 0x8;
public const COMPRESSION_ERROR = 0x9;
public const CONNECT_ERROR = 0xa;
public const ENHANCE_YOUR_CALM = 0xb;
public const INADEQUATE_SECURITY = 0xc;
public const HTTP_1_1_REQUIRED = 0xd;
public static function getFrameName(int $type): string
{
$names = [
self::DATA => 'DATA',
self::HEADERS => 'HEADERS',
self::PRIORITY => 'PRIORITY',
self::RST_STREAM => 'RST_STREAM',
self::SETTINGS => 'SETTINGS',
self::PUSH_PROMISE => 'PUSH_PROMISE',
self::PING => 'PING',
self::GOAWAY => 'GOAWAY',
self::WINDOW_UPDATE => 'WINDOW_UPDATE',
self::CONTINUATION => 'CONTINUATION',
];
return $names[$type] ?? ('0x' . \bin2hex(\chr($type)));
}
public static function logDebugFrame(
string $action,
int $frameType,
int $frameFlags,
int $streamId,
int $frameLength
): bool {
$env = \getenv("AMP_DEBUG_HTTP2_FRAMES") ?: "0";
if (($env !== "0" && $env !== "false") || (\defined("AMP_DEBUG_HTTP2_FRAMES") && \AMP_DEBUG_HTTP2_FRAMES)) {
\fwrite(
\STDERR,
$action . ' ' . self::getFrameName($frameType) . ' <flags = ' . \bin2hex(\chr($frameFlags)) . ', stream = ' . $streamId . ', length = ' . $frameLength . '>' . "\r\n"
);
}
return true;
}
/** @var string */
private $buffer = '';
/** @var int */
private $bufferOffset = 0;
/** @var int */
private $headerSizeLimit = self::DEFAULT_MAX_FRAME_SIZE; // Should be configurable?
/** @var bool */
private $continuationExpected = false;
/** @var int */
private $headerFrameType = 0;
/** @var string */
private $headerBuffer = '';
/** @var int */
private $headerStream = 0;
/** @var HPack */
private $hpack;
/** @var Http2Processor */
private $handler;
/** @var int */
private $receivedFrameCount = 0;
/** @var int */
private $receivedByteCount = 0;
public function __construct(Http2Processor $handler)
{
$this->hpack = new HPack;
$this->handler = $handler;
}
public function getReceivedByteCount(): int
{
return $this->receivedByteCount;
}
public function getReceivedFrameCount(): int
{
return $this->receivedFrameCount;
}
public function parse(string $settings = null): \Generator
{
if ($settings !== null) {
$this->parseSettings($settings, \strlen($settings), self::NO_FLAG, 0);
}
$this->buffer = yield;
while (true) {
$frameHeader = yield from $this->consume(9);
[
'length' => $frameLength,
'type' => $frameType,
'flags' => $frameFlags,
'id' => $streamId,
] = \unpack('Nlength/ctype/cflags/Nid', "\0" . $frameHeader);
$streamId &= 0x7fffffff;
$frameBuffer = $frameLength === 0 ? '' : yield from $this->consume($frameLength);
$this->receivedFrameCount++;
\assert(self::logDebugFrame('recv', $frameType, $frameFlags, $streamId, $frameLength));
try {
// Do we want to allow increasing the maximum frame size?
if ($frameLength > self::DEFAULT_MAX_FRAME_SIZE) {
throw new Http2ConnectionException("Frame size limit exceeded", self::FRAME_SIZE_ERROR);
}
if ($this->continuationExpected && $frameType !== self::CONTINUATION) {
throw new Http2ConnectionException("Expected continuation frame", self::PROTOCOL_ERROR);
}
switch ($frameType) {
case self::DATA:
$this->parseDataFrame($frameBuffer, $frameLength, $frameFlags, $streamId);
break;
case self::PUSH_PROMISE:
$this->parsePushPromise($frameBuffer, $frameLength, $frameFlags, $streamId);
break;
case self::HEADERS:
$this->parseHeaders($frameBuffer, $frameLength, $frameFlags, $streamId);
break;
case self::PRIORITY:
$this->parsePriorityFrame($frameBuffer, $frameLength, $streamId);
break;
case self::RST_STREAM:
$this->parseStreamReset($frameBuffer, $frameLength, $streamId);
break;
case self::SETTINGS:
$this->parseSettings($frameBuffer, $frameLength, $frameFlags, $streamId);
break;
case self::PING:
$this->parsePing($frameBuffer, $frameLength, $frameFlags, $streamId);
break;
case self::GOAWAY:
$this->parseGoAway($frameBuffer, $frameLength, $streamId);
break;
case self::WINDOW_UPDATE:
$this->parseWindowUpdate($frameBuffer, $frameLength, $streamId);
break;
case self::CONTINUATION:
$this->parseContinuation($frameBuffer, $frameFlags, $streamId);
break;
default: // Ignore and discard unknown frame per spec
break;
}
} catch (Http2StreamException $exception) {
$this->handler->handleStreamException($exception);
} catch (Http2ConnectionException $exception) {
$this->handler->handleConnectionException($exception);
throw $exception;
}
}
}
private function consume(int $bytes): \Generator
{
$bufferEnd = $this->bufferOffset + $bytes;
while (\strlen($this->buffer) < $bufferEnd) {
$this->buffer .= yield;
}
$consumed = \substr($this->buffer, $this->bufferOffset, $bytes);
if ($bufferEnd > 2048) {
$this->buffer = \substr($this->buffer, $bufferEnd);
$this->bufferOffset = 0;
} else {
$this->bufferOffset += $bytes;
}
$this->receivedByteCount += $bytes;
return $consumed;
}
private function parseDataFrame(string $frameBuffer, int $frameLength, int $frameFlags, int $streamId): void
{
$isPadded = $frameFlags & self::PADDED;
$headerLength = $isPadded ? 1 : 0;
if ($frameLength < $headerLength) {
$this->throwInvalidFrameSizeError();
}
$header = $headerLength === 0 ? '' : \substr($frameBuffer, 0, $headerLength);
$padding = $isPadded ? \ord($header[0]) : 0;
if ($streamId === 0) {
$this->throwInvalidZeroStreamIdError();
}
if ($frameLength - $headerLength - $padding < 0) {
$this->throwInvalidPaddingError();
}
$data = \substr($frameBuffer, $headerLength, $frameLength - $headerLength - $padding);
$this->handler->handleData($streamId, $data);
if ($frameFlags & self::END_STREAM) {
$this->handler->handleStreamEnd($streamId);
}
}
/** @see https://http2.github.io/http2-spec/#rfc.section.6.6 */
private function parsePushPromise(string $frameBuffer, int $frameLength, int $frameFlags, int $streamId): void
{
$isPadded = $frameFlags & self::PADDED;
$headerLength = $isPadded ? 5 : 4;
if ($frameLength < $headerLength) {
$this->throwInvalidFrameSizeError();
}
$header = \substr($frameBuffer, 0, $headerLength);
$padding = $isPadded ? \ord($header[0]) : 0;
$pushId = \unpack("N", $header)[1] & 0x7fffffff;
if ($frameLength - $headerLength - $padding < 0) {
$this->throwInvalidPaddingError();
}
$this->headerFrameType = self::PUSH_PROMISE;
$this->pushHeaderBlockFragment(
$pushId,
\substr($frameBuffer, $headerLength, $frameLength - $headerLength - $padding)
);
if ($frameFlags & self::END_HEADERS) {
$this->continuationExpected = false;
[$pseudo, $headers] = $this->parseHeaderBuffer();
$this->handler->handlePushPromise($streamId, $pushId, $pseudo, $headers);
} else {
$this->continuationExpected = true;
}
if ($frameFlags & self::END_STREAM) {
$this->handler->handleStreamEnd($streamId);
}
}
private function parseHeaderBuffer(): array
{
if ($this->headerStream === 0) {
throw new Http2ConnectionException('Invalid stream ID 0 for header block', self::PROTOCOL_ERROR);
}
if ($this->headerBuffer === '') {
throw new Http2StreamException('Invalid empty header section', $this->headerStream, self::PROTOCOL_ERROR);
}
$decoded = $this->hpack->decode($this->headerBuffer, $this->headerSizeLimit);
if ($decoded === null) {
throw new Http2ConnectionException("Compression error in headers", self::COMPRESSION_ERROR);
}
$headers = [];
$pseudo = [];
foreach ($decoded as [$name, $value]) {
if (!\preg_match(self::HEADER_NAME_REGEX, $name)) {
throw new Http2StreamException("Invalid header field name", $this->headerStream, self::PROTOCOL_ERROR);
}
if ($name[0] === ':') {
if (!empty($headers)) {
throw new Http2ConnectionException(
"Pseudo header after other headers",
self::PROTOCOL_ERROR
);
}
if (isset($pseudo[$name])) {
throw new Http2ConnectionException(
"Repeat pseudo header",
self::PROTOCOL_ERROR
);
}
$pseudo[$name] = $value;
continue;
}
$headers[$name][] = $value;
}
$this->headerBuffer = '';
$this->headerStream = 0;
return [$pseudo, $headers];
}
private function pushHeaderBlockFragment(int $streamId, string $buffer): void
{
if ($this->headerStream !== 0 && $this->headerStream !== $streamId) {
throw new Http2ConnectionException(
"Expected CONTINUATION frame for stream ID " . $this->headerStream,
self::PROTOCOL_ERROR
);
}
$this->headerStream = $streamId;
$this->headerBuffer .= $buffer;
}
/** @see https://http2.github.io/http2-spec/#HEADERS */
private function parseHeaders(string $frameBuffer, int $frameLength, int $frameFlags, int $streamId): void
{
if ($streamId === 0) {
$this->throwInvalidZeroStreamIdError();
}
$headerLength = 0;
$isPadded = $frameFlags & self::PADDED;
$isPriority = $frameFlags & self::PRIORITY_FLAG;
if ($isPadded) {
$headerLength++;
}
if ($isPriority) {
$headerLength += 5;
}
if ($frameLength < $headerLength) {
$this->throwInvalidFrameSizeError();
}
$header = \substr($frameBuffer, 0, $headerLength);
$padding = $isPadded ? \ord($header[0]) : 0;
if ($isPriority) {
['parent' => $parent, 'weight' => $weight] = \unpack("Nparent/Cweight", $header, $isPadded ? 1 : 0);
$parent &= 0x7fffffff;
if ($parent === $streamId) {
$this->throwInvalidRecursiveDependency($streamId);
}
// $weight + 256 用于区分
$this->handler->handlePriority($streamId, $parent, $weight + 1 + 256);
}
if ($frameLength - $headerLength - $padding < 0) {
$this->throwInvalidPaddingError();
}
$this->headerFrameType = self::HEADERS;
$this->pushHeaderBlockFragment(
$streamId,
\substr($frameBuffer, $headerLength, $frameLength - $headerLength - $padding)
);
$ended = $frameFlags & self::END_STREAM;
if ($frameFlags & self::END_HEADERS) {
$this->continuationExpected = false;
$headersTooLarge = \strlen($this->headerBuffer) > $this->headerSizeLimit;
[$pseudo, $headers] = $this->parseHeaderBuffer();
// This must happen after the parsing, otherwise we loose the connection state and must close the whole
// connection, which is not what we want here…
if ($headersTooLarge) {
throw new Http2StreamException(
"Headers exceed maximum configured size of {$this->headerSizeLimit} bytes",
$streamId,
self::ENHANCE_YOUR_CALM
);
}
$this->handler->handleHeaders($streamId, $pseudo, $headers, $ended);
} else {
$this->continuationExpected = true;
}
if ($ended) {
$this->handler->handleStreamEnd($streamId);
}
}
private function parsePriorityFrame(string $frameBuffer, int $frameLength, int $streamId): void
{
if ($frameLength !== 5) {
$this->throwInvalidFrameSizeError();
}
['parent' => $parent, 'weight' => $weight] = \unpack("Nparent/Cweight", $frameBuffer);
if ($exclusive = ($parent & 0x80000000)) {
$parent &= 0x7fffffff;
}
if ($streamId === 0) {
$this->throwInvalidZeroStreamIdError();
}
if ($parent === $streamId) {
$this->throwInvalidRecursiveDependency($streamId);
}
$this->handler->handlePriority($streamId, $parent, $weight + 1);
}
private function parseStreamReset(string $frameBuffer, int $frameLength, int $streamId): void
{
if ($frameLength !== 4) {
$this->throwInvalidFrameSizeError();
}
if ($streamId === 0) {
$this->throwInvalidZeroStreamIdError();
}
$errorCode = \unpack('N', $frameBuffer)[1];
$this->handler->handleStreamReset($streamId, $errorCode);
}
private function parseSettings(string $frameBuffer, int $frameLength, int $frameFlags, int $streamId): void
{
if ($streamId !== 0) {
$this->throwInvalidNonZeroStreamIdError();
}
if ($frameFlags & self::ACK) {
if ($frameLength) {
$this->throwInvalidFrameSizeError();
}
return; // Got ACK, nothing to do
}
if ($frameLength % 6 !== 0) {
$this->throwInvalidFrameSizeError();
}
if ($frameLength > 60) {
// Even with room for a few future options, sending that a big SETTINGS frame is just about
// wasting our processing time. We declare this a protocol error.
throw new Http2ConnectionException("Excessive SETTINGS frame", self::PROTOCOL_ERROR);
}
$settings = [];
while ($frameLength > 0) {
['key' => $key, 'value' => $value] = \unpack("nkey/Nvalue", $frameBuffer);
if ($value < 0) {
throw new Http2ConnectionException(
"Invalid setting: {$value}",
self::PROTOCOL_ERROR
);
}
$settings[$key] = $value;
$frameBuffer = \substr($frameBuffer, 6);
$frameLength -= 6;
}
$this->handler->handleSettings($settings);
}
/** @see https://http2.github.io/http2-spec/#rfc.section.6.7 */
private function parsePing(string $frameBuffer, int $frameLength, int $frameFlags, int $streamId): void
{
if ($frameLength !== 8) {
$this->throwInvalidFrameSizeError();
}
if ($streamId !== 0) {
$this->throwInvalidNonZeroStreamIdError();
}
if ($frameFlags & self::ACK) {
$this->handler->handlePong($frameBuffer);
} else {
$this->handler->handlePing($frameBuffer);
}
}
/** @see https://http2.github.io/http2-spec/#rfc.section.6.8 */
private function parseGoAway(string $frameBuffer, int $frameLength, int $streamId): void
{
if ($frameLength < 8) {
$this->throwInvalidFrameSizeError();
}
if ($streamId !== 0) {
$this->throwInvalidNonZeroStreamIdError();
}
['last' => $lastId, 'error' => $error] = \unpack("Nlast/Nerror", $frameBuffer);
$this->handler->handleShutdown($lastId & 0x7fffffff, $error);
}
/** @see https://http2.github.io/http2-spec/#rfc.section.6.9 */
private function parseWindowUpdate(string $frameBuffer, int $frameLength, int $streamId): void
{
if ($frameLength !== 4) {
$this->throwInvalidFrameSizeError();
}
$windowSize = \unpack('N', $frameBuffer)[1];
if ($windowSize === 0) {
if ($streamId) {
throw new Http2StreamException(
"Invalid zero window update value",
$streamId,
self::PROTOCOL_ERROR
);
}
throw new Http2ConnectionException("Invalid zero window update value", self::PROTOCOL_ERROR);
}
if ($streamId) {
$this->handler->handleStreamWindowIncrement($streamId, $windowSize);
} else {
$this->handler->handleConnectionWindowIncrement($windowSize);
}
}
/** @see https://http2.github.io/http2-spec/#rfc.section.6.10 */
private function parseContinuation(string $frameBuffer, int $frameFlags, int $streamId): void
{
if ($streamId !== $this->headerStream) {
throw new Http2ConnectionException(
"Invalid CONTINUATION frame stream ID",
self::PROTOCOL_ERROR
);
}
if ($this->headerBuffer === '') {
throw new Http2ConnectionException(
"Unexpected CONTINUATION frame for stream ID " . $this->headerStream,
self::PROTOCOL_ERROR
);
}
$this->pushHeaderBlockFragment($streamId, $frameBuffer);
$ended = $frameFlags & self::END_STREAM;
if ($frameFlags & self::END_HEADERS) {
$this->continuationExpected = false;
$isPush = $this->headerFrameType === self::PUSH_PROMISE;
$pushId = $this->headerStream;
[$pseudo, $headers] = $this->parseHeaderBuffer();
if ($isPush) {
$this->handler->handlePushPromise($streamId, $pushId, $pseudo, $headers);
} else {
$this->handler->handleHeaders($streamId, $pseudo, $headers, $ended);
}
}
if ($ended) {
$this->handler->handleStreamEnd($streamId);
}
}
private function throwInvalidFrameSizeError(): void
{
throw new Http2ConnectionException("Invalid frame length", self::PROTOCOL_ERROR);
}
private function throwInvalidRecursiveDependency(int $streamId): void
{
throw new Http2ConnectionException(
"Invalid recursive dependency for stream {$streamId}",
self::PROTOCOL_ERROR
);
}
private function throwInvalidPaddingError(): void
{
throw new Http2ConnectionException("Padding greater than length", self::PROTOCOL_ERROR);
}
private function throwInvalidZeroStreamIdError(): void
{
throw new Http2ConnectionException("Invalid zero stream ID", self::PROTOCOL_ERROR);
}
private function throwInvalidNonZeroStreamIdError(): void
{
throw new Http2ConnectionException("Invalid non-zero stream ID", self::PROTOCOL_ERROR);
}
}