-
Notifications
You must be signed in to change notification settings - Fork 29.8k
/
core.js
2603 lines (2281 loc) Β· 82.4 KB
/
core.js
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
'use strict';
/* eslint-disable no-use-before-define */
require('internal/util').assertCrypto();
const binding = process.binding('http2');
const assert = require('assert');
const Buffer = require('buffer').Buffer;
const EventEmitter = require('events');
const net = require('net');
const tls = require('tls');
const util = require('util');
const fs = require('fs');
const errors = require('internal/errors');
const { Duplex } = require('stream');
const { URL } = require('url');
const { onServerStream,
Http2ServerRequest,
Http2ServerResponse,
} = require('internal/http2/compat');
const { utcDate } = require('internal/http');
const { promisify } = require('internal/util');
const { isUint8Array } = require('internal/util/types');
const { _connectionListener: httpConnectionListener } = require('http');
const { createPromise, promiseResolve } = process.binding('util');
const debug = util.debuglog('http2');
const {
assertIsObject,
assertValidPseudoHeaderResponse,
assertValidPseudoHeaderTrailer,
assertWithinRange,
getDefaultSettings,
getSessionState,
getSettings,
getStreamState,
isPayloadMeaningless,
mapToHeaders,
NghttpError,
sessionName,
toHeaderObject,
updateOptionsBuffer,
updateSettingsBuffer
} = require('internal/http2/util');
const {
_unrefActive,
enroll,
unenroll
} = require('timers');
const { WriteWrap } = process.binding('stream_wrap');
const { constants } = binding;
const NETServer = net.Server;
const TLSServer = tls.Server;
const kInspect = require('internal/util').customInspectSymbol;
const kAuthority = Symbol('authority');
const kDestroySocket = Symbol('destroy-socket');
const kHandle = Symbol('handle');
const kID = Symbol('id');
const kInit = Symbol('init');
const kLocalSettings = Symbol('local-settings');
const kOptions = Symbol('options');
const kOwner = Symbol('owner');
const kProceed = Symbol('proceed');
const kProtocol = Symbol('protocol');
const kRemoteSettings = Symbol('remote-settings');
const kServer = Symbol('server');
const kSession = Symbol('session');
const kSocket = Symbol('socket');
const kState = Symbol('state');
const kType = Symbol('type');
const kDefaultSocketTimeout = 2 * 60 * 1000;
const kRenegTest = /TLS session renegotiation disabled for this socket/;
const {
paddingBuffer,
PADDING_BUF_FRAME_LENGTH,
PADDING_BUF_MAX_PAYLOAD_LENGTH,
PADDING_BUF_RETURN_VALUE
} = binding;
const {
NGHTTP2_CANCEL,
NGHTTP2_DEFAULT_WEIGHT,
NGHTTP2_FLAG_END_STREAM,
NGHTTP2_HCAT_PUSH_RESPONSE,
NGHTTP2_HCAT_RESPONSE,
NGHTTP2_INTERNAL_ERROR,
NGHTTP2_NO_ERROR,
NGHTTP2_PROTOCOL_ERROR,
NGHTTP2_REFUSED_STREAM,
NGHTTP2_SESSION_CLIENT,
NGHTTP2_SESSION_SERVER,
NGHTTP2_ERR_NOMEM,
NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE,
NGHTTP2_ERR_INVALID_ARGUMENT,
NGHTTP2_ERR_STREAM_CLOSED,
HTTP2_HEADER_AUTHORITY,
HTTP2_HEADER_DATE,
HTTP2_HEADER_METHOD,
HTTP2_HEADER_PATH,
HTTP2_HEADER_SCHEME,
HTTP2_HEADER_STATUS,
HTTP2_HEADER_CONTENT_LENGTH,
NGHTTP2_SETTINGS_HEADER_TABLE_SIZE,
NGHTTP2_SETTINGS_ENABLE_PUSH,
NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS,
NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE,
NGHTTP2_SETTINGS_MAX_FRAME_SIZE,
NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE,
HTTP2_METHOD_GET,
HTTP2_METHOD_HEAD,
HTTP2_METHOD_CONNECT,
HTTP_STATUS_CONTINUE,
HTTP_STATUS_RESET_CONTENT,
HTTP_STATUS_OK,
HTTP_STATUS_NO_CONTENT,
HTTP_STATUS_NOT_MODIFIED,
HTTP_STATUS_SWITCHING_PROTOCOLS,
STREAM_OPTION_EMPTY_PAYLOAD,
STREAM_OPTION_GET_TRAILERS
} = constants;
// Top level to avoid creating a closure
function emit(self, ...args) {
self.emit(...args);
}
// Called when a new block of headers has been received for a given
// stream. The stream may or may not be new. If the stream is new,
// create the associated Http2Stream instance and emit the 'stream'
// event. If the stream is not new, emit the 'headers' event to pass
// the block of headers on.
function onSessionHeaders(id, cat, flags, headers) {
const owner = this[kOwner];
_unrefActive(owner);
debug(`[${sessionName(owner[kType])}] headers were received on ` +
`stream ${id}: ${cat}`);
const streams = owner[kState].streams;
const endOfStream = !!(flags & NGHTTP2_FLAG_END_STREAM);
let stream = streams.get(id);
// Convert the array of header name value pairs into an object
const obj = toHeaderObject(headers);
if (stream === undefined) {
// owner[kType] can be only one of two possible values
if (owner[kType] === NGHTTP2_SESSION_SERVER) {
stream = new ServerHttp2Stream(owner, id,
{ readable: !endOfStream },
obj);
if (obj[HTTP2_HEADER_METHOD] === HTTP2_METHOD_HEAD) {
// For head requests, there must not be a body...
// end the writable side immediately.
stream.end();
stream[kState].headRequest = true;
}
} else {
stream = new ClientHttp2Stream(owner, id, { readable: !endOfStream });
}
streams.set(id, stream);
process.nextTick(emit, owner, 'stream', stream, obj, flags, headers);
} else {
let event;
const status = obj[HTTP2_HEADER_STATUS];
if (cat === NGHTTP2_HCAT_RESPONSE) {
if (!endOfStream &&
status !== undefined &&
status >= 100 &&
status < 200) {
event = 'headers';
} else {
event = 'response';
}
} else if (cat === NGHTTP2_HCAT_PUSH_RESPONSE) {
event = 'push';
} else { // cat === NGHTTP2_HCAT_HEADERS:
if (!endOfStream && status !== undefined && status >= 200) {
event = 'response';
} else {
event = endOfStream ? 'trailers' : 'headers';
}
}
debug(`[${sessionName(owner[kType])}] emitting stream '${event}' event`);
process.nextTick(emit, stream, event, obj, flags, headers);
}
if (endOfStream) {
stream.push(null);
}
}
// Called to determine if there are trailers to be sent at the end of a
// Stream. The 'getTrailers' callback is invoked and passed a holder object.
// The trailers to return are set on that object by the handler. Once the
// event handler returns, those are sent off for processing. Note that this
// is a necessarily synchronous operation. We need to know immediately if
// there are trailing headers to send.
function onSessionTrailers(id) {
const owner = this[kOwner];
debug(`[${sessionName(owner[kType])}] checking for trailers`);
const streams = owner[kState].streams;
const stream = streams.get(id);
// It should not be possible for the stream not to exist at this point.
// If it does not exist, there is something very very wrong.
assert(stream !== undefined,
'Internal HTTP/2 Failure. Stream does not exist. Please ' +
'report this as a bug in Node.js');
const getTrailers = stream[kState].getTrailers;
// We should not have been able to get here at all if getTrailers
// was not a function, and there's no code that could have changed
// it between there and here.
assert.strictEqual(typeof getTrailers, 'function');
const trailers = Object.create(null);
getTrailers.call(stream, trailers);
const headersList = mapToHeaders(trailers, assertValidPseudoHeaderTrailer);
if (!Array.isArray(headersList)) {
process.nextTick(emit, stream, 'error', headersList);
return;
}
return headersList;
}
// Called when the stream is closed. The streamClosed event is emitted on the
// Http2Stream instance. Note that this event is distinctly different than the
// require('stream') interface 'close' event which deals with the state of the
// Readable and Writable sides of the Duplex.
function onSessionStreamClose(id, code) {
const owner = this[kOwner];
debug(`[${sessionName(owner[kType])}] session is closing the stream ` +
`${id}: ${code}`);
const stream = owner[kState].streams.get(id);
if (stream === undefined)
return;
_unrefActive(owner);
// Set the rst state for the stream
abort(stream);
const state = stream[kState];
state.rst = true;
state.rstCode = code;
if (state.fd !== undefined) {
debug(`Closing fd ${state.fd} for stream ${id}`);
fs.close(state.fd, afterFDClose.bind(stream));
}
setImmediate(stream.destroy.bind(stream));
}
function afterFDClose(err) {
if (err)
process.nextTick(emit, this, 'error', err);
}
// Called when an error event needs to be triggered
function onSessionError(error) {
const owner = this[kOwner];
_unrefActive(owner);
process.nextTick(emit, owner, 'error', error);
}
// Receives a chunk of data for a given stream and forwards it on
// to the Http2Stream Duplex for processing.
function onSessionRead(nread, buf, handle) {
const owner = this[kOwner];
const streams = owner[kState].streams;
const id = handle.id;
const stream = streams.get(id);
// It should not be possible for the stream to not exist at this point.
// If it does not, something is very very wrong
assert(stream !== undefined,
'Internal HTTP/2 Failure. Stream does not exist. Please ' +
'report this as a bug in Node.js');
const state = stream[kState];
_unrefActive(owner); // Reset the session timeout timer
_unrefActive(stream); // Reset the stream timeout timer
if (nread >= 0 && !stream.destroyed) {
if (!stream.push(buf)) {
this.streamReadStop(id);
state.reading = false;
}
} else {
// Last chunk was received. End the readable side.
stream.push(null);
}
}
// Called when the remote peer settings have been updated.
// Resets the cached settings.
function onSettings(ack) {
const owner = this[kOwner];
debug(`[${sessionName(owner[kType])}] new settings received`);
_unrefActive(owner);
let event = 'remoteSettings';
if (ack) {
if (owner[kState].pendingAck > 0)
owner[kState].pendingAck--;
owner[kLocalSettings] = undefined;
event = 'localSettings';
} else {
owner[kRemoteSettings] = undefined;
}
// Only emit the event if there are listeners registered
if (owner.listenerCount(event) > 0) {
const settings = event === 'localSettings' ?
owner.localSettings : owner.remoteSettings;
process.nextTick(emit, owner, event, settings);
}
}
// If the stream exists, an attempt will be made to emit an event
// on the stream object itself. Otherwise, forward it on to the
// session (which may, in turn, forward it on to the server)
function onPriority(id, parent, weight, exclusive) {
const owner = this[kOwner];
debug(`[${sessionName(owner[kType])}] priority advisement for stream ` +
`${id}: \n parent: ${parent},\n weight: ${weight},\n` +
` exclusive: ${exclusive}`);
_unrefActive(owner);
const streams = owner[kState].streams;
const stream = streams.get(id);
const emitter = stream === undefined ? owner : stream;
process.nextTick(emit, emitter, 'priority', id, parent, weight, exclusive);
}
function emitFrameError(self, id, type, code) {
if (!self.emit('frameError', type, code, id)) {
const err = new errors.Error('ERR_HTTP2_FRAME_ERROR', type, code, id);
err.errno = code;
self.emit('error', err);
}
}
// Called by the native layer when an error has occurred sending a
// frame. This should be exceedingly rare.
function onFrameError(id, type, code) {
const owner = this[kOwner];
debug(`[${sessionName(owner[kType])}] error sending frame type ` +
`${type} on stream ${id}, code: ${code}`);
_unrefActive(owner);
const streams = owner[kState].streams;
const stream = streams.get(id);
const emitter = stream !== undefined ? stream : owner;
process.nextTick(emitFrameError, emitter, id, type, code);
}
function emitGoaway(self, code, lastStreamID, buf) {
self.emit('goaway', code, lastStreamID, buf);
// Tear down the session or destroy
const state = self[kState];
if (state.destroying || state.destroyed)
return;
if (!state.shuttingDown && !state.shutdown) {
self.shutdown({}, self.destroy.bind(self));
} else {
self.destroy();
}
}
// Called by the native layer when a goaway frame has been received
function onGoawayData(code, lastStreamID, buf) {
const owner = this[kOwner];
debug(`[${sessionName(owner[kType])}] goaway data received`);
process.nextTick(emitGoaway, owner, code, lastStreamID, buf);
}
// Returns the padding to use per frame. The selectPadding callback is set
// on the options. It is invoked with two arguments, the frameLen, and the
// maxPayloadLen. The method must return a numeric value within the range
// frameLen <= n <= maxPayloadLen.
function onSelectPadding(fn) {
assert(typeof fn === 'function',
'options.selectPadding must be a function. Please report this as a ' +
'bug in Node.js');
return function getPadding() {
debug('fetching padding for frame');
const frameLen = paddingBuffer[PADDING_BUF_FRAME_LENGTH];
const maxFramePayloadLen = paddingBuffer[PADDING_BUF_MAX_PAYLOAD_LENGTH];
paddingBuffer[PADDING_BUF_RETURN_VALUE] =
Math.min(maxFramePayloadLen,
Math.max(frameLen,
fn(frameLen,
maxFramePayloadLen) | 0));
};
}
// When a ClientHttp2Session is first created, the socket may not yet be
// connected. If request() is called during this time, the actual request
// will be deferred until the socket is ready to go.
function requestOnConnect(headers, options) {
const session = this[kSession];
debug(`[${sessionName(session[kType])}] connected.. initializing request`);
const streams = session[kState].streams;
validatePriorityOptions(options);
const handle = session[kHandle];
const headersList = mapToHeaders(headers);
if (!Array.isArray(headersList)) {
process.nextTick(emit, this, 'error', headersList);
return;
}
let streamOptions = 0;
if (options.endStream)
streamOptions |= STREAM_OPTION_EMPTY_PAYLOAD;
if (typeof options.getTrailers === 'function') {
streamOptions |= STREAM_OPTION_GET_TRAILERS;
this[kState].getTrailers = options.getTrailers;
}
// ret will be either the reserved stream ID (if positive)
// or an error code (if negative)
const ret = handle.submitRequest(headersList,
streamOptions,
options.parent | 0,
options.weight | 0,
!!options.exclusive);
// In an error condition, one of three possible response codes will be
// possible:
// * NGHTTP2_ERR_NOMEM - Out of memory, this should be fatal to the process.
// * NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE - Maximum stream ID is reached, this
// is fatal for the session
// * NGHTTP2_ERR_INVALID_ARGUMENT - Stream was made dependent on itself, this
// impacts on this stream.
// For the first two, emit the error on the session,
// For the third, emit the error on the stream, it will bubble up to the
// session if not handled.
let err;
switch (ret) {
case NGHTTP2_ERR_NOMEM:
err = new errors.Error('ERR_OUTOFMEMORY');
process.nextTick(emit, session, 'error', err);
break;
case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE:
err = new errors.Error('ERR_HTTP2_OUT_OF_STREAMS');
process.nextTick(emit, session, 'error', err);
break;
case NGHTTP2_ERR_INVALID_ARGUMENT:
err = new errors.Error('ERR_HTTP2_STREAM_SELF_DEPENDENCY');
process.nextTick(emit, this, 'error', err);
break;
default:
// Some other, unexpected error was returned. Emit on the session.
if (ret < 0) {
err = new NghttpError(ret);
process.nextTick(emit, session, 'error', err);
break;
}
debug(`[${sessionName(session[kType])}] stream ${ret} initialized`);
this[kInit](ret);
streams.set(ret, this);
}
}
function validatePriorityOptions(options) {
if (options.weight === undefined) {
options.weight = NGHTTP2_DEFAULT_WEIGHT;
} else if (typeof options.weight !== 'number') {
const err = new errors.TypeError('ERR_INVALID_OPT_VALUE',
'weight',
options.weight);
Error.captureStackTrace(err, validatePriorityOptions);
throw err;
}
if (options.parent === undefined) {
options.parent = 0;
} else if (typeof options.parent !== 'number' || options.parent < 0) {
const err = new errors.TypeError('ERR_INVALID_OPT_VALUE',
'parent',
options.parent);
Error.captureStackTrace(err, validatePriorityOptions);
throw err;
}
if (options.exclusive === undefined) {
options.exclusive = false;
} else if (typeof options.exclusive !== 'boolean') {
const err = new errors.TypeError('ERR_INVALID_OPT_VALUE',
'exclusive',
options.exclusive);
Error.captureStackTrace(err, validatePriorityOptions);
throw err;
}
if (options.silent === undefined) {
options.silent = false;
} else if (typeof options.silent !== 'boolean') {
const err = new errors.TypeError('ERR_INVALID_OPT_VALUE',
'silent',
options.silent);
Error.captureStackTrace(err, validatePriorityOptions);
throw err;
}
}
// Creates the internal binding.Http2Session handle for an Http2Session
// instance. This occurs only after the socket connection has been
// established. Note: the binding.Http2Session will take over ownership
// of the socket. No other code should read from or write to the socket.
function setupHandle(session, socket, type, options) {
return function() {
debug(`[${sessionName(type)}] setting up session handle`);
session[kState].connecting = false;
updateOptionsBuffer(options);
const handle = new binding.Http2Session(type);
handle[kOwner] = session;
handle.onpriority = onPriority;
handle.onsettings = onSettings;
handle.onheaders = onSessionHeaders;
handle.ontrailers = onSessionTrailers;
handle.onstreamclose = onSessionStreamClose;
handle.onerror = onSessionError;
handle.onread = onSessionRead;
handle.onframeerror = onFrameError;
handle.ongoawaydata = onGoawayData;
if (typeof options.selectPadding === 'function')
handle.ongetpadding = onSelectPadding(options.selectPadding);
assert(socket._handle !== undefined,
'Internal HTTP/2 Failure. The socket is not connected. Please ' +
'report this as a bug in Node.js');
handle.consume(socket._handle._externalStream);
session[kHandle] = handle;
const settings = typeof options.settings === 'object' ?
options.settings : Object.create(null);
session.settings(settings);
process.nextTick(emit, session, 'connect', session, socket);
};
}
// Submits a SETTINGS frame to be sent to the remote peer.
function submitSettings(settings) {
debug(`[${sessionName(this[kType])}] submitting actual settings`);
_unrefActive(this);
this[kLocalSettings] = undefined;
updateSettingsBuffer(settings);
const handle = this[kHandle];
const ret = handle.submitSettings();
let err;
switch (ret) {
case NGHTTP2_ERR_NOMEM:
err = new errors.Error('ERR_OUTOFMEMORY');
process.nextTick(emit, this, 'error', err);
break;
default:
// Some other unexpected error was reported.
if (ret < 0) {
err = new NghttpError(ret);
process.nextTick(emit, this, 'error', err);
}
}
debug(`[${sessionName(this[kType])}] settings complete`);
}
// Submits a PRIORITY frame to be sent to the remote peer
// Note: If the silent option is true, the change will be made
// locally with no PRIORITY frame sent.
function submitPriority(stream, options) {
debug(`[${sessionName(this[kType])}] submitting actual priority`);
_unrefActive(this);
const handle = this[kHandle];
const ret =
handle.submitPriority(
stream[kID],
options.parent | 0,
options.weight | 0,
!!options.exclusive,
!!options.silent);
let err;
switch (ret) {
case NGHTTP2_ERR_NOMEM:
err = new errors.Error('ERR_OUTOFMEMORY');
process.nextTick(emit, this, 'error', err);
break;
default:
// Some other unexpected error was reported.
if (ret < 0) {
err = new NghttpError(ret);
process.nextTick(emit, stream, 'error', err);
}
}
debug(`[${sessionName(this[kType])}] priority complete`);
}
// Submit an RST-STREAM frame to be sent to the remote peer.
// This will cause the Http2Stream to be closed.
function submitRstStream(stream, code) {
debug(`[${sessionName(this[kType])}] submit actual rststream`);
_unrefActive(this);
const id = stream[kID];
const handle = this[kHandle];
const ret = handle.submitRstStream(id, code);
let err;
switch (ret) {
case NGHTTP2_ERR_NOMEM:
err = new errors.Error('ERR_OUTOFMEMORY');
process.nextTick(emit, this, 'error', err);
break;
default:
// Some other unexpected error was reported.
if (ret < 0) {
err = new NghttpError(ret);
process.nextTick(emit, stream, 'error', err);
break;
}
stream.destroy();
}
debug(`[${sessionName(this[kType])}] rststream complete`);
}
function doShutdown(self, options) {
const handle = self[kHandle];
const state = self[kState];
if (handle === undefined || state.shutdown)
return; // Nothing to do, possibly because the session shutdown already.
const ret = handle.submitGoaway(options.errorCode | 0,
options.lastStreamID | 0,
options.opaqueData);
state.shuttingDown = false;
state.shutdown = true;
if (ret < 0) {
debug(`[${sessionName(self[kType])}] shutdown failed! code: ${ret}`);
const err = new NghttpError(ret);
process.nextTick(emit, self, 'error', err);
return;
}
process.nextTick(emit, self, 'shutdown', options);
debug(`[${sessionName(self[kType])}] shutdown is complete`);
}
// Submit a graceful or immediate shutdown request for the Http2Session.
function submitShutdown(options) {
debug(`[${sessionName(this[kType])}] submitting actual shutdown request`);
const handle = this[kHandle];
const type = this[kType];
if (type === NGHTTP2_SESSION_SERVER &&
options.graceful === true) {
// first send a shutdown notice
handle.submitShutdownNotice();
// then, on flip of the event loop, do the actual shutdown
setImmediate(doShutdown, this, options);
} else {
doShutdown(this, options);
}
}
function finishSessionDestroy(self, socket) {
const state = self[kState];
if (!socket.destroyed)
socket.destroy();
state.destroying = false;
state.destroyed = true;
// Destroy the handle
const handle = self[kHandle];
if (handle !== undefined) {
handle.destroy(state.skipUnconsume);
debug(`[${sessionName(self[kType])}] nghttp2session handle destroyed`);
}
self[kHandle] = undefined;
process.nextTick(emit, self, 'close');
debug(`[${sessionName(self[kType])}] nghttp2session destroyed`);
}
// Upon creation, the Http2Session takes ownership of the socket. The session
// may not be ready to use immediately if the socket is not yet fully connected.
class Http2Session extends EventEmitter {
// type { number } either NGHTTP2_SESSION_SERVER or NGHTTP2_SESSION_CLIENT
// options { Object }
// socket { net.Socket | tls.TLSSocket }
constructor(type, options, socket) {
super();
// No validation is performed on the input parameters because this
// constructor is not exported directly for users.
// If the session property already exists on the socket,
// then it has already been bound to an Http2Session instance
// and cannot be attached again.
if (socket[kSession] !== undefined)
throw new errors.Error('ERR_HTTP2_SOCKET_BOUND');
socket[kSession] = this;
this[kState] = {
streams: new Map(),
destroyed: false,
shutdown: false,
shuttingDown: false,
pendingAck: 0,
maxPendingAck: Math.max(1, (options.maxPendingAck | 0) || 10)
};
this[kType] = type;
this[kSocket] = socket;
// Do not use nagle's algorithm
socket.setNoDelay();
// Disable TLS renegotiation on the socket
if (typeof socket.disableRenegotiation === 'function')
socket.disableRenegotiation();
socket[kDestroySocket] = socket.destroy;
socket.destroy = socketDestroy;
const setupFn = setupHandle(this, socket, type, options);
if (socket.connecting) {
this[kState].connecting = true;
socket.once('connect', setupFn);
} else {
setupFn();
}
// Any individual session can have any number of active open
// streams, these may all need to be made aware of changes
// in state that occur -- such as when the associated socket
// is closed. To do so, we need to set the max listener count
// to something more reasonable because we may have any number
// of concurrent streams (2^31-1 is the upper limit on the number
// of streams)
this.setMaxListeners((2 ** 31) - 1);
debug(`[${sessionName(type)}] http2session created`);
}
[kInspect](depth, opts) {
const state = this[kState];
const obj = {
type: this[kType],
destroyed: state.destroyed,
destroying: state.destroying,
shutdown: state.shutdown,
shuttingDown: state.shuttingDown,
state: this.state,
localSettings: this.localSettings,
remoteSettings: this.remoteSettings
};
return `Http2Session ${util.format(obj)}`;
}
// The socket owned by this session
get socket() {
return this[kSocket];
}
// The session type
get type() {
return this[kType];
}
// true if the Http2Session is waiting for a settings acknowledgement
get pendingSettingsAck() {
return this[kState].pendingAck > 0;
}
// true if the Http2Session has been destroyed
get destroyed() {
return this[kState].destroyed;
}
// Retrieves state information for the Http2Session
get state() {
const handle = this[kHandle];
return handle !== undefined ?
getSessionState(handle) :
Object.create(null);
}
// The settings currently in effect for the local peer. These will
// be updated only when a settings acknowledgement has been received.
get localSettings() {
let settings = this[kLocalSettings];
if (settings !== undefined)
return settings;
const handle = this[kHandle];
if (handle === undefined)
return Object.create(null);
settings = getSettings(handle, false); // Local
this[kLocalSettings] = settings;
return settings;
}
// The settings currently in effect for the remote peer.
get remoteSettings() {
let settings = this[kRemoteSettings];
if (settings !== undefined)
return settings;
const handle = this[kHandle];
if (handle === undefined)
return Object.create(null);
settings = getSettings(handle, true); // Remote
this[kRemoteSettings] = settings;
return settings;
}
// Submits a SETTINGS frame to be sent to the remote peer.
settings(settings) {
if (this[kState].destroyed || this[kState].destroying)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION');
// Validate the input first
assertIsObject(settings, 'settings');
settings = Object.assign(Object.create(null), settings);
assertWithinRange('headerTableSize',
settings.headerTableSize,
0, 2 ** 32 - 1);
assertWithinRange('initialWindowSize',
settings.initialWindowSize,
0, 2 ** 32 - 1);
assertWithinRange('maxFrameSize',
settings.maxFrameSize,
16384, 2 ** 24 - 1);
assertWithinRange('maxConcurrentStreams',
settings.maxConcurrentStreams,
0, 2 ** 31 - 1);
assertWithinRange('maxHeaderListSize',
settings.maxHeaderListSize,
0, 2 ** 32 - 1);
if (settings.enablePush !== undefined &&
typeof settings.enablePush !== 'boolean') {
const err = new errors.TypeError('ERR_HTTP2_INVALID_SETTING_VALUE',
'enablePush', settings.enablePush);
err.actual = settings.enablePush;
throw err;
}
if (this[kState].pendingAck === this[kState].maxPendingAck) {
throw new errors.Error('ERR_HTTP2_MAX_PENDING_SETTINGS_ACK',
this[kState].pendingAck);
}
debug(`[${sessionName(this[kType])}] sending settings`);
this[kState].pendingAck++;
if (this[kState].connecting) {
debug(`[${sessionName(this[kType])}] session still connecting, ` +
'queue settings');
this.once('connect', submitSettings.bind(this, settings));
return;
}
submitSettings.call(this, settings);
}
// Submits a PRIORITY frame to be sent to the remote peer.
priority(stream, options) {
if (this[kState].destroyed || this[kState].destroying)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION');
if (!(stream instanceof Http2Stream)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
'stream',
'Http2Stream');
}
assertIsObject(options, 'options');
options = Object.assign(Object.create(null), options);
validatePriorityOptions(options);
debug(`[${sessionName(this[kType])}] sending priority for stream ` +
`${stream[kID]}`);
// A stream cannot be made to depend on itself
if (options.parent === stream[kID]) {
debug(`[${sessionName(this[kType])}] session still connecting. queue ` +
'priority');
throw new errors.TypeError('ERR_INVALID_OPT_VALUE',
'parent',
options.parent);
}
if (stream[kID] === undefined) {
stream.once('ready', submitPriority.bind(this, stream, options));
return;
}
submitPriority.call(this, stream, options);
}
// Submits an RST-STREAM frame to be sent to the remote peer. This will
// cause the stream to be closed.
rstStream(stream, code = NGHTTP2_NO_ERROR) {
// Do not check destroying here, as the rstStream may be sent while
// the session is in the middle of being destroyed.
if (this[kState].destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION');
if (!(stream instanceof Http2Stream)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
'stream',
'Http2Stream');
}
if (typeof code !== 'number') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
'code',
'number');
}
if (this[kState].rst) {
// rst has already been called, do not call again,
// skip straight to destroy
stream.destroy();
return;
}
stream[kState].rst = true;
stream[kState].rstCode = code;
debug(`[${sessionName(this[kType])}] initiating rststream for stream ` +
`${stream[kID]}: ${code}`);
if (stream[kID] === undefined) {
debug(`[${sessionName(this[kType])}] session still connecting, queue ` +
'rststream');
stream.once('ready', submitRstStream.bind(this, stream, code));
return;
}
submitRstStream.call(this, stream, code);
}
// Destroy the Http2Session
destroy() {
const state = this[kState];
if (state.destroyed || state.destroying)
return;
debug(`[${sessionName(this[kType])}] destroying nghttp2session`);
state.destroying = true;
state.destroyed = false;
// Unenroll the timer
this.setTimeout(0, sessionOnTimeout);
// Shut down any still open streams
const streams = state.streams;
streams.forEach((stream) => stream.destroy());
// Disassociate from the socket and server
const socket = this[kSocket];
// socket.pause();
delete this[kSocket];
delete this[kServer];
if (this[kHandle] !== undefined)
this[kHandle].destroying();
setImmediate(finishSessionDestroy, this, socket);
}
// Graceful or immediate shutdown of the Http2Session. Graceful shutdown
// is only supported on the server-side
shutdown(options, callback) {
if (this[kState].destroyed || this[kState].destroying)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION');
if (this[kState].shutdown || this[kState].shuttingDown)
return;
const type = this[kType];
if (typeof options === 'function') {
callback = options;
options = undefined;
}
assertIsObject(options, 'options');
options = Object.assign(Object.create(null), options);
if (options.opaqueData !== undefined &&
!isUint8Array(options.opaqueData)) {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE',
'opaqueData',
options.opaqueData);