forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsession.cc
2401 lines (2105 loc) · 84.2 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 "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::BigInt;
using v8::Boolean;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Integer;
using v8::Just;
using v8::Local;
using v8::Maybe;
using v8::Nothing;
using v8::Object;
using v8::PropertyAttribute;
using v8::String;
using v8::Uint32;
using v8::Undefined;
using v8::Value;
namespace quic {
#define SESSION_STATE(V) \
/* Set if the JavaScript wrapper has a path-validation event listener */ \
V(PATH_VALIDATION, path_validation, uint8_t) \
/* Set if the JavaScript wrapper has a version-negotiation event listener */ \
V(VERSION_NEGOTIATION, version_negotiation, uint8_t) \
/* Set if the JavaScript wrapper has a datagram event listener */ \
V(DATAGRAM, datagram, uint8_t) \
/* Set if the JavaScript wrapper has a session-ticket event listener */ \
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(DESTROYED, destroyed, 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) \
/* A Session is wrapped if it has been passed out to JS */ \
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(DESTROYED_AT, destroyed_at) \
V(HANDSHAKE_COMPLETED_AT, handshake_completed_at) \
V(HANDSHAKE_CONFIRMED_AT, handshake_confirmed_at) \
V(GRACEFUL_CLOSING_AT, graceful_closing_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(LOSS_RETRANSMIT_COUNT, loss_retransmit_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(DoDestroy, 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(DoOpenStream, openStream, false) \
V(DoSendDatagram, sendDatagram, false)
struct Session::State {
#define V(_, name, type) type name;
SESSION_STATE(V)
#undef V
};
STAT_STRUCT(Session, SESSION)
// ============================================================================
// Used to conditionally trigger sending an explicit connection
// close. If there are multiple MaybeCloseConnectionScope in the
// stack, the determination of whether to send the close will be
// done once the final scope is closed.
struct Session::MaybeCloseConnectionScope final {
Session* session;
bool silent = false;
MaybeCloseConnectionScope(Session* session_, bool silent_)
: session(session_),
silent(silent_ || session->connection_close_depth_ > 0) {
Debug(session_,
"Entering maybe close connection scope. Silent? %s",
silent ? "yes" : "no");
session->connection_close_depth_++;
}
DISALLOW_COPY_AND_MOVE(MaybeCloseConnectionScope)
~MaybeCloseConnectionScope() {
// We only want to trigger the sending the connection close if ...
// a) Silent is not explicitly true at this scope.
// b) We're not within the scope of an ngtcp2 callback, and
// c) We are not already in a closing or draining period.
if (--session->connection_close_depth_ == 0 && !silent &&
session->can_send_packets()) {
session->SendConnectionClose();
}
}
};
// ============================================================================
// Used to conditionally trigger sending of any pending data the session may
// be holding onto. If there are multiple SendPendingDataScope in the stack,
// the determination of whether to send the data will be done once the final
// scope is closed.
Session::SendPendingDataScope::SendPendingDataScope(Session* session)
: session(session) {
Debug(session, "Entering send pending data scope");
session->send_scope_depth_++;
}
Session::SendPendingDataScope::SendPendingDataScope(
const BaseObjectPtr<Session>& session)
: SendPendingDataScope(session.get()) {}
Session::SendPendingDataScope::~SendPendingDataScope() {
if (--session->send_scope_depth_ == 0 && session->can_send_packets()) {
session->application().SendPendingData();
}
}
// ============================================================================
namespace {
inline 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>";
}
// 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 v8::Local<Object>& object,
const v8::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 v8::Local<Object>& object,
const v8::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, Session::Application_Options Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const v8::Local<Object>& object,
const v8::Local<String>& name) {
Local<Value> value;
Session::Application_Options opts;
if (!object->Get(env->context(), name).ToLocal(&value) ||
!Session::Application_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 v8::Local<Object>& object,
const v8::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;
}
} // namespace
// ============================================================================
Session::Config::Config(Side side,
const Endpoint& endpoint,
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;
settings.tokenlen = 0;
settings.token = nullptr;
if (options.qlog) {
settings.qlog_write = on_qlog_write;
}
if (endpoint.env()->enabled_debug_list()->enabled(
DebugCategory::NGTCP2_DEBUG)) {
settings.log_printf = ngtcp2_debug_log;
}
// We pull parts of the settings for the session from the endpoint options.
auto& config = endpoint.options();
settings.no_tx_udp_payload_size_shaping = config.no_udp_payload_size_shaping;
settings.handshake_timeout = config.handshake_timeout;
settings.max_stream_window = config.max_stream_window;
settings.max_window = config.max_window;
settings.cc_algo = config.cc_algorithm;
settings.max_tx_udp_payload_size = config.max_payload_size;
if (config.unacknowledged_packet_threshold > 0) {
settings.ack_thresh = config.unacknowledged_packet_threshold;
}
}
Session::Config::Config(const Endpoint& endpoint,
const Options& options,
const SocketAddress& local_address,
const SocketAddress& remote_address,
const CID& ocid)
: Config(Side::CLIENT,
endpoint,
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("{");
auto sidestr = ([&] {
switch (side) {
case Side::CLIENT:
return "client";
case Side::SERVER:
return "server";
}
return "<unknown>";
})();
res += prefix + "side: " + std::string(sidestr);
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(application_options) || !SET(qlog)) {
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("application_options", application_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);
auto policy = ([&] {
switch (preferred_address_strategy) {
case PreferredAddress::Policy::USE_PREFERRED:
return "use";
case PreferredAddress::Policy::IGNORE_PREFERRED:
return "ignore";
}
return "<unknown>";
})();
res += prefix + "preferred address policy: " + std::string(policy);
res += prefix + "transport params: " + transport_params.ToString();
res += prefix + "crypto options: " + tls_options.ToString();
res += prefix + "application options: " + application_options.ToString();
res += prefix + "qlog: " + (qlog ? std::string("yes") : std::string("no"));
res += indent.Close();
return res;
}
// ============================================================================
bool Session::HasInstance(Environment* env, Local<Value> value) {
return GetConstructorTemplate(env)->HasInstance(value);
}
BaseObjectPtr<Session> Session::Create(
Endpoint* endpoint,
const Config& config,
TLSContext* tls_context,
const std::optional<SessionTicket>& ticket) {
Local<Object> obj;
if (!GetConstructorTemplate(endpoint->env())
->InstanceTemplate()
->NewInstance(endpoint->env()->context())
.ToLocal(&obj)) {
return BaseObjectPtr<Session>();
}
return MakeDetachedBaseObject<Session>(
endpoint, obj, config, tls_context, ticket);
}
Session::Session(Endpoint* endpoint,
v8::Local<v8::Object> object,
const Config& config,
TLSContext* tls_context,
const std::optional<SessionTicket>& session_ticket)
: AsyncWrap(endpoint->env(), object, AsyncWrap::PROVIDER_QUIC_SESSION),
stats_(env()->isolate()),
state_(env()->isolate()),
allocator_(BindingData::Get(env())),
endpoint_(BaseObjectWeakPtr<Endpoint>(endpoint)),
config_(config),
local_address_(config.local_address),
remote_address_(config.remote_address),
connection_(InitConnection()),
tls_session_(tls_context->NewSession(this, session_ticket)),
application_(select_application()),
timer_(env(),
[this, self = BaseObjectPtr<Session>(this)] { OnTimeout(); }) {
MakeWeak();
Debug(this, "Session created.");
timer_.Unref();
application().ExtendMaxStreams(EndpointLabel::LOCAL,
Direction::BIDIRECTIONAL,
TransportParams::DEFAULT_MAX_STREAMS_BIDI);
application().ExtendMaxStreams(EndpointLabel::LOCAL,
Direction::UNIDIRECTIONAL,
TransportParams::DEFAULT_MAX_STREAMS_UNI);
const auto defineProperty = [&](auto name, auto value) {
object
->DefineOwnProperty(
env()->context(), name, value, PropertyAttribute::ReadOnly)
.Check();
};
defineProperty(env()->state_string(), state_.GetArrayBuffer());
defineProperty(env()->stats_string(), stats_.GetArrayBuffer());
auto& state = BindingData::Get(env());
if (config_.options.qlog) [[unlikely]] {
qlog_stream_ = LogStream::Create(env());
if (qlog_stream_)
defineProperty(state.qlog_string(), qlog_stream_->object());
}
if (config_.options.tls_options.keylog) [[unlikely]] {
keylog_stream_ = LogStream::Create(env());
if (keylog_stream_)
defineProperty(state.keylog_string(), keylog_stream_->object());
}
// We index the Session by our local CID (the scid) and dcid (the peer's cid)
endpoint_->AddSession(config_.scid, BaseObjectPtr<Session>(this));
endpoint_->AssociateCID(config_.dcid, config_.scid);
UpdateDataStats();
}
Session::~Session() {
Debug(this, "Session destroyed.");
if (conn_closebuf_) {
conn_closebuf_->Done(0);
}
if (qlog_stream_) {
Debug(this, "Closing the qlog stream for this session");
env()->SetImmediate(
[ptr = std::move(qlog_stream_)](Environment*) { ptr->End(); });
}
if (keylog_stream_) {
Debug(this, "Closing the keylog stream for this session");
env()->SetImmediate(
[ptr = std::move(keylog_stream_)](Environment*) { ptr->End(); });
}
DCHECK(streams_.empty());
}
size_t Session::max_packet_size() const {
return ngtcp2_conn_get_max_tx_udp_payload_size(*this);
}
Session::operator ngtcp2_conn*() const {
return connection_.get();
}
uint32_t Session::version() const {
return config_.version;
}
Endpoint& Session::endpoint() const {
return *endpoint_;
}
TLSSession& Session::tls_session() {
return *tls_session_;
}
Session::Application& Session::application() {
return *application_;
}
const SocketAddress& Session::remote_address() const {
return remote_address_;
}
const SocketAddress& Session::local_address() const {
return local_address_;
}
bool Session::is_closing() const {
return state_->closing;
}
bool Session::is_graceful_closing() const {
return state_->graceful_close;
}
bool Session::is_silent_closing() const {
return state_->silent_close;
}
bool Session::is_destroyed() const {
return state_->destroyed;
}
bool Session::is_server() const {
return config_.side == Side::SERVER;
}
std::string Session::diagnostic_name() const {
const auto get_type = [&] { return is_server() ? "server" : "client"; };
return std::string("Session (") + get_type() + "," +
std::to_string(env()->thread_id()) + ":" +
std::to_string(static_cast<int64_t>(get_async_id())) + ")";
}
const Session::Config& Session::config() const {
return config_;
}
const Session::Options& Session::options() const {
return config_.options;
}
void Session::HandleQlog(uint32_t flags, const void* data, size_t len) {
if (qlog_stream_) {
// Fun fact... ngtcp2 does not emit the final qlog statement until the
// ngtcp2_conn object is destroyed. Ideally, destroying is explicit, but
// sometimes the Session object can be garbage collected without being
// explicitly destroyed. During those times, we cannot call out to
// JavaScript. Because we don't know for sure if we're in in a GC when this
// is called, it is safer to just defer writes to immediate, and to keep it
// consistent, let's just always defer (this is not performance sensitive so
// the deferring is fine).
std::vector<uint8_t> buffer(len);
memcpy(buffer.data(), data, len);
Debug(this, "Emitting qlog data to the qlog stream");
env()->SetImmediate(
[ptr = qlog_stream_, buffer = std::move(buffer), flags](Environment*) {
ptr->Emit(buffer.data(),
buffer.size(),
flags & NGTCP2_QLOG_WRITE_FLAG_FIN
? LogStream::EmitOption::FIN
: LogStream::EmitOption::NONE);
});
}
}
TransportParams Session::GetLocalTransportParams() const {
DCHECK(!is_destroyed());
return TransportParams(ngtcp2_conn_get_local_transport_params(*this));
}
TransportParams Session::GetRemoteTransportParams() const {
DCHECK(!is_destroyed());
return TransportParams(ngtcp2_conn_get_remote_transport_params(*this));
}
void Session::SetLastError(QuicError&& error) {
Debug(this, "Setting last error to %s", error);
last_error_ = std::move(error);
}
void Session::Close(Session::CloseMethod method) {
if (is_destroyed()) return;
switch (method) {
case CloseMethod::DEFAULT: {
Debug(this, "Closing session");
DoClose(false);
break;
}
case CloseMethod::SILENT: {
Debug(this, "Closing session silently");
DoClose(true);
break;
}
case CloseMethod::GRACEFUL: {
if (is_graceful_closing()) return;
Debug(this, "Closing session gracefully");
// If there are no open streams, then we can close just immediately and
// not worry about waiting around for the right moment.
if (streams_.empty()) {
DoClose(false);
} else {
state_->graceful_close = 1;
STAT_RECORD_TIMESTAMP(Stats, graceful_closing_at);
}
break;
}
}
}
void Session::Destroy() {
if (is_destroyed()) return;
Debug(this, "Session destroyed");
// The DoClose() method should have already been called.
DCHECK(state_->closing);
// We create a copy of the streams because they will remove themselves
// from streams_ as they are cleaning up, causing the iterator to be
// invalidated.
auto streams = streams_;
for (auto& stream : streams) stream.second->Destroy(last_error_);
DCHECK(streams_.empty());
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);
state_->closing = 0;
state_->graceful_close = 0;
timer_.Stop();
// The Session instances are kept alive using a in the Endpoint. Removing the
// Session from the Endpoint will free that pointer, allowing the Session to
// be deconstructed once the stack unwinds and any remaining
// BaseObjectPtr<Session> instances fall out of scope.
MaybeStackBuffer<ngtcp2_cid, 10> cids(ngtcp2_conn_get_scid(*this, nullptr));
ngtcp2_conn_get_scid(*this, cids.out());
MaybeStackBuffer<ngtcp2_cid_token, 10> tokens(
ngtcp2_conn_get_active_dcid(*this, nullptr));
ngtcp2_conn_get_active_dcid(*this, 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));
}
}
state_->destroyed = 1;
// 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 = std::move(endpoint_);
endpoint->RemoveSession(config_.scid);
}
bool Session::Receive(Store&& store,
const SocketAddress& local_address,
const SocketAddress& remote_address) {
if (is_destroyed()) return false;
const auto receivePacket = [&](ngtcp2_path* path, ngtcp2_vec vec) {
DCHECK(!is_destroyed());
uint64_t now = uv_hrtime();
ngtcp2_pkt_info pi{}; // Not used but required.
int err = ngtcp2_conn_read_pkt(*this, path, &pi, vec.base, vec.len, now);
switch (err) {
case 0: {
// Return true so we send after receiving.
Debug(this, "Session successfully received packet");
return true;
}
case NGTCP2_ERR_DRAINING: {
// Connection has entered the draining state, no further data should be
// sent. This happens when the remote peer has sent a CONNECTION_CLOSE.
Debug(this, "Session is draining");
return false;
}
case NGTCP2_ERR_CLOSING: {
// Connection has entered the closing state, no further data should be
// sent. This happens when the local peer has called
// ngtcp2_conn_write_connection_close.
Debug(this, "Session is closing");
return false;
}
case NGTCP2_ERR_CRYPTO: {
// Crypto error happened! Set the last error to the tls alert
last_error_ = QuicError::ForTlsAlert(ngtcp2_conn_get_tls_alert(*this));
Debug(this, "Crypto error while receiving packet: %s", last_error_);
Close();
return false;
}
case NGTCP2_ERR_RETRY: {
// This should only ever happen on the server. We have to send a path
// validation challenge in the form of a RETRY packet to the peer and
// drop the connection.
DCHECK(is_server());
Debug(this, "Server must send a retry packet");
endpoint_->SendRetry(PathDescriptor{
version(),
config_.dcid,
config_.scid,
local_address_,
remote_address_,
});
Close(CloseMethod::SILENT);
return false;
}
case NGTCP2_ERR_DROP_CONN: {
// There's nothing else to do but drop the connection state.
Debug(this, "Session must drop the connection");
Close(CloseMethod::SILENT);
return false;
}
}
// Shouldn't happen but just in case.
last_error_ = QuicError::ForNgtcp2Error(err);
Debug(this, "Error while receiving packet: %s (%d)", last_error_, err);
Close();
return false;
};
auto update_stats = OnScopeLeave([&] { UpdateDataStats(); });
remote_address_ = remote_address;
Path path(local_address, remote_address_);
Debug(this, "Session is receiving packet received along path %s", path);
STAT_INCREMENT_N(Stats, bytes_received, store.length());
if (receivePacket(&path, store)) application().SendPendingData();
if (!is_destroyed()) UpdateTimer();
return true;
}
void Session::Send(Packet* packet) {
// Sending a Packet is generally best effort. If we're not in a state
// where we can send a packet, it's ok to drop it on the floor. The
// packet loss mechanisms will cause the packet data to be resent later
// if appropriate (and possible).
DCHECK(!is_destroyed());
DCHECK(!is_in_draining_period());
if (can_send_packets() && packet->length() > 0) {
Debug(this, "Session is sending %s", packet->ToString());
STAT_INCREMENT_N(Stats, bytes_sent, packet->length());
endpoint_->Send(packet);
return;
}
Debug(this, "Session could not send %s", packet->ToString());
packet->Done(packet->length() > 0 ? UV_ECANCELED : 0);
}
void Session::Send(Packet* packet, const PathStorage& path) {
UpdatePath(path);
Send(packet);
}
void Session::UpdatePacketTxTime() {
ngtcp2_conn_update_pkt_tx_time(*this, uv_hrtime());
}
uint64_t Session::SendDatagram(Store&& data) {
auto tp = ngtcp2_conn_get_remote_transport_params(*this);
uint64_t max_datagram_size = tp->max_datagram_frame_size;
if (max_datagram_size == 0 || data.length() > max_datagram_size) {
// Datagram is too large.
Debug(this, "Data is too large to send as a datagram");
return 0;
}
Debug(this, "Session is sending datagram");
Packet* packet = nullptr;
uint8_t* pos = nullptr;
int accepted = 0;
ngtcp2_vec vec = data;
PathStorage path;
int flags = NGTCP2_WRITE_DATAGRAM_FLAG_MORE;
uint64_t did = state_->last_datagram_id + 1;
// Let's give it a max number of attempts to send the datagram
static const int kMaxAttempts = 16;
int attempts = 0;
for (;;) {
// We may have to make several attempts at encoding and sending the
// datagram packet. On each iteration here we'll try to encode the
// datagram. It's entirely up to ngtcp2 whether to include the datagram
// in the packet on each call to ngtcp2_conn_writev_datagram.
if (packet == nullptr) {
packet = Packet::Create(env(),
endpoint_.get(),
remote_address_,
ngtcp2_conn_get_max_tx_udp_payload_size(*this),
"datagram");
// Typically sending datagrams is best effort, but if we cannot create
// the packet, then we handle it as a fatal error.
if (packet == nullptr) {
last_error_ = QuicError::ForNgtcp2Error(NGTCP2_ERR_INTERNAL);
Close(CloseMethod::SILENT);
return 0;
}
pos = ngtcp2_vec(*packet).base;
}
ssize_t nwrite = ngtcp2_conn_writev_datagram(*this,
&path.path,
nullptr,
pos,
packet->length(),
&accepted,
flags,
did,
&vec,
1,
uv_hrtime());
ngtcp2_conn_update_pkt_tx_time(*this, uv_hrtime());
if (nwrite <= 0) {
// Nothing was written to the packet.
switch (nwrite) {
case 0: {
// We cannot send data because of congestion control or the data will
// not fit. Since datagrams are best effort, we are going to abandon
// the attempt and just return.
CHECK_EQ(accepted, 0);
packet->Done(UV_ECANCELED);
return 0;
}
case NGTCP2_ERR_WRITE_MORE: {
// We keep on looping! Keep on sending!
continue;
}
case NGTCP2_ERR_INVALID_STATE: {
// The remote endpoint does not want to accept datagrams. That's ok,
// just return 0.
packet->Done(UV_ECANCELED);
return 0;
}
case NGTCP2_ERR_INVALID_ARGUMENT: {
// The datagram is too large. That should have been caught above but
// that's ok. We'll just abandon the attempt and return.
packet->Done(UV_ECANCELED);
return 0;
}
case NGTCP2_ERR_PKT_NUM_EXHAUSTED: {
// We've exhausted the packet number space. Sadly we have to treat it
// as a fatal condition.
break;
}
case NGTCP2_ERR_CALLBACK_FAILURE: {
// There was an internal failure. Sadly we have to treat it as a fatal
// condition.
break;
}
}
packet->Done(UV_ECANCELED);
last_error_ = QuicError::ForNgtcp2Error(nwrite);
Close(CloseMethod::SILENT);
return 0;
}
// In this case, a complete packet was written and we need to send it along.
// Note that this doesn't mean that the packet actually contains the
// datagram! We'll check that next by checking the accepted value.
packet->Truncate(nwrite);
Send(std::move(packet));
if (accepted != 0) {
// Yay! The datagram was accepted into the packet we just sent and we can
// return the datagram ID.
Debug(this, "Session successfully encoded datagram");
STAT_INCREMENT(Stats, datagrams_sent);
STAT_INCREMENT_N(Stats, bytes_sent, vec.len);
state_->last_datagram_id = did;
return did;
}
// We sent a packet, but it wasn't the datagram packet. That can happen.
// Let's loop around and try again.
if (++attempts == kMaxAttempts) {
Debug(this, "Too many attempts to send the datagram");
// Too many attempts to send the datagram.
break;
}
}
return 0;
}
void Session::UpdatePath(const PathStorage& storage) {
remote_address_.Update(storage.path.remote.addr, storage.path.remote.addrlen);
local_address_.Update(storage.path.local.addr, storage.path.local.addrlen);