forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathnode_quic_session.h
1516 lines (1225 loc) · 48.5 KB
/
node_quic_session.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
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
#ifndef SRC_QUIC_NODE_QUIC_SESSION_H_
#define SRC_QUIC_NODE_QUIC_SESSION_H_
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
#include "aliased_buffer.h"
#include "aliased_struct.h"
#include "async_wrap.h"
#include "env.h"
#include "handle_wrap.h"
#include "node.h"
#include "node_crypto.h"
#include "node_http_common.h"
#include "node_mem.h"
#include "node_quic_state.h"
#include "node_quic_buffer-inl.h"
#include "node_quic_crypto.h"
#include "node_quic_util.h"
#include "node_sockaddr.h"
#include "stream_base.h"
#include "timer_wrap.h"
#include "v8.h"
#include "uv.h"
#include <ngtcp2/ngtcp2.h>
#include <ngtcp2/ngtcp2_crypto.h>
#include <nghttp3/nghttp3.h>
#include <openssl/ssl.h>
#include <unordered_map>
#include <string>
#include <vector>
namespace node {
namespace quic {
using ConnectionPointer = DeleteFnPtr<ngtcp2_conn, ngtcp2_conn_del>;
class QuicApplication;
class QuicPacket;
class QuicSocket;
class QuicStream;
using QuicHeader = NgHeaderBase<QuicApplication>;
using StreamsMap = std::unordered_map<int64_t, BaseObjectPtr<QuicStream>>;
enum class QlogMode {
kDisabled,
kEnabled
};
typedef void(*ConnectionIDStrategy)(
QuicSession* session,
ngtcp2_cid* cid,
size_t cidlen);
typedef void(*PreferredAddressStrategy)(
QuicSession* session,
const PreferredAddress& preferred_address);
// The QuicSessionConfig class holds the initial transport parameters and
// configuration options set by the JavaScript side when either a
// client or server QuicSession is created. Instances are
// stack created and use a combination of an AliasedBuffer to pass
// the numeric settings quickly (see node_quic_state.h) and passed
// in non-numeric settings (e.g. preferred_addr).
class QuicSessionConfig final : public ngtcp2_settings {
public:
QuicSessionConfig() = default;
explicit QuicSessionConfig(QuicState* quic_state) {
Set(quic_state);
}
QuicSessionConfig(const QuicSessionConfig& config) {
initial_ts = uv_hrtime();
transport_params = config.transport_params;
max_udp_payload_size = config.max_udp_payload_size;
cc_algo = config.cc_algo;
cc = config.cc;
qlog = config.qlog;
log_printf = config.log_printf;
token = config.token;
}
void ResetToDefaults(QuicState* quic_state);
// QuicSessionConfig::Set() pulls values out of the AliasedBuffer
// defined in node_quic_state.h and stores the values in settings_.
// If preferred_addr is not nullptr, it is copied into the
// settings_.preferred_addr field
void Set(QuicState* quic_state,
const struct sockaddr* preferred_addr = nullptr);
inline void set_original_connection_id(
const QuicCID& ocid,
const QuicCID& scid);
// Generates the stateless reset token for the settings_
inline void GenerateStatelessResetToken(
QuicSession* session,
const QuicCID& cid);
// If the preferred address is set, generates the associated tokens
inline void GeneratePreferredAddressToken(
ConnectionIDStrategy connection_id_strategy,
QuicSession* session,
QuicCID* pscid);
inline void set_qlog(const ngtcp2_qlog_settings& qlog);
};
// Options to alter the behavior of various functions on the
// server QuicSession. These are set on the QuicSocket when
// the listen() function is called and are passed to the
// constructor of the server QuicSession.
enum QuicServerSessionOptions : uint32_t {
// When set, instructs the server QuicSession to reject
// client authentication certs that cannot be verified.
QUICSERVERSESSION_OPTION_REJECT_UNAUTHORIZED = 0x1,
// When set, instructs the server QuicSession to request
// a client authentication cert
QUICSERVERSESSION_OPTION_REQUEST_CERT = 0x2
};
// Options to alter the behavior of various functions on the
// client QuicSession. These are set on the client QuicSession
// constructor.
enum QuicClientSessionOptions : uint32_t {
// When set, instructs the client QuicSession to include an
// OCSP request in the initial TLS handshake
QUICCLIENTSESSION_OPTION_REQUEST_OCSP = 0x1,
// When set, instructs the client QuicSession to verify the
// hostname identity. This is required by QUIC and enabled
// by default. We allow disabling it only for debugging
// purposes.
QUICCLIENTSESSION_OPTION_VERIFY_HOSTNAME_IDENTITY = 0x2,
// When set, instructs the client QuicSession to perform
// additional checks on TLS session resumption.
QUICCLIENTSESSION_OPTION_RESUME = 0x4
};
#define QUICSESSION_SHARED_STATE(V) \
V(KEYLOG_ENABLED, keylog_enabled, uint8_t) \
V(CLIENT_HELLO_ENABLED, client_hello_enabled, uint8_t) \
V(OCSP_ENABLED, ocsp_enabled, uint8_t) \
V(PATH_VALIDATED_ENABLED, path_validated_enabled, uint8_t) \
V(USE_PREFERRED_ADDRESS_ENABLED, use_preferred_address_enabled, uint8_t) \
V(HANDSHAKE_CONFIRMED, handshake_confirmed, uint8_t) \
V(IDLE_TIMEOUT, idle_timeout, uint8_t) \
V(MAX_STREAMS_BIDI, max_streams_bidi, uint64_t) \
V(MAX_STREAMS_UNI, max_streams_uni, uint64_t) \
V(MAX_DATA_LEFT, max_data_left, uint64_t) \
V(BYTES_IN_FLIGHT, bytes_in_flight, uint64_t)
#define V(_, name, type) type name;
struct QuicSessionState {
QUICSESSION_SHARED_STATE(V)
};
#undef V
#define V(id, name, _) \
IDX_QUICSESSION_STATE_##id = offsetof(QuicSessionState, name),
enum QuicSessionStateFields {
QUICSESSION_SHARED_STATE(V)
IDX_QUICSESSION_STATE_END
};
#undef V
#define SESSION_STATS(V) \
V(CREATED_AT, created_at, "Created At") \
V(HANDSHAKE_START_AT, handshake_start_at, "Handshake Started") \
V(HANDSHAKE_SEND_AT, handshake_send_at, "Handshke Last Sent") \
V(HANDSHAKE_CONTINUE_AT, handshake_continue_at, "Handshke Continued") \
V(HANDSHAKE_COMPLETED_AT, handshake_completed_at, "Handshake Completed") \
V(HANDSHAKE_CONFIRMED_AT, handshake_confirmed_at, "Handshake Confirmed") \
V(HANDSHAKE_ACKED_AT, handshake_acked_at, "Handshake Last Acknowledged") \
V(SENT_AT, sent_at, "Last Sent At") \
V(RECEIVED_AT, received_at, "Last Received At") \
V(CLOSING_AT, closing_at, "Closing") \
V(DESTROYED_AT, destroyed_at, "Destroyed At") \
V(BYTES_RECEIVED, bytes_received, "Bytes Received") \
V(BYTES_SENT, bytes_sent, "Bytes Sent") \
V(BIDI_STREAM_COUNT, bidi_stream_count, "Bidi Stream Count") \
V(UNI_STREAM_COUNT, uni_stream_count, "Uni Stream Count") \
V(STREAMS_IN_COUNT, streams_in_count, "Streams In Count") \
V(STREAMS_OUT_COUNT, streams_out_count, "Streams Out Count") \
V(KEYUPDATE_COUNT, keyupdate_count, "Key Update Count") \
V(LOSS_RETRANSMIT_COUNT, loss_retransmit_count, "Loss Retransmit Count") \
V(ACK_DELAY_RETRANSMIT_COUNT, \
ack_delay_retransmit_count, \
"Ack Delay Retransmit Count") \
V(PATH_VALIDATION_SUCCESS_COUNT, \
path_validation_success_count, \
"Path Validation Success Count") \
V(PATH_VALIDATION_FAILURE_COUNT, \
path_validation_failure_count, \
"Path Validation Failure Count") \
V(MAX_BYTES_IN_FLIGHT, max_bytes_in_flight, "Max Bytes In Flight") \
V(BLOCK_COUNT, block_count, "Block Count") \
V(MIN_RTT, min_rtt, "Minimum RTT") \
V(LATEST_RTT, latest_rtt, "Latest RTT") \
V(SMOOTHED_RTT, smoothed_rtt, "Smoothed RTT")
#define V(name, _, __) IDX_QUIC_SESSION_STATS_##name,
enum QuicSessionStatsIdx : int {
SESSION_STATS(V)
IDX_QUIC_SESSION_STATS_COUNT
};
#undef V
#define V(_, name, __) uint64_t name;
struct QuicSessionStats {
SESSION_STATS(V)
};
#undef V
struct QuicSessionStatsTraits {
using Stats = QuicSessionStats;
using Base = QuicSession;
template <typename Fn>
static void ToString(const Base& ptr, Fn&& add_field);
};
class QLogStream final : public AsyncWrap,
public StreamBase {
public:
static BaseObjectPtr<QLogStream> Create(Environment* env);
QLogStream(Environment* env, v8::Local<v8::Object> obj);
void Emit(const uint8_t* data, size_t len);
void End() { ended_ = true; }
int ReadStart() override { return 0; }
int ReadStop() override { return 0; }
int DoShutdown(ShutdownWrap* req_wrap) override;
int DoWrite(WriteWrap* w,
uv_buf_t* bufs,
size_t count,
uv_stream_t* send_handle) override;
bool IsAlive() override;
bool IsClosing() override;
AsyncWrap* GetAsyncWrap() override { return this; }
SET_NO_MEMORY_INFO();
SET_MEMORY_INFO_NAME(QLogStream);
SET_SELF_SIZE(QLogStream);
private:
bool ended_ = false;
};
class QuicSessionListener {
public:
enum SessionCloseFlags {
SESSION_CLOSE_FLAG_NONE,
SESSION_CLOSE_FLAG_SILENT,
SESSION_CLOSE_FLAG_STATELESS_RESET
};
virtual ~QuicSessionListener();
virtual void OnKeylog(const char* str, size_t size);
virtual void OnClientHello(
const char* alpn,
const char* server_name);
virtual void OnCert(const char* server_name);
virtual void OnOCSP(v8::Local<v8::Value> ocsp);
virtual void OnStreamHeaders(
int64_t stream_id,
int kind,
const std::vector<std::unique_ptr<QuicHeader>>& headers,
int64_t push_id);
virtual void OnStreamClose(
int64_t stream_id,
uint64_t app_error_code);
virtual void OnStreamReset(
int64_t stream_id,
uint64_t app_error_code);
virtual void OnSessionClose(
QuicError error,
int flags = SESSION_CLOSE_FLAG_NONE);
virtual void OnStreamReady(BaseObjectPtr<QuicStream> stream);
virtual void OnHandshakeCompleted();
virtual void OnPathValidation(
ngtcp2_path_validation_result res,
const sockaddr* local,
const sockaddr* remote);
virtual void OnUsePreferredAddress(
int family,
const PreferredAddress& preferred_address);
virtual void OnSessionTicket(int size, SSL_SESSION* session);
virtual void OnStreamBlocked(int64_t stream_id);
virtual void OnVersionNegotiation(
uint32_t supported_version,
const uint32_t* versions,
size_t vcnt);
virtual void OnQLog(QLogStream* qlog_stream);
QuicSession* session() const { return session_.get(); }
private:
BaseObjectWeakPtr<QuicSession> session_;
QuicSessionListener* previous_listener_ = nullptr;
friend class QuicSession;
};
class JSQuicSessionListener final : public QuicSessionListener {
public:
void OnKeylog(const char* str, size_t size) override;
void OnClientHello(
const char* alpn,
const char* server_name) override;
void OnCert(const char* server_name) override;
void OnOCSP(v8::Local<v8::Value> ocsp) override;
void OnStreamHeaders(
int64_t stream_id,
int kind,
const std::vector<std::unique_ptr<QuicHeader>>& headers,
int64_t push_id) override;
void OnStreamClose(
int64_t stream_id,
uint64_t app_error_code) override;
void OnStreamReset(
int64_t stream_id,
uint64_t app_error_code) override;
void OnSessionClose(
QuicError error,
int flags = SESSION_CLOSE_FLAG_NONE) override;
void OnStreamReady(BaseObjectPtr<QuicStream> stream) override;
void OnHandshakeCompleted() override;
void OnPathValidation(
ngtcp2_path_validation_result res,
const sockaddr* local,
const sockaddr* remote) override;
void OnSessionTicket(int size, SSL_SESSION* session) override;
void OnUsePreferredAddress(
int family,
const PreferredAddress& preferred_address) override;
void OnStreamBlocked(int64_t stream_id) override;
void OnVersionNegotiation(
uint32_t supported_version,
const uint32_t* versions,
size_t vcnt) override;
void OnQLog(QLogStream* qlog_stream) override;
private:
friend class QuicSession;
};
#define QUICCRYPTOCONTEXT_FLAGS(V) \
V(IN_TLS_CALLBACK, in_tls_callback) \
V(IN_KEY_UPDATE, in_key_update) \
V(IN_OCSP_RESPONSE, in_ocsp_request) \
V(IN_CLIENT_HELLO, in_client_hello) \
V(EARLY_DATA, early_data)
// The QuicCryptoContext class encapsulates all of the crypto/TLS
// handshake details on behalf of a QuicSession.
class QuicCryptoContext final : public MemoryRetainer {
public:
inline QuicCryptoContext(
QuicSession* session,
BaseObjectPtr<crypto::SecureContext> secure_context,
ngtcp2_crypto_side side,
uint32_t options);
~QuicCryptoContext() override;
inline uint64_t Cancel();
// Outgoing crypto data must be retained in memory until it is
// explicitly acknowledged. AcknowledgeCryptoData will be invoked
// when ngtcp2 determines that it has received an acknowledgement
// for crypto data at the specified level. This is our indication
// that the data for that level can be released.
void AcknowledgeCryptoData(ngtcp2_crypto_level level, uint64_t datalen);
inline void Initialize();
// Enables openssl's TLS tracing mechanism for this session only.
void EnableTrace();
// Returns the server's prepared OCSP response for transmission. This
// is not used by client QuicSession instances.
inline v8::MaybeLocal<v8::Value> ocsp_response() const;
// Returns ngtcp2's understanding of the current inbound crypto level
inline ngtcp2_crypto_level read_crypto_level() const;
// Returns ngtcp2's understanding of the current outbound crypto level
inline ngtcp2_crypto_level write_crypto_level() const;
inline bool early_data() const;
bool is_option_set(uint32_t option) const { return options_ & option; }
// Emits a single keylog line to the JavaScript layer
inline void Keylog(const char* line);
int OnClientHello();
inline void OnClientHelloDone();
int OnOCSP();
void OnOCSPDone(
BaseObjectPtr<crypto::SecureContext> secure_context,
v8::Local<v8::Value> ocsp_response);
bool OnSecrets(
ngtcp2_crypto_level level,
const uint8_t* rx_secret,
const uint8_t* tx_secret,
size_t secretlen);
int OnTLSStatus();
// Receives and processes TLS handshake details
int Receive(
ngtcp2_crypto_level crypto_level,
uint64_t offset,
const uint8_t* data,
size_t datalen);
// Resumes the TLS handshake following a client hello or
// OCSP callback
inline void ResumeHandshake();
inline v8::MaybeLocal<v8::Value> cert() const;
inline v8::MaybeLocal<v8::Value> cipher_name() const;
inline v8::MaybeLocal<v8::Value> cipher_version() const;
inline v8::MaybeLocal<v8::Object> ephemeral_key() const;
inline const char* hello_alpn() const;
inline v8::MaybeLocal<v8::Array> hello_ciphers() const;
inline const char* hello_servername() const;
inline v8::MaybeLocal<v8::Value> peer_cert(bool abbreviated) const;
inline std::string selected_alpn() const;
inline const char* servername() const;
void set_option(uint32_t option, bool on = true) {
if (on)
options_ |= option;
else
options_ &= ~option;
}
#define V(id, name) \
inline bool is_##name() const { \
return flags_ & (1 << QUICCRYPTOCONTEXT_FLAG_##id); } \
inline void set_##name(bool on = true) { \
if (on) \
flags_ |= (1 << QUICCRYPTOCONTEXT_FLAG_##id); \
else \
flags_ &= ~(1 << QUICCRYPTOCONTEXT_FLAG_##id); \
}
QUICCRYPTOCONTEXT_FLAGS(V)
#undef V
inline bool set_session(crypto::SSLSessionPointer session);
inline void set_tls_alert(int err);
ngtcp2_crypto_side side() const { return side_; }
void WriteHandshake(
ngtcp2_crypto_level level,
const uint8_t* data,
size_t datalen);
bool InitiateKeyUpdate();
int VerifyPeerIdentity();
QuicSession* session() const { return session_.get(); }
void MemoryInfo(MemoryTracker* tracker) const override;
SET_MEMORY_INFO_NAME(QuicCryptoContext)
SET_SELF_SIZE(QuicCryptoContext)
private:
bool SetSecrets(
ngtcp2_crypto_level level,
const uint8_t* rx_secret,
const uint8_t* tx_secret,
size_t secretlen);
BaseObjectWeakPtr<QuicSession> session_;
BaseObjectPtr<crypto::SecureContext> secure_context_;
ngtcp2_crypto_side side_;
crypto::SSLPointer ssl_;
QuicBuffer handshake_[3];
uint32_t options_;
uint32_t flags_ = 0;
v8::Global<v8::ArrayBufferView> ocsp_response_;
crypto::BIOPointer bio_trace_;
#define V(id, _) QUICCRYPTOCONTEXT_FLAG_##id,
enum QuicCryptoContextFlags : uint32_t {
QUICCRYPTOCONTEXT_FLAGS(V)
QUICCRYPTOCONTEXT_FLAG_COUNT
};
#undef V
class TLSCallbackScope {
public:
explicit TLSCallbackScope(QuicCryptoContext* context) :
context_(context) {
context_->set_in_tls_callback();
}
~TLSCallbackScope() {
context_->set_in_tls_callback(false);
}
static bool is_in_callback(QuicCryptoContext* context) {
return context->is_in_tls_callback();
}
private:
QuicCryptoContext* context_;
};
class TLSHandshakeScope {
public:
using DoneCB = std::function<void()>;
TLSHandshakeScope(
QuicCryptoContext* context,
DoneCB done) :
context_(context),
done_(done) {}
~TLSHandshakeScope() {
if (!is_handshake_suspended())
return;
done_();
// Only continue the TLS handshake if we are not currently running
// synchronously within the TLS handshake function. This can happen
// when the callback function passed to the clientHello and cert
// event handlers is called synchronously. If the function is called
// asynchronously, then we have to manually continue the handshake.
if (!TLSCallbackScope::is_in_callback(context_))
context_->ResumeHandshake();
}
private:
bool is_handshake_suspended() const {
return context_->is_in_ocsp_request() || context_->is_in_client_hello();
}
QuicCryptoContext* context_;
DoneCB done_;
};
friend class QuicSession;
};
// A QuicApplication encapsulates the specific details of
// working with a specific QUIC application (e.g. http/3).
class QuicApplication : public MemoryRetainer,
public mem::NgLibMemoryManagerBase {
public:
inline explicit QuicApplication(QuicSession* session);
virtual ~QuicApplication() = default;
// The QuicSession will call Initialize as soon as the TLS
// secrets have been set. See QuicCryptoContext::OnSecrets
virtual bool Initialize() = 0;
// QuicSession will forward all received stream data immediately
// on to the QuicApplication. The only additional processing the
// QuicSession does is to automatically adjust the QuicSession-level
// flow control window. It is up to the QuicApplication to do
// the same for the QuicStream-level flow control.
//
// flags are passed on directly from ngtcp2. The most important
// of which here is NGTCP2_STREAM_DATA_FLAG_FIN, which indicates
// that this is the final chunk of data that the peer will send
// for this stream.
//
// It is also possible for the NGTCP2_STREAM_DATA_FLAG_0RTT flag
// to be set, indicating that this chunk of data was received in
// a 0RTT packet before the TLS handshake completed. This would
// indicate that it is not as secure and could be replayed by
// an attacker. We're not currently making use of that flag.
virtual bool ReceiveStreamData(
uint32_t flags,
int64_t stream_id,
const uint8_t* data,
size_t datalen,
uint64_t offset) = 0;
virtual void AcknowledgeStreamData(
int64_t stream_id,
uint64_t offset,
size_t datalen) {
Acknowledge(stream_id, offset, datalen);
}
virtual bool BlockStream(int64_t id) { return true; }
virtual void ExtendMaxStreamsRemoteUni(uint64_t max_streams) {}
virtual void ExtendMaxStreamsRemoteBidi(uint64_t max_streams) {}
virtual void ExtendMaxStreamData(int64_t stream_id, uint64_t max_data) {}
virtual void ResumeStream(int64_t stream_id) {}
virtual void SetSessionTicketAppData(const SessionTicketAppData& app_data) {
// TODO(@jasnell): Different QUIC applications may wish to set some
// application data in the session ticket (e.g. http/3 would set
// server settings in the application data). For now, doing nothing
// as I'm just adding the basic mechanism.
}
virtual SessionTicketAppData::Status GetSessionTicketAppData(
const SessionTicketAppData& app_data,
SessionTicketAppData::Flag flag) {
// TODO(@jasnell): Different QUIC application may wish to set some
// application data in the session ticket (e.g. http/3 would set
// server settings in the application data). For now, doing nothing
// as I'm just adding the basic mechanism.
return flag == SessionTicketAppData::Flag::STATUS_RENEW ?
SessionTicketAppData::Status::TICKET_USE_RENEW :
SessionTicketAppData::Status::TICKET_USE;
}
virtual void StreamHeaders(
int64_t stream_id,
int kind,
const std::vector<std::unique_ptr<QuicHeader>>& headers,
int64_t push_id = 0);
virtual void StreamClose(
int64_t stream_id,
uint64_t app_error_code);
virtual void StreamReset(
int64_t stream_id,
uint64_t app_error_code);
virtual bool SubmitInformation(
int64_t stream_id,
v8::Local<v8::Array> headers) { return false; }
virtual bool SubmitHeaders(
int64_t stream_id,
v8::Local<v8::Array> headers,
uint32_t flags) { return false; }
virtual bool SubmitTrailers(
int64_t stream_id,
v8::Local<v8::Array> headers) { return false; }
virtual BaseObjectPtr<QuicStream> SubmitPush(
int64_t stream_id,
v8::Local<v8::Array> headers) {
// By default, push streams are not supported
// by an application.
return {};
}
inline Environment* env() const;
bool SendPendingData();
size_t max_header_pairs() const { return max_header_pairs_; }
size_t max_header_length() const { return max_header_length_; }
protected:
QuicSession* session() const { return session_.get(); }
bool needs_init() const { return needs_init_; }
void set_init_done() { needs_init_ = false; }
inline void set_stream_fin(int64_t stream_id);
void set_max_header_pairs(size_t max) { max_header_pairs_ = max; }
void set_max_header_length(size_t max) { max_header_length_ = max; }
inline std::unique_ptr<QuicPacket> CreateStreamDataPacket();
struct StreamData {
size_t count = 0;
size_t remaining = 0;
int64_t id = -1;
int fin = 0;
ngtcp2_vec data[kMaxVectorCount] {};
ngtcp2_vec* buf = nullptr;
BaseObjectPtr<QuicStream> stream;
StreamData() { buf = data; }
};
void Acknowledge(
int64_t stream_id,
uint64_t offset,
size_t datalen);
virtual int GetStreamData(StreamData* data) = 0;
virtual bool StreamCommit(StreamData* data, size_t datalen) = 0;
virtual bool ShouldSetFin(const StreamData& data) = 0;
ssize_t WriteVStream(
QuicPathStorage* path,
uint8_t* buf,
ssize_t* ndatalen,
const StreamData& stream_data);
private:
void MaybeSetFin(const StreamData& stream_data);
BaseObjectWeakPtr<QuicSession> session_;
bool needs_init_ = true;
size_t max_header_pairs_ = 0;
size_t max_header_length_ = 0;
};
// QUICSESSION_FLAGS are converted into is_{name}() and set_{name}(bool on)
// accessors on the QuicSession class.
#define QUICSESSION_FLAGS(V) \
V(WRAPPED, wrapped) \
V(CLOSING, closing) \
V(GRACEFUL_CLOSING, graceful_closing) \
V(DESTROYED, destroyed) \
V(TRANSPORT_PARAMS_SET, transport_params_set) \
V(NGTCP2_CALLBACK, in_ngtcp2_callback) \
V(CONNECTION_CLOSE_SCOPE, in_connection_close_scope) \
V(SILENT_CLOSE, silent_closing) \
V(STATELESS_RESET, stateless_reset) \
V(CLOSING_TIMER_ENABLED, closing_timer_enabled)
// QUIC sessions are logical connections that exchange data
// back and forth between peer endpoints via UDP. Every QuicSession
// has an associated TLS context and all data transfered between
// the peers is always encrypted. Unlike TLS over TCP, however,
// The QuicSession uses a session identifier that is independent
// of both the local *and* peer IP address, allowing a QuicSession
// to persist across changes in the network (one of the key features
// of QUIC). QUIC sessions also support 0RTT, implement error
// correction mechanisms to recover from lost packets, and flow
// control. In other words, there's quite a bit going on within
// a QuicSession object.
class QuicSession final : public AsyncWrap,
public mem::NgLibMemoryManager<
QuicSession,
ngtcp2_mem>,
public StatsBase<QuicSessionStatsTraits> {
public:
// The default preferred address strategy is to ignore it
static void IgnorePreferredAddressStrategy(
QuicSession* session,
const PreferredAddress& preferred_address);
static void UsePreferredAddressStrategy(
QuicSession* session,
const PreferredAddress& preferred_address);
static void Initialize(
Environment* env,
v8::Local<v8::Object> target,
v8::Local<v8::Context> context);
static BaseObjectPtr<QuicSession> CreateServer(
QuicSocket* socket,
const QuicSessionConfig& config,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
const QuicCID& dcid,
const QuicCID& scid,
const QuicCID& ocid,
uint32_t version,
const std::string& alpn = NGHTTP3_ALPN_H3,
uint32_t options = 0,
QlogMode qlog = QlogMode::kDisabled);
static BaseObjectPtr<QuicSession> CreateClient(
QuicSocket* socket,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
BaseObjectPtr<crypto::SecureContext> secure_context,
ngtcp2_transport_params* early_transport_params,
crypto::SSLSessionPointer early_session_ticket,
v8::Local<v8::Value> dcid,
PreferredAddressStrategy preferred_address_strategy =
IgnorePreferredAddressStrategy,
const std::string& alpn = NGHTTP3_ALPN_H3,
const std::string& hostname = "",
uint32_t options = 0,
QlogMode qlog = QlogMode::kDisabled);
static const int kInitialClientBufferLength = 4096;
QuicSession(
ngtcp2_crypto_side side,
// The QuicSocket that created this session. Note that
// it is possible to replace this socket later, after
// the TLS handshake has completed. The QuicSession
// should never assume that the socket will always
// remain the same.
QuicSocket* socket,
v8::Local<v8::Object> wrap,
BaseObjectPtr<crypto::SecureContext> secure_context,
AsyncWrap::ProviderType provider_type,
// QUIC is generally just a transport. The ALPN identifier
// is used to specify the application protocol that is
// layered on top. If not specified, this will default
// to the HTTP/3 identifier. For QUIC, the alpn identifier
// is always required.
const std::string& alpn,
const std::string& hostname,
const QuicCID& dcid,
uint32_t options = 0,
PreferredAddressStrategy preferred_address_strategy =
IgnorePreferredAddressStrategy);
// Server Constructor
QuicSession(
QuicSocket* socket,
const QuicSessionConfig& config,
v8::Local<v8::Object> wrap,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
const QuicCID& dcid,
const QuicCID& scid,
const QuicCID& ocid,
uint32_t version,
const std::string& alpn,
uint32_t options,
QlogMode qlog);
// Client Constructor
QuicSession(
QuicSocket* socket,
v8::Local<v8::Object> wrap,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
BaseObjectPtr<crypto::SecureContext> secure_context,
ngtcp2_transport_params* early_transport_params,
crypto::SSLSessionPointer early_session_ticket,
v8::Local<v8::Value> dcid,
PreferredAddressStrategy preferred_address_strategy,
const std::string& alpn,
const std::string& hostname,
uint32_t options,
QlogMode qlog);
~QuicSession() override;
std::string diagnostic_name() const override;
inline QuicCID dcid() const;
QuicApplication* application() const { return application_.get(); }
QuicCryptoContext* crypto_context() const { return crypto_context_.get(); }
QuicSessionListener* listener() const { return listener_; }
BaseObjectPtr<QuicStream> CreateStream(int64_t id);
BaseObjectPtr<QuicStream> FindStream(int64_t id) const;
inline bool HasStream(int64_t id) const;
inline bool allow_early_data() const;
#define V(id, name) \
bool is_##name() const { return flags_ & (1 << QUICSESSION_FLAG_##id); } \
void set_##name(bool on = true) { \
if (on) \
flags_ |= (1 << QUICSESSION_FLAG_##id); \
else \
flags_ &= ~(1 << QUICSESSION_FLAG_##id); \
}
QUICSESSION_FLAGS(V)
#undef V
// Returns true if the QuicSession has entered the
// closing period after sending a CONNECTION_CLOSE.
// While true, the QuicSession is only permitted to
// transmit CONNECTION_CLOSE frames until either the
// idle timeout period elapses or until the QuicSession
// is explicitly destroyed.
inline bool is_in_closing_period() const;
// Returns true if the QuicSession has received a
// CONNECTION_CLOSE frame from the peer. Once in
// the draining period, the QuicSession is not
// permitted to send any frames to the peer. The
// QuicSession will be silently closed after either
// the idle timeout period elapses or until the
// QuicSession is explicitly destroyed.
inline bool is_in_draining_period() const;
inline bool is_server() const;
// Starting a GracefulClose disables the ability to open or accept
// new streams for this session. Existing streams are allowed to
// close naturally on their own. Once called, the QuicSession will
// be immediately closed once there are no remaining streams. Note
// that no notification is given to the connecting peer that we're
// in a graceful closing state. A CONNECTION_CLOSE will be sent only
// once Close() is called.
inline void StartGracefulClose();
QuicError last_error() const { return last_error_; }
size_t max_packet_length() const { return max_pktlen_; }
BaseObjectPtr<QLogStream> qlog_stream();
// Get the ALPN protocol identifier configured for this QuicSession.
// For server sessions, this will be compared against the client requested
// ALPN identifier to determine if there is a protocol match.
const std::string& alpn() const { return alpn_; }
// Get the hostname configured for this QuicSession. This is generally
// only used by client sessions.
const std::string& hostname() const { return hostname_; }
// Returns the associated peer's address. Note that this
// value can change over the lifetime of the QuicSession.
// The fact that the session is not tied intrinsically to
// a single address is one of the benefits of QUIC.
const SocketAddress& remote_address() const { return remote_address_; }
inline QuicSocket* socket() const;
ngtcp2_conn* connection() const { return connection_.get(); }
void AddStream(BaseObjectPtr<QuicStream> stream);
void AddToSocket(QuicSocket* socket);
// Immediately discards the state of the QuicSession
// and renders the QuicSession instance completely
// unusable.
void Destroy();
// Extends the QUIC stream flow control window. This is
// called after received data has been consumed and we
// want to allow the peer to send more data.
inline void ExtendStreamOffset(int64_t stream_id, size_t amount);
// Extends the QUIC session flow control window
inline void ExtendOffset(size_t amount);
// Retrieve the local transport parameters established for
// this ngtcp2_conn
inline void GetLocalTransportParams(ngtcp2_transport_params* params);
// The QUIC version that has been negotiated for this session
inline uint32_t negotiated_version() const;
// True only if ngtcp2 considers the TLS handshake to be completed
inline bool is_handshake_completed() const;
// Checks to see if data needs to be retransmitted
void OnRetransmitTimeout();
// Called when the session has been determined to have been
// idle for too long and needs to be torn down.
inline void OnIdleTimeout();
bool OpenBidirectionalStream(int64_t* stream_id);
bool OpenUnidirectionalStream(int64_t* stream_id);
// Ping causes the QuicSession to serialize any currently
// pending frames in it's queue, including any necessary
// PROBE packets. This is a best attempt, fire-and-forget
// type of operation. There is no way to listen for a ping
// response. The main intent of using Ping is to either keep
// the connection from becoming idle or to update RTT stats.
void Ping();
// Receive and process a QUIC packet received from the peer
bool Receive(
ssize_t nread,
const uint8_t* data,
const SocketAddress& local_addr,
const SocketAddress& remote_addr,
unsigned int flags);
// Receive a chunk of QUIC stream data received from the peer
bool ReceiveStreamData(
uint32_t flags,
int64_t stream_id,
const uint8_t* data,
size_t datalen,
uint64_t offset);
void RemoveStream(int64_t stream_id);
void RemoveFromSocket();