xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/quic_packets.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright (c) 2012 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_PACKETS_H_
6 #define QUICHE_QUIC_CORE_QUIC_PACKETS_H_
7 
8 #include <sys/types.h>
9 
10 #include <cstddef>
11 #include <cstdint>
12 #include <memory>
13 #include <ostream>
14 #include <string>
15 #include <utility>
16 
17 #include "absl/strings/string_view.h"
18 #include "quiche/quic/core/frames/quic_frame.h"
19 #include "quiche/quic/core/quic_ack_listener_interface.h"
20 #include "quiche/quic/core/quic_bandwidth.h"
21 #include "quiche/quic/core/quic_constants.h"
22 #include "quiche/quic/core/quic_error_codes.h"
23 #include "quiche/quic/core/quic_time.h"
24 #include "quiche/quic/core/quic_types.h"
25 #include "quiche/quic/core/quic_versions.h"
26 #include "quiche/quic/platform/api/quic_export.h"
27 #include "quiche/quic/platform/api/quic_socket_address.h"
28 
29 namespace quic {
30 
31 class QuicPacket;
32 struct QuicPacketHeader;
33 
34 // Returns the destination connection ID of |header| when |perspective| is
35 // server, and the source connection ID when |perspective| is client.
36 QUICHE_EXPORT QuicConnectionId GetServerConnectionIdAsRecipient(
37     const QuicPacketHeader& header, Perspective perspective);
38 
39 // Returns the destination connection ID of |header| when |perspective| is
40 // client, and the source connection ID when |perspective| is server.
41 QUICHE_EXPORT QuicConnectionId GetClientConnectionIdAsRecipient(
42     const QuicPacketHeader& header, Perspective perspective);
43 
44 // Returns the destination connection ID of |header| when |perspective| is
45 // client, and the source connection ID when |perspective| is server.
46 QUICHE_EXPORT QuicConnectionId GetServerConnectionIdAsSender(
47     const QuicPacketHeader& header, Perspective perspective);
48 
49 // Returns the destination connection ID included of |header| when |perspective|
50 // is client, and the source connection ID included when |perspective| is
51 // server.
52 QUICHE_EXPORT QuicConnectionIdIncluded GetServerConnectionIdIncludedAsSender(
53     const QuicPacketHeader& header, Perspective perspective);
54 
55 // Returns the destination connection ID of |header| when |perspective| is
56 // server, and the source connection ID when |perspective| is client.
57 QUICHE_EXPORT QuicConnectionId GetClientConnectionIdAsSender(
58     const QuicPacketHeader& header, Perspective perspective);
59 
60 // Returns the destination connection ID included of |header| when |perspective|
61 // is server, and the source connection ID included when |perspective| is
62 // client.
63 QUICHE_EXPORT QuicConnectionIdIncluded GetClientConnectionIdIncludedAsSender(
64     const QuicPacketHeader& header, Perspective perspective);
65 
66 // Number of connection ID bytes that are actually included over the wire.
67 QUICHE_EXPORT uint8_t
68 GetIncludedConnectionIdLength(QuicConnectionId connection_id,
69                               QuicConnectionIdIncluded connection_id_included);
70 
71 // Number of destination connection ID bytes that are actually included over the
72 // wire for this particular header.
73 QUICHE_EXPORT uint8_t
74 GetIncludedDestinationConnectionIdLength(const QuicPacketHeader& header);
75 
76 // Number of source connection ID bytes that are actually included over the
77 // wire for this particular header.
78 QUICHE_EXPORT uint8_t
79 GetIncludedSourceConnectionIdLength(const QuicPacketHeader& header);
80 
81 // Size in bytes of the data packet header.
82 QUICHE_EXPORT size_t GetPacketHeaderSize(QuicTransportVersion version,
83                                          const QuicPacketHeader& header);
84 
85 QUICHE_EXPORT size_t GetPacketHeaderSize(
86     QuicTransportVersion version, uint8_t destination_connection_id_length,
87     uint8_t source_connection_id_length, bool include_version,
88     bool include_diversification_nonce,
89     QuicPacketNumberLength packet_number_length,
90     quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
91     QuicByteCount retry_token_length,
92     quiche::QuicheVariableLengthIntegerLength length_length);
93 
94 // Index of the first byte in a QUIC packet of encrypted data.
95 QUICHE_EXPORT size_t GetStartOfEncryptedData(QuicTransportVersion version,
96                                              const QuicPacketHeader& header);
97 
98 QUICHE_EXPORT size_t GetStartOfEncryptedData(
99     QuicTransportVersion version, uint8_t destination_connection_id_length,
100     uint8_t source_connection_id_length, bool include_version,
101     bool include_diversification_nonce,
102     QuicPacketNumberLength packet_number_length,
103     quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
104     QuicByteCount retry_token_length,
105     quiche::QuicheVariableLengthIntegerLength length_length);
106 
107 struct QUICHE_EXPORT QuicPacketHeader {
108   QuicPacketHeader();
109   QuicPacketHeader(const QuicPacketHeader& other);
110   ~QuicPacketHeader();
111 
112   QuicPacketHeader& operator=(const QuicPacketHeader& other);
113 
114   QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os,
115                                                 const QuicPacketHeader& header);
116 
117   // Universal header. All QuicPacket headers will have a connection_id and
118   // public flags.
119   QuicConnectionId destination_connection_id;
120   QuicConnectionIdIncluded destination_connection_id_included;
121   QuicConnectionId source_connection_id;
122   QuicConnectionIdIncluded source_connection_id_included;
123   // This is only used for Google QUIC.
124   bool reset_flag;
125   // For Google QUIC, version flag in packets from the server means version
126   // negotiation packet. For IETF QUIC, version flag means long header.
127   bool version_flag;
128   // Indicates whether |possible_stateless_reset_token| contains a valid value
129   // parsed from the packet buffer. IETF QUIC only, always false for GQUIC.
130   bool has_possible_stateless_reset_token;
131   QuicPacketNumberLength packet_number_length;
132   uint8_t type_byte;
133   ParsedQuicVersion version;
134   // nonce contains an optional, 32-byte nonce value. If not included in the
135   // packet, |nonce| will be empty.
136   DiversificationNonce* nonce;
137   QuicPacketNumber packet_number;
138   // Format of this header.
139   PacketHeaderFormat form;
140   // Short packet type is reflected in packet_number_length.
141   QuicLongHeaderType long_packet_type;
142   // Only valid if |has_possible_stateless_reset_token| is true.
143   // Stores last 16 bytes of a this packet, used to check whether this packet is
144   // a stateless reset packet on decryption failure.
145   StatelessResetToken possible_stateless_reset_token;
146   // Length of the retry token length variable length integer field,
147   // carried only by v99 IETF Initial packets.
148   quiche::QuicheVariableLengthIntegerLength retry_token_length_length;
149   // Retry token, carried only by v99 IETF Initial packets.
150   absl::string_view retry_token;
151   // Length of the length variable length integer field,
152   // carried only by v99 IETF Initial, 0-RTT and Handshake packets.
153   quiche::QuicheVariableLengthIntegerLength length_length;
154   // Length of the packet number and payload, carried only by v99 IETF Initial,
155   // 0-RTT and Handshake packets. Also includes the length of the
156   // diversification nonce in server to client 0-RTT packets.
157   QuicByteCount remaining_packet_length;
158 
159   bool operator==(const QuicPacketHeader& other) const;
160   bool operator!=(const QuicPacketHeader& other) const;
161 };
162 
163 struct QUICHE_EXPORT QuicPublicResetPacket {
164   QuicPublicResetPacket();
165   explicit QuicPublicResetPacket(QuicConnectionId connection_id);
166 
167   QuicConnectionId connection_id;
168   QuicPublicResetNonceProof nonce_proof;
169   QuicSocketAddress client_address;
170   // An arbitrary string to identify an endpoint. Used by clients to
171   // differentiate traffic from Google servers vs Non-google servers.
172   // Will not be used if empty().
173   std::string endpoint_id;
174 };
175 
176 struct QUICHE_EXPORT QuicVersionNegotiationPacket {
177   QuicVersionNegotiationPacket();
178   explicit QuicVersionNegotiationPacket(QuicConnectionId connection_id);
179   QuicVersionNegotiationPacket(const QuicVersionNegotiationPacket& other);
180   ~QuicVersionNegotiationPacket();
181 
182   QuicConnectionId connection_id;
183   ParsedQuicVersionVector versions;
184 };
185 
186 struct QUICHE_EXPORT QuicIetfStatelessResetPacket {
187   QuicIetfStatelessResetPacket();
188   QuicIetfStatelessResetPacket(const QuicPacketHeader& header,
189                                StatelessResetToken token);
190   QuicIetfStatelessResetPacket(const QuicIetfStatelessResetPacket& other);
191   ~QuicIetfStatelessResetPacket();
192 
193   QuicPacketHeader header;
194   StatelessResetToken stateless_reset_token;
195 };
196 
197 class QUICHE_EXPORT QuicData {
198  public:
199   // Creates a QuicData from a buffer and length. Does not own the buffer.
200   QuicData(const char* buffer, size_t length);
201   // Creates a QuicData from a buffer and length,
202   // optionally taking ownership of the buffer.
203   QuicData(const char* buffer, size_t length, bool owns_buffer);
204   // Creates a QuicData from a absl::string_view. Does not own the
205   // buffer.
206   QuicData(absl::string_view data);
207   QuicData(const QuicData&) = delete;
208   QuicData& operator=(const QuicData&) = delete;
209   virtual ~QuicData();
210 
AsStringPiece()211   absl::string_view AsStringPiece() const {
212     return absl::string_view(data(), length());
213   }
214 
data()215   const char* data() const { return buffer_; }
length()216   size_t length() const { return length_; }
217 
218  private:
219   const char* buffer_;
220   size_t length_;
221   bool owns_buffer_;
222 };
223 
224 class QUICHE_EXPORT QuicPacket : public QuicData {
225  public:
226   QuicPacket(
227       char* buffer, size_t length, bool owns_buffer,
228       uint8_t destination_connection_id_length,
229       uint8_t source_connection_id_length, bool includes_version,
230       bool includes_diversification_nonce,
231       QuicPacketNumberLength packet_number_length,
232       quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
233       QuicByteCount retry_token_length,
234       quiche::QuicheVariableLengthIntegerLength length_length);
235   QuicPacket(QuicTransportVersion version, char* buffer, size_t length,
236              bool owns_buffer, const QuicPacketHeader& header);
237   QuicPacket(const QuicPacket&) = delete;
238   QuicPacket& operator=(const QuicPacket&) = delete;
239 
240   absl::string_view AssociatedData(QuicTransportVersion version) const;
241   absl::string_view Plaintext(QuicTransportVersion version) const;
242 
mutable_data()243   char* mutable_data() { return buffer_; }
244 
245  private:
246   char* buffer_;
247   const uint8_t destination_connection_id_length_;
248   const uint8_t source_connection_id_length_;
249   const bool includes_version_;
250   const bool includes_diversification_nonce_;
251   const QuicPacketNumberLength packet_number_length_;
252   const quiche::QuicheVariableLengthIntegerLength retry_token_length_length_;
253   const QuicByteCount retry_token_length_;
254   const quiche::QuicheVariableLengthIntegerLength length_length_;
255 };
256 
257 class QUICHE_EXPORT QuicEncryptedPacket : public QuicData {
258  public:
259   // Creates a QuicEncryptedPacket from a buffer and length.
260   // Does not own the buffer.
261   QuicEncryptedPacket(const char* buffer, size_t length);
262   // Creates a QuicEncryptedPacket from a buffer and length,
263   // optionally taking ownership of the buffer.
264   QuicEncryptedPacket(const char* buffer, size_t length, bool owns_buffer);
265   // Creates a QuicEncryptedPacket from a absl::string_view.
266   // Does not own the buffer.
267   QuicEncryptedPacket(absl::string_view data);
268 
269   QuicEncryptedPacket(const QuicEncryptedPacket&) = delete;
270   QuicEncryptedPacket& operator=(const QuicEncryptedPacket&) = delete;
271 
272   // Clones the packet into a new packet which owns the buffer.
273   std::unique_ptr<QuicEncryptedPacket> Clone() const;
274 
275   // By default, gtest prints the raw bytes of an object. The bool data
276   // member (in the base class QuicData) causes this object to have padding
277   // bytes, which causes the default gtest object printer to read
278   // uninitialize memory. So we need to teach gtest how to print this object.
279   QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os,
280                                                 const QuicEncryptedPacket& s);
281 };
282 
283 namespace test {
284 class QuicReceivedPacketPeer;
285 }  // namespace test
286 
287 // A received encrypted QUIC packet, with a recorded time of receipt.
288 class QUICHE_EXPORT QuicReceivedPacket : public QuicEncryptedPacket {
289  public:
290   QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time);
291   QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time,
292                      bool owns_buffer);
293   QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time,
294                      bool owns_buffer, int ttl, bool ttl_valid);
295   QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time,
296                      bool owns_buffer, int ttl, bool ttl_valid,
297                      char* packet_headers, size_t headers_length,
298                      bool owns_header_buffer);
299   QuicReceivedPacket(const char* buffer, size_t length, QuicTime receipt_time,
300                      bool owns_buffer, int ttl, bool ttl_valid,
301                      char* packet_headers, size_t headers_length,
302                      bool owns_header_buffer, QuicEcnCodepoint ecn_codepoint);
303   ~QuicReceivedPacket();
304   QuicReceivedPacket(const QuicReceivedPacket&) = delete;
305   QuicReceivedPacket& operator=(const QuicReceivedPacket&) = delete;
306 
307   // Clones the packet into a new packet which owns the buffer.
308   std::unique_ptr<QuicReceivedPacket> Clone() const;
309 
310   // Returns the time at which the packet was received.
receipt_time()311   QuicTime receipt_time() const { return receipt_time_; }
312 
313   // This is the TTL of the packet, assuming ttl_vaild_ is true.
ttl()314   int ttl() const { return ttl_; }
315 
316   // Start of packet headers.
packet_headers()317   char* packet_headers() const { return packet_headers_; }
318 
319   // Length of packet headers.
headers_length()320   int headers_length() const { return headers_length_; }
321 
322   // By default, gtest prints the raw bytes of an object. The bool data
323   // member (in the base class QuicData) causes this object to have padding
324   // bytes, which causes the default gtest object printer to read
325   // uninitialize memory. So we need to teach gtest how to print this object.
326   QUICHE_EXPORT friend std::ostream& operator<<(std::ostream& os,
327                                                 const QuicReceivedPacket& s);
328 
ecn_codepoint()329   QuicEcnCodepoint ecn_codepoint() const { return ecn_codepoint_; }
330 
331  private:
332   friend class test::QuicReceivedPacketPeer;
333 
334   const QuicTime receipt_time_;
335   int ttl_;
336   // Points to the start of packet headers.
337   char* packet_headers_;
338   // Length of packet headers.
339   int headers_length_;
340   // Whether owns the buffer for packet headers.
341   bool owns_header_buffer_;
342   QuicEcnCodepoint ecn_codepoint_;
343 };
344 
345 // SerializedPacket contains information of a serialized(encrypted) packet.
346 //
347 // WARNING:
348 //
349 //   If you add a member field to this class, please make sure it is properly
350 //   copied in |CopySerializedPacket|.
351 //
352 struct QUICHE_EXPORT SerializedPacket {
353   SerializedPacket(QuicPacketNumber packet_number,
354                    QuicPacketNumberLength packet_number_length,
355                    const char* encrypted_buffer,
356                    QuicPacketLength encrypted_length, bool has_ack,
357                    bool has_stop_waiting);
358 
359   // Copy constructor & assignment are deleted. Use |CopySerializedPacket| to
360   // make a copy.
361   SerializedPacket(const SerializedPacket& other) = delete;
362   SerializedPacket& operator=(const SerializedPacket& other) = delete;
363   SerializedPacket(SerializedPacket&& other);
364   ~SerializedPacket();
365 
366   // TODO(wub): replace |encrypted_buffer|+|release_encrypted_buffer| by a
367   // QuicOwnedPacketBuffer.
368   // Not owned if |release_encrypted_buffer| is nullptr. Otherwise it is
369   // released by |release_encrypted_buffer| on destruction.
370   const char* encrypted_buffer;
371   QuicPacketLength encrypted_length;
372   std::function<void(const char*)> release_encrypted_buffer;
373 
374   QuicFrames retransmittable_frames;
375   QuicFrames nonretransmittable_frames;
376   IsHandshake has_crypto_handshake;
377   QuicPacketNumber packet_number;
378   QuicPacketNumberLength packet_number_length;
379   EncryptionLevel encryption_level;
380   // TODO(fayang): Remove has_ack and has_stop_waiting.
381   bool has_ack;
382   bool has_stop_waiting;
383   bool has_ack_ecn = false;  // ack frame contains ECN counts.
384   TransmissionType transmission_type;
385   // The largest acked of the AckFrame in this packet if has_ack is true,
386   // 0 otherwise.
387   QuicPacketNumber largest_acked;
388   // Indicates whether this packet has a copy of ack frame in
389   // nonretransmittable_frames.
390   bool has_ack_frame_copy;
391   bool has_ack_frequency;
392   bool has_message;
393   SerializedPacketFate fate;
394   QuicSocketAddress peer_address;
395   // Sum of bytes from frames that are not retransmissions. This field is only
396   // populated for packets with "mixed frames": at least one frame of a
397   // retransmission type and at least one frame of NOT_RETRANSMISSION type.
398   std::optional<QuicByteCount> bytes_not_retransmitted;
399   // Only populated if encryption_level is ENCRYPTION_INITIAL.
400   // TODO(b/265777524): remove this.
401   std::optional<QuicPacketHeader> initial_header;
402 };
403 
404 // Make a copy of |serialized| (including the underlying frames). |copy_buffer|
405 // indicates whether the encrypted buffer should be copied.
406 QUICHE_EXPORT SerializedPacket* CopySerializedPacket(
407     const SerializedPacket& serialized,
408     quiche::QuicheBufferAllocator* allocator, bool copy_buffer);
409 
410 // Allocates a new char[] of size |packet.encrypted_length| and copies in
411 // |packet.encrypted_buffer|.
412 QUICHE_EXPORT char* CopyBuffer(const SerializedPacket& packet);
413 // Allocates a new char[] of size |encrypted_length| and copies in
414 // |encrypted_buffer|.
415 QUICHE_EXPORT char* CopyBuffer(const char* encrypted_buffer,
416                                QuicPacketLength encrypted_length);
417 
418 // Context for an incoming packet.
419 struct QUICHE_EXPORT QuicPerPacketContext {
~QuicPerPacketContextQuicPerPacketContext420   virtual ~QuicPerPacketContext() {}
421 };
422 
423 // ReceivedPacketInfo comprises information obtained by parsing the unencrypted
424 // bytes of a received packet.
425 struct QUICHE_EXPORT ReceivedPacketInfo {
426   ReceivedPacketInfo(const QuicSocketAddress& self_address,
427                      const QuicSocketAddress& peer_address,
428                      const QuicReceivedPacket& packet);
429   ReceivedPacketInfo(const ReceivedPacketInfo& other) = default;
430 
431   ~ReceivedPacketInfo();
432 
433   std::string ToString() const;
434 
435   QUICHE_EXPORT friend std::ostream& operator<<(
436       std::ostream& os, const ReceivedPacketInfo& packet_info);
437 
438   const QuicSocketAddress& self_address;
439   const QuicSocketAddress& peer_address;
440   const QuicReceivedPacket& packet;
441 
442   PacketHeaderFormat form;
443   // This is only used if the form is IETF_QUIC_LONG_HEADER_PACKET.
444   QuicLongHeaderType long_packet_type;
445   bool version_flag;
446   bool use_length_prefix;
447   QuicVersionLabel version_label;
448   ParsedQuicVersion version;
449   QuicConnectionId destination_connection_id;
450   QuicConnectionId source_connection_id;
451   std::optional<absl::string_view> retry_token;
452 };
453 
454 }  // namespace quic
455 
456 #endif  // QUICHE_QUIC_CORE_QUIC_PACKETS_H_
457