-
Notifications
You must be signed in to change notification settings - Fork 31.1k
/
Copy pathendpoint.cc
1343 lines (1159 loc) Β· 45.8 KB
/
endpoint.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 "endpoint.h"
#include <aliased_struct-inl.h>
#include <async_wrap-inl.h>
#include <env-inl.h>
#include <memory_tracker-inl.h>
#include <ngtcp2/ngtcp2.h>
#include <node_errors.h>
#include <node_sockaddr-inl.h>
#include <req_wrap-inl.h>
#include <util-inl.h>
#include <uv.h>
#include <v8.h>
#include "defs.h"
namespace node {
using v8::ArrayBufferView;
using v8::BackingStore;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Int32;
using v8::Integer;
using v8::Just;
using v8::Local;
using v8::Maybe;
using v8::Nothing;
using v8::Number;
using v8::Object;
using v8::PropertyAttribute;
using v8::String;
using v8::Value;
namespace quic {
// ============================================================================
namespace {
#ifdef DEBUG
bool is_diagnostic_packet_loss(double probability) {
if (LIKELY(probability == 0.0)) return false;
unsigned char c = 255;
CHECK(crypto::CSPRNG(&c, 1).is_ok());
return (static_cast<double>(c) / 255) < probability;
}
#endif // DEBUG
template <typename Opt, ngtcp2_cc_algo Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const v8::Local<v8::Object>& object,
const v8::Local<v8::String>& name) {
v8::Local<v8::Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) return false;
if (!value->IsUndefined()) {
int num = value.As<Int32>()->Value();
switch (num) {
case NGTCP2_CC_ALGO_RENO:
[[fallthrough]];
case NGTCP2_CC_ALGO_CUBIC:
[[fallthrough]];
case NGTCP2_CC_ALGO_BBR:
[[fallthrough]];
case NGTCP2_CC_ALGO_BBR2:
break;
default:
THROW_ERR_INVALID_ARG_VALUE(env, "The cc_algorithm is invalid");
return false;
}
options->*member = static_cast<ngtcp2_cc_algo>(num);
}
return true;
}
template <typename Opt, double Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const v8::Local<v8::Object>& object,
const v8::Local<v8::String>& name) {
v8::Local<v8::Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) return false;
if (!value->IsUndefined()) {
CHECK(value->IsNumber());
options->*member = value.As<Number>()->Value();
}
return true;
}
template <typename Opt, uint32_t Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const v8::Local<v8::Object>& object,
const v8::Local<v8::String>& name) {
v8::Local<v8::Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) return false;
if (!value->IsUndefined()) {
CHECK(value->IsNumber());
options->*member = value.As<Int32>()->Value();
}
return true;
}
template <typename Opt, uint8_t Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const v8::Local<v8::Object>& object,
const v8::Local<v8::String>& name) {
v8::Local<v8::Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) return false;
if (!value->IsUndefined()) {
CHECK(value->IsNumber());
options->*member = value.As<Int32>()->Value();
}
return true;
}
template <typename Opt, TokenSecret Opt::*member>
bool SetOption(Environment* env,
Opt* options,
const v8::Local<v8::Object>& object,
const v8::Local<v8::String>& name) {
v8::Local<v8::Value> value;
if (!object->Get(env->context(), name).ToLocal(&value)) return false;
if (!value->IsUndefined()) {
CHECK(value->IsArrayBufferView());
Store store(value.As<ArrayBufferView>());
CHECK_EQ(store.length(), TokenSecret::QUIC_TOKENSECRET_LEN);
ngtcp2_vec buf = store;
options->*member = buf.base;
}
return true;
}
} // namespace
Maybe<Endpoint::Options> Endpoint::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<Endpoint::Options, &Endpoint::Options::name>( \
env, &options, params, state.name##_string())
if (!SET(retry_token_expiration) || !SET(token_expiration) ||
!SET(max_connections_per_host) || !SET(max_connections_total) ||
!SET(max_stateless_resets) || !SET(address_lru_size) ||
!SET(max_retries) || !SET(max_payload_size) ||
!SET(unacknowledged_packet_threshold) || !SET(validate_address) ||
!SET(disable_stateless_reset) || !SET(ipv6_only) ||
#ifdef DEBUG
!SET(rx_loss) || !SET(tx_loss) ||
#endif
!SET(cc_algorithm) || !SET(udp_receive_buffer_size) ||
!SET(udp_send_buffer_size) || !SET(udp_ttl) || !SET(reset_token_secret) ||
!SET(token_secret)) {
return Nothing<Options>();
}
return Just<Options>(options);
#undef SET
}
void Endpoint::Options::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("reset_token_secret", reset_token_secret);
tracker->TrackField("token_secret", token_secret);
}
// ======================================================================================
// Endpoint::UDP and Endpoint::UDP::Impl
class Endpoint::UDP::Impl final : public HandleWrap {
public:
static Local<FunctionTemplate> GetConstructorTemplate(Environment* env) {
auto& state = BindingData::Get(env);
auto tmpl = state.udp_constructor_template();
if (tmpl.IsEmpty()) {
tmpl = NewFunctionTemplate(env->isolate(), IllegalConstructor);
tmpl->Inherit(HandleWrap::GetConstructorTemplate(env));
tmpl->InstanceTemplate()->SetInternalFieldCount(
HandleWrap::kInternalFieldCount);
tmpl->SetClassName(state.endpoint_udp_string());
state.set_udp_constructor_template(tmpl);
}
return tmpl;
}
static BaseObjectPtr<Impl> Create(Endpoint* endpoint) {
Local<Object> obj;
if (!GetConstructorTemplate(endpoint->env())
->InstanceTemplate()
->NewInstance(endpoint->env()->context())
.ToLocal(&obj)) {
return BaseObjectPtr<Impl>();
}
return MakeDetachedBaseObject<Impl>(endpoint, obj);
}
static Impl* From(uv_udp_t* handle) {
return ContainerOf(&Impl::handle_, handle);
}
static Impl* From(uv_handle_t* handle) {
return From(reinterpret_cast<uv_udp_t*>(handle));
}
Impl(Endpoint* endpoint, Local<Object> object)
: HandleWrap(endpoint->env(),
object,
reinterpret_cast<uv_handle_t*>(&handle_),
AsyncWrap::PROVIDER_QUIC_UDP),
endpoint_(endpoint) {
CHECK_EQ(uv_udp_init(endpoint->env()->event_loop(), &handle_), 0);
handle_.data = this;
}
SET_NO_MEMORY_INFO()
SET_MEMORY_INFO_NAME(Endpoint::UDP::Impl)
SET_SELF_SIZE(Impl)
private:
static void ClosedCb(uv_handle_t* handle) {
std::unique_ptr<Impl> ptr(From(handle));
}
static void OnAlloc(uv_handle_t* handle,
size_t suggested_size,
uv_buf_t* buf) {
*buf = From(handle)->env()->allocate_managed_buffer(suggested_size);
}
static void OnReceive(uv_udp_t* handle,
ssize_t nread,
const uv_buf_t* buf,
const sockaddr* addr,
unsigned int flags) {
// Nothing to do in these cases. Specifically, if the nread
// is zero or we've received a partial packet, we're just
// going to ignore it.
if (nread == 0 || flags & UV_UDP_PARTIAL) return;
auto impl = From(handle);
DCHECK_NOT_NULL(impl);
DCHECK_NOT_NULL(impl->endpoint_);
if (nread < 0) {
impl->endpoint_->Destroy(CloseContext::RECEIVE_FAILURE,
static_cast<int>(nread));
return;
}
impl->endpoint_->Receive(uv_buf_t{buf->base, static_cast<size_t>(nread)},
SocketAddress(addr));
}
uv_udp_t handle_;
Endpoint* endpoint_;
friend class UDP;
};
Endpoint::UDP::UDP(Endpoint* endpoint) : impl_(Impl::Create(endpoint)) {
endpoint->env()->AddCleanupHook(CleanupHook, this);
}
Endpoint::UDP::~UDP() {
Close();
}
int Endpoint::UDP::Bind(const Endpoint::Options& options) {
if (is_bound_) return UV_EALREADY;
if (is_closed() || impl_->IsHandleClosing()) return UV_EBADF;
int flags = 0;
if (options.local_address.family() == AF_INET6 && options.ipv6_only)
flags |= UV_UDP_IPV6ONLY;
int err = uv_udp_bind(&impl_->handle_, options.local_address.data(), flags);
int size;
if (!err) {
is_bound_ = true;
size = static_cast<int>(options.udp_receive_buffer_size);
if (size > 0) {
err = uv_recv_buffer_size(reinterpret_cast<uv_handle_t*>(&impl_->handle_),
&size);
if (err) return err;
}
size = static_cast<int>(options.udp_send_buffer_size);
if (size > 0) {
err = uv_send_buffer_size(reinterpret_cast<uv_handle_t*>(&impl_->handle_),
&size);
if (err) return err;
}
size = static_cast<int>(options.udp_ttl);
if (size > 0) {
err = uv_udp_set_ttl(&impl_->handle_, size);
if (err) return err;
}
}
return err;
}
void Endpoint::UDP::Ref() {
if (!is_closed()) uv_ref(reinterpret_cast<uv_handle_t*>(&impl_->handle_));
}
void Endpoint::UDP::Unref() {
if (!is_closed()) uv_unref(reinterpret_cast<uv_handle_t*>(&impl_->handle_));
}
int Endpoint::UDP::Start() {
if (is_closed() || impl_->IsHandleClosing()) return UV_EBADF;
if (is_started_) return 0;
int err = uv_udp_recv_start(&impl_->handle_, Impl::OnAlloc, Impl::OnReceive);
is_started_ = (err == 0);
return err;
}
void Endpoint::UDP::Stop() {
if (is_closed() || impl_->IsHandleClosing() || !is_started_) return;
USE(uv_udp_recv_stop(&impl_->handle_));
is_started_ = false;
}
void Endpoint::UDP::Close() {
if (is_closed() || impl_->IsHandleClosing()) return;
Stop();
is_bound_ = false;
impl_->env()->RemoveCleanupHook(CleanupHook, this);
impl_->Close();
impl_.reset();
}
bool Endpoint::UDP::is_bound() const {
return is_bound_;
}
bool Endpoint::UDP::is_closed() const {
return !impl_;
}
Endpoint::UDP::operator bool() const {
return !impl_;
}
SocketAddress Endpoint::UDP::local_address() const {
CHECK(!is_closed() && is_bound());
return SocketAddress::FromSockName(impl_->handle_);
}
int Endpoint::UDP::Send(BaseObjectPtr<Packet> packet) {
if (is_closed() || impl_->IsHandleClosing()) return UV_EBADF;
CHECK(packet && !packet->is_sending());
uv_buf_t buf = *packet;
return packet->Dispatch(
uv_udp_send,
&impl_->handle_,
&buf,
1,
packet->destination().data(),
uv_udp_send_cb{[](uv_udp_send_t* req, int status) {
auto ptr = static_cast<Packet*>(ReqWrap<uv_udp_send_t>::from_req(req));
ptr->Done(status);
}});
}
void Endpoint::UDP::MemoryInfo(MemoryTracker* tracker) const {
if (impl_) tracker->TrackField("impl", impl_);
}
void Endpoint::UDP::CleanupHook(void* data) {
static_cast<UDP*>(data)->Close();
}
// ============================================================================
bool Endpoint::HasInstance(Environment* env, Local<Value> value) {
return GetConstructorTemplate(env)->HasInstance(value);
}
Local<FunctionTemplate> Endpoint::GetConstructorTemplate(Environment* env) {
auto& state = BindingData::Get(env);
auto tmpl = state.endpoint_constructor_template();
if (tmpl.IsEmpty()) {
auto isolate = env->isolate();
tmpl = NewFunctionTemplate(isolate, IllegalConstructor);
tmpl->Inherit(AsyncWrap::GetConstructorTemplate(env));
tmpl->SetClassName(state.endpoint_string());
tmpl->InstanceTemplate()->SetInternalFieldCount(
Endpoint::kInternalFieldCount);
SetProtoMethod(isolate, tmpl, "listen", DoListen);
SetProtoMethod(isolate, tmpl, "closeGracefully", DoCloseGracefully);
SetProtoMethod(isolate, tmpl, "connect", DoConnect);
SetProtoMethod(isolate, tmpl, "markBusy", MarkBusy);
SetProtoMethod(isolate, tmpl, "ref", Ref);
SetProtoMethod(isolate, tmpl, "unref", Unref);
SetProtoMethodNoSideEffect(isolate, tmpl, "address", LocalAddress);
state.set_endpoint_constructor_template(tmpl);
}
return tmpl;
}
void Endpoint::Initialize(Environment* env, Local<Object> target) {
SetMethod(env->context(), target, "createEndpoint", CreateEndpoint);
#define V(name, _) NODE_DEFINE_CONSTANT(target, IDX_STATS_ENDPOINT_##name);
ENDPOINT_STATS(V)
#undef V
#define V(name, _, __) NODE_DEFINE_CONSTANT(target, IDX_STATE_ENDPOINT_##name);
ENDPOINT_STATE(V)
#undef V
}
void Endpoint::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(CreateEndpoint);
registry->Register(DoConnect);
registry->Register(DoListen);
registry->Register(DoCloseGracefully);
registry->Register(LocalAddress);
registry->Register(Ref);
registry->Register(Unref);
}
BaseObjectPtr<Endpoint> Endpoint::Create(Environment* env,
const Endpoint::Options& options) {
Local<Object> obj;
if (!GetConstructorTemplate(env)
->InstanceTemplate()
->NewInstance(env->context())
.ToLocal(&obj)) {
return BaseObjectPtr<Endpoint>();
}
return MakeDetachedBaseObject<Endpoint>(env, obj, options);
}
Endpoint::Endpoint(Environment* env,
Local<Object> object,
const Endpoint::Options& options)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_QUIC_ENDPOINT),
stats_(env->isolate()),
state_(env->isolate()),
options_(std::move(options)),
udp_(this),
addrLRU_(options_.address_lru_size) {
MakeWeak();
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());
}
Endpoint::~Endpoint() {
udp_.Close();
DCHECK_EQ(state_->pending_callbacks, 0);
DCHECK(sessions_.empty());
DCHECK(is_closed());
}
SocketAddress Endpoint::local_address() const {
CHECK(!is_closed());
return udp_.local_address();
}
void Endpoint::MarkAsBusy(bool on) {
state_->busy = on ? 1 : 0;
}
Maybe<RegularToken> Endpoint::GenerateNewToken(
uint32_t version, const SocketAddress& remote_address) {
if (is_closed() || is_closing()) {
THROW_ERR_INVALID_STATE(env(),
"Endpoint is closed. Unable to create token.");
return Nothing<RegularToken>();
}
return Just(RegularToken(version, remote_address, options_.token_secret));
}
Maybe<StatelessResetToken> Endpoint::GenerateNewStatelessResetToken(
uint8_t* token, const CID& cid) const {
if (is_closed() || is_closing()) {
THROW_ERR_INVALID_STATE(env(),
"Endpoint is closed. Unable to create token.");
return Nothing<StatelessResetToken>();
}
return Just(StatelessResetToken(token, options_.reset_token_secret, cid));
}
void Endpoint::AddSession(const CID& cid, BaseObjectPtr<Session> session) {
if (is_closed() || is_closing()) return;
sessions_[cid] = session;
IncrementSocketAddressCounter(session->remote_address());
if (session->is_server()) {
STAT_INCREMENT(Stats, server_sessions);
} else {
STAT_INCREMENT(Stats, client_sessions);
}
if (session->is_server()) EmitNewSession(session);
}
void Endpoint::RemoveSession(const CID& cid) {
if (is_closed()) return;
auto session = FindSession(cid);
if (!session) return;
DecrementSocketAddressCounter(session->remote_address());
sessions_.erase(cid);
if (state_->waiting_for_callbacks == 1) MaybeDestroy();
}
BaseObjectPtr<Session> Endpoint::FindSession(const CID& cid) {
BaseObjectPtr<Session> session;
auto session_it = sessions_.find(cid);
if (session_it == std::end(sessions_)) {
auto scid_it = dcid_to_scid_.find(cid);
if (scid_it != std::end(dcid_to_scid_)) {
session_it = sessions_.find(scid_it->second);
CHECK_NE(session_it, std::end(sessions_));
session = session_it->second;
}
} else {
session = session_it->second;
}
return session;
}
void Endpoint::AssociateCID(const CID& cid, const CID& scid) {
if (!is_closed() && !is_closing() && cid && scid && cid != scid &&
dcid_to_scid_[cid] != scid) {
dcid_to_scid_.emplace(cid, scid);
}
}
void Endpoint::DisassociateCID(const CID& cid) {
if (!is_closed() && cid) dcid_to_scid_.erase(cid);
}
void Endpoint::AssociateStatelessResetToken(const StatelessResetToken& token,
Session* session) {
if (is_closed() || is_closing()) return;
token_map_[token] = session;
}
void Endpoint::DisassociateStatelessResetToken(
const StatelessResetToken& token) {
if (!is_closed()) token_map_.erase(token);
}
void Endpoint::Send(BaseObjectPtr<Packet> packet) {
#ifdef DEBUG
// When diagnostic packet loss is enabled, the packet will be randomly
// dropped. This can happen to any type of packet. We use this only in
// testing to test various reliability issues.
if (UNLIKELY(is_diagnostic_packet_loss(options_.tx_loss))) {
packet->Done(0);
// Simulating tx packet loss
return;
}
#endif // DEBUG
if (is_closed() || is_closing() || packet->length() == 0) return;
state_->pending_callbacks++;
int err = udp_.Send(packet);
if (err != 0) {
packet->Done(err);
Destroy(CloseContext::SEND_FAILURE, err);
}
STAT_INCREMENT_N(Stats, bytes_sent, packet->length());
STAT_INCREMENT(Stats, packets_sent);
}
void Endpoint::SendRetry(const PathDescriptor& options) {
// Generating and sending retry packets does consume some system resources,
// and it is possible for a malicious peer to trigger sending a large number
// of retry packets, resulting in a potential DOS vector. To help ward that
// off, we track how many retry packets we send to a particular host and
// enforce limits. Note that since we are using an LRU cache these limits
// aren't strict. If a retry is sent, we increment the retry_count statistic
// to give application code a means of detecting and responding to abuse on
// its own. What this count does not give is the rate of retry, so it is still
// somewhat limited.
auto info = addrLRU_.Upsert(options.remote_address);
if (++(info->retry_count) <= options_.max_retries) {
auto packet =
Packet::CreateRetryPacket(env(), this, options, options_.token_secret);
if (packet) {
STAT_INCREMENT(Stats, retry_count);
Send(std::move(packet));
}
// If creating the retry is unsuccessful, we just drop things on the floor.
// It's not worth committing any further resources to this one packet. We
// might want to log the failure at some point tho.
}
}
void Endpoint::SendVersionNegotiation(const PathDescriptor& options) {
// While creating and sending a version negotiation packet does consume a
// small amount of system resources, and while it is fairly trivial for a
// malicious peer to force a version negotiation to be sent, these are more
// trivial to create than the cryptographically generated retry and stateless
// reset packets. If the packet is sent, then we'll at least increment the
// version_negotiation_count statistic so that application code can keep an
// eye on it.
auto packet = Packet::CreateVersionNegotiationPacket(env(), this, options);
if (packet) {
STAT_INCREMENT(Stats, version_negotiation_count);
Send(std::move(packet));
}
// If creating the packet is unsuccessful, we just drop things on the floor.
// It's not worth committing any further resources to this one packet. We
// might want to log the failure at some point tho.
}
bool Endpoint::SendStatelessReset(const PathDescriptor& options,
size_t source_len) {
if (UNLIKELY(options_.disable_stateless_reset)) return false;
const auto exceeds_limits = [&] {
SocketAddressInfoTraits::Type* counts =
addrLRU_.Peek(options.remote_address);
auto count = counts != nullptr ? counts->reset_count : 0;
return count >= options_.max_stateless_resets;
};
// Per the QUIC spec, we need to protect against sending too many stateless
// reset tokens to an endpoint to prevent endless looping.
if (exceeds_limits()) return false;
auto packet = Packet::CreateStatelessResetPacket(
env(), this, options, options_.reset_token_secret, source_len);
if (packet) {
addrLRU_.Upsert(options.remote_address)->reset_count++;
STAT_INCREMENT(Stats, stateless_reset_count);
Send(std::move(packet));
return true;
}
return false;
}
void Endpoint::SendImmediateConnectionClose(const PathDescriptor& options,
QuicError reason) {
// While it is possible for a malicious peer to cause us to create a large
// number of these, generating them is fairly trivial.
auto packet = Packet::CreateImmediateConnectionClosePacket(
env(), this, options, reason);
if (packet) {
STAT_INCREMENT(Stats, immediate_close_count);
Send(std::move(packet));
}
}
bool Endpoint::Start() {
if (is_closed() || is_closing()) return false;
if (state_->receiving == 1) return true;
int err = 0;
if (state_->bound == 0) {
err = udp_.Bind(options_);
if (err != 0) {
// If we failed to bind, destroy the endpoint. There's nothing we can do.
Destroy(CloseContext::BIND_FAILURE, err);
return false;
}
state_->bound = 1;
}
err = udp_.Start();
if (err != 0) {
// If we failed to start listening, destroy the endpoint. There's nothing we
// can do.
Destroy(CloseContext::START_FAILURE, err);
return false;
}
BindingData::Get(env()).listening_endpoints[this] =
BaseObjectPtr<Endpoint>(this);
state_->receiving = 1;
return true;
}
void Endpoint::Listen(const Session::Options& options) {
if (is_closed() || is_closing() || state_->listening == 1) return;
server_options_ = options;
if (Start()) state_->listening = 1;
}
BaseObjectPtr<Session> Endpoint::Connect(
const SocketAddress& remote_address,
const Session::Options& options,
std::optional<SessionTicket> sessionTicket) {
// TODO(@jasnell): Implement as part of Session...
// If starting fails, the endpoint will be destroyed.
if (!Start()) return BaseObjectPtr<Session>();
// auto config = Session::Config(
// Side::CLIENT,
// *this,
// // For client sessions, we always generate a random intial CID for the
// // server. This is generally just a throwaway. The server will generate
// // it's own CID and send that back to us.
// CIDFactory::random().Generate(NGTCP2_MIN_INITIAL_DCIDLEN),
// local_address(),
// remote_address);
// if (options.qlog) config.EnableQLog();
// config.session_ticket = sessionTicket;
// auto session =
// Session::Create(BaseObjectPtr<Endpoint>(this), config, options);
// if (!session) return BaseObjectPtr<Session>();
// session->set_wrapped();
// auto on_exit = OnScopeLeave([&] { session->SendPendingData(); });
return BaseObjectPtr<Session>();
}
void Endpoint::MaybeDestroy() {
if (!is_closing() && sessions_.empty() && state_->pending_callbacks == 0 &&
state_->listening == 0) {
Destroy();
}
}
void Endpoint::Destroy(CloseContext context, int status) {
if (is_closed() || is_closing()) return;
STAT_RECORD_TIMESTAMP(Stats, destroyed_at);
state_->closing = 1;
state_->listening = 0;
close_context_ = context;
close_status_ = status;
// If there are open sessions still, shut them down. As those clean themselves
// up, they will remove themselves. The cleanup here will be synchronous and
// no attempt will be made to communicate further with the peer.
// Intentionally copy the sessions map so that we can safely iterate over it
// while those clean themselves up.
auto sessions = sessions_;
for (auto& session : sessions)
session.second->Close(Session::CloseMethod::SILENT);
sessions.clear();
CHECK(sessions_.empty());
token_map_.clear();
dcid_to_scid_.clear();
udp_.Close();
state_->closing = 0;
state_->bound = 0;
state_->receiving = 0;
BindingData::Get(env()).listening_endpoints.erase(this);
EmitClose(close_context_, close_status_);
}
void Endpoint::CloseGracefully() {
if (!is_closed() && !is_closing() && state_->waiting_for_callbacks == 0) {
state_->listening = 0;
state_->waiting_for_callbacks = 1;
}
// Maybe we can go ahead and destroy now?
MaybeDestroy();
}
void Endpoint::Receive(const uv_buf_t& buf,
const SocketAddress& remote_address) {
const auto receive = [&](Store&& store,
const SocketAddress& local_address,
const SocketAddress& remote_address,
const CID& dcid,
const CID& scid) {
STAT_INCREMENT_N(Stats, bytes_received, store.length());
auto session = FindSession(dcid);
return session && !session->is_destroyed()
? session->Receive(
std::move(store), local_address, remote_address)
: false;
};
const auto accept = [&](const Session::Config& config, Store&& store) {
if (is_closed() || is_closing() || !is_listening()) return false;
auto session = Session::Create(
BaseObjectPtr<Endpoint>(this), config, server_options_.value());
return session ? session->Receive(std::move(store),
config.local_address,
config.remote_address)
: false;
};
const auto acceptInitialPacket = [&](const uint32_t version,
const CID& dcid,
const CID& scid,
Store&& store,
const SocketAddress& local_address,
const SocketAddress& remote_address) {
// Conditionally accept an initial packet to create a new session.
// If we're not listening, do not accept.
if (state_->listening == 0) return false;
ngtcp2_pkt_hd hd;
// This is our first condition check... A minimal check to see if ngtcp2 can
// even recognize this packet as a quic packet with the correct version.
ngtcp2_vec vec = store;
switch (ngtcp2_accept(&hd, vec.base, vec.len)) {
case 1:
// The requested QUIC protocol version is not supported
SendVersionNegotiation(
PathDescriptor{version, dcid, scid, local_address, remote_address});
// The packet was successfully processed, even if we did refuse the
// connection and send a version negotiation in response.
return true;
case -1:
// The packet is invalid and we're just going to ignore it.
return false;
}
// This is the second condition check... If the server has been marked busy
// or the remote peer has exceeded their maximum number of concurrent
// connections, any new connections will be shut down immediately.
const auto limits_exceeded = [&] {
if (sessions_.size() >= options_.max_connections_total) return true;
SocketAddressInfoTraits::Type* counts = addrLRU_.Peek(remote_address);
auto count = counts != nullptr ? counts->active_connections : 0;
return count >= options_.max_connections_per_host;
};
if (state_->busy || limits_exceeded()) {
// Endpoint is busy or the connection count is exceeded. The connection is
// refused.
if (state_->busy) STAT_INCREMENT(Stats, server_busy_count);
SendImmediateConnectionClose(
PathDescriptor{version, scid, dcid, local_address, remote_address},
QuicError::ForTransport(NGTCP2_CONNECTION_REFUSED));
// The packet was successfully processed, even if we did refuse the
// connection.
return true;
}
// At this point, we start to set up the configuration for our local
// session. The second argument to the Config constructor here is the dcid.
// We pass the received scid here as the value because that is the value
// *this* session will use as it's outbound dcid.
auto config = Session::Config(Side::SERVER,
*this,
scid,
local_address,
remote_address,
version,
version,
dcid);
// The this point, the config.scid and config.dcid represent *our* views of
// the CIDs. Specifically, config.dcid identifies the peer and config.scid
// identifies us. config.dcid should equal scid. config.scid should *not*
// equal dcid.
const auto is_remote_address_validated = [&] {
auto info = addrLRU_.Peek(remote_address);
return info != nullptr ? info->validated : false;
};
// QUIC has address validation built in to the handshake but allows for
// an additional explicit validation request using RETRY frames. If we
// are using explicit validation, we check for the existence of a valid
// token in the packet. If one does not exist, we send a retry with
// a new token. If it does exist, and if it's valid, we grab the original
// cid and continue.
if (!is_remote_address_validated()) {
switch (hd.type) {
case NGTCP2_PKT_INITIAL:
// First, let's see if we need to do anything here.
if (options_.validate_address) {
// If there is no token, generate and send one.
if (hd.token.len == 0) {
SendRetry(PathDescriptor{
version,
dcid,
scid,
local_address,
remote_address,
});
// We still consider this a successfully handled packet even
// if we send a retry.
return true;
}
// We have two kinds of tokens, each prefixed with a different magic
// byte.
switch (hd.token.base[0]) {
case RetryToken::kTokenMagic: {
RetryToken token(hd.token.base, hd.token.len);
auto ocid = token.Validate(
version,
remote_address,
dcid,
options_.token_secret,
options_.retry_token_expiration * NGTCP2_SECONDS);
if (ocid == std::nullopt) {
// Invalid retry token was detected. Close the connection.
SendImmediateConnectionClose(
PathDescriptor{
version, scid, dcid, local_address, remote_address},
QuicError::ForTransport(NGTCP2_CONNECTION_REFUSED));
// We still consider this a successfully handled packet even
// if we send a connection close.
return true;
}
// The ocid is the original dcid that was encoded into the
// original retry packet sent to the client. We use it for
// validation.
config.ocid.emplace(ocid.value());
config.retry_scid.emplace(dcid);
break;
}
case RegularToken::kTokenMagic: {
RegularToken token(hd.token.base, hd.token.len);
if (!token.Validate(
version,
remote_address,
options_.token_secret,
options_.token_expiration * NGTCP2_SECONDS)) {
SendRetry(PathDescriptor{
version,
dcid,
scid,
local_address,
remote_address,
});
// We still consider this to be a successfully handled packet
// if a retry is sent.
return true;
}
hd.token.base = nullptr;
hd.token.len = 0;
break;
}
default: {
SendRetry(PathDescriptor{
version,
dcid,
scid,
local_address,
remote_address,
});
return true;
}
}
// Ok! If we've got this far, our token is valid! Which means our
// path to the remote address is valid (for now). Let's record that
// so we don't have to do this dance again for this endpoint
// instance.
addrLRU_.Upsert(remote_address)->validated = true;
} else if (hd.token.len > 0) {
// If validation is turned off and there is a token, that's weird.
// The peer should only have a token if we sent it to them and we
// wouldn't have sent it unless validation was turned on. Let's
// assume the peer is buggy or malicious and drop the packet on the
// floor.
return false;
}
break;
case NGTCP2_PKT_0RTT:
// If it's a 0RTT packet, we're always going to perform path
// validation no matter what. This is a bit unfortunate since
// ORTT is supposed to be, you know, 0RTT, but sending a retry
// forces a round trip... but if the remote address is not