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