/
node_quic_socket.h
627 lines (497 loc) Β· 20.2 KB
/
node_quic_socket.h
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
#ifndef SRC_QUIC_NODE_QUIC_SOCKET_H_
#define SRC_QUIC_NODE_QUIC_SOCKET_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "base_object.h"
#include "node.h"
#include "node_crypto.h"
#include "node_internals.h"
#include "ngtcp2/ngtcp2.h"
#include "nghttp3/nghttp3.h"
#include "node_quic_state.h"
#include "node_quic_session.h"
#include "node_quic_util.h"
#include "node_sockaddr.h"
#include "env.h"
#include "udp_wrap.h"
#include "v8.h"
#include "uv.h"
#include <deque>
#include <map>
#include <string>
#include <vector>
namespace node {
using v8::Context;
using v8::FunctionCallbackInfo;
using v8::Local;
using v8::Object;
using v8::Value;
namespace quic {
class QuicSocket;
class QuicEndpoint;
#define QUICSOCKET_OPTIONS(V) \
V(VALIDATE_ADDRESS, validate_address) \
V(VALIDATE_ADDRESS_LRU, validate_address_lru)
#define V(id, _) QUICSOCKET_OPTIONS_##id,
enum QuicSocketOptions : uint32_t {
QUICSOCKET_OPTIONS(V)
QUICSOCKET_OPTIONS_COUNT
};
#undef V
#define QUICSOCKET_FLAGS(V) \
V(GRACEFUL_CLOSE, graceful_closing) \
V(WAITING_FOR_CALLBACKS, waiting_for_callbacks) \
V(SERVER_LISTENING, server_listening) \
V(SERVER_BUSY, server_busy) \
V(DISABLE_STATELESS_RESET, stateless_reset_disabled)
#define SOCKET_STATS(V) \
V(CREATED_AT, created_at, "Created At") \
V(BOUND_AT, bound_at, "Bound At") \
V(LISTEN_AT, listen_at, "Listen At") \
V(BYTES_RECEIVED, bytes_received, "Bytes Received") \
V(BYTES_SENT, bytes_sent, "Bytes Sent") \
V(PACKETS_RECEIVED, packets_received, "Packets Received") \
V(PACKETS_IGNORED, packets_ignored, "Packets Ignored") \
V(PACKETS_SENT, packets_sent, "Packets Sent") \
V(SERVER_SESSIONS, server_sessions, "Server Sessions") \
V(CLIENT_SESSIONS, client_sessions, "Client Sessions") \
V(STATELESS_RESET_COUNT, stateless_reset_count, "Stateless Reset Count") \
V(SERVER_BUSY_COUNT, server_busy_count, "Server Busy Count")
#define V(name, _, __) IDX_QUIC_SOCKET_STATS_##name,
enum QuicSocketStatsIdx : int {
SOCKET_STATS(V)
IDX_QUIC_SOCKET_STATS_COUNT
};
#undef V
#define V(_, name, __) uint64_t name;
struct QuicSocketStats {
SOCKET_STATS(V)
};
#undef V
struct QuicSocketStatsTraits {
using Stats = QuicSocketStats;
using Base = QuicSocket;
template <typename Fn>
static void ToString(const Base& ptr, Fn&& add_field);
};
// This is the generic interface for objects that control QuicSocket
// instances. The default `JSQuicSocketListener` emits events to
// JavaScript
class QuicSocketListener {
public:
virtual ~QuicSocketListener();
virtual void OnError(ssize_t code);
virtual void OnSessionReady(BaseObjectPtr<QuicSession> session);
virtual void OnServerBusy(bool busy);
virtual void OnEndpointDone(QuicEndpoint* endpoint);
virtual void OnDestroy();
QuicSocket* socket() const { return socket_.get(); }
private:
BaseObjectWeakPtr<QuicSocket> socket_;
QuicSocketListener* previous_listener_ = nullptr;
friend class QuicSocket;
};
class JSQuicSocketListener final : public QuicSocketListener {
public:
void OnError(ssize_t code) override;
void OnSessionReady(BaseObjectPtr<QuicSession> session) override;
void OnServerBusy(bool busy) override;
void OnEndpointDone(QuicEndpoint* endpoint) override;
void OnDestroy() override;
};
// This is just a formality as the QUIC spec normatively
// defines that the ipv4 max pktlen is always going to be
// larger than the ipv6 max pktlen, but in the off chance
// ever changes (which is unlikely) we check here.
constexpr size_t MAX_PKTLEN =
std::max<size_t>(NGTCP2_MAX_PKTLEN_IPV4, NGTCP2_MAX_PKTLEN_IPV6);
// A serialized QuicPacket to be sent by a QuicSocket instance.
// QuicPackets are intended to be transient. They are created,
// filled with the contents of a serialized packet, and passed
// off immediately to the QuicSocket to be sent. As soon as
// the packet is sent, it is freed.
class QuicPacket : public MemoryRetainer {
public:
// Creates a new QuicPacket. By default the packet will be
// stack allocated with a max size of NGTCP2_MAX_PKTLEN_IPV4.
// If a larger packet size is specified, it will be heap
// allocated. A QUIC packet should never be larger than the
// current MTU to avoid IP fragmentation.
//
// The content of a QuicPacket is provided by ngtcp2 and is
// opaque for us. The typical use pattern is to create a QuicPacket
// instance and then pass a pointer to it's internal buffer and max
// size in to an ngtcp2 function that serializes the data.
// ngtcp2 will fill the buffer as much as possible then return
// the number of bytes serialized. User code is then responsible
// for calling set_length() to set the final length of the
// QuicPacket prior to sending it off to the QuicSocket.
//
// The diagnostic label is used in NODE_DEBUG_NATIVE output
// to differentiate send operations. This should always be
// a statically allocated string or nullptr (in which case
// the value "unspecified" is used in the debug output).
//
// Instances of std::unique_ptr<QuicPacket> are moved through
// QuicSocket and ultimately become the responsibility of the
// SendWrap instance. When the SendWrap is cleaned up, the
// QuicPacket instance will be freed.
static inline std::unique_ptr<QuicPacket> Create(
const char* diagnostic_label = nullptr,
size_t len = MAX_PKTLEN);
// Copy the data of the QuicPacket to a new one. Currently,
// this is only used when retransmitting close connection
// packets from a QuicServer.
static inline std::unique_ptr<QuicPacket> Copy(
const std::unique_ptr<QuicPacket>& other);
QuicPacket(const char* diagnostic_label, size_t len);
QuicPacket(const QuicPacket& other);
uint8_t* data() { return data_; }
size_t length() const { return len_; }
uv_buf_t buf() const {
return uv_buf_init(
const_cast<char*>(reinterpret_cast<const char*>(&data_)),
length());
}
inline void set_length(size_t len);
const char* diagnostic_label() const;
SET_NO_MEMORY_INFO();
SET_MEMORY_INFO_NAME(QuicPacket);
SET_SELF_SIZE(QuicPacket);
private:
uint8_t data_[MAX_PKTLEN];
size_t len_ = MAX_PKTLEN;
const char* diagnostic_label_ = nullptr;
};
// QuicEndpointListener listens to events generated by a QuicEndpoint.
class QuicEndpointListener {
public:
virtual void OnError(QuicEndpoint* endpoint, ssize_t error) = 0;
virtual void OnReceive(
ssize_t nread,
AllocatedBuffer buf,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
unsigned int flags) = 0;
virtual ReqWrap<uv_udp_send_t>* OnCreateSendWrap(size_t msg_size) = 0;
virtual void OnSendDone(ReqWrap<uv_udp_send_t>* wrap, int status) = 0;
virtual void OnBind(QuicEndpoint* endpoint) = 0;
virtual void OnEndpointDone(QuicEndpoint* endpoint) = 0;
};
// A QuicEndpoint wraps a UDPBaseWrap. A single QuicSocket may
// have multiple QuicEndpoints, the lifecycles of which are
// attached to the QuicSocket.
class QuicEndpoint final : public BaseObject,
public UDPListener {
public:
static void Initialize(
Environment* env,
Local<Object> target,
Local<Context> context);
QuicEndpoint(
QuicState* quic_state,
Local<Object> wrap,
QuicSocket* listener,
Local<Object> udp_wrap);
~QuicEndpoint() override;
SocketAddress local_address() const {
return udp_->GetSockName();
}
// Implementation for UDPListener
uv_buf_t OnAlloc(size_t suggested_size) override;
void OnRecv(ssize_t nread,
const uv_buf_t& buf,
const sockaddr* addr,
unsigned int flags) override;
ReqWrap<uv_udp_send_t>* CreateSendWrap(size_t msg_size) override;
void OnSendDone(ReqWrap<uv_udp_send_t>* wrap, int status) override;
void OnAfterBind() override;
inline int ReceiveStart();
inline int ReceiveStop();
inline int Send(
uv_buf_t* buf,
size_t len,
const sockaddr* addr);
void IncrementPendingCallbacks() { pending_callbacks_++; }
void DecrementPendingCallbacks() { pending_callbacks_--; }
bool has_pending_callbacks() const { return pending_callbacks_ > 0; }
inline void WaitForPendingCallbacks();
QuicState* quic_state() const { return quic_state_.get(); }
SET_NO_MEMORY_INFO();
SET_MEMORY_INFO_NAME(QuicEndpoint)
SET_SELF_SIZE(QuicEndpoint)
private:
BaseObjectWeakPtr<QuicSocket> listener_;
UDPWrapBase* udp_;
BaseObjectPtr<AsyncWrap> strong_ptr_;
size_t pending_callbacks_ = 0;
bool waiting_for_callbacks_ = false;
BaseObjectPtr<QuicState> quic_state_;
};
// QuicSocket manages the flow of data from the UDP socket to the
// QuicSession. It is responsible for managing the lifecycle of the
// UDP sockets, listening for new server QuicSession instances, and
// passing data two and from the remote peer.
class QuicSocket : public AsyncWrap,
public QuicEndpointListener,
public mem::NgLibMemoryManager<QuicSocket, ngtcp2_mem>,
public StatsBase<QuicSocketStatsTraits> {
public:
static void Initialize(
Environment* env,
Local<Object> target,
Local<Context> context);
QuicSocket(
QuicState* quic_state,
Local<Object> wrap,
// A retry token should only be valid for a small window of time.
// The retry_token_expiration specifies the number of seconds a
// retry token is permitted to be valid.
uint64_t retry_token_expiration,
// To prevent malicious clients from opening too many concurrent
// connections, we limit the maximum number per remote sockaddr.
size_t max_connections,
size_t max_connections_per_host,
size_t max_stateless_resets_per_host
= DEFAULT_MAX_STATELESS_RESETS_PER_HOST,
uint32_t options = 0,
QlogMode qlog = QlogMode::kDisabled,
const uint8_t* session_reset_secret = nullptr,
bool disable_session_reset = false);
~QuicSocket() override;
// Returns the default/preferred local address. Additional
// QuicEndpoint instances may be associated with the
// QuicSocket bound to other local addresses.
inline SocketAddress local_address() const;
void MaybeClose();
inline void AddSession(
const QuicCID& cid,
BaseObjectPtr<QuicSession> session);
inline void AssociateCID(
const QuicCID& cid,
const QuicCID& scid);
inline void DisassociateCID(
const QuicCID& cid);
inline void AssociateStatelessResetToken(
const StatelessResetToken& token,
BaseObjectPtr<QuicSession> session);
inline void DisassociateStatelessResetToken(
const StatelessResetToken& token);
void Listen(
BaseObjectPtr<crypto::SecureContext> context,
const sockaddr* preferred_address = nullptr,
const std::string& alpn = NGHTTP3_ALPN_H3,
uint32_t options = 0);
inline void ReceiveStart();
inline void ReceiveStop();
inline void RemoveSession(
const QuicCID& cid,
const SocketAddress& addr);
inline void ReportSendError(int error);
int SendPacket(
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
std::unique_ptr<QuicPacket> packet,
BaseObjectPtr<QuicSession> session = BaseObjectPtr<QuicSession>());
#define V(id, name) \
inline bool is_##name() const { \
return flags_ & (1 << QUICSOCKET_FLAG_##id); } \
inline void set_##name(bool on = true) { \
if (on) \
flags_ |= (1 << QUICSOCKET_FLAG_##id); \
else \
flags_ &= ~(1 << QUICSOCKET_FLAG_##id); \
}
QUICSOCKET_FLAGS(V)
#undef V
#define V(id, name) \
bool has_option_##name() const { \
return options_ & (1 << QUICSOCKET_OPTIONS_##id); }
QUICSOCKET_OPTIONS(V)
#undef V
inline void ServerBusy(bool on);
inline void set_diagnostic_packet_loss(double rx = 0.0, double tx = 0.0);
inline void StopListening();
// Toggles whether or not stateless reset is enabled or not.
// Returns true if stateless reset is enabled, false if it
// is not.
inline bool EnableStatelessReset(bool on = true);
BaseObjectPtr<crypto::SecureContext> server_secure_context() const {
return server_secure_context_;
}
QuicState* quic_state() { return quic_state_.get(); }
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(QuicSocket)
SET_SELF_SIZE(QuicSocket)
// Implementation for mem::NgLibMemoryManager
void CheckAllocatedSize(size_t previous_size) const;
void IncreaseAllocatedSize(size_t size);
void DecreaseAllocatedSize(size_t size);
const uint8_t* session_reset_secret() { return reset_token_secret_; }
// Implementation for QuicListener
ReqWrap<uv_udp_send_t>* OnCreateSendWrap(size_t msg_size) override;
// Implementation for QuicListener
void OnSendDone(ReqWrap<uv_udp_send_t>* wrap, int status) override;
// Implementation for QuicListener
void OnBind(QuicEndpoint* endpoint) override;
// Implementation for QuicListener
void OnReceive(
ssize_t nread,
AllocatedBuffer buf,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
unsigned int flags) override;
// Implementation for QuicListener
void OnError(QuicEndpoint* endpoint, ssize_t error) override;
// Implementation for QuicListener
void OnEndpointDone(QuicEndpoint* endpoint) override;
// Serializes and transmits a RETRY packet to the connected peer.
bool SendRetry(
const QuicCID& dcid,
const QuicCID& scid,
const SocketAddress& local_addr,
const SocketAddress& remote_addr);
// Serializes and transmits a Stateless Reset to the connected peer.
bool SendStatelessReset(
const QuicCID& cid,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
size_t source_len);
// Serializes and transmits a Version Negotiation packet to the
// connected peer.
void SendVersionNegotiation(
uint32_t version,
const QuicCID& dcid,
const QuicCID& scid,
const SocketAddress& local_addr,
const SocketAddress& remote_addr);
void PushListener(QuicSocketListener* listener);
void RemoveListener(QuicSocketListener* listener);
inline void AddEndpoint(
BaseObjectPtr<QuicEndpoint> endpoint,
bool preferred = false);
void ImmediateConnectionClose(
const QuicCID& scid,
const QuicCID& dcid,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
int64_t reason = NGTCP2_INVALID_TOKEN);
private:
static void OnAlloc(
uv_handle_t* handle,
size_t suggested_size,
uv_buf_t* buf);
void OnSend(int status, QuicPacket* packet);
inline void set_validated_address(const SocketAddress& addr);
inline bool is_validated_address(const SocketAddress& addr) const;
bool MaybeStatelessReset(
const QuicCID& dcid,
const QuicCID& scid,
ssize_t nread,
const uint8_t* data,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
unsigned int flags);
BaseObjectPtr<QuicSession> AcceptInitialPacket(
uint32_t version,
const QuicCID& dcid,
const QuicCID& scid,
ssize_t nread,
const uint8_t* data,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
unsigned int flags);
BaseObjectPtr<QuicSession> FindSession(const QuicCID& cid);
inline void IncrementSocketAddressCounter(const SocketAddress& addr);
inline void DecrementSocketAddressCounter(const SocketAddress& addr);
inline void IncrementStatelessResetCounter(const SocketAddress& addr);
inline size_t GetCurrentSocketAddressCounter(const SocketAddress& addr);
inline size_t GetCurrentStatelessResetCounter(const SocketAddress& addr);
// Returns true if, and only if, diagnostic packet loss is enabled
// and the current packet should be artificially considered lost.
inline bool is_diagnostic_packet_loss(double prob) const;
#define V(id, _) QUICSOCKET_FLAG_##id,
enum QuicSocketFlags : uint32_t {
QUICSOCKET_FLAGS(V)
QUICSOCKET_FLAG_COUNT
};
#undef V
ngtcp2_mem alloc_info_;
std::vector<BaseObjectPtr<QuicEndpoint>> endpoints_;
SocketAddress::Map<BaseObjectWeakPtr<QuicEndpoint>> bound_endpoints_;
BaseObjectWeakPtr<QuicEndpoint> preferred_endpoint_;
uint32_t flags_ = 0;
uint32_t options_ = 0;
uint32_t server_options_;
size_t max_connections_ = DEFAULT_MAX_CONNECTIONS;
size_t max_connections_per_host_ = DEFAULT_MAX_CONNECTIONS_PER_HOST;
size_t current_ngtcp2_memory_ = 0;
size_t max_stateless_resets_per_host_ = DEFAULT_MAX_STATELESS_RESETS_PER_HOST;
uint64_t retry_token_expiration_;
// Used to specify diagnostic packet loss probabilities
double rx_loss_ = 0.0;
double tx_loss_ = 0.0;
QuicSocketListener* listener_;
JSQuicSocketListener default_listener_;
QuicSessionConfig server_session_config_;
QlogMode qlog_ = QlogMode::kDisabled;
BaseObjectPtr<crypto::SecureContext> server_secure_context_;
std::string server_alpn_;
QuicCID::Map<BaseObjectPtr<QuicSession>> sessions_;
QuicCID::Map<QuicCID> dcid_to_scid_;
uint8_t token_secret_[kTokenSecretLen];
uint8_t reset_token_secret_[NGTCP2_STATELESS_RESET_TOKENLEN];
// Counts the number of active connections per remote
// address. A custom std::hash specialization for
// sockaddr instances is used. Values are incremented
// when a QuicSession is added to the socket, and
// decremented when the QuicSession is removed. If the
// value reaches the value of max_connections_per_host_,
// attempts to create new connections will be ignored
// until the value falls back below the limit.
SocketAddress::Map<size_t> addr_counts_;
// Counts the number of stateless resets sent per
// remote address.
// TODO(@jasnell): this counter persists through the
// lifetime of the QuicSocket, and therefore can become
// a possible risk. Specifically, a malicious peer could
// attempt the local peer to count an increasingly large
// number of remote addresses. Need to mitigate the
// potential risk.
SocketAddress::Map<size_t> reset_counts_;
// Counts the number of retry attempts sent per
// remote address.
StatelessResetToken::Map<QuicSession> token_map_;
// The validated_addrs_ vector is used as an LRU cache for
// validated addresses only when the VALIDATE_ADDRESS_LRU
// option is set.
typedef size_t SocketAddressHash;
std::deque<SocketAddressHash> validated_addrs_;
class SendWrap : public ReqWrap<uv_udp_send_t> {
public:
SendWrap(QuicState* quic_state,
v8::Local<v8::Object> req_wrap_obj,
size_t total_length_);
void set_packet(std::unique_ptr<QuicPacket> packet) {
packet_ = std::move(packet);
}
QuicPacket* packet() { return packet_.get(); }
void set_session(BaseObjectPtr<QuicSession> session) { session_ = session; }
size_t total_length() const { return total_length_; }
QuicState* quic_state() { return quic_state_.get(); }
SET_SELF_SIZE(SendWrap);
std::string MemoryInfoName() const override;
void MemoryInfo(MemoryTracker* tracker) const override;
private:
BaseObjectPtr<QuicSession> session_;
std::unique_ptr<QuicPacket> packet_;
size_t total_length_;
BaseObjectPtr<QuicState> quic_state_;
};
SendWrap* last_created_send_wrap_ = nullptr;
BaseObjectPtr<QuicState> quic_state_;
friend class QuicSocketListener;
};
} // namespace quic
} // namespace node
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#endif // SRC_QUIC_NODE_QUIC_SOCKET_H_