forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendpoint.cc
1771 lines (1569 loc) · 64.3 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 <debug_utils-inl.h>
#include <env-inl.h>
#include <memory_tracker-inl.h>
#include <ngtcp2/ngtcp2.h>
#include <node_errors.h>
#include <node_external_reference.h>
#include <node_process-inl.h>
#include <node_sockaddr-inl.h>
#include <req_wrap-inl.h>
#include <util-inl.h>
#include <uv.h>
#include <v8.h>
#include <limits>
#include "application.h"
#include "bindingdata.h"
#include "defs.h"
#include "http3.h"
#include "ncrypto.h"
namespace node {
using v8::ArrayBufferView;
using v8::BackingStore;
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::Number;
using v8::Object;
using v8::ObjectTemplate;
using v8::PropertyAttribute;
using v8::String;
using v8::Uint32;
using v8::Value;
namespace quic {
#define ENDPOINT_STATE(V) \
/* Bound to the UDP port */ \
V(BOUND, bound, uint8_t) \
/* Receiving packets on the UDP port */ \
V(RECEIVING, receiving, uint8_t) \
/* Listening as a QUIC server */ \
V(LISTENING, listening, uint8_t) \
/* In the process of closing down, waiting for pending send callbacks */ \
V(CLOSING, closing, uint8_t) \
/* Temporarily paused serving new initial requests */ \
V(BUSY, busy, uint8_t) \
/* The number of pending send callbacks */ \
V(PENDING_CALLBACKS, pending_callbacks, uint64_t)
#define ENDPOINT_STATS(V) \
V(CREATED_AT, created_at) \
V(DESTROYED_AT, destroyed_at) \
V(BYTES_RECEIVED, bytes_received) \
V(BYTES_SENT, bytes_sent) \
V(PACKETS_RECEIVED, packets_received) \
V(PACKETS_SENT, packets_sent) \
V(SERVER_SESSIONS, server_sessions) \
V(CLIENT_SESSIONS, client_sessions) \
V(SERVER_BUSY_COUNT, server_busy_count) \
V(RETRY_COUNT, retry_count) \
V(VERSION_NEGOTIATION_COUNT, version_negotiation_count) \
V(STATELESS_RESET_COUNT, stateless_reset_count) \
V(IMMEDIATE_CLOSE_COUNT, immediate_close_count)
struct Endpoint::State {
#define V(_, name, type) type name;
ENDPOINT_STATE(V)
#undef V
};
STAT_STRUCT(Endpoint, ENDPOINT)
// ============================================================================
// Endpoint::Options
namespace {
#ifdef DEBUG
bool is_diagnostic_packet_loss(double probability) {
if (probability == 0.0) [[unlikely]] {
return false;
}
unsigned char c = 255;
CHECK(ncrypto::CSPRNG(&c, 1));
return (static_cast<double>(c) / 255) < probability;
}
template <typename Opt, double 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()) {
Local<Number> num;
if (!value->ToNumber(env->context()).ToLocal(&num)) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env, "The %s option must be a number", *nameStr);
return false;
}
options->*member = num->Value();
}
return true;
}
#endif // DEBUG
template <typename Opt, uint8_t 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()) {
if (!value->IsUint32()) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env, "The %s option must be an uint8", *nameStr);
return false;
}
Local<Uint32> num;
if (!value->ToUint32(env->context()).ToLocal(&num) ||
num->Value() > std::numeric_limits<uint8_t>::max()) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env, "The %s option must be an uint8", *nameStr);
return false;
}
options->*member = num->Value();
}
return true;
}
template <typename Opt, TokenSecret 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()) {
if (!value->IsArrayBufferView()) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env, "The %s option must be an ArrayBufferView", *nameStr);
return false;
}
Store store(value.As<ArrayBufferView>());
if (store.length() != TokenSecret::QUIC_TOKENSECRET_LEN) {
Utf8Value nameStr(env->isolate(), name);
THROW_ERR_INVALID_ARG_VALUE(
env,
"The %s option must be an ArrayBufferView of length %d",
*nameStr,
TokenSecret::QUIC_TOKENSECRET_LEN);
return false;
}
ngtcp2_vec buf = store;
TokenSecret secret(buf.base);
options->*member = secret;
}
return true;
}
} // namespace
Maybe<Endpoint::Options> Endpoint::Options::From(Environment* env,
Local<Value> value) {
if (value.IsEmpty() || !value->IsObject()) {
if (value->IsUndefined()) return Just(Endpoint::Options());
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(validate_address) ||
!SET(disable_stateless_reset) || !SET(ipv6_only) ||
#ifdef DEBUG
!SET(rx_loss) || !SET(tx_loss) ||
#endif
!SET(udp_receive_buffer_size) || !SET(udp_send_buffer_size) ||
!SET(udp_ttl) || !SET(reset_token_secret) || !SET(token_secret)) {
return Nothing<Options>();
}
Local<Value> address;
if (!params->Get(env->context(), env->address_string()).ToLocal(&address)) {
return Nothing<Options>();
}
if (!address->IsUndefined()) {
if (!SocketAddressBase::HasInstance(env, address)) {
THROW_ERR_INVALID_ARG_TYPE(env,
"The address option must be a SocketAddress");
return Nothing<Options>();
}
auto addr = FromJSObject<SocketAddressBase>(address.As<v8::Object>());
options.local_address = addr->address();
} else {
options.local_address = std::make_shared<SocketAddress>();
if (!SocketAddress::New("127.0.0.1", 0, options.local_address.get())) {
THROW_ERR_INVALID_ADDRESS(env);
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);
}
std::string Endpoint::Options::ToString() const {
DebugIndentScope indent;
auto prefix = indent.Prefix();
auto boolToString = [](uint8_t val) {
return val ? std::string("yes") : std::string("no");
};
std::string res = "{ ";
res += prefix + "local address: " + local_address->ToString();
res += prefix +
"retry token expiration: " + std::to_string(retry_token_expiration) +
" seconds";
res += prefix + "token expiration: " + std::to_string(token_expiration) +
" seconds";
res += prefix + "max connections per host: " +
std::to_string(max_connections_per_host);
res += prefix +
"max connections total: " + std::to_string(max_connections_total);
res +=
prefix + "max stateless resets: " + std::to_string(max_stateless_resets);
res += prefix + "address lru size: " + std::to_string(address_lru_size);
res += prefix + "max retries: " + std::to_string(max_retries);
res += prefix + "validate address: " + boolToString(validate_address);
res += prefix +
"disable stateless reset: " + boolToString(disable_stateless_reset);
#ifdef DEBUG
res += prefix + "rx loss: " + std::to_string(rx_loss);
res += prefix + "tx loss: " + std::to_string(tx_loss);
#endif
res += prefix + "reset token secret: " + reset_token_secret.ToString();
res += prefix + "token secret: " + token_secret.ToString();
res += prefix + "ipv6 only: " + boolToString(ipv6_only);
res += prefix +
"udp receive buffer size: " + std::to_string(udp_receive_buffer_size);
res +=
prefix + "udp send buffer size: " + std::to_string(udp_send_buffer_size);
res += prefix + "udp ttl: " + std::to_string(udp_ttl);
res += indent.Close();
return res;
}
// ======================================================================================
// 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 Impl* Create(Endpoint* endpoint) {
Local<Object> obj;
if (!GetConstructorTemplate(endpoint->env())
->InstanceTemplate()
->NewInstance(endpoint->env()->context())
.ToLocal(&obj)) {
return nullptr;
}
return new 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 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_init(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)) {
DCHECK(impl_);
// The endpoint starts in an inactive, unref'd state. It will be ref'd when
// the endpoint is either configured to listen as a server or when then are
// active client sessions.
Unref();
}
Endpoint::UDP::~UDP() {
Close();
}
int Endpoint::UDP::Bind(const Endpoint::Options& options) {
if (is_bound_) return UV_EALREADY;
if (is_closed_or_closing()) 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_or_closing()) {
uv_ref(reinterpret_cast<uv_handle_t*>(&impl_->handle_));
}
}
void Endpoint::UDP::Unref() {
if (!is_closed_or_closing()) {
uv_unref(reinterpret_cast<uv_handle_t*>(&impl_->handle_));
}
}
int Endpoint::UDP::Start() {
if (is_closed_or_closing()) 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_or_closing() || !is_started_) return;
USE(uv_udp_recv_stop(&impl_->handle_));
is_started_ = false;
}
void Endpoint::UDP::Close() {
if (is_closed_or_closing()) return;
DCHECK(impl_);
Stop();
is_bound_ = false;
is_closed_ = true;
impl_->Close();
impl_.reset();
}
bool Endpoint::UDP::is_bound() const {
return is_bound_;
}
bool Endpoint::UDP::is_closed() const {
return is_closed_;
}
bool Endpoint::UDP::is_closed_or_closing() const {
if (is_closed() || !impl_) return true;
return impl_->IsHandleClosing();
}
Endpoint::UDP::operator bool() const {
return impl_;
}
SocketAddress Endpoint::UDP::local_address() const {
DCHECK(!is_closed_or_closing() && is_bound());
return SocketAddress::FromSockName(impl_->handle_);
}
int Endpoint::UDP::Send(const BaseObjectPtr<Packet>& packet) {
DCHECK(packet);
DCHECK(!packet->IsDispatched());
if (is_closed_or_closing()) return UV_EBADF;
uv_buf_t buf = *packet;
// We don't use the default implementation of Dispatch because the packet
// itself is going to be reset and added to a freelist to be reused. The
// default implementation of Dispatch will cause the packet to be deleted,
// which we don't want.
packet->ClearWeak();
packet->Dispatched();
int err = uv_udp_send(packet->req(),
&impl_->handle_,
&buf,
1,
packet->destination().data(),
uv_udp_send_cb{[](uv_udp_send_t* req, int status) {
auto ptr = BaseObjectPtr<Packet>(static_cast<Packet*>(
ReqWrap<uv_udp_send_t>::from_req(req)));
ptr->env()->DecreaseWaitingRequestCounter();
ptr->Done(status);
}});
if (err < 0) {
// The packet failed.
packet->Done(err);
packet->MakeWeak();
} else {
packet->env()->IncreaseWaitingRequestCounter();
}
return err;
}
void Endpoint::UDP::MemoryInfo(MemoryTracker* tracker) const {
if (impl_) tracker->TrackField("impl", impl_);
}
// ============================================================================
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, New);
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);
SetProtoMethodNoSideEffect(isolate, tmpl, "address", LocalAddress);
state.set_endpoint_constructor_template(tmpl);
}
return tmpl;
}
void Endpoint::InitPerIsolate(IsolateData* data, Local<ObjectTemplate> target) {
// TODO(@jasnell): Implement the per-isolate state
Http3Application::InitPerIsolate(data, target);
}
void Endpoint::InitPerContext(Realm* realm, Local<Object> target) {
#define V(name, _) IDX_STATS_ENDPOINT_##name,
enum IDX_STATS_ENDPOINT { ENDPOINT_STATS(V) IDX_STATS_ENDPOINT_COUNT };
NODE_DEFINE_CONSTANT(target, IDX_STATS_ENDPOINT_COUNT);
#undef V
#define V(name, key) NODE_DEFINE_CONSTANT(target, IDX_STATS_ENDPOINT_##name);
ENDPOINT_STATS(V);
#undef V
#define V(name, key, type) \
static constexpr auto IDX_STATE_ENDPOINT_##name = \
offsetof(Endpoint::State, key); \
static constexpr auto IDX_STATE_ENDPOINT_##name##_SIZE = sizeof(type); \
NODE_DEFINE_CONSTANT(target, IDX_STATE_ENDPOINT_##name); \
NODE_DEFINE_CONSTANT(target, IDX_STATE_ENDPOINT_##name##_SIZE);
ENDPOINT_STATE(V)
#undef V
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_CONNECTIONS);
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_CONNECTIONS_PER_HOST);
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_SOCKETADDRESS_LRU_SIZE);
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_STATELESS_RESETS);
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_RETRY_LIMIT);
static constexpr auto DEFAULT_RETRYTOKEN_EXPIRATION =
RetryToken::QUIC_DEFAULT_RETRYTOKEN_EXPIRATION / NGTCP2_SECONDS;
static constexpr auto DEFAULT_REGULARTOKEN_EXPIRATION =
RegularToken::QUIC_DEFAULT_REGULARTOKEN_EXPIRATION / NGTCP2_SECONDS;
static constexpr auto DEFAULT_MAX_PACKET_LENGTH = kDefaultMaxPacketLength;
NODE_DEFINE_CONSTANT(target, DEFAULT_RETRYTOKEN_EXPIRATION);
NODE_DEFINE_CONSTANT(target, DEFAULT_REGULARTOKEN_EXPIRATION);
NODE_DEFINE_CONSTANT(target, DEFAULT_MAX_PACKET_LENGTH);
static constexpr auto CLOSECONTEXT_CLOSE =
static_cast<int>(CloseContext::CLOSE);
static constexpr auto CLOSECONTEXT_BIND_FAILURE =
static_cast<int>(CloseContext::BIND_FAILURE);
static constexpr auto CLOSECONTEXT_LISTEN_FAILURE =
static_cast<int>(CloseContext::LISTEN_FAILURE);
static constexpr auto CLOSECONTEXT_RECEIVE_FAILURE =
static_cast<int>(CloseContext::RECEIVE_FAILURE);
static constexpr auto CLOSECONTEXT_SEND_FAILURE =
static_cast<int>(CloseContext::SEND_FAILURE);
static constexpr auto CLOSECONTEXT_START_FAILURE =
static_cast<int>(CloseContext::START_FAILURE);
NODE_DEFINE_CONSTANT(target, CLOSECONTEXT_CLOSE);
NODE_DEFINE_CONSTANT(target, CLOSECONTEXT_BIND_FAILURE);
NODE_DEFINE_CONSTANT(target, CLOSECONTEXT_LISTEN_FAILURE);
NODE_DEFINE_CONSTANT(target, CLOSECONTEXT_RECEIVE_FAILURE);
NODE_DEFINE_CONSTANT(target, CLOSECONTEXT_SEND_FAILURE);
NODE_DEFINE_CONSTANT(target, CLOSECONTEXT_START_FAILURE);
Http3Application::InitPerContext(realm, target);
SetConstructorFunction(realm->context(),
target,
"Endpoint",
GetConstructorTemplate(realm->env()));
}
void Endpoint::RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(New);
registry->Register(DoConnect);
registry->Register(DoListen);
registry->Register(DoCloseGracefully);
registry->Register(LocalAddress);
registry->Register(Ref);
registry->Register(MarkBusy);
}
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_(options),
udp_(this),
addrLRU_(options_.address_lru_size) {
MakeWeak();
udp_.Unref();
STAT_RECORD_TIMESTAMP(Stats, created_at);
IF_QUIC_DEBUG(env) {
Debug(this, "Endpoint created. Options %s", options.ToString());
}
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());
}
SocketAddress Endpoint::local_address() const {
DCHECK(!is_closed() && !is_closing());
return udp_.local_address();
}
void Endpoint::MarkAsBusy(bool on) {
Debug(this, "Marking endpoint as %s", on ? "busy" : "not busy");
if (on) STAT_INCREMENT(Stats, server_busy_count);
state_->busy = on ? 1 : 0;
}
RegularToken Endpoint::GenerateNewToken(uint32_t version,
const SocketAddress& remote_address) {
Debug(this,
"Generating new regular token for version %u and remote address %s",
version,
remote_address);
DCHECK(!is_closed() && !is_closing());
return RegularToken(version, remote_address, options_.token_secret);
}
StatelessResetToken Endpoint::GenerateNewStatelessResetToken(
uint8_t* token, const CID& cid) const {
Debug(const_cast<Endpoint*>(this),
"Generating new stateless reset token for CID %s",
cid);
DCHECK(!is_closed() && !is_closing());
return StatelessResetToken(token, options_.reset_token_secret, cid);
}
void Endpoint::AddSession(const CID& cid, BaseObjectPtr<Session> session) {
DCHECK(!is_closed() && !is_closing());
Debug(this, "Adding session for CID %s", cid);
IncrementSocketAddressCounter(session->remote_address());
AssociateCID(session->config().dcid, session->config().scid);
sessions_[cid] = session;
if (session->is_server()) {
STAT_INCREMENT(Stats, server_sessions);
// We only emit the new session event for server sessions.
EmitNewSession(session);
// It is important to note that the session may be closed/destroyed
// when it is emitted here.
} else {
STAT_INCREMENT(Stats, client_sessions);
}
udp_.Ref();
}
void Endpoint::RemoveSession(const CID& cid,
const SocketAddress& remote_address) {
if (is_closed()) return;
Debug(this, "Removing session for CID %s", cid);
if (sessions_.erase(cid)) {
DecrementSocketAddressCounter(remote_address);
}
if (sessions_.empty()) {
udp_.Unref();
}
if (state_->closing == 1) MaybeDestroy();
}
BaseObjectPtr<Session> Endpoint::FindSession(const CID& cid) {
auto session_it = sessions_.find(cid);
if (session_it == std::end(sessions_)) {
// If our given cid is not a match that doesn't mean we
// give up. A session might be identified by multiple
// CIDs. Let's see if our secondary map has a match!
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_));
return session_it->second;
}
// No match found.
return {};
}
// Match found!
return session_it->second;
}
void Endpoint::AssociateCID(const CID& cid, const CID& scid) {
if (!is_closed() && !is_closing() && cid && scid && cid != scid &&
dcid_to_scid_[cid] != scid) {
Debug(this, "Associating CID %s with SCID %s", cid, scid);
dcid_to_scid_.emplace(cid, scid);
}
}
void Endpoint::DisassociateCID(const CID& cid) {
if (!is_closed() && cid) {
Debug(this, "Disassociating CID %s", cid);
dcid_to_scid_.erase(cid);
}
}
void Endpoint::AssociateStatelessResetToken(const StatelessResetToken& token,
Session* session) {
if (is_closed() || is_closing()) return;
Debug(this, "Associating stateless reset token %s with session", token);
token_map_[token] = session;
}
void Endpoint::DisassociateStatelessResetToken(
const StatelessResetToken& token) {
if (!is_closed()) {
Debug(this, "Disassociating stateless reset token %s", token);
token_map_.erase(token);
}
}
void Endpoint::Send(const 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 (is_diagnostic_packet_loss(options_.tx_loss)) [[unlikely]] {
packet->Done(0);
// Simulating tx packet loss
return;
}
#endif // DEBUG
if (is_closed() || is_closing() || packet->length() == 0) {
packet->Done(UV_ECANCELED);
return;
}
Debug(this, "Sending %s", packet->ToString());
state_->pending_callbacks++;
int err = udp_.Send(packet);
if (err != 0) {
Debug(this, "Sending packet failed with error %d", err);
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.
Debug(this, "Sending retry on path %s", options);
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));
packet.reset();
}
// 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) {
Debug(this, "Sending version negotiation on path %s", 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));
packet.reset();
}
// 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 (options_.disable_stateless_reset) [[unlikely]] {
return false;
}
Debug(this,
"Sending stateless reset on path %s with len %" PRIu64,
options,
source_len);
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));
packet.reset();
return true;
}
return false;
}
void Endpoint::SendImmediateConnectionClose(const PathDescriptor& options,
QuicError reason) {
Debug(this,
"Sending immediate connection close on path %s with reason %s",
options,
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));
packet.reset();
}
}
bool Endpoint::Start() {
if (is_closed() || is_closing()) return false;
// state_->receiving indicates that we're accepting inbound packets. It
// could be for server or client side, or both.
if (state_->receiving == 1) return true;
Debug(this, "Starting");
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();
udp_.Ref();
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;
DCHECK(!server_state_.has_value());
// We need at least one key and one cert to complete the tls handshake on the
// server. Why not make this an error? We could but it's not strictly
// necessary.
if (options.tls_options.keys.empty() || options.tls_options.certs.empty()) {
env()->EmitProcessEnvWarning();
ProcessEmitWarning(env(),
"The QUIC TLS options did not include a key or cert. "
"This means the TLS handshake will fail. This is likely "
"not what you want.");
}
auto context = TLSContext::CreateServer(options.tls_options);
if (!*context) {
THROW_ERR_INVALID_STATE(
env(), "Failed to create TLS context: %s", context->validation_error());
return;
}
server_state_ = {
options,
std::move(context),
};
if (Start()) {
Debug(this, "Listening with options %s", server_state_->options);
state_->listening = 1;
}
}
BaseObjectPtr<Session> Endpoint::Connect(
const SocketAddress& remote_address,
const Session::Options& options,
std::optional<SessionTicket> session_ticket) {
// If starting fails, the endpoint will be destroyed.
if (!Start()) return {};
Session::Config config(env(), options, local_address(), remote_address);
Debug(this,
"Connecting to %s with options %s and config %s [has 0rtt ticket? %s]",
remote_address,
options,
config,
session_ticket.has_value() ? "yes" : "no");
auto tls_context = TLSContext::CreateClient(options.tls_options);
if (!*tls_context) {
THROW_ERR_INVALID_STATE(env(),
"Failed to create TLS context: %s",
tls_context->validation_error());
return {};
}
auto session =
Session::Create(this, config, tls_context.get(), session_ticket);
if (!session) {
THROW_ERR_INVALID_STATE(env(), "Failed to create session");
return {};
}
if (!session->tls_session()) {
THROW_ERR_INVALID_STATE(env(),
"Failed to create TLS session: %s",
session->tls_session().validation_error());
return {};
}
// Marking a session as "wrapped" means that the reference has been
// (or will be) passed out to JavaScript.
Session::SendPendingDataScope send_scope(session);
session->set_wrapped();
AddSession(config.scid, session);
return session;
}
void Endpoint::MaybeDestroy() {
if (!is_closed() && sessions_.empty() && state_->pending_callbacks == 0 &&
state_->listening == 0) {
// Destroy potentially creates v8 handles so let's make sure
// we have a HandleScope on the stack.
HandleScope scope(env()->isolate());
Destroy();
}
}
void Endpoint::Destroy(CloseContext context, int status) {
if (is_closed()) return;
IF_QUIC_DEBUG(env()) {