forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsession.cc
2848 lines (2484 loc) · 96.3 KB
/
session.cc
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
#if HAVE_OPENSSL && NODE_OPENSSL_HAS_QUIC
#include "session.h"
#include <aliased_struct-inl.h>
#include <async_wrap-inl.h>
#include <crypto/crypto_util.h>
#include <debug_utils-inl.h>
#include <env-inl.h>
#include <memory_tracker-inl.h>
#include <ngtcp2/ngtcp2.h>
#include <node_bob-inl.h>
#include <node_errors.h>
#include <node_http_common-inl.h>
#include <node_sockaddr-inl.h>
#include <req_wrap-inl.h>
#include <timer_wrap-inl.h>
#include <util-inl.h>
#include <uv.h>
#include <v8.h>
#include "application.h"
#include "bindingdata.h"
#include "cid.h"
#include "data.h"
#include "defs.h"
#include "endpoint.h"
#include "http3.h"
#include "logstream.h"
#include "ncrypto.h"
#include "packet.h"
#include "preferredaddress.h"
#include "sessionticket.h"
#include "streams.h"
#include "tlscontext.h"
#include "transportparams.h"
namespace node {
using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BackingStoreInitializationMode;
using v8::BigInt;
using v8::Boolean;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Int32;
using v8::Integer;
using v8::Just;
using v8::Local;
using v8::LocalVector;
using v8::Maybe;
using v8::MaybeLocal;
using v8::Nothing;
using v8::Object;
using v8::ObjectTemplate;
using v8::PropertyAttribute;
using v8::String;
using v8::Uint32;
using v8::Undefined;
using v8::Value;
namespace quic {
#define SESSION_STATE(V) \
V(PATH_VALIDATION, path_validation, uint8_t) \
V(VERSION_NEGOTIATION, version_negotiation, uint8_t) \
V(DATAGRAM, datagram, uint8_t) \
V(SESSION_TICKET, session_ticket, uint8_t) \
V(CLOSING, closing, uint8_t) \
V(GRACEFUL_CLOSE, graceful_close, uint8_t) \
V(SILENT_CLOSE, silent_close, uint8_t) \
V(STATELESS_RESET, stateless_reset, uint8_t) \
V(HANDSHAKE_COMPLETED, handshake_completed, uint8_t) \
V(HANDSHAKE_CONFIRMED, handshake_confirmed, uint8_t) \
V(STREAM_OPEN_ALLOWED, stream_open_allowed, uint8_t) \
V(PRIORITY_SUPPORTED, priority_supported, uint8_t) \
V(WRAPPED, wrapped, uint8_t) \
V(LAST_DATAGRAM_ID, last_datagram_id, uint64_t)
#define SESSION_STATS(V) \
V(CREATED_AT, created_at) \
V(CLOSING_AT, closing_at) \
V(HANDSHAKE_COMPLETED_AT, handshake_completed_at) \
V(HANDSHAKE_CONFIRMED_AT, handshake_confirmed_at) \
V(BYTES_RECEIVED, bytes_received) \
V(BYTES_SENT, bytes_sent) \
V(BIDI_IN_STREAM_COUNT, bidi_in_stream_count) \
V(BIDI_OUT_STREAM_COUNT, bidi_out_stream_count) \
V(UNI_IN_STREAM_COUNT, uni_in_stream_count) \
V(UNI_OUT_STREAM_COUNT, uni_out_stream_count) \
V(MAX_BYTES_IN_FLIGHT, max_bytes_in_flight) \
V(BYTES_IN_FLIGHT, bytes_in_flight) \
V(BLOCK_COUNT, block_count) \
V(CWND, cwnd) \
V(LATEST_RTT, latest_rtt) \
V(MIN_RTT, min_rtt) \
V(RTTVAR, rttvar) \
V(SMOOTHED_RTT, smoothed_rtt) \
V(SSTHRESH, ssthresh) \
V(DATAGRAMS_RECEIVED, datagrams_received) \
V(DATAGRAMS_SENT, datagrams_sent) \
V(DATAGRAMS_ACKNOWLEDGED, datagrams_acknowledged) \
V(DATAGRAMS_LOST, datagrams_lost)
#define SESSION_JS_METHODS(V) \
V(Destroy, destroy, false) \
V(GetRemoteAddress, getRemoteAddress, true) \
V(GetCertificate, getCertificate, true) \
V(GetEphemeralKeyInfo, getEphemeralKey, true) \
V(GetPeerCertificate, getPeerCertificate, true) \
V(GracefulClose, gracefulClose, false) \
V(SilentClose, silentClose, false) \
V(UpdateKey, updateKey, false) \
V(OpenStream, openStream, false) \
V(SendDatagram, sendDatagram, false)
struct Session::State final {
#define V(_, name, type) type name;
SESSION_STATE(V)
#undef V
};
STAT_STRUCT(Session, SESSION)
// ============================================================================
class Http3Application;
namespace {
std::string to_string(PreferredAddress::Policy policy) {
switch (policy) {
case PreferredAddress::Policy::USE_PREFERRED:
return "use";
case PreferredAddress::Policy::IGNORE_PREFERRED:
return "ignore";
}
return "<unknown>";
}
std::string to_string(Side side) {
switch (side) {
case Side::CLIENT:
return "client";
case Side::SERVER:
return "server";
}
return "<unknown>";
}
std::string to_string(ngtcp2_encryption_level level) {
switch (level) {
case NGTCP2_ENCRYPTION_LEVEL_1RTT:
return "1rtt";
case NGTCP2_ENCRYPTION_LEVEL_0RTT:
return "0rtt";
case NGTCP2_ENCRYPTION_LEVEL_HANDSHAKE:
return "handshake";
case NGTCP2_ENCRYPTION_LEVEL_INITIAL:
return "initial";
}
return "<unknown>";
}
std::string to_string(ngtcp2_cc_algo cc_algorithm) {
#define V(name, label) \
case NGTCP2_CC_ALGO_##name: \
return #label;
switch (cc_algorithm) { CC_ALGOS(V) }
return "<unknown>";
#undef V
}
Maybe<ngtcp2_cc_algo> getAlgoFromString(Environment* env, Local<String> input) {
auto& state = BindingData::Get(env);
#define V(name, str) \
if (input->StringEquals(state.str##_string())) { \
return Just(NGTCP2_CC_ALGO_##name); \
}
CC_ALGOS(V)
#undef V
return Nothing<ngtcp2_cc_algo>();
}
// Qlog is a JSON-based logging format that is being standardized for low-level
// debug logging of QUIC connections and dataflows. The qlog output is generated
// optionally by ngtcp2 for us. The on_qlog_write callback is registered with
// ngtcp2 to emit the qlog information. Every Session will have it's own qlog
// stream.
void on_qlog_write(void* user_data,
uint32_t flags,
const void* data,
size_t len) {
static_cast<Session*>(user_data)->HandleQlog(flags, data, len);
}
// Forwards detailed(verbose) debugging information from ngtcp2. Enabled using
// the NODE_DEBUG_NATIVE=NGTCP2_DEBUG category.
void ngtcp2_debug_log(void* user_data, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
std::string format(fmt, strlen(fmt) + 1);
format[strlen(fmt)] = '\n';
// Debug() does not work with the va_list here. So we use vfprintf
// directly instead. Ngtcp2DebugLog is only enabled when the debug
// category is enabled.
vfprintf(stderr, format.c_str(), ap);
va_end(ap);
}
template <typename Opt, PreferredAddress::Policy Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const Local<Object>& object,
const Local<String>& name) {
Local<Value> value;
PreferredAddress::Policy policy = PreferredAddress::Policy::USE_PREFERRED;
if (!object->Get(env->context(), name).ToLocal(&value) ||
!PreferredAddress::tryGetPolicy(env, value).To(&policy)) {
return false;
}
options->*member = policy;
return true;
}
template <typename Opt, TLSContext::Options Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const Local<Object>& object,
const Local<String>& name) {
Local<Value> value;
TLSContext::Options opts;
if (!object->Get(env->context(), name).ToLocal(&value) ||
!TLSContext::Options::From(env, value).To(&opts)) {
return false;
}
options->*member = opts;
return true;
}
template <typename Opt, TransportParams::Options Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const Local<Object>& object,
const Local<String>& name) {
Local<Value> value;
TransportParams::Options opts;
if (!object->Get(env->context(), name).ToLocal(&value) ||
!TransportParams::Options::From(env, value).To(&opts)) {
return false;
}
options->*member = opts;
return true;
}
template <typename Opt,
BaseObjectPtr<Session::ApplicationProvider> Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const Local<Object>& object,
const Local<String>& name) {
Local<Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) {
return false;
}
if (!value->IsUndefined()) {
// We currently only support Http3Application for this option.
if (!Http3Application::HasInstance(env, value)) {
THROW_ERR_INVALID_ARG_TYPE(env,
"Application must be an Http3Application");
return false;
}
Http3Application* app;
ASSIGN_OR_RETURN_UNWRAP(&app, value.As<Object>(), false);
CHECK_NOT_NULL(app);
auto& assigned = options->*member =
BaseObjectPtr<Session::ApplicationProvider>(app);
assigned->Detach();
}
return true;
}
template <typename Opt, ngtcp2_cc_algo Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const Local<Object>& object,
const Local<String>& name) {
Local<Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) return false;
if (!value->IsUndefined()) {
ngtcp2_cc_algo algo;
if (value->IsString()) {
if (!getAlgoFromString(env, value.As<String>()).To(&algo)) {
THROW_ERR_INVALID_ARG_VALUE(env, "The cc_algorithm option is invalid");
return false;
}
} else {
if (!value->IsInt32()) {
THROW_ERR_INVALID_ARG_VALUE(
env, "The cc_algorithm option must be a string or an integer");
return false;
}
Local<Int32> num;
if (!value->ToInt32(env->context()).ToLocal(&num)) {
THROW_ERR_INVALID_ARG_VALUE(env, "The cc_algorithm option is invalid");
return false;
}
switch (num->Value()) {
#define V(name, _) \
case NGTCP2_CC_ALGO_##name: \
break;
CC_ALGOS(V)
#undef V
default:
THROW_ERR_INVALID_ARG_VALUE(env,
"The cc_algorithm option is invalid");
return false;
}
algo = static_cast<ngtcp2_cc_algo>(num->Value());
}
options->*member = algo;
}
return true;
}
} // namespace
// ============================================================================
Session::Config::Config(Environment* env,
Side side,
const Options& options,
uint32_t version,
const SocketAddress& local_address,
const SocketAddress& remote_address,
const CID& dcid,
const CID& scid,
const CID& ocid)
: side(side),
options(options),
version(version),
local_address(local_address),
remote_address(remote_address),
dcid(dcid),
scid(scid),
ocid(ocid) {
ngtcp2_settings_default(&settings);
settings.initial_ts = uv_hrtime();
// We currently do not support Path MTU Discovery. Once we do, unset this.
settings.no_pmtud = 1;
// Per the ngtcp2 documentation, when no_tx_udp_payload_size_shaping is set
// to a non-zero value, ngtcp2 not to limit the UDP payload size to
// NGTCP2_MAX_UDP_PAYLOAD_SIZE` and will instead "use the minimum size among
// the given buffer size, :member:`max_tx_udp_payload_size`, and the
// received max_udp_payload_size QUIC transport parameter." For now, this
// works for us, especially since we do not implement Path MTU discovery.
settings.no_tx_udp_payload_size_shaping = 1;
settings.max_tx_udp_payload_size = options.max_payload_size;
settings.tokenlen = 0;
settings.token = nullptr;
if (options.qlog) {
settings.qlog_write = on_qlog_write;
}
if (env->enabled_debug_list()->enabled(DebugCategory::NGTCP2_DEBUG)) {
settings.log_printf = ngtcp2_debug_log;
}
settings.handshake_timeout = options.handshake_timeout;
settings.max_stream_window = options.max_stream_window;
settings.max_window = options.max_window;
settings.ack_thresh = options.unacknowledged_packet_threshold;
settings.cc_algo = options.cc_algorithm;
}
Session::Config::Config(Environment* env,
const Options& options,
const SocketAddress& local_address,
const SocketAddress& remote_address,
const CID& ocid)
: Config(env,
Side::CLIENT,
options,
options.version,
local_address,
remote_address,
CID::Factory::random().Generate(NGTCP2_MIN_INITIAL_DCIDLEN),
options.cid_factory->Generate(),
ocid) {}
void Session::Config::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("options", options);
tracker->TrackField("local_address", local_address);
tracker->TrackField("remote_address", remote_address);
tracker->TrackField("dcid", dcid);
tracker->TrackField("scid", scid);
tracker->TrackField("ocid", ocid);
tracker->TrackField("retry_scid", retry_scid);
}
void Session::Config::set_token(const uint8_t* token,
size_t len,
ngtcp2_token_type type) {
settings.token = token;
settings.tokenlen = len;
settings.token_type = type;
}
void Session::Config::set_token(const RetryToken& token) {
ngtcp2_vec vec = token;
set_token(vec.base, vec.len, NGTCP2_TOKEN_TYPE_RETRY);
}
void Session::Config::set_token(const RegularToken& token) {
ngtcp2_vec vec = token;
set_token(vec.base, vec.len, NGTCP2_TOKEN_TYPE_NEW_TOKEN);
}
std::string Session::Config::ToString() const {
DebugIndentScope indent;
auto prefix = indent.Prefix();
std::string res("{");
res += prefix + "side: " + to_string(side);
res += prefix + "options: " + options.ToString();
res += prefix + "version: " + std::to_string(version);
res += prefix + "local address: " + local_address.ToString();
res += prefix + "remote address: " + remote_address.ToString();
res += prefix + "dcid: " + dcid.ToString();
res += prefix + "scid: " + scid.ToString();
res += prefix + "ocid: " + ocid.ToString();
res += prefix + "retry scid: " + retry_scid.ToString();
res += prefix + "preferred address cid: " + preferred_address_cid.ToString();
res += indent.Close();
return res;
}
// ============================================================================
Maybe<Session::Options> Session::Options::From(Environment* env,
Local<Value> value) {
if (value.IsEmpty() || !value->IsObject()) {
THROW_ERR_INVALID_ARG_TYPE(env, "options must be an object");
return Nothing<Options>();
}
auto& state = BindingData::Get(env);
auto params = value.As<Object>();
Options options;
#define SET(name) \
SetOption<Session::Options, &Session::Options::name>( \
env, &options, params, state.name##_string())
if (!SET(version) || !SET(min_version) || !SET(preferred_address_strategy) ||
!SET(transport_params) || !SET(tls_options) || !SET(qlog) ||
!SET(application_provider) || !SET(handshake_timeout) ||
!SET(max_stream_window) || !SET(max_window) || !SET(max_payload_size) ||
!SET(unacknowledged_packet_threshold) || !SET(cc_algorithm)) {
return Nothing<Options>();
}
#undef SET
// TODO(@jasnell): Later we will also support setting the CID::Factory.
// For now, we're just using the default random factory.
return Just<Options>(options);
}
void Session::Options::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("transport_params", transport_params);
tracker->TrackField("crypto_options", tls_options);
tracker->TrackField("cid_factory_ref", cid_factory_ref);
}
std::string Session::Options::ToString() const {
DebugIndentScope indent;
auto prefix = indent.Prefix();
std::string res("{");
res += prefix + "version: " + std::to_string(version);
res += prefix + "min version: " + std::to_string(min_version);
res += prefix +
"preferred address policy: " + to_string(preferred_address_strategy);
res += prefix + "transport params: " + transport_params.ToString();
res += prefix + "crypto options: " + tls_options.ToString();
if (qlog) {
res += prefix + "qlog: yes";
}
if (handshake_timeout == UINT64_MAX) {
res += prefix + "handshake timeout: <none>";
} else {
res += prefix + "handshake timeout: " + std::to_string(handshake_timeout) +
" nanoseconds";
}
res += prefix + "max stream window: " + std::to_string(max_stream_window);
res += prefix + "max window: " + std::to_string(max_window);
res += prefix + "max payload size: " + std::to_string(max_payload_size);
if (unacknowledged_packet_threshold != 0) {
res += prefix + "unacknowledged packet threshold: " +
std::to_string(unacknowledged_packet_threshold);
} else {
res += prefix + "unacknowledged packet threshold: <default>";
}
res += prefix + "cc algorithm: " + to_string(cc_algorithm);
res += indent.Close();
return res;
}
// ============================================================================
// ngtcp2 static callback functions
// Utility used only within Session::Impl to reduce boilerplate
#define NGTCP2_CALLBACK_SCOPE(name) \
auto name = Impl::From(conn, user_data); \
if (name == nullptr) return NGTCP2_ERR_CALLBACK_FAILURE; \
NgTcp2CallbackScope scope(name->env());
// Session::Impl maintains most of the internal state of an active Session.
struct Session::Impl final : public MemoryRetainer {
Session* session_;
AliasedStruct<Stats> stats_;
AliasedStruct<State> state_;
BaseObjectWeakPtr<Endpoint> endpoint_;
Config config_;
SocketAddress local_address_;
SocketAddress remote_address_;
std::unique_ptr<Application> application_;
StreamsMap streams_;
TimerWrapHandle timer_;
size_t send_scope_depth_ = 0;
QuicError last_error_;
PendingStream::PendingStreamQueue pending_bidi_stream_queue_;
PendingStream::PendingStreamQueue pending_uni_stream_queue_;
Impl(Session* session, Endpoint* endpoint, const Config& config)
: session_(session),
stats_(env()->isolate()),
state_(env()->isolate()),
endpoint_(endpoint),
config_(config),
local_address_(config.local_address),
remote_address_(config.remote_address),
application_(SelectApplication(session, config_)),
timer_(session_->env(), [this] { session_->OnTimeout(); }) {
timer_.Unref();
}
inline bool is_closing() const { return state_->closing; }
/**
* @returns {boolean} Returns true if the Session can be destroyed
* immediately.
*/
bool Close() {
if (state_->closing) return true;
state_->closing = 1;
STAT_RECORD_TIMESTAMP(Stats, closing_at);
// Iterate through all of the known streams and close them. The streams
// will remove themselves from the Session as soon as they are closed.
// Note: we create a copy because the streams will remove themselves
// while they are cleaning up which will invalidate the iterator.
StreamsMap streams = streams_;
for (auto& stream : streams) stream.second->Destroy(last_error_);
DCHECK(streams.empty());
// Clear the pending streams.
while (!pending_bidi_stream_queue_.IsEmpty()) {
pending_bidi_stream_queue_.PopFront()->reject(last_error_);
}
while (!pending_uni_stream_queue_.IsEmpty()) {
pending_uni_stream_queue_.PopFront()->reject(last_error_);
}
// If we are able to send packets, we should try sending a connection
// close packet to the remote peer.
if (!state_->silent_close) {
session_->SendConnectionClose();
}
timer_.Close();
return !state_->wrapped;
}
~Impl() {
// Ensure that Close() was called before dropping
DCHECK(is_closing());
DCHECK(endpoint_);
// Removing the session from the endpoint may cause the endpoint to be
// destroyed if it is waiting on the last session to be destroyed. Let's
// grab a reference just to be safe for the rest of the function.
BaseObjectPtr<Endpoint> endpoint = endpoint_;
endpoint_.reset();
MaybeStackBuffer<ngtcp2_cid, 10> cids(
ngtcp2_conn_get_scid(*session_, nullptr));
ngtcp2_conn_get_scid(*session_, cids.out());
MaybeStackBuffer<ngtcp2_cid_token, 10> tokens(
ngtcp2_conn_get_active_dcid(*session_, nullptr));
ngtcp2_conn_get_active_dcid(*session_, tokens.out());
endpoint->DisassociateCID(config_.dcid);
endpoint->DisassociateCID(config_.preferred_address_cid);
for (size_t n = 0; n < cids.length(); n++) {
endpoint->DisassociateCID(CID(cids[n]));
}
for (size_t n = 0; n < tokens.length(); n++) {
if (tokens[n].token_present) {
endpoint->DisassociateStatelessResetToken(
StatelessResetToken(tokens[n].token));
}
}
endpoint->RemoveSession(config_.scid, remote_address_);
}
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("config", config_);
tracker->TrackField("endpoint", endpoint_);
tracker->TrackField("streams", streams_);
tracker->TrackField("local_address", local_address_);
tracker->TrackField("remote_address", remote_address_);
tracker->TrackField("application", application_);
tracker->TrackField("timer", timer_);
}
SET_SELF_SIZE(Impl)
SET_MEMORY_INFO_NAME(Session::Impl)
Environment* env() const { return session_->env(); }
// Gets the Session pointer from the user_data void pointer
// provided by ngtcp2.
static Session* From(ngtcp2_conn* conn, void* user_data) {
if (user_data == nullptr) [[unlikely]] {
return nullptr;
}
auto session = static_cast<Session*>(user_data);
if (session->is_destroyed()) [[unlikely]] {
return nullptr;
}
return session;
}
// JavaScript APIs
static void Destroy(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
session->Destroy();
}
static void GetRemoteAddress(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
auto address = session->remote_address();
args.GetReturnValue().Set(
SocketAddressBase::Create(env, std::make_shared<SocketAddress>(address))
->object());
}
static void GetCertificate(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
Local<Value> ret;
if (session->tls_session().cert(env).ToLocal(&ret))
args.GetReturnValue().Set(ret);
}
static void GetEphemeralKeyInfo(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
Local<Object> ret;
if (!session->is_server() &&
session->tls_session().ephemeral_key(env).ToLocal(&ret))
args.GetReturnValue().Set(ret);
}
static void GetPeerCertificate(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
Local<Value> ret;
if (session->tls_session().peer_cert(env).ToLocal(&ret))
args.GetReturnValue().Set(ret);
}
static void GracefulClose(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
session->Close(CloseMethod::GRACEFUL);
}
static void SilentClose(const FunctionCallbackInfo<Value>& args) {
// This is exposed for testing purposes only!
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
session->Close(CloseMethod::SILENT);
}
static void UpdateKey(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
// Initiating a key update may fail if it is done too early (either
// before the TLS handshake has been confirmed or while a previous
// key update is being processed). When it fails, InitiateKeyUpdate()
// will return false.
SendPendingDataScope send_scope(session);
args.GetReturnValue().Set(session->tls_session().InitiateKeyUpdate());
}
static void OpenStream(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
DCHECK(args[0]->IsUint32());
// GetDataQueueFromSource handles type validation.
std::shared_ptr<DataQueue> data_source =
Stream::GetDataQueueFromSource(env, args[1]).ToChecked();
if (data_source == nullptr) {
THROW_ERR_INVALID_ARG_VALUE(env, "Invalid data source");
}
SendPendingDataScope send_scope(session);
auto direction = static_cast<Direction>(args[0].As<Uint32>()->Value());
Local<Object> stream;
if (session->OpenStream(direction, std::move(data_source)).ToLocal(&stream))
[[likely]] {
args.GetReturnValue().Set(stream);
}
}
static void SendDatagram(const FunctionCallbackInfo<Value>& args) {
auto env = Environment::GetCurrent(args);
Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
if (session->is_destroyed()) {
THROW_ERR_INVALID_STATE(env, "Session is destroyed");
}
DCHECK(args[0]->IsArrayBufferView());
SendPendingDataScope send_scope(session);
args.GetReturnValue().Set(BigInt::New(
env->isolate(),
session->SendDatagram(Store(args[0].As<ArrayBufferView>()))));
}
// Internal ngtcp2 callbacks
static int on_acknowledge_stream_data_offset(ngtcp2_conn* conn,
int64_t stream_id,
uint64_t offset,
uint64_t datalen,
void* user_data,
void* stream_user_data) {
NGTCP2_CALLBACK_SCOPE(session)
// The callback will be invoked with datalen 0 if a zero-length
// stream frame with fin flag set is received. In that case, let's
// just ignore it.
// Per ngtcp2, the range of bytes that are being acknowledged here
// are `[offset, offset + datalen]` but we only really care about
// the datalen as our accounting does not track the offset and
// acknowledges should never come out of order here.
if (datalen == 0) return NGTCP2_SUCCESS;
return session->application().AcknowledgeStreamData(stream_id, datalen)
? NGTCP2_SUCCESS
: NGTCP2_ERR_CALLBACK_FAILURE;
}
static int on_acknowledge_datagram(ngtcp2_conn* conn,
uint64_t dgram_id,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->DatagramStatus(dgram_id, DatagramStatus::ACKNOWLEDGED);
return NGTCP2_SUCCESS;
}
static int on_cid_status(ngtcp2_conn* conn,
ngtcp2_connection_id_status_type type,
uint64_t seq,
const ngtcp2_cid* cid,
const uint8_t* token,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
std::optional<StatelessResetToken> maybe_reset_token;
if (token != nullptr) maybe_reset_token.emplace(token);
auto& endpoint = session->endpoint();
switch (type) {
case NGTCP2_CONNECTION_ID_STATUS_TYPE_ACTIVATE: {
endpoint.AssociateCID(session->config().scid, CID(cid));
if (token != nullptr) {
endpoint.AssociateStatelessResetToken(StatelessResetToken(token),
session);
}
break;
}
case NGTCP2_CONNECTION_ID_STATUS_TYPE_DEACTIVATE: {
endpoint.DisassociateCID(CID(cid));
if (token != nullptr) {
endpoint.DisassociateStatelessResetToken(StatelessResetToken(token));
}
break;
}
}
return NGTCP2_SUCCESS;
}
static int on_extend_max_remote_streams_bidi(ngtcp2_conn* conn,
uint64_t max_streams,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
// TODO(@jasnell): Do anything here?
return NGTCP2_SUCCESS;
}
static int on_extend_max_remote_streams_uni(ngtcp2_conn* conn,
uint64_t max_streams,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
// TODO(@jasnell): Do anything here?
return NGTCP2_SUCCESS;
}
static int on_extend_max_streams_bidi(ngtcp2_conn* conn,
uint64_t max_streams,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->ProcessPendingBidiStreams();
return NGTCP2_SUCCESS;
}
static int on_extend_max_streams_uni(ngtcp2_conn* conn,
uint64_t max_streams,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->ProcessPendingUniStreams();
return NGTCP2_SUCCESS;
}
static int on_extend_max_stream_data(ngtcp2_conn* conn,
int64_t stream_id,
uint64_t max_data,
void* user_data,
void* stream_user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->application().ExtendMaxStreamData(Stream::From(stream_user_data),
max_data);
return NGTCP2_SUCCESS;
}
static int on_get_new_cid(ngtcp2_conn* conn,
ngtcp2_cid* cid,
uint8_t* token,
size_t cidlen,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->GenerateNewConnectionId(cid, cidlen, token);
return NGTCP2_SUCCESS;
}
static int on_handshake_completed(ngtcp2_conn* conn, void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
return session->HandshakeCompleted() ? NGTCP2_SUCCESS
: NGTCP2_ERR_CALLBACK_FAILURE;
}
static int on_handshake_confirmed(ngtcp2_conn* conn, void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->HandshakeConfirmed();
return NGTCP2_SUCCESS;
}
static int on_lost_datagram(ngtcp2_conn* conn,
uint64_t dgram_id,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->DatagramStatus(dgram_id, DatagramStatus::LOST);
return NGTCP2_SUCCESS;
}
static int on_path_validation(ngtcp2_conn* conn,
uint32_t flags,
const ngtcp2_path* path,
const ngtcp2_path* old_path,
ngtcp2_path_validation_result res,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
bool flag_preferred_address =
flags & NGTCP2_PATH_VALIDATION_FLAG_PREFERRED_ADDR;
ValidatedPath newValidatedPath{
std::make_shared<SocketAddress>(path->local.addr),
std::make_shared<SocketAddress>(path->remote.addr)};
std::optional<ValidatedPath> oldValidatedPath = std::nullopt;
if (old_path != nullptr) {
oldValidatedPath =
ValidatedPath{std::make_shared<SocketAddress>(old_path->local.addr),
std::make_shared<SocketAddress>(old_path->remote.addr)};
}
session->EmitPathValidation(static_cast<PathValidationResult>(res),
PathValidationFlags{flag_preferred_address},
newValidatedPath,
oldValidatedPath);
return NGTCP2_SUCCESS;
}
static int on_receive_datagram(ngtcp2_conn* conn,
uint32_t flags,
const uint8_t* data,
size_t datalen,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
session->DatagramReceived(
data,
datalen,
DatagramReceivedFlags{
.early = (flags & NGTCP2_DATAGRAM_FLAG_0RTT) ==
NGTCP2_DATAGRAM_FLAG_0RTT,
});
return NGTCP2_SUCCESS;
}
static int on_receive_new_token(ngtcp2_conn* conn,
const uint8_t* token,
size_t tokenlen,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
// We currently do nothing with this callback.
return NGTCP2_SUCCESS;
}
static int on_receive_rx_key(ngtcp2_conn* conn,
ngtcp2_encryption_level level,
void* user_data) {
NGTCP2_CALLBACK_SCOPE(session)
CHECK(!session->is_server());
if (level != NGTCP2_ENCRYPTION_LEVEL_1RTT) return NGTCP2_SUCCESS;
Debug(session,
"Receiving RX key for level %s for dcid %s",