1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef QUICHE_QUIC_CORE_QUIC_TYPES_H_
6 #define QUICHE_QUIC_CORE_QUIC_TYPES_H_
7
8 #include <array>
9 #include <cstddef>
10 #include <cstdint>
11 #include <map>
12 #include <optional>
13 #include <ostream>
14 #include <vector>
15
16 #include "absl/container/inlined_vector.h"
17 #include "absl/strings/str_format.h"
18 #include "absl/strings/string_view.h"
19 #include "quiche/quic/core/quic_connection_id.h"
20 #include "quiche/quic/core/quic_error_codes.h"
21 #include "quiche/quic/core/quic_packet_number.h"
22 #include "quiche/quic/core/quic_time.h"
23 #include "quiche/quic/platform/api/quic_export.h"
24 #include "quiche/quic/platform/api/quic_flags.h"
25 #include "quiche/common/quiche_endian.h"
26 #include "quiche/web_transport/web_transport.h"
27
28 namespace quic {
29
30 using QuicPacketLength = uint16_t;
31 using QuicControlFrameId = uint32_t;
32 using QuicMessageId = uint32_t;
33
34 // IMPORTANT: IETF QUIC defines stream IDs and stream counts as being unsigned
35 // 62-bit numbers. However, we have decided to only support up to 2^32-1 streams
36 // in order to reduce the size of data structures such as QuicStreamFrame
37 // and QuicTransmissionInfo, as that allows them to fit in cache lines and has
38 // visible perfomance impact.
39 using QuicStreamId = uint32_t;
40
41 // Count of stream IDs. Used in MAX_STREAMS and STREAMS_BLOCKED frames.
42 using QuicStreamCount = QuicStreamId;
43
44 using QuicByteCount = uint64_t;
45 using QuicPacketCount = uint64_t;
46 using QuicPublicResetNonceProof = uint64_t;
47 using QuicStreamOffset = uint64_t;
48 using DiversificationNonce = std::array<char, 32>;
49 using PacketTimeVector = std::vector<std::pair<QuicPacketNumber, QuicTime>>;
50
51 enum : size_t { kStatelessResetTokenLength = 16 };
52 using StatelessResetToken = std::array<char, kStatelessResetTokenLength>;
53
54 // WebTransport session IDs are stream IDs.
55 using WebTransportSessionId = uint64_t;
56 // WebTransport stream reset codes are 32-bit.
57 using WebTransportStreamError = ::webtransport::StreamErrorCode;
58 // WebTransport session error codes are 32-bit.
59 using WebTransportSessionError = ::webtransport::SessionErrorCode;
60
61 enum : size_t { kQuicPathFrameBufferSize = 8 };
62 using QuicPathFrameBuffer = std::array<uint8_t, kQuicPathFrameBufferSize>;
63
64 // The connection id sequence number specifies the order that connection
65 // ids must be used in. This is also the sequence number carried in
66 // the IETF QUIC NEW_CONNECTION_ID and RETIRE_CONNECTION_ID frames.
67 using QuicConnectionIdSequenceNumber = uint64_t;
68
69 // A custom data that represents application-specific settings.
70 // In HTTP/3 for example, it includes the encoded SETTINGS.
71 using ApplicationState = std::vector<uint8_t>;
72
73 // A struct for functions which consume data payloads and fins.
74 struct QUICHE_EXPORT QuicConsumedData {
QuicConsumedDataQuicConsumedData75 constexpr QuicConsumedData(size_t bytes_consumed, bool fin_consumed)
76 : bytes_consumed(bytes_consumed), fin_consumed(fin_consumed) {}
77
78 // By default, gtest prints the raw bytes of an object. The bool data
79 // member causes this object to have padding bytes, which causes the
80 // default gtest object printer to read uninitialize memory. So we need
81 // to teach gtest how to print this object.
82 QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os,
83 const QuicConsumedData& s);
84
85 // How many bytes were consumed.
86 size_t bytes_consumed;
87
88 // True if an incoming fin was consumed.
89 bool fin_consumed;
90 };
91
92 // QuicAsyncStatus enumerates the possible results of an asynchronous
93 // operation.
94 enum QuicAsyncStatus {
95 QUIC_SUCCESS = 0,
96 QUIC_FAILURE = 1,
97 // QUIC_PENDING results from an operation that will occur asynchronously. When
98 // the operation is complete, a callback's |Run| method will be called.
99 QUIC_PENDING = 2,
100 };
101
102 // TODO(wtc): see if WriteStatus can be replaced by QuicAsyncStatus.
103 enum WriteStatus : int16_t {
104 WRITE_STATUS_OK,
105 // Write is blocked, caller needs to retry.
106 WRITE_STATUS_BLOCKED,
107 // Write is blocked but the packet data is buffered, caller should not retry.
108 WRITE_STATUS_BLOCKED_DATA_BUFFERED,
109 // To make the IsWriteError(WriteStatus) function work properly:
110 // - Non-errors MUST be added before WRITE_STATUS_ERROR.
111 // - Errors MUST be added after WRITE_STATUS_ERROR.
112 WRITE_STATUS_ERROR,
113 WRITE_STATUS_MSG_TOO_BIG,
114 WRITE_STATUS_FAILED_TO_COALESCE_PACKET,
115 WRITE_STATUS_NUM_VALUES,
116 };
117
118 std::string HistogramEnumString(WriteStatus enum_value);
119 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
120 const WriteStatus& status);
121
HistogramEnumDescription(WriteStatus)122 inline std::string HistogramEnumDescription(WriteStatus /*dummy*/) {
123 return "status";
124 }
125
IsWriteBlockedStatus(WriteStatus status)126 inline bool IsWriteBlockedStatus(WriteStatus status) {
127 return status == WRITE_STATUS_BLOCKED ||
128 status == WRITE_STATUS_BLOCKED_DATA_BUFFERED;
129 }
130
IsWriteError(WriteStatus status)131 inline bool IsWriteError(WriteStatus status) {
132 return status >= WRITE_STATUS_ERROR;
133 }
134
135 // A struct used to return the result of write calls including either the number
136 // of bytes written or the error code, depending upon the status.
137 struct QUICHE_EXPORT WriteResult {
WriteResultWriteResult138 constexpr WriteResult(WriteStatus status, int bytes_written_or_error_code)
139 : status(status), bytes_written(bytes_written_or_error_code) {}
140
WriteResultWriteResult141 constexpr WriteResult() : WriteResult(WRITE_STATUS_ERROR, 0) {}
142
143 bool operator==(const WriteResult& other) const {
144 if (status != other.status) {
145 return false;
146 }
147 switch (status) {
148 case WRITE_STATUS_OK:
149 return bytes_written == other.bytes_written;
150 case WRITE_STATUS_BLOCKED:
151 case WRITE_STATUS_BLOCKED_DATA_BUFFERED:
152 return true;
153 default:
154 return error_code == other.error_code;
155 }
156 }
157
158 QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os,
159 const WriteResult& s);
160
set_batch_idWriteResult161 WriteResult& set_batch_id(uint32_t new_batch_id) {
162 batch_id = new_batch_id;
163 return *this;
164 }
165
166 WriteStatus status;
167 // Number of packets dropped as a result of this write.
168 // Only used by batch writers. Otherwise always 0.
169 uint16_t dropped_packets = 0;
170 // The batch id the packet being written belongs to. For debugging only.
171 // Only used by batch writers. Only valid if the packet being written started
172 // a new batch, or added to an existing batch.
173 uint32_t batch_id = 0;
174 // The delta between a packet's ideal and actual send time:
175 // actual_send_time = ideal_send_time + send_time_offset
176 // = (now + release_time_delay) + send_time_offset
177 // Only valid if |status| is WRITE_STATUS_OK.
178 QuicTime::Delta send_time_offset = QuicTime::Delta::Zero();
179 // TODO(wub): In some cases, WRITE_STATUS_ERROR may set an error_code and
180 // WRITE_STATUS_BLOCKED_DATA_BUFFERED may set bytes_written. This may need
181 // some cleaning up so that perhaps both values can be set and valid.
182 union {
183 int bytes_written; // only valid when status is WRITE_STATUS_OK
184 int error_code; // only valid when status is WRITE_STATUS_ERROR
185 };
186 };
187
188 enum TransmissionType : int8_t {
189 NOT_RETRANSMISSION,
190 FIRST_TRANSMISSION_TYPE = NOT_RETRANSMISSION,
191 HANDSHAKE_RETRANSMISSION, // Retransmits due to handshake timeouts.
192 ALL_ZERO_RTT_RETRANSMISSION, // Retransmits all packets encrypted with 0-RTT
193 // key.
194 LOSS_RETRANSMISSION, // Retransmits due to loss detection.
195 PTO_RETRANSMISSION, // Retransmission due to probe timeout.
196 PATH_RETRANSMISSION, // Retransmission proactively due to underlying
197 // network change.
198 ALL_INITIAL_RETRANSMISSION, // Retransmit all packets encrypted with INITIAL
199 // key.
200 LAST_TRANSMISSION_TYPE = ALL_INITIAL_RETRANSMISSION,
201 };
202
203 QUICHE_EXPORT std::string TransmissionTypeToString(
204 TransmissionType transmission_type);
205
206 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
207 TransmissionType transmission_type);
208
209 enum HasRetransmittableData : uint8_t {
210 NO_RETRANSMITTABLE_DATA,
211 HAS_RETRANSMITTABLE_DATA,
212 };
213
214 enum IsHandshake : uint8_t { NOT_HANDSHAKE, IS_HANDSHAKE };
215
216 enum class Perspective : uint8_t { IS_SERVER, IS_CLIENT };
217
218 QUICHE_EXPORT std::string PerspectiveToString(Perspective perspective);
219 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
220 const Perspective& perspective);
221
222 // Describes whether a ConnectionClose was originated by the peer.
223 enum class ConnectionCloseSource { FROM_PEER, FROM_SELF };
224
225 QUICHE_EXPORT std::string ConnectionCloseSourceToString(
226 ConnectionCloseSource connection_close_source);
227 QUICHE_EXPORT std::ostream& operator<<(
228 std::ostream& os, const ConnectionCloseSource& connection_close_source);
229
230 // Should a connection be closed silently or not.
231 enum class ConnectionCloseBehavior {
232 SILENT_CLOSE,
233 SILENT_CLOSE_WITH_CONNECTION_CLOSE_PACKET_SERIALIZED,
234 SEND_CONNECTION_CLOSE_PACKET
235 };
236
237 QUICHE_EXPORT std::string ConnectionCloseBehaviorToString(
238 ConnectionCloseBehavior connection_close_behavior);
239 QUICHE_EXPORT std::ostream& operator<<(
240 std::ostream& os, const ConnectionCloseBehavior& connection_close_behavior);
241
242 enum QuicFrameType : uint8_t {
243 // Regular frame types. The values set here cannot change without the
244 // introduction of a new QUIC version.
245 PADDING_FRAME = 0,
246 RST_STREAM_FRAME = 1,
247 CONNECTION_CLOSE_FRAME = 2,
248 GOAWAY_FRAME = 3,
249 WINDOW_UPDATE_FRAME = 4,
250 BLOCKED_FRAME = 5,
251 STOP_WAITING_FRAME = 6,
252 PING_FRAME = 7,
253 CRYPTO_FRAME = 8,
254 // TODO(b/157935330): stop hard coding this when deprecate T050.
255 HANDSHAKE_DONE_FRAME = 9,
256
257 // STREAM and ACK frames are special frames. They are encoded differently on
258 // the wire and their values do not need to be stable.
259 STREAM_FRAME,
260 ACK_FRAME,
261 // The path MTU discovery frame is encoded as a PING frame on the wire.
262 MTU_DISCOVERY_FRAME,
263
264 // These are for IETF-specific frames for which there is no mapping
265 // from Google QUIC frames. These are valid/allowed if and only if IETF-
266 // QUIC has been negotiated. Values are not important, they are not
267 // the values that are in the packets (see QuicIetfFrameType, below).
268 NEW_CONNECTION_ID_FRAME,
269 MAX_STREAMS_FRAME,
270 STREAMS_BLOCKED_FRAME,
271 PATH_RESPONSE_FRAME,
272 PATH_CHALLENGE_FRAME,
273 STOP_SENDING_FRAME,
274 MESSAGE_FRAME,
275 NEW_TOKEN_FRAME,
276 RETIRE_CONNECTION_ID_FRAME,
277 ACK_FREQUENCY_FRAME,
278 RESET_STREAM_AT_FRAME,
279
280 NUM_FRAME_TYPES
281 };
282
283 // Human-readable string suitable for logging.
284 QUICHE_EXPORT std::string QuicFrameTypeToString(QuicFrameType t);
285 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
286 const QuicFrameType& t);
287
288 // Ietf frame types. These are defined in the IETF QUIC Specification.
289 // Explicit values are given in the enum so that we can be sure that
290 // the symbol will map to the correct stream type.
291 // All types are defined here, even if we have not yet implmented the
292 // quic/core/stream/.... stuff needed.
293 // Note: The protocol specifies that frame types are varint-62 encoded,
294 // further stating that the shortest encoding must be used. The current set of
295 // frame types all have values less than 0x40 (64) so can be encoded in a single
296 // byte, with the two most significant bits being 0. Thus, the following
297 // enumerations are valid as both the numeric values of frame types AND their
298 // encodings.
299 enum QuicIetfFrameType : uint64_t {
300 IETF_PADDING = 0x00,
301 IETF_PING = 0x01,
302 IETF_ACK = 0x02,
303 IETF_ACK_ECN = 0x03,
304 IETF_RST_STREAM = 0x04,
305 IETF_STOP_SENDING = 0x05,
306 IETF_CRYPTO = 0x06,
307 IETF_NEW_TOKEN = 0x07,
308 // the low-3 bits of the stream frame type value are actually flags
309 // declaring what parts of the frame are/are-not present, as well as
310 // some other control information. The code would then do something
311 // along the lines of "if ((frame_type & 0xf8) == 0x08)" to determine
312 // whether the frame is a stream frame or not, and then examine each
313 // bit specifically when/as needed.
314 IETF_STREAM = 0x08,
315 // 0x09 through 0x0f are various flag settings of the IETF_STREAM frame.
316 IETF_MAX_DATA = 0x10,
317 IETF_MAX_STREAM_DATA = 0x11,
318 IETF_MAX_STREAMS_BIDIRECTIONAL = 0x12,
319 IETF_MAX_STREAMS_UNIDIRECTIONAL = 0x13,
320 IETF_DATA_BLOCKED = 0x14,
321 IETF_STREAM_DATA_BLOCKED = 0x15,
322 IETF_STREAMS_BLOCKED_BIDIRECTIONAL = 0x16,
323 IETF_STREAMS_BLOCKED_UNIDIRECTIONAL = 0x17,
324 IETF_NEW_CONNECTION_ID = 0x18,
325 IETF_RETIRE_CONNECTION_ID = 0x19,
326 IETF_PATH_CHALLENGE = 0x1a,
327 IETF_PATH_RESPONSE = 0x1b,
328 // Both of the following are "Connection Close" frames,
329 // the first signals transport-layer errors, the second application-layer
330 // errors.
331 IETF_CONNECTION_CLOSE = 0x1c,
332 IETF_APPLICATION_CLOSE = 0x1d,
333
334 IETF_HANDSHAKE_DONE = 0x1e,
335
336 // The MESSAGE frame type has not yet been fully standardized.
337 // QUIC versions starting with 46 and before 99 use 0x20-0x21.
338 // IETF QUIC (v99) uses 0x30-0x31, see draft-pauly-quic-datagram.
339 IETF_EXTENSION_MESSAGE_NO_LENGTH = 0x20,
340 IETF_EXTENSION_MESSAGE = 0x21,
341 IETF_EXTENSION_MESSAGE_NO_LENGTH_V99 = 0x30,
342 IETF_EXTENSION_MESSAGE_V99 = 0x31,
343
344 // An QUIC extension frame for sender control of acknowledgement delays
345 IETF_ACK_FREQUENCY = 0xaf,
346
347 // A QUIC extension frame which augments the IETF_ACK frame definition with
348 // packet receive timestamps.
349 // TODO(ianswett): Determine a proper value to replace this temporary value.
350 IETF_ACK_RECEIVE_TIMESTAMPS = 0x22,
351
352 // https://datatracker.ietf.org/doc/html/draft-ietf-quic-reliable-stream-reset
353 IETF_RESET_STREAM_AT = 0x24,
354 };
355 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
356 const QuicIetfFrameType& c);
357 QUICHE_EXPORT std::string QuicIetfFrameTypeString(QuicIetfFrameType t);
358
359 // Masks for the bits that indicate the frame is a Stream frame vs the
360 // bits used as flags.
361 #define IETF_STREAM_FRAME_TYPE_MASK 0xfffffffffffffff8
362 #define IETF_STREAM_FRAME_FLAG_MASK 0x07
363 #define IS_IETF_STREAM_FRAME(_stype_) \
364 (((_stype_) & IETF_STREAM_FRAME_TYPE_MASK) == IETF_STREAM)
365
366 // These are the values encoded in the low-order 3 bits of the
367 // IETF_STREAMx frame type.
368 #define IETF_STREAM_FRAME_FIN_BIT 0x01
369 #define IETF_STREAM_FRAME_LEN_BIT 0x02
370 #define IETF_STREAM_FRAME_OFF_BIT 0x04
371
372 enum QuicPacketNumberLength : uint8_t {
373 PACKET_1BYTE_PACKET_NUMBER = 1,
374 PACKET_2BYTE_PACKET_NUMBER = 2,
375 PACKET_3BYTE_PACKET_NUMBER = 3, // Used in versions 45+.
376 PACKET_4BYTE_PACKET_NUMBER = 4,
377 IETF_MAX_PACKET_NUMBER_LENGTH = 4,
378 // TODO(b/145819870): Remove 6 and 8 when we remove Q043 since these values
379 // are not representable with later versions.
380 PACKET_6BYTE_PACKET_NUMBER = 6,
381 PACKET_8BYTE_PACKET_NUMBER = 8
382 };
383
384 // Used to indicate a QuicSequenceNumberLength using two flag bits.
385 enum QuicPacketNumberLengthFlags {
386 PACKET_FLAGS_1BYTE_PACKET = 0, // 00
387 PACKET_FLAGS_2BYTE_PACKET = 1, // 01
388 PACKET_FLAGS_4BYTE_PACKET = 1 << 1, // 10
389 PACKET_FLAGS_8BYTE_PACKET = 1 << 1 | 1, // 11
390 };
391
392 // The public flags are specified in one byte.
393 enum QuicPacketPublicFlags {
394 PACKET_PUBLIC_FLAGS_NONE = 0,
395
396 // Bit 0: Does the packet header contains version info?
397 PACKET_PUBLIC_FLAGS_VERSION = 1 << 0,
398
399 // Bit 1: Is this packet a public reset packet?
400 PACKET_PUBLIC_FLAGS_RST = 1 << 1,
401
402 // Bit 2: indicates the header includes a nonce.
403 PACKET_PUBLIC_FLAGS_NONCE = 1 << 2,
404
405 // Bit 3: indicates whether a ConnectionID is included.
406 PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID = 0,
407 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID = 1 << 3,
408
409 // Deprecated version 32 and earlier used two bits to indicate an 8-byte
410 // connection ID. We send this from the client because of some broken
411 // middleboxes that are still checking this bit.
412 PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD = 1 << 3 | 1 << 2,
413
414 // Bits 4 and 5 describe the packet number length as follows:
415 // --00----: 1 byte
416 // --01----: 2 bytes
417 // --10----: 4 bytes
418 // --11----: 6 bytes
419 PACKET_PUBLIC_FLAGS_1BYTE_PACKET = PACKET_FLAGS_1BYTE_PACKET << 4,
420 PACKET_PUBLIC_FLAGS_2BYTE_PACKET = PACKET_FLAGS_2BYTE_PACKET << 4,
421 PACKET_PUBLIC_FLAGS_4BYTE_PACKET = PACKET_FLAGS_4BYTE_PACKET << 4,
422 PACKET_PUBLIC_FLAGS_6BYTE_PACKET = PACKET_FLAGS_8BYTE_PACKET << 4,
423
424 // Reserved, unimplemented flags:
425
426 // Bit 7: indicates the presence of a second flags byte.
427 PACKET_PUBLIC_FLAGS_TWO_OR_MORE_BYTES = 1 << 7,
428
429 // All bits set (bits 6 and 7 are not currently used): 00111111
430 PACKET_PUBLIC_FLAGS_MAX = (1 << 6) - 1,
431 };
432
433 // The private flags are specified in one byte.
434 enum QuicPacketPrivateFlags {
435 PACKET_PRIVATE_FLAGS_NONE = 0,
436
437 // Bit 0: Does this packet contain an entropy bit?
438 PACKET_PRIVATE_FLAGS_ENTROPY = 1 << 0,
439
440 // (bits 1-7 are not used): 00000001
441 PACKET_PRIVATE_FLAGS_MAX = (1 << 1) - 1
442 };
443
444 // Defines for all types of congestion control algorithms that can be used in
445 // QUIC. Note that this is separate from the congestion feedback type -
446 // some congestion control algorithms may use the same feedback type
447 // (Reno and Cubic are the classic example for that).
448 enum CongestionControlType {
449 kCubicBytes,
450 kRenoBytes,
451 kBBR,
452 kPCC,
453 kGoogCC,
454 kBBRv2, // TODO(rch): This is effectively BBRv3. We should finish the
455 // implementation and rename this enum.
456 };
457
458 QUICHE_EXPORT std::string CongestionControlTypeToString(
459 CongestionControlType cc_type);
460
461 // EncryptionLevel enumerates the stages of encryption that a QUIC connection
462 // progresses through. When retransmitting a packet, the encryption level needs
463 // to be specified so that it is retransmitted at a level which the peer can
464 // understand.
465 enum EncryptionLevel : int8_t {
466 ENCRYPTION_INITIAL = 0,
467 ENCRYPTION_HANDSHAKE = 1,
468 ENCRYPTION_ZERO_RTT = 2,
469 ENCRYPTION_FORWARD_SECURE = 3,
470
471 NUM_ENCRYPTION_LEVELS,
472 };
473
EncryptionLevelIsValid(EncryptionLevel level)474 inline bool EncryptionLevelIsValid(EncryptionLevel level) {
475 return ENCRYPTION_INITIAL <= level && level < NUM_ENCRYPTION_LEVELS;
476 }
477
478 QUICHE_EXPORT std::string EncryptionLevelToString(EncryptionLevel level);
479
480 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, EncryptionLevel level);
481
482 // Enumeration of whether a server endpoint will request a client certificate,
483 // and whether that endpoint requires a valid client certificate to establish a
484 // connection.
485 enum class ClientCertMode : uint8_t {
486 kNone, // Do not request a client certificate. Default server behavior.
487 kRequest, // Request a certificate, but allow unauthenticated connections.
488 kRequire, // Require clients to provide a valid certificate.
489 };
490
491 QUICHE_EXPORT absl::string_view ClientCertModeToString(ClientCertMode mode);
492
493 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, ClientCertMode mode);
494
495 enum AddressChangeType : uint8_t {
496 // IP address and port remain unchanged.
497 NO_CHANGE,
498 // Port changed, but IP address remains unchanged.
499 PORT_CHANGE,
500 // IPv4 address changed, but within the /24 subnet (port may have changed.)
501 IPV4_SUBNET_CHANGE,
502 // IPv4 address changed, excluding /24 subnet change (port may have changed.)
503 IPV4_TO_IPV4_CHANGE,
504 // IP address change from an IPv4 to an IPv6 address (port may have changed.)
505 IPV4_TO_IPV6_CHANGE,
506 // IP address change from an IPv6 to an IPv4 address (port may have changed.)
507 IPV6_TO_IPV4_CHANGE,
508 // IP address change from an IPv6 to an IPv6 address (port may have changed.)
509 IPV6_TO_IPV6_CHANGE,
510 };
511
512 QUICHE_EXPORT std::string AddressChangeTypeToString(AddressChangeType type);
513
514 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
515 AddressChangeType type);
516
517 enum StreamSendingState {
518 // Sender has more data to send on this stream.
519 NO_FIN,
520 // Sender is done sending on this stream.
521 FIN,
522 // Sender is done sending on this stream and random padding needs to be
523 // appended after all stream frames.
524 FIN_AND_PADDING,
525 };
526
527 enum SentPacketState : uint8_t {
528 // The packet is in flight and waiting to be acked.
529 OUTSTANDING,
530 FIRST_PACKET_STATE = OUTSTANDING,
531 // The packet was never sent.
532 NEVER_SENT,
533 // The packet has been acked.
534 ACKED,
535 // This packet is not expected to be acked.
536 UNACKABLE,
537 // This packet has been delivered or unneeded.
538 NEUTERED,
539
540 // States below are corresponding to retransmission types in TransmissionType.
541
542 // This packet has been retransmitted when retransmission timer fires in
543 // HANDSHAKE mode.
544 HANDSHAKE_RETRANSMITTED,
545 // This packet is considered as lost, this is used for LOST_RETRANSMISSION.
546 LOST,
547 // This packet has been retransmitted when PTO fires.
548 PTO_RETRANSMITTED,
549 // This packet is sent on a different path or is a PING only packet.
550 // Do not update RTT stats and congestion control if the packet is the
551 // largest_acked of an incoming ACK.
552 NOT_CONTRIBUTING_RTT,
553 LAST_PACKET_STATE = NOT_CONTRIBUTING_RTT,
554 };
555
556 enum PacketHeaderFormat : uint8_t {
557 IETF_QUIC_LONG_HEADER_PACKET,
558 IETF_QUIC_SHORT_HEADER_PACKET,
559 GOOGLE_QUIC_PACKET,
560 };
561
562 QUICHE_EXPORT std::string PacketHeaderFormatToString(PacketHeaderFormat format);
563
564 // Information about a newly acknowledged packet.
565 struct QUICHE_EXPORT AckedPacket {
AckedPacketAckedPacket566 constexpr AckedPacket(QuicPacketNumber packet_number,
567 QuicPacketLength bytes_acked,
568 QuicTime receive_timestamp)
569 : packet_number(packet_number),
570 bytes_acked(bytes_acked),
571 receive_timestamp(receive_timestamp) {}
572
573 friend QUICHE_EXPORT std::ostream& operator<<(
574 std::ostream& os, const AckedPacket& acked_packet);
575
576 QuicPacketNumber packet_number;
577 // Number of bytes sent in the packet that was acknowledged.
578 QuicPacketLength bytes_acked;
579 // Whether the packet has been marked as lost before the ack. |bytes_acked|
580 // should be 0 if this is true.
581 bool spurious_loss = false;
582 // The time |packet_number| was received by the peer, according to the
583 // optional timestamp the peer included in the ACK frame which acknowledged
584 // |packet_number|. Zero if no timestamp was available for this packet.
585 QuicTime receive_timestamp;
586 };
587
588 // A vector of acked packets.
589 using AckedPacketVector = absl::InlinedVector<AckedPacket, 2>;
590
591 // Information about a newly lost packet.
592 struct QUICHE_EXPORT LostPacket {
LostPacketLostPacket593 LostPacket(QuicPacketNumber packet_number, QuicPacketLength bytes_lost)
594 : packet_number(packet_number), bytes_lost(bytes_lost) {}
595
596 friend QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
597 const LostPacket& lost_packet);
598
599 QuicPacketNumber packet_number;
600 // Number of bytes sent in the packet that was lost.
601 QuicPacketLength bytes_lost;
602 };
603
604 // A vector of lost packets.
605 using LostPacketVector = absl::InlinedVector<LostPacket, 2>;
606
607 // Please note, this value cannot used directly for packet serialization.
608 enum QuicLongHeaderType : uint8_t {
609 VERSION_NEGOTIATION,
610 INITIAL,
611 ZERO_RTT_PROTECTED,
612 HANDSHAKE,
613 RETRY,
614
615 INVALID_PACKET_TYPE,
616 };
617
618 QUICHE_EXPORT std::string QuicLongHeaderTypeToString(QuicLongHeaderType type);
619
620 enum QuicPacketHeaderTypeFlags : uint8_t {
621 // Bit 2: Key phase bit for IETF QUIC short header packets.
622 FLAGS_KEY_PHASE_BIT = 1 << 2,
623 // Bit 3: Google QUIC Demultiplexing bit, the short header always sets this
624 // bit to 0, allowing to distinguish Google QUIC packets from short header
625 // packets.
626 FLAGS_DEMULTIPLEXING_BIT = 1 << 3,
627 // Bits 4 and 5: Reserved bits for short header.
628 FLAGS_SHORT_HEADER_RESERVED_1 = 1 << 4,
629 FLAGS_SHORT_HEADER_RESERVED_2 = 1 << 5,
630 // Bit 6: the 'QUIC' bit.
631 FLAGS_FIXED_BIT = 1 << 6,
632 // Bit 7: Indicates the header is long or short header.
633 FLAGS_LONG_HEADER = 1 << 7,
634 };
635
636 enum MessageStatus {
637 MESSAGE_STATUS_SUCCESS,
638 MESSAGE_STATUS_ENCRYPTION_NOT_ESTABLISHED, // Failed to send message because
639 // encryption is not established
640 // yet.
641 MESSAGE_STATUS_UNSUPPORTED, // Failed to send message because MESSAGE frame
642 // is not supported by the connection.
643 MESSAGE_STATUS_BLOCKED, // Failed to send message because connection is
644 // congestion control blocked or underlying socket is
645 // write blocked.
646 MESSAGE_STATUS_TOO_LARGE, // Failed to send message because the message is
647 // too large to fit into a single packet.
648 MESSAGE_STATUS_INTERNAL_ERROR, // Failed to send message because connection
649 // reaches an invalid state.
650 };
651
652 QUICHE_EXPORT std::string MessageStatusToString(MessageStatus message_status);
653
654 // Used to return the result of SendMessage calls
655 struct QUICHE_EXPORT MessageResult {
656 MessageResult(MessageStatus status, QuicMessageId message_id);
657
658 bool operator==(const MessageResult& other) const {
659 return status == other.status && message_id == other.message_id;
660 }
661
662 QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os,
663 const MessageResult& mr);
664
665 MessageStatus status;
666 // Only valid when status is MESSAGE_STATUS_SUCCESS.
667 QuicMessageId message_id;
668 };
669
670 QUICHE_EXPORT std::string MessageResultToString(MessageResult message_result);
671
672 enum WriteStreamDataResult {
673 WRITE_SUCCESS,
674 STREAM_MISSING, // Trying to write data of a nonexistent stream (e.g.
675 // closed).
676 WRITE_FAILED, // Trying to write nonexistent data of a stream
677 };
678
679 enum StreamType : uint8_t {
680 // Bidirectional streams allow for data to be sent in both directions.
681 BIDIRECTIONAL,
682
683 // Unidirectional streams carry data in one direction only.
684 WRITE_UNIDIRECTIONAL,
685 READ_UNIDIRECTIONAL,
686 // Not actually a stream type. Used only by QuicCryptoStream when it uses
687 // CRYPTO frames and isn't actually a QuicStream.
688 CRYPTO,
689 };
690
691 // A packet number space is the context in which a packet can be processed and
692 // acknowledged.
693 enum PacketNumberSpace : uint8_t {
694 INITIAL_DATA = 0, // Only used in IETF QUIC.
695 HANDSHAKE_DATA = 1,
696 APPLICATION_DATA = 2,
697
698 NUM_PACKET_NUMBER_SPACES,
699 };
700
701 QUICHE_EXPORT std::string PacketNumberSpaceToString(
702 PacketNumberSpace packet_number_space);
703
704 // Used to return the result of processing a received ACK frame.
705 enum AckResult {
706 PACKETS_NEWLY_ACKED,
707 NO_PACKETS_NEWLY_ACKED,
708 UNSENT_PACKETS_ACKED, // Peer acks unsent packets.
709 UNACKABLE_PACKETS_ACKED, // Peer acks packets that are not expected to be
710 // acked. For example, encryption is reestablished,
711 // and all sent encrypted packets cannot be
712 // decrypted by the peer. Version gets negotiated,
713 // and all sent packets in the different version
714 // cannot be processed by the peer.
715 PACKETS_ACKED_IN_WRONG_PACKET_NUMBER_SPACE,
716 };
717
718 // Used to return the result of processing a received NEW_CID frame.
719 enum class NewConnectionIdResult : uint8_t {
720 kOk,
721 kDuplicateFrame, // Not an error.
722 kProtocolViolation,
723 };
724
725 // Indicates the fate of a serialized packet in WritePacket().
726 enum SerializedPacketFate : uint8_t {
727 DISCARD, // Discard the packet.
728 COALESCE, // Try to coalesce packet.
729 BUFFER, // Buffer packet in buffered_packets_.
730 SEND_TO_WRITER, // Send packet to writer.
731 };
732
733 QUICHE_EXPORT std::string SerializedPacketFateToString(
734 SerializedPacketFate fate);
735
736 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
737 const SerializedPacketFate fate);
738
739 // There are three different forms of CONNECTION_CLOSE.
740 enum QuicConnectionCloseType {
741 GOOGLE_QUIC_CONNECTION_CLOSE = 0,
742 IETF_QUIC_TRANSPORT_CONNECTION_CLOSE = 1,
743 IETF_QUIC_APPLICATION_CONNECTION_CLOSE = 2
744 };
745
746 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
747 const QuicConnectionCloseType type);
748
749 QUICHE_EXPORT std::string QuicConnectionCloseTypeString(
750 QuicConnectionCloseType type);
751
752 // Indicate handshake state of a connection.
753 enum HandshakeState {
754 // Initial state.
755 HANDSHAKE_START,
756 // Only used in IETF QUIC with TLS handshake. State proceeds to
757 // HANDSHAKE_PROCESSED after a packet of HANDSHAKE packet number space
758 // gets successfully processed, and the initial key can be dropped.
759 HANDSHAKE_PROCESSED,
760 // In QUIC crypto, state proceeds to HANDSHAKE_COMPLETE if client receives
761 // SHLO or server successfully processes an ENCRYPTION_FORWARD_SECURE
762 // packet, such that the handshake packets can be neutered. In IETF QUIC
763 // with TLS handshake, state proceeds to HANDSHAKE_COMPLETE once the client
764 // has both 1-RTT send and receive keys.
765 HANDSHAKE_COMPLETE,
766 // Only used in IETF QUIC with TLS handshake. State proceeds to
767 // HANDSHAKE_CONFIRMED if 1) a client receives HANDSHAKE_DONE frame or
768 // acknowledgment for 1-RTT packet or 2) server has
769 // 1-RTT send and receive keys.
770 HANDSHAKE_CONFIRMED,
771 };
772
773 struct QUICHE_EXPORT NextReleaseTimeResult {
774 // The ideal release time of the packet being sent.
775 QuicTime release_time;
776 // Whether it is allowed to send the packet before release_time.
777 bool allow_burst;
778 };
779
780 // QuicPacketBuffer bundles a buffer and a function that releases it. Note
781 // it does not assume ownership of buffer, i.e. it doesn't release the buffer on
782 // destruction.
783 struct QUICHE_EXPORT QuicPacketBuffer {
784 QuicPacketBuffer() = default;
785
QuicPacketBufferQuicPacketBuffer786 QuicPacketBuffer(char* buffer,
787 std::function<void(const char*)> release_buffer)
788 : buffer(buffer), release_buffer(std::move(release_buffer)) {}
789
790 char* buffer = nullptr;
791 std::function<void(const char*)> release_buffer;
792 };
793
794 // QuicOwnedPacketBuffer is a QuicPacketBuffer that assumes buffer ownership.
795 struct QUICHE_EXPORT QuicOwnedPacketBuffer : public QuicPacketBuffer {
796 QuicOwnedPacketBuffer(const QuicOwnedPacketBuffer&) = delete;
797 QuicOwnedPacketBuffer& operator=(const QuicOwnedPacketBuffer&) = delete;
798
QuicOwnedPacketBufferQuicOwnedPacketBuffer799 QuicOwnedPacketBuffer(char* buffer,
800 std::function<void(const char*)> release_buffer)
801 : QuicPacketBuffer(buffer, std::move(release_buffer)) {}
802
QuicOwnedPacketBufferQuicOwnedPacketBuffer803 QuicOwnedPacketBuffer(QuicOwnedPacketBuffer&& owned_buffer)
804 : QuicPacketBuffer(std::move(owned_buffer)) {
805 // |owned_buffer| does not own a buffer any more.
806 owned_buffer.buffer = nullptr;
807 }
808
QuicOwnedPacketBufferQuicOwnedPacketBuffer809 explicit QuicOwnedPacketBuffer(QuicPacketBuffer&& packet_buffer)
810 : QuicPacketBuffer(std::move(packet_buffer)) {}
811
~QuicOwnedPacketBufferQuicOwnedPacketBuffer812 ~QuicOwnedPacketBuffer() {
813 if (release_buffer != nullptr && buffer != nullptr) {
814 release_buffer(buffer);
815 }
816 }
817 };
818
819 // These values must remain stable as they are uploaded to UMA histograms.
820 enum class KeyUpdateReason {
821 kInvalid = 0,
822 kRemote = 1,
823 kLocalForTests = 2,
824 kLocalForInteropRunner = 3,
825 kLocalAeadConfidentialityLimit = 4,
826 kLocalKeyUpdateLimitOverride = 5,
827 kMaxValue = kLocalKeyUpdateLimitOverride,
828 };
829
830 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
831 const KeyUpdateReason reason);
832
833 QUICHE_EXPORT std::string KeyUpdateReasonString(KeyUpdateReason reason);
834
835 using QuicSignatureAlgorithmVector = absl::InlinedVector<uint16_t, 8>;
836
837 // QuicSSLConfig contains configurations to be applied on a SSL object, which
838 // overrides the configurations in SSL_CTX.
839 struct QUICHE_EXPORT QuicSSLConfig {
840 // Whether TLS early data should be enabled. If not set, default to enabled.
841 std::optional<bool> early_data_enabled;
842 // Whether TLS session tickets are supported. If not set, default to
843 // supported.
844 std::optional<bool> disable_ticket_support;
845 // If set, used to configure the SSL object with
846 // SSL_set_signing_algorithm_prefs.
847 std::optional<QuicSignatureAlgorithmVector> signing_algorithm_prefs;
848 // Client certificate mode for mTLS support. Only used at server side.
849 ClientCertMode client_cert_mode = ClientCertMode::kNone;
850 // As a client, the ECHConfigList to use with ECH. If empty, ECH is not
851 // offered.
852 std::string ech_config_list;
853 // As a client, whether ECH GREASE is enabled. If `ech_config_list` is
854 // not empty, this value does nothing.
855 bool ech_grease_enabled = false;
856 };
857
858 // QuicDelayedSSLConfig contains a subset of SSL config that can be applied
859 // after BoringSSL's early select certificate callback. This overwrites all SSL
860 // configs applied before cert selection.
861 struct QUICHE_EXPORT QuicDelayedSSLConfig {
862 // Client certificate mode for mTLS support. Only used at server side.
863 // std::nullopt means do not change client certificate mode.
864 std::optional<ClientCertMode> client_cert_mode;
865 // QUIC transport parameters as serialized by ProofSourceHandle.
866 std::optional<std::vector<uint8_t>> quic_transport_parameters;
867 };
868
869 // ParsedClientHello contains client hello information extracted from a fully
870 // received client hello.
871 struct QUICHE_EXPORT ParsedClientHello {
872 std::string sni; // QUIC crypto and TLS.
873 std::string uaid; // QUIC crypto only.
874 std::vector<uint16_t> supported_groups; // TLS only.
875 std::vector<std::string> alpns; // QUIC crypto and TLS.
876 // The unvalidated retry token from the last received packet of a potentially
877 // multi-packet client hello. TLS only.
878 std::string retry_token;
879 bool resumption_attempted = false; // TLS only.
880 bool early_data_attempted = false; // TLS only.
881 };
882
883 QUICHE_EXPORT bool operator==(const ParsedClientHello& a,
884 const ParsedClientHello& b);
885
886 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os,
887 const ParsedClientHello& parsed_chlo);
888
889 // The two bits in the IP header for Explicit Congestion Notification can take
890 // one of four values.
891 enum QuicEcnCodepoint {
892 // The NOT-ECT codepoint, indicating the packet sender is not using (or the
893 // network has disabled) ECN.
894 ECN_NOT_ECT = 0,
895 // The ECT(1) codepoint, indicating the packet sender is using Low Latency,
896 // Low Loss, Scalable Throughput (L4S) ECN (RFC9330).
897 ECN_ECT1 = 1,
898 // The ECT(0) codepoint, indicating the packet sender is using classic ECN
899 // (RFC3168).
900 ECN_ECT0 = 2,
901 // The CE ("Congestion Experienced") codepoint, indicating the packet sender
902 // is using ECN, and a router is experiencing congestion.
903 ECN_CE = 3,
904 };
905
906 QUICHE_EXPORT std::string EcnCodepointToString(QuicEcnCodepoint ecn);
907
908 // This struct reports the Explicit Congestion Notification (ECN) contents of
909 // the ACK_ECN frame. They are the cumulative number of QUIC packets received
910 // for that codepoint in a given Packet Number Space.
911 struct QUICHE_EXPORT QuicEcnCounts {
912 QuicEcnCounts() = default;
QuicEcnCountsQuicEcnCounts913 QuicEcnCounts(QuicPacketCount ect0, QuicPacketCount ect1, QuicPacketCount ce)
914 : ect0(ect0), ect1(ect1), ce(ce) {}
915
ToStringQuicEcnCounts916 std::string ToString() const {
917 return absl::StrFormat("ECT(0): %s, ECT(1): %s, CE: %s",
918 std::to_string(ect0), std::to_string(ect1),
919 std::to_string(ce));
920 }
921
922 bool operator==(const QuicEcnCounts& other) const {
923 return (this->ect0 == other.ect0 && this->ect1 == other.ect1 &&
924 this->ce == other.ce);
925 }
926
927 QuicPacketCount ect0 = 0;
928 QuicPacketCount ect1 = 0;
929 QuicPacketCount ce = 0;
930 };
931
932 // Type of the priorities used by a QUIC session.
933 enum class QuicPriorityType : uint8_t {
934 // HTTP priorities as defined by RFC 9218
935 kHttp,
936 // WebTransport priorities as defined by <https://w3c.github.io/webtransport/>
937 kWebTransport,
938 };
939
940 QUICHE_EXPORT std::string QuicPriorityTypeToString(QuicPriorityType type);
941 QUICHE_EXPORT std::ostream& operator<<(std::ostream& os, QuicPriorityType type);
942
943 } // namespace quic
944
945 #endif // QUICHE_QUIC_CORE_QUIC_TYPES_H_
946