-
Notifications
You must be signed in to change notification settings - Fork 176
/
http.ts
825 lines (682 loc) · 26 KB
/
http.ts
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
import * as assert from 'assert';
import { LLParse, source } from 'llparse';
import Match = source.node.Match;
import Node = source.node.Node;
import {
CharList,
CONNECTION_TOKEN_CHARS, ERROR, FINISH, FLAGS, H_METHOD_MAP, HEADER_CHARS,
HEADER_STATE, HEX_MAP,
HTTPMode,
MAJOR, METHOD_MAP, METHODS, MINOR, NUM_MAP, SPECIAL_HEADERS, STRICT_TOKEN,
TOKEN, TYPE,
} from './constants';
import { URL } from './url';
type MaybeNode = string | Match | Node;
const NODES: ReadonlyArray<string> = [
'start',
'start_req',
'start_res',
'start_req_or_res',
'req_or_res_method',
'res_http_major',
'res_http_dot',
'res_http_minor',
'res_http_end',
'res_status_code',
'res_status_code_otherwise',
'res_status_start',
'res_status',
'res_line_almost_done',
'req_first_space_before_url',
'req_spaces_before_url',
'req_http_start',
'req_http_major',
'req_http_dot',
'req_http_minor',
'req_http_end',
'header_field_start',
'header_field',
'header_field_colon',
'header_field_general',
'header_field_general_otherwise',
'header_value_discard_ws',
'header_value_discard_ws_almost_done',
'header_value_discard_lws',
'header_value_discard_rws',
'header_value_start',
'header_value',
'header_value_otherwise',
'header_value_lenient',
'header_value_lws',
'header_value_te_chunked',
'header_value_content_length_once',
'header_value_content_length',
'header_value_content_length_ws',
'header_value_connection',
'header_value_connection_ws',
'header_value_connection_token',
'header_value_almost_done',
'headers_almost_done',
'headers_done',
'chunk_size_start',
'chunk_size_digit',
'chunk_size',
'chunk_size_otherwise',
'chunk_size_almost_done',
'chunk_size_almost_done_lf',
'chunk_parameters',
'chunk_data',
'chunk_data_almost_done',
'chunk_data_almost_done_skip',
'chunk_complete',
'body_identity',
'body_identity_eof',
'message_done',
'eof',
'cleanup',
'closed',
'restart',
];
interface ISpanMap {
readonly body: source.Span;
readonly headerField: source.Span;
readonly headerValue: source.Span;
readonly status: source.Span;
}
interface ICallbackMap {
readonly afterHeadersComplete: source.code.Code;
readonly afterMessageComplete: source.code.Code;
readonly beforeHeadersComplete: source.code.Code;
readonly onChunkComplete: source.code.Code;
readonly onChunkHeader: source.code.Code;
readonly onHeadersComplete: source.code.Code;
readonly onMessageBegin: source.code.Code;
readonly onMessageComplete: source.code.Code;
}
interface IMulTargets {
readonly overflow: string | Node;
readonly success: string | Node;
}
interface IMulOptions {
readonly base: number;
readonly max?: number;
readonly signed: boolean;
}
interface IIsEqualTargets {
readonly equal: string | Node;
readonly notEqual: string | Node;
}
export interface IHTTPResult {
readonly entry: Node;
}
export class HTTP {
private readonly url: URL;
private readonly TOKEN: CharList;
private readonly span: ISpanMap;
private readonly callback: ICallbackMap;
private readonly nodes: Map<string, Match> = new Map();
constructor(private readonly llparse: LLParse,
private readonly mode: HTTPMode = 'loose') {
const p = llparse;
this.url = new URL(p, mode);
this.TOKEN = mode === 'strict' ? STRICT_TOKEN : TOKEN;
this.span = {
body: p.span(p.code.span('llhttp__on_body')),
headerField: p.span(p.code.span('llhttp__on_header_field')),
headerValue: p.span(p.code.span('llhttp__on_header_value')),
status: p.span(p.code.span('llhttp__on_status')),
};
/* tslint:disable:object-literal-sort-keys */
this.callback = {
// User callbacks
onHeadersComplete: p.code.match('llhttp__on_headers_complete'),
onMessageBegin: p.code.match('llhttp__on_message_begin'),
onMessageComplete: p.code.match('llhttp__on_message_complete'),
onChunkHeader: p.code.match('llhttp__on_chunk_header'),
onChunkComplete: p.code.match('llhttp__on_chunk_complete'),
// Internal callbacks `src/http.c`
beforeHeadersComplete:
p.code.match('llhttp__before_headers_complete'),
afterHeadersComplete: p.code.match('llhttp__after_headers_complete'),
afterMessageComplete: p.code.match('llhttp__after_message_complete'),
};
/* tslint:enable:object-literal-sort-keys */
NODES.forEach((name) => this.nodes.set(name, p.node(name) as Match));
}
public build(): IHTTPResult {
const p = this.llparse;
p.property('i64', 'content_length');
p.property('i8', 'type');
p.property('i8', 'method');
p.property('i8', 'http_major');
p.property('i8', 'http_minor');
p.property('i8', 'header_state');
p.property('i16', 'flags');
p.property('i8', 'upgrade');
p.property('i16', 'status_code');
p.property('i8', 'finish');
// Verify defaults
assert.strictEqual(FINISH.SAFE, 0);
assert.strictEqual(TYPE.BOTH, 0);
// Shared settings (to be used in C wrapper)
p.property('ptr', 'settings');
this.buildLine();
this.buildHeaders();
return {
entry: this.node('start'),
};
}
private buildLine(): void {
const p = this.llparse;
const span = this.span;
const n = (name: string): Match => this.node<Match>(name);
const url = this.url.build();
const switchType = this.load('type', {
[TYPE.REQUEST]: n('start_req'),
[TYPE.RESPONSE]: n('start_res'),
}, n('start_req_or_res'));
n('start')
.match([ '\r', '\n' ], n('start'))
.otherwise(this.update('finish', FINISH.UNSAFE,
this.invokePausable('on_message_begin',
ERROR.CB_MESSAGE_BEGIN, switchType)));
n('start_req_or_res')
.peek('H', n('req_or_res_method'))
.otherwise(this.update('type', TYPE.REQUEST, 'start_req'));
n('req_or_res_method')
.select(H_METHOD_MAP, this.store('method',
this.update('type', TYPE.REQUEST, 'req_first_space_before_url')))
.match('HTTP/', this.update('type', TYPE.RESPONSE, 'res_http_major'))
.otherwise(p.error(ERROR.INVALID_CONSTANT, 'Invalid word encountered'));
// Response
n('start_res')
.match('HTTP/', n('res_http_major'))
.otherwise(p.error(ERROR.INVALID_CONSTANT, 'Expected HTTP/'));
n('res_http_major')
.select(MAJOR, this.store('http_major', 'res_http_dot'))
.otherwise(p.error(ERROR.INVALID_VERSION, 'Invalid major version'));
n('res_http_dot')
.match('.', n('res_http_minor'))
.otherwise(p.error(ERROR.INVALID_VERSION, 'Expected dot'));
n('res_http_minor')
.select(MINOR, this.store('http_minor', 'res_http_end'))
.otherwise(p.error(ERROR.INVALID_VERSION, 'Invalid minor version'));
n('res_http_end')
.match(' ', this.update('status_code', 0, 'res_status_code'))
.otherwise(p.error(ERROR.INVALID_VERSION,
'Expected space after version'));
n('res_status_code')
.select(NUM_MAP, this.mulAdd('status_code', {
overflow: p.error(ERROR.INVALID_STATUS, 'Response overflow'),
success: 'res_status_code',
}, { base: 10, signed: false, max: 999 }))
.otherwise(n('res_status_code_otherwise'));
n('res_status_code_otherwise')
.match(' ', n('res_status_start'))
.peek([ '\r', '\n' ], n('res_status_start'))
.otherwise(p.error(ERROR.INVALID_STATUS, 'Invalid response status'));
n('res_status_start')
.match('\r', n('res_line_almost_done'))
.match('\n', n('header_field_start'))
.otherwise(span.status.start(n('res_status')));
n('res_status')
.peek('\r', span.status.end().skipTo(n('res_line_almost_done')))
.peek('\n', span.status.end().skipTo(n('header_field_start')))
.skipTo(n('res_status'));
if (this.mode === 'strict') {
n('res_line_almost_done')
.match('\n', n('header_field_start'))
.otherwise(p.error(ERROR.STRICT, 'Expected LF after CR'));
} else {
n('res_line_almost_done')
.skipTo(n('header_field_start'));
}
// Request
n('start_req')
.select(METHOD_MAP,
this.store('method', 'req_first_space_before_url'))
.otherwise(p.error(ERROR.INVALID_METHOD, 'Invalid method encountered'));
n('req_first_space_before_url')
.match(' ', n('req_spaces_before_url'))
.otherwise(p.error(ERROR.INVALID_METHOD, 'Expected space after method'));
n('req_spaces_before_url')
.match(' ', n('req_spaces_before_url'))
.otherwise(this.isEqual('method', METHODS.CONNECT, {
equal: url.entry.connect,
notEqual: url.entry.normal,
}));
url.exit.toHTTP
.otherwise(n('req_http_start'));
url.exit.toHTTP09
.otherwise(
this.update('http_major', 0,
this.update('http_minor', 9, 'header_field_start')),
);
const isSource = this.isEqual('method', METHODS.SOURCE, {
equal: n('req_http_major'),
notEqual: p.error(ERROR.INVALID_CONSTANT,
'Expected SOURCE method for ICE/x.x request'),
});
n('req_http_start')
.match('HTTP/', n('req_http_major'))
.match('ICE/', isSource)
.match(' ', n('req_http_start'))
.otherwise(p.error(ERROR.INVALID_CONSTANT, 'Expected HTTP/'));
n('req_http_major')
.select(MAJOR, this.store('http_major', 'req_http_dot'))
.otherwise(p.error(ERROR.INVALID_VERSION, 'Invalid major version'));
n('req_http_dot')
.match('.', n('req_http_minor'))
.otherwise(p.error(ERROR.INVALID_VERSION, 'Expected dot'));
n('req_http_minor')
.select(MINOR, this.store('http_minor', 'req_http_end'))
.otherwise(p.error(ERROR.INVALID_VERSION, 'Invalid minor version'));
n('req_http_end')
.match([ '\r\n', '\n' ], n('header_field_start'))
.otherwise(p.error(ERROR.INVALID_VERSION, 'Expected CRLF after version'));
}
private buildHeaders(): void {
this.buildHeaderField();
this.buildHeaderValue();
}
private buildHeaderField(): void {
const p = this.llparse;
const span = this.span;
const n = (name: string): Match => this.node<Match>(name);
n('header_field_start')
.match('\r', n('headers_almost_done'))
/* they might be just sending \n instead of \r\n so this would be
* the second \n to denote the end of headers*/
.peek('\n', n('headers_almost_done'))
.otherwise(span.headerField.start(n('header_field')));
n('header_field')
.transform(p.transform.toLowerUnsafe())
// Match headers that need special treatment
.select(SPECIAL_HEADERS, this.store('header_state', 'header_field_colon'))
.otherwise(this.resetHeaderState('header_field_general'));
n('header_field_colon')
.match(' ', n('header_field_colon'))
.peek(':', span.headerField.end().skipTo(n('header_value_discard_ws')))
// Fallback to general header, there're additional characters:
// `Connection-Duration` instead of `Connection` and so on.
.otherwise(this.resetHeaderState('header_field_general'));
n('header_field_general')
.match(this.TOKEN, n('header_field_general'))
.otherwise(n('header_field_general_otherwise'));
// Just a performance optimization, split the node so that the fast case
// remains in `header_field_general`
n('header_field_general_otherwise')
.peek(':', span.headerField.end().skipTo(n('header_value_discard_ws')))
.otherwise(p.error(ERROR.INVALID_HEADER_TOKEN, 'Invalid header token'));
}
private buildHeaderValue(): void {
const p = this.llparse;
const span = this.span;
const callback = this.callback;
const n = (name: string): Match => this.node<Match>(name);
const fallback = this.resetHeaderState('header_value');
n('header_value_discard_ws')
.match([ ' ', '\t' ], n('header_value_discard_ws'))
.match('\r', n('header_value_discard_ws_almost_done'))
.match('\n', n('header_value_discard_lws'))
.otherwise(span.headerValue.start(n('header_value_start')));
if (this.mode === 'strict') {
n('header_value_discard_ws_almost_done')
.match('\n', n('header_value_discard_lws'))
.otherwise(p.error(ERROR.STRICT, 'Expected LF after CR'));
} else {
n('header_value_discard_ws_almost_done').skipTo(
n('header_value_discard_lws'));
}
n('header_value_discard_lws')
.match([ ' ', '\t' ], n('header_value_discard_ws'))
.otherwise(this.setHeaderFlags(
this.emptySpan(span.headerValue, 'header_field_start')));
n('header_value_start')
.otherwise(this.load('header_state', {
[HEADER_STATE.UPGRADE]: this.setFlag(FLAGS.UPGRADE, fallback),
[HEADER_STATE.TRANSFER_ENCODING]: n('header_value_te_chunked'),
[HEADER_STATE.CONTENT_LENGTH]: n('header_value_content_length_once'),
[HEADER_STATE.CONNECTION]: n('header_value_connection'),
}, 'header_value'));
n('header_value_te_chunked')
.transform(p.transform.toLowerUnsafe())
.match(
'chunked',
this.update('header_state', HEADER_STATE.TRANSFER_ENCODING_CHUNKED,
'header_value_discard_rws'),
)
.peek([ ' ', '\r', '\n' ], n('header_value_discard_rws'))
.otherwise(fallback);
const invalidContentLength = (reason: string): Node => {
// End span for easier testing
// TODO(indutny): minimize code size
return span.headerValue.end()
.otherwise(p.error(ERROR.INVALID_CONTENT_LENGTH, reason));
};
n('header_value_content_length_once')
.otherwise(this.testFlags(FLAGS.CONTENT_LENGTH, {
0: n('header_value_content_length'),
}, p.error(ERROR.UNEXPECTED_CONTENT_LENGTH, 'Duplicate Content-Length')));
n('header_value_content_length')
.select(NUM_MAP, this.mulAdd('content_length', {
overflow: invalidContentLength('Content-Length overflow'),
success: 'header_value_content_length',
}))
.otherwise(n('header_value_content_length_ws'));
n('header_value_content_length_ws')
.match(' ', n('header_value_content_length_ws'))
.peek([ '\r', '\n' ],
this.setFlag(FLAGS.CONTENT_LENGTH, 'header_value_discard_rws'))
.otherwise(invalidContentLength('Invalid character in Content-Length'));
n('header_value_connection')
.transform(p.transform.toLowerUnsafe())
// TODO(indutny): extra node for token back-edge?
// Skip lws
.match([ ' ', '\t' ], n('header_value_connection'))
.match(
'close',
this.update('header_state', HEADER_STATE.CONNECTION_CLOSE,
'header_value_connection_ws'),
)
.match(
'upgrade',
this.update('header_state', HEADER_STATE.CONNECTION_UPGRADE,
'header_value_connection_ws'),
)
.match(
'keep-alive',
this.update('header_state', HEADER_STATE.CONNECTION_KEEP_ALIVE,
'header_value_connection_ws'),
)
.otherwise(n('header_value_connection_token'));
n('header_value_connection_ws')
.match(',', this.setHeaderFlags('header_value_connection'))
.match(' ', n('header_value_connection_ws'))
.peek([ '\r', '\n' ], n('header_value_otherwise'))
.otherwise(this.resetHeaderState('header_value_connection_token'));
n('header_value_connection_token')
.match(',', n('header_value_connection'))
.match(CONNECTION_TOKEN_CHARS,
n('header_value_connection_token'))
.otherwise(n('header_value_otherwise'));
n('header_value_discard_rws')
.match(' ', n('header_value_discard_rws'))
.peek([ '\r', '\n' ], n('header_value_otherwise'))
.otherwise(fallback);
// Split for performance reasons
n('header_value')
.match(HEADER_CHARS, n('header_value'))
.otherwise(n('header_value_otherwise'));
const checkLenient = this.testFlags(FLAGS.LENIENT, {
1: n('header_value_lenient'),
}, p.error(ERROR.INVALID_HEADER_TOKEN, 'Invalid header value char'));
n('header_value_otherwise')
.peek('\r', span.headerValue.end().skipTo(n('header_value_almost_done')))
.peek('\n', span.headerValue.end(n('header_value_almost_done')))
.otherwise(checkLenient);
n('header_value_lenient')
.peek('\r', span.headerValue.end().skipTo(n('header_value_almost_done')))
.peek('\n', span.headerValue.end(n('header_value_almost_done')))
.skipTo(n('header_value_lenient'));
n('header_value_almost_done')
.match('\n', n('header_value_lws'))
.otherwise(p.error(ERROR.LF_EXPECTED,
'Missing expected LF after header value'));
n('header_value_lws')
.peek([ ' ', '\t' ], span.headerValue.start(n('header_value_start')))
.otherwise(this.setHeaderFlags('header_field_start'));
const checkTrailing = this.testFlags(FLAGS.TRAILING, {
1: this.invokePausable('on_chunk_complete',
ERROR.CB_CHUNK_COMPLETE, 'message_done'),
});
if (this.mode === 'strict') {
n('headers_almost_done')
.match('\n', checkTrailing)
.otherwise(p.error(ERROR.STRICT, 'Expected LF after headers'));
} else {
n('headers_almost_done')
.skipTo(checkTrailing);
}
/* Cannot use chunked encoding and a content-length header together
per the HTTP specification. */
const ENCODING_CONFLICT = FLAGS.CHUNKED | FLAGS.CONTENT_LENGTH;
const checkEncConflict = this.testFlags(ENCODING_CONFLICT, {
1: p.error(ERROR.UNEXPECTED_CONTENT_LENGTH,
'Content-Length can\'t be present with chunked encoding'),
});
checkTrailing.otherwise(checkEncConflict);
// Set `upgrade` if needed
const beforeHeadersComplete = p.invoke(callback.beforeHeadersComplete);
/* Here we call the headers_complete callback. This is somewhat
* different than other callbacks because if the user returns 1, we
* will interpret that as saying that this message has no body. This
* is needed for the annoying case of recieving a response to a HEAD
* request.
*
* We'd like to use CALLBACK_NOTIFY_NOADVANCE() here but we cannot, so
* we have to simulate it by handling a change in errno below.
*/
const onHeadersComplete = p.invoke(callback.onHeadersComplete, {
0: n('headers_done'),
1: this.setFlag(FLAGS.SKIPBODY, 'headers_done'),
2: this.update('upgrade', 1,
this.setFlag(FLAGS.SKIPBODY, 'headers_done')),
[ERROR.PAUSED]: this.pause('Paused by on_headers_complete',
'headers_done'),
}, p.error(ERROR.CB_HEADERS_COMPLETE, 'User callback error'));
checkEncConflict.otherwise(beforeHeadersComplete);
beforeHeadersComplete.otherwise(onHeadersComplete);
const upgradePause = p.pause(ERROR.PAUSED_UPGRADE,
'Pause on CONNECT/Upgrade');
const afterHeadersComplete = p.invoke(callback.afterHeadersComplete, {
1: this.invokePausable('on_message_complete',
ERROR.CB_MESSAGE_COMPLETE, upgradePause),
2: n('chunk_size_start'),
3: n('body_identity'),
4: n('body_identity_eof'),
});
n('headers_done')
.otherwise(afterHeadersComplete);
upgradePause
.otherwise(n('cleanup'));
afterHeadersComplete
.otherwise(this.invokePausable('on_message_complete',
ERROR.CB_MESSAGE_COMPLETE, 'cleanup'));
n('body_identity')
.otherwise(span.body.start()
.otherwise(p.consume('content_length').otherwise(
span.body.end(n('message_done')))));
n('body_identity_eof')
.otherwise(
this.update('finish', FINISH.SAFE_WITH_CB, span.body.start(n('eof'))));
// Just read everything until EOF
n('eof')
.skipTo(n('eof'));
n('chunk_size_start')
.otherwise(this.update('content_length', 0, 'chunk_size_digit'));
const addContentLength = this.mulAdd('content_length', {
overflow: p.error(ERROR.INVALID_CHUNK_SIZE, 'Chunk size overflow'),
success: 'chunk_size',
}, { signed: false, base: 0x10 });
n('chunk_size_digit')
.select(HEX_MAP, addContentLength)
.otherwise(p.error(ERROR.INVALID_CHUNK_SIZE,
'Invalid character in chunk size'));
n('chunk_size')
.select(HEX_MAP, addContentLength)
.otherwise(n('chunk_size_otherwise'));
n('chunk_size_otherwise')
.match('\r', n('chunk_size_almost_done'))
.match([ ';', ' ' ], n('chunk_parameters'))
.otherwise(p.error(ERROR.INVALID_CHUNK_SIZE,
'Invalid character in chunk size'));
// just ignore this.
n('chunk_parameters')
.match('\r', n('chunk_size_almost_done'))
.skipTo(n('chunk_parameters'));
if (this.mode === 'strict') {
n('chunk_size_almost_done')
.match('\n', n('chunk_size_almost_done_lf'))
.otherwise(p.error(ERROR.STRICT, 'Expected LF after chunk size'));
} else {
n('chunk_size_almost_done')
.skipTo(n('chunk_size_almost_done_lf'));
}
const toChunk = this.isEqual('content_length', 0, {
equal: this.setFlag(FLAGS.TRAILING, 'header_field_start'),
notEqual: 'chunk_data',
});
n('chunk_size_almost_done_lf')
.otherwise(this.invokePausable('on_chunk_header',
ERROR.CB_CHUNK_HEADER, toChunk));
n('chunk_data')
.otherwise(span.body.start()
.otherwise(p.consume('content_length').otherwise(
span.body.end(n('chunk_data_almost_done')))));
if (this.mode === 'strict') {
n('chunk_data_almost_done')
.match('\r\n', n('chunk_complete'))
.otherwise(p.error(ERROR.STRICT, 'Expected CRLF after chunk'));
} else {
n('chunk_data_almost_done')
.skipTo(n('chunk_data_almost_done_skip'));
}
n('chunk_data_almost_done_skip')
.skipTo(n('chunk_complete'));
n('chunk_complete')
.otherwise(this.invokePausable('on_chunk_complete',
ERROR.CB_CHUNK_COMPLETE, 'chunk_size_start'));
const upgradeAfterDone = this.isEqual('upgrade', 1, {
// Exit, the rest of the message is in a different protocol.
equal: upgradePause,
// Restart
notEqual: 'cleanup',
});
n('message_done')
.otherwise(this.invokePausable('on_message_complete',
ERROR.CB_MESSAGE_COMPLETE, upgradeAfterDone));
// Check if we'd like to keep-alive
if (this.mode === 'strict') {
n('cleanup')
.otherwise(p.invoke(callback.afterMessageComplete, {
1: n('restart'),
}, this.update('finish', FINISH.SAFE, n('closed'))));
} else {
n('cleanup')
.otherwise(p.invoke(callback.afterMessageComplete, n('restart')));
}
n('closed')
.match([ '\r', '\n' ], n('closed'))
.skipTo(p.error(ERROR.CLOSED_CONNECTION,
'Data after `Connection: close`'));
n('restart')
.otherwise(this.update('finish', FINISH.SAFE, n('start')));
}
private node<T extends Node>(name: string | T): T {
if (name instanceof Node) {
return name;
}
assert(this.nodes.has(name), `Unknown node with name "${name}"`);
return this.nodes.get(name)! as any;
}
private load(field: string, map: { [key: number]: Node },
next?: string | Node): Node {
const p = this.llparse;
const res = p.invoke(p.code.load(field), map);
if (next !== undefined) {
res.otherwise(this.node(next));
}
return res;
}
private store(field: string, next?: string | Node): Node {
const p = this.llparse;
const res = p.invoke(p.code.store(field));
if (next !== undefined) {
res.otherwise(this.node(next));
}
return res;
}
private update(field: string, value: number, next?: string | Node): Node {
const p = this.llparse;
const res = p.invoke(p.code.update(field, value));
if (next !== undefined) {
res.otherwise(this.node(next));
}
return res;
}
private resetHeaderState(next: string | Node): Node {
return this.update('header_state', HEADER_STATE.GENERAL, next);
}
private emptySpan(span: source.Span, next: string | Node): Node {
return span.start(span.end(this.node(next)));
}
private setFlag(flag: FLAGS, next: string | Node): Node {
const p = this.llparse;
return p.invoke(p.code.or('flags', flag), this.node(next));
}
private testFlags(flag: FLAGS, map: { [key: number]: Node },
next?: string | Node): Node {
const p = this.llparse;
const res = p.invoke(p.code.test('flags', flag), map);
if (next !== undefined) {
res.otherwise(this.node(next));
}
return res;
}
private setHeaderFlags(next: string | Node): Node {
const HS = HEADER_STATE;
const F = FLAGS;
const toConnection =
this.update('header_state', HEADER_STATE.CONNECTION, next);
return this.load('header_state', {
[HS.CONNECTION_KEEP_ALIVE]:
this.setFlag(F.CONNECTION_KEEP_ALIVE, toConnection),
[HS.CONNECTION_CLOSE]: this.setFlag(F.CONNECTION_CLOSE, toConnection),
[HS.CONNECTION_UPGRADE]: this.setFlag(F.CONNECTION_UPGRADE, toConnection),
[HS.TRANSFER_ENCODING_CHUNKED]: this.setFlag(F.CHUNKED, next),
}, this.node(next));
}
private mulAdd(field: string, targets: IMulTargets,
options: IMulOptions = { base: 10, signed: false }): Node {
const p = this.llparse;
return p.invoke(p.code.mulAdd(field, options), {
1: this.node(targets.overflow),
}, this.node(targets.success));
}
private isEqual(field: string, value: number, map: IIsEqualTargets) {
const p = this.llparse;
return p.invoke(p.code.isEqual(field, value), {
0: this.node(map.notEqual),
}, this.node(map.equal));
}
private pause(msg: string, next?: string | Node) {
const p = this.llparse;
const res = p.pause(ERROR.PAUSED, msg);
if (next !== undefined) {
res.otherwise(this.node(next));
}
return res;
}
// TODO(indutny): use type for `name`
private invokePausable(name: string, errorCode: ERROR, next: string | Node)
: Node {
let cb;
if (name === 'on_message_begin') {
cb = this.callback.onMessageBegin;
} else if (name === 'on_message_complete') {
cb = this.callback.onMessageComplete;
} else if (name === 'on_chunk_header') {
cb = this.callback.onChunkHeader;
} else if (name === 'on_chunk_complete') {
cb = this.callback.onChunkComplete;
} else {
throw new Error('Unknown callback: ' + name);
}
const p = this.llparse;
return p.invoke(cb, {
0: this.node(next),
[ERROR.PAUSED]: this.pause(`${name} pause`, next),
}, p.error(errorCode, `\`${name}\` callback error`));
}
}