xref: /aosp_15_r20/external/cronet/net/third_party/quiche/src/quiche/quic/core/quic_framer.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_FRAMER_H_
6 #define QUICHE_QUIC_CORE_QUIC_FRAMER_H_
7 
8 #include <cstddef>
9 #include <cstdint>
10 #include <memory>
11 #include <string>
12 
13 #include "absl/strings/string_view.h"
14 #include "quiche/quic/core/connection_id_generator.h"
15 #include "quiche/quic/core/crypto/quic_decrypter.h"
16 #include "quiche/quic/core/crypto/quic_encrypter.h"
17 #include "quiche/quic/core/crypto/quic_random.h"
18 #include "quiche/quic/core/frames/quic_reset_stream_at_frame.h"
19 #include "quiche/quic/core/quic_connection_id.h"
20 #include "quiche/quic/core/quic_packets.h"
21 #include "quiche/quic/core/quic_types.h"
22 #include "quiche/quic/platform/api/quic_export.h"
23 
24 namespace quic {
25 
26 namespace test {
27 class QuicFramerPeer;
28 }  // namespace test
29 
30 class QuicDataReader;
31 class QuicDataWriter;
32 class QuicFramer;
33 class QuicStreamFrameDataProducer;
34 
35 // Number of bytes reserved for the frame type preceding each frame.
36 inline constexpr size_t kQuicFrameTypeSize = 1;
37 // Number of bytes reserved for error code.
38 inline constexpr size_t kQuicErrorCodeSize = 4;
39 // Number of bytes reserved to denote the length of error details field.
40 inline constexpr size_t kQuicErrorDetailsLengthSize = 2;
41 
42 // Maximum number of bytes reserved for stream id.
43 inline constexpr size_t kQuicMaxStreamIdSize = 4;
44 // Maximum number of bytes reserved for byte offset in stream frame.
45 inline constexpr size_t kQuicMaxStreamOffsetSize = 8;
46 // Number of bytes reserved to store payload length in stream frame.
47 inline constexpr size_t kQuicStreamPayloadLengthSize = 2;
48 // Number of bytes to reserve for IQ Error codes (for the Connection Close,
49 // Application Close, and Reset Stream frames).
50 inline constexpr size_t kQuicIetfQuicErrorCodeSize = 2;
51 // Minimum size of the IETF QUIC Error Phrase's length field
52 inline constexpr size_t kIetfQuicMinErrorPhraseLengthSize = 1;
53 
54 // Size in bytes reserved for the delta time of the largest observed
55 // packet number in ack frames.
56 inline constexpr size_t kQuicDeltaTimeLargestObservedSize = 2;
57 // Size in bytes reserved for the number of received packets with timestamps.
58 inline constexpr size_t kQuicNumTimestampsSize = 1;
59 // Size in bytes reserved for the number of missing packets in ack frames.
60 inline constexpr size_t kNumberOfNackRangesSize = 1;
61 // Size in bytes reserved for the number of ack blocks in ack frames.
62 inline constexpr size_t kNumberOfAckBlocksSize = 1;
63 // Maximum number of missing packet ranges that can fit within an ack frame.
64 inline constexpr size_t kMaxNackRanges =
65     (1 << (kNumberOfNackRangesSize * 8)) - 1;
66 // Maximum number of ack blocks that can fit within an ack frame.
67 inline constexpr size_t kMaxAckBlocks = (1 << (kNumberOfAckBlocksSize * 8)) - 1;
68 
69 // This class receives callbacks from the framer when packets
70 // are processed.
71 class QUICHE_EXPORT QuicFramerVisitorInterface {
72  public:
~QuicFramerVisitorInterface()73   virtual ~QuicFramerVisitorInterface() {}
74 
75   // Called if an error is detected in the QUIC protocol.
76   virtual void OnError(QuicFramer* framer) = 0;
77 
78   // Called only when |perspective_| is IS_SERVER and the framer gets a
79   // packet with version flag true and the version on the packet doesn't match
80   // |quic_version_|. The visitor should return true after it updates the
81   // version of the |framer_| to |received_version| or false to stop processing
82   // this packet.
83   virtual bool OnProtocolVersionMismatch(
84       ParsedQuicVersion received_version) = 0;
85 
86   // Called when a new packet has been received, before it
87   // has been validated or processed.
88   virtual void OnPacket() = 0;
89 
90   // Called only when |perspective_| is IS_CLIENT and a version negotiation
91   // packet has been parsed.
92   virtual void OnVersionNegotiationPacket(
93       const QuicVersionNegotiationPacket& packet) = 0;
94 
95   // Called only when |perspective_| is IS_CLIENT and a retry packet has been
96   // parsed. |new_connection_id| contains the value of the Source Connection
97   // ID field, and |retry_token| contains the value of the Retry Token field.
98   // On versions where UsesTls() is false,
99   // |original_connection_id| contains the value of the Original Destination
100   // Connection ID field, and both |retry_integrity_tag| and
101   // |retry_without_tag| are empty.
102   // On versions where UsesTls() is true,
103   // |original_connection_id| is empty, |retry_integrity_tag| contains the
104   // value of the Retry Integrity Tag field, and |retry_without_tag| contains
105   // the entire RETRY packet except the Retry Integrity Tag field.
106   virtual void OnRetryPacket(QuicConnectionId original_connection_id,
107                              QuicConnectionId new_connection_id,
108                              absl::string_view retry_token,
109                              absl::string_view retry_integrity_tag,
110                              absl::string_view retry_without_tag) = 0;
111 
112   // Called when all fields except packet number has been parsed, but has not
113   // been authenticated. If it returns false, framing for this packet will
114   // cease.
115   virtual bool OnUnauthenticatedPublicHeader(
116       const QuicPacketHeader& header) = 0;
117 
118   // Called when the unauthenticated portion of the header has been parsed.
119   // If OnUnauthenticatedHeader returns false, framing for this packet will
120   // cease.
121   virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) = 0;
122 
123   // Called when a packet has been decrypted. |length| is the packet length,
124   // and |level| is the encryption level of the packet.
125   virtual void OnDecryptedPacket(size_t length, EncryptionLevel level) = 0;
126 
127   // Called when the complete header of a packet had been parsed.
128   // If OnPacketHeader returns false, framing for this packet will cease.
129   virtual bool OnPacketHeader(const QuicPacketHeader& header) = 0;
130 
131   // Called when the packet being processed contains multiple IETF QUIC packets,
132   // which is due to there being more data after what is covered by the length
133   // field. |packet| contains the remaining data which can be processed.
134   // Note that this is called when the framer parses the length field, before
135   // it attempts to decrypt the first payload. It is the visitor's
136   // responsibility to buffer the packet and call ProcessPacket on it
137   // after the framer is done parsing the current payload. |packet| does not
138   // own its internal buffer, the visitor should make a copy of it.
139   virtual void OnCoalescedPacket(const QuicEncryptedPacket& packet) = 0;
140 
141   // Called when the packet being processed failed to decrypt.
142   // |has_decryption_key| indicates whether the framer knew which decryption
143   // key to use for this packet and already had a suitable key.
144   virtual void OnUndecryptablePacket(const QuicEncryptedPacket& packet,
145                                      EncryptionLevel decryption_level,
146                                      bool has_decryption_key) = 0;
147 
148   // Called when a StreamFrame has been parsed.
149   virtual bool OnStreamFrame(const QuicStreamFrame& frame) = 0;
150 
151   // Called when a CRYPTO frame has been parsed.
152   virtual bool OnCryptoFrame(const QuicCryptoFrame& frame) = 0;
153 
154   // Called when largest acked of an AckFrame has been parsed.
155   virtual bool OnAckFrameStart(QuicPacketNumber largest_acked,
156                                QuicTime::Delta ack_delay_time) = 0;
157 
158   // Called when ack range [start, end) of an AckFrame has been parsed.
159   virtual bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) = 0;
160 
161   // Called when a timestamp in the AckFrame has been parsed.
162   virtual bool OnAckTimestamp(QuicPacketNumber packet_number,
163                               QuicTime timestamp) = 0;
164 
165   // Called after the last ack range in an AckFrame has been parsed.
166   // |start| is the starting value of the last ack range. |ecn_counts| are
167   // the reported ECN counts in the ack frame, if present.
168   virtual bool OnAckFrameEnd(
169       QuicPacketNumber start,
170       const std::optional<QuicEcnCounts>& ecn_counts) = 0;
171 
172   // Called when a StopWaitingFrame has been parsed.
173   virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) = 0;
174 
175   // Called when a QuicPaddingFrame has been parsed.
176   virtual bool OnPaddingFrame(const QuicPaddingFrame& frame) = 0;
177 
178   // Called when a PingFrame has been parsed.
179   virtual bool OnPingFrame(const QuicPingFrame& frame) = 0;
180 
181   // Called when a RstStreamFrame has been parsed.
182   virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0;
183 
184   // Called when a ConnectionCloseFrame, of any type, has been parsed.
185   virtual bool OnConnectionCloseFrame(
186       const QuicConnectionCloseFrame& frame) = 0;
187 
188   // Called when a StopSendingFrame has been parsed.
189   virtual bool OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0;
190 
191   // Called when a PathChallengeFrame has been parsed.
192   virtual bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) = 0;
193 
194   // Called when a PathResponseFrame has been parsed.
195   virtual bool OnPathResponseFrame(const QuicPathResponseFrame& frame) = 0;
196 
197   // Called when a GoAwayFrame has been parsed.
198   virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) = 0;
199 
200   // Called when a WindowUpdateFrame has been parsed.
201   virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0;
202 
203   // Called when a BlockedFrame has been parsed.
204   virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) = 0;
205 
206   // Called when a NewConnectionIdFrame has been parsed.
207   virtual bool OnNewConnectionIdFrame(
208       const QuicNewConnectionIdFrame& frame) = 0;
209 
210   // Called when a RetireConnectionIdFrame has been parsed.
211   virtual bool OnRetireConnectionIdFrame(
212       const QuicRetireConnectionIdFrame& frame) = 0;
213 
214   // Called when a NewTokenFrame has been parsed.
215   virtual bool OnNewTokenFrame(const QuicNewTokenFrame& frame) = 0;
216 
217   // Called when a message frame has been parsed.
218   virtual bool OnMessageFrame(const QuicMessageFrame& frame) = 0;
219 
220   // Called when a handshake done frame has been parsed.
221   virtual bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) = 0;
222 
223   // Called when an AckFrequencyFrame has been parsed.
224   virtual bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) = 0;
225 
226   // Called when an ResetStreamAtFrame has been parsed.
227   virtual bool OnResetStreamAtFrame(const QuicResetStreamAtFrame& frame) = 0;
228 
229   // Called when a packet has been completely processed.
230   virtual void OnPacketComplete() = 0;
231 
232   // Called to check whether |token| is a valid stateless reset token.
233   virtual bool IsValidStatelessResetToken(
234       const StatelessResetToken& token) const = 0;
235 
236   // Called when an IETF stateless reset packet has been parsed and validated
237   // with the stateless reset token.
238   virtual void OnAuthenticatedIetfStatelessResetPacket(
239       const QuicIetfStatelessResetPacket& packet) = 0;
240 
241   // Called when an IETF MaxStreams frame has been parsed.
242   virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0;
243 
244   // Called when an IETF StreamsBlocked frame has been parsed.
245   virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0;
246 
247   // Called when a Key Phase Update has been initiated. This is called for both
248   // locally and peer initiated key updates. If the key update was locally
249   // initiated, this does not indicate the peer has received the key update yet.
250   virtual void OnKeyUpdate(KeyUpdateReason reason) = 0;
251 
252   // Called on the first decrypted packet in each key phase (including the
253   // first key phase.)
254   virtual void OnDecryptedFirstPacketInKeyPhase() = 0;
255 
256   // Called when the framer needs to generate a decrypter for the next key
257   // phase. Each call should generate the key for phase n+1.
258   virtual std::unique_ptr<QuicDecrypter>
259   AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0;
260 
261   // Called when the framer needs to generate an encrypter. The key corresponds
262   // to the key phase of the last decrypter returned by
263   // AdvanceKeysAndCreateCurrentOneRttDecrypter().
264   virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0;
265 };
266 
267 // Class for parsing and constructing QUIC packets.  It has a
268 // QuicFramerVisitorInterface that is called when packets are parsed.
269 class QUICHE_EXPORT QuicFramer {
270  public:
271   // Constructs a new framer that installs a kNULL QuicEncrypter and
272   // QuicDecrypter for level ENCRYPTION_INITIAL. |supported_versions| specifies
273   // the list of supported QUIC versions. |quic_version_| is set to the maximum
274   // version in |supported_versions|.
275   QuicFramer(const ParsedQuicVersionVector& supported_versions,
276              QuicTime creation_time, Perspective perspective,
277              uint8_t expected_server_connection_id_length);
278   QuicFramer(const QuicFramer&) = delete;
279   QuicFramer& operator=(const QuicFramer&) = delete;
280 
281   virtual ~QuicFramer();
282 
283   // Returns true if |version| is a supported protocol version.
284   bool IsSupportedVersion(const ParsedQuicVersion version) const;
285 
286   // Set callbacks to be called from the framer.  A visitor must be set, or
287   // else the framer will likely crash.  It is acceptable for the visitor
288   // to do nothing.  If this is called multiple times, only the last visitor
289   // will be used.
set_visitor(QuicFramerVisitorInterface * visitor)290   void set_visitor(QuicFramerVisitorInterface* visitor) { visitor_ = visitor; }
291 
supported_versions()292   const ParsedQuicVersionVector& supported_versions() const {
293     return supported_versions_;
294   }
295 
transport_version()296   QuicTransportVersion transport_version() const {
297     return version_.transport_version;
298   }
299 
version()300   ParsedQuicVersion version() const { return version_; }
301 
302   void set_version(const ParsedQuicVersion version);
303 
304   // Does not QUICHE_DCHECK for supported version. Used by tests to set
305   // unsupported version to trigger version negotiation.
set_version_for_tests(const ParsedQuicVersion version)306   void set_version_for_tests(const ParsedQuicVersion version) {
307     version_ = version;
308   }
309 
error()310   QuicErrorCode error() const { return error_; }
311 
312   // Allows enabling or disabling of timestamp processing and serialization.
313   // TODO(ianswett): Remove the const once timestamps are negotiated via
314   // transport params.
set_process_timestamps(bool process_timestamps)315   void set_process_timestamps(bool process_timestamps) const {
316     process_timestamps_ = process_timestamps;
317   }
318 
319   // Sets the max number of receive timestamps to send per ACK frame.
320   // TODO(wub): Remove the const once timestamps are negotiated via
321   // transport params.
set_max_receive_timestamps_per_ack(uint32_t max_timestamps)322   void set_max_receive_timestamps_per_ack(uint32_t max_timestamps) const {
323     max_receive_timestamps_per_ack_ = max_timestamps;
324   }
325 
326   // Sets the exponent to use when writing/reading ACK receive timestamps.
set_receive_timestamps_exponent(uint32_t exponent)327   void set_receive_timestamps_exponent(uint32_t exponent) const {
328     receive_timestamps_exponent_ = exponent;
329   }
330 
331   // Allows enabling RESET_STREAM_AT frame processing.
set_process_reset_stream_at(bool process_reset_stream_at)332   void set_process_reset_stream_at(bool process_reset_stream_at) {
333     process_reset_stream_at_ = process_reset_stream_at;
334   }
335 
336   // Pass a UDP packet into the framer for parsing.
337   // Return true if the packet was processed successfully. |packet| must be a
338   // single, complete UDP packet (not a frame of a packet).  This packet
339   // might be null padded past the end of the payload, which will be correctly
340   // ignored.
341   bool ProcessPacket(const QuicEncryptedPacket& packet);
342 
343   // Whether we are in the middle of a call to this->ProcessPacket.
is_processing_packet()344   bool is_processing_packet() const { return is_processing_packet_; }
345 
346   // Largest size in bytes of all stream frame fields without the payload.
347   static size_t GetMinStreamFrameSize(QuicTransportVersion version,
348                                       QuicStreamId stream_id,
349                                       QuicStreamOffset offset,
350                                       bool last_frame_in_packet,
351                                       size_t data_length);
352   // Returns the overhead of framing a CRYPTO frame with the specific offset and
353   // data length provided, but not counting the size of the data payload.
354   static size_t GetMinCryptoFrameSize(QuicStreamOffset offset,
355                                       QuicPacketLength data_length);
356   static size_t GetMessageFrameSize(bool last_frame_in_packet,
357                                     QuicByteCount length);
358   // Size in bytes of all ack frame fields without the missing packets or ack
359   // blocks.
360   static size_t GetMinAckFrameSize(QuicTransportVersion version,
361                                    const QuicAckFrame& ack_frame,
362                                    uint32_t local_ack_delay_exponent,
363                                    bool use_ietf_ack_with_receive_timestamp);
364   // Size in bytes of a stop waiting frame.
365   static size_t GetStopWaitingFrameSize(
366       QuicPacketNumberLength packet_number_length);
367   // Size in bytes of all reset stream frame fields.
368   static size_t GetRstStreamFrameSize(QuicTransportVersion version,
369                                       const QuicRstStreamFrame& frame);
370   // Size in bytes of all ack frenquency frame fields.
371   static size_t GetAckFrequencyFrameSize(const QuicAckFrequencyFrame& frame);
372   // Size in bytes of all RESET_STREAM_AT frame fields.
373   static size_t GetResetStreamAtFrameSize(const QuicResetStreamAtFrame& frame);
374   // Size in bytes of all connection close frame fields, including the error
375   // details.
376   static size_t GetConnectionCloseFrameSize(
377       QuicTransportVersion version, const QuicConnectionCloseFrame& frame);
378   // Size in bytes of all GoAway frame fields without the reason phrase.
379   static size_t GetMinGoAwayFrameSize();
380   // Size in bytes of all WindowUpdate frame fields.
381   // For version 99, determines whether a MAX DATA or MAX STREAM DATA frame will
382   // be generated and calculates the appropriate size.
383   static size_t GetWindowUpdateFrameSize(QuicTransportVersion version,
384                                          const QuicWindowUpdateFrame& frame);
385   // Size in bytes of all MaxStreams frame fields.
386   static size_t GetMaxStreamsFrameSize(QuicTransportVersion version,
387                                        const QuicMaxStreamsFrame& frame);
388   // Size in bytes of all StreamsBlocked frame fields.
389   static size_t GetStreamsBlockedFrameSize(
390       QuicTransportVersion version, const QuicStreamsBlockedFrame& frame);
391   // Size in bytes of all Blocked frame fields.
392   static size_t GetBlockedFrameSize(QuicTransportVersion version,
393                                     const QuicBlockedFrame& frame);
394   // Size in bytes of PathChallenge frame.
395   static size_t GetPathChallengeFrameSize(const QuicPathChallengeFrame& frame);
396   // Size in bytes of PathResponse frame.
397   static size_t GetPathResponseFrameSize(const QuicPathResponseFrame& frame);
398   // Size in bytes required to serialize the stream id.
399   static size_t GetStreamIdSize(QuicStreamId stream_id);
400   // Size in bytes required to serialize the stream offset.
401   static size_t GetStreamOffsetSize(QuicStreamOffset offset);
402   // Size in bytes for a serialized new connection id frame
403   static size_t GetNewConnectionIdFrameSize(
404       const QuicNewConnectionIdFrame& frame);
405 
406   // Size in bytes for a serialized retire connection id frame
407   static size_t GetRetireConnectionIdFrameSize(
408       const QuicRetireConnectionIdFrame& frame);
409 
410   // Size in bytes for a serialized new token frame
411   static size_t GetNewTokenFrameSize(const QuicNewTokenFrame& frame);
412 
413   // Size in bytes required for a serialized stop sending frame.
414   static size_t GetStopSendingFrameSize(const QuicStopSendingFrame& frame);
415 
416   // Size in bytes required for a serialized retransmittable control |frame|.
417   static size_t GetRetransmittableControlFrameSize(QuicTransportVersion version,
418                                                    const QuicFrame& frame);
419 
420   // Returns the number of bytes added to the packet for the specified frame,
421   // and 0 if the frame doesn't fit.  Includes the header size for the first
422   // frame.
423   size_t GetSerializedFrameLength(const QuicFrame& frame, size_t free_bytes,
424                                   bool first_frame_in_packet,
425                                   bool last_frame_in_packet,
426                                   QuicPacketNumberLength packet_number_length);
427 
428   // Returns the associated data from the encrypted packet |encrypted| as a
429   // stringpiece.
430   static absl::string_view GetAssociatedDataFromEncryptedPacket(
431       QuicTransportVersion version, const QuicEncryptedPacket& encrypted,
432       uint8_t destination_connection_id_length,
433       uint8_t source_connection_id_length, bool includes_version,
434       bool includes_diversification_nonce,
435       QuicPacketNumberLength packet_number_length,
436       quiche::QuicheVariableLengthIntegerLength retry_token_length_length,
437       uint64_t retry_token_length,
438       quiche::QuicheVariableLengthIntegerLength length_length);
439 
440   // Parses the unencrypted fields in a QUIC header using |reader| as input,
441   // stores the result in the other parameters.
442   // |expected_destination_connection_id_length| is only used for short headers.
443   // When server connection IDs are generated by a
444   // ConnectionIdGeneartor interface, and callers need an accurate
445   // Destination Connection ID for short header packets, call
446   // ParsePublicHeaderDispatcherShortHeaderLengthUnknown() instead.
447   static QuicErrorCode ParsePublicHeader(
448       QuicDataReader* reader, uint8_t expected_destination_connection_id_length,
449       bool ietf_format, uint8_t* first_byte, PacketHeaderFormat* format,
450       bool* version_present, bool* has_length_prefix,
451       QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version,
452       QuicConnectionId* destination_connection_id,
453       QuicConnectionId* source_connection_id,
454       QuicLongHeaderType* long_packet_type,
455       quiche::QuicheVariableLengthIntegerLength* retry_token_length_length,
456       absl::string_view* retry_token, std::string* detailed_error);
457 
458   // Parses the unencrypted fields in |packet| and stores them in the other
459   // parameters. This can only be called on the server.
460   // |expected_destination_connection_id_length| is only used
461   // for short headers. When callers need an accurate Destination Connection ID
462   // specifically for short header packets, call
463   // ParsePublicHeaderDispatcherShortHeaderLengthUnknown() instead.
464   static QuicErrorCode ParsePublicHeaderDispatcher(
465       const QuicEncryptedPacket& packet,
466       uint8_t expected_destination_connection_id_length,
467       PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type,
468       bool* version_present, bool* has_length_prefix,
469       QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version,
470       QuicConnectionId* destination_connection_id,
471       QuicConnectionId* source_connection_id,
472       std::optional<absl::string_view>* retry_token,
473       std::string* detailed_error);
474 
475   // Parses the unencrypted fields in |packet| and stores them in the other
476   // parameters. The only callers that should use this method are ones where
477   // (1) the short-header connection ID length is only known by looking at the
478   // connection ID itself (and |generator| can provide the answer), and (2)
479   // the caller is interested in the parsed contents even if the packet has a
480   // short header. Some callers are only interested in parsing long header
481   // packets to peer into the handshake, and should use
482   // ParsePublicHeaderDispatcher instead.
483   static QuicErrorCode ParsePublicHeaderDispatcherShortHeaderLengthUnknown(
484       const QuicEncryptedPacket& packet, PacketHeaderFormat* format,
485       QuicLongHeaderType* long_packet_type, bool* version_present,
486       bool* has_length_prefix, QuicVersionLabel* version_label,
487       ParsedQuicVersion* parsed_version,
488       QuicConnectionId* destination_connection_id,
489       QuicConnectionId* source_connection_id,
490       std::optional<absl::string_view>* retry_token,
491       std::string* detailed_error, ConnectionIdGeneratorInterface& generator);
492 
493   // Serializes a packet containing |frames| into |buffer|.
494   // Returns the length of the packet, which must not be longer than
495   // |packet_length|.  Returns 0 if it fails to serialize.
496   size_t BuildDataPacket(const QuicPacketHeader& header,
497                          const QuicFrames& frames, char* buffer,
498                          size_t packet_length, EncryptionLevel level);
499 
500   // Returns a new public reset packet.
501   static std::unique_ptr<QuicEncryptedPacket> BuildPublicResetPacket(
502       const QuicPublicResetPacket& packet);
503 
504   // Returns the minimal stateless reset packet length.
505   static size_t GetMinStatelessResetPacketLength();
506 
507   // Returns a new IETF stateless reset packet.
508   static std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket(
509       QuicConnectionId connection_id, size_t received_packet_length,
510       StatelessResetToken stateless_reset_token);
511 
512   // Returns a new IETF stateless reset packet with random bytes generated from
513   // |random|->InsecureRandBytes(). NOTE: the first two bits of the random bytes
514   // will be modified to 01b to make it look like a short header packet.
515   static std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket(
516       QuicConnectionId connection_id, size_t received_packet_length,
517       StatelessResetToken stateless_reset_token, QuicRandom* random);
518 
519   // Returns a new version negotiation packet.
520   static std::unique_ptr<QuicEncryptedPacket> BuildVersionNegotiationPacket(
521       QuicConnectionId server_connection_id,
522       QuicConnectionId client_connection_id, bool ietf_quic,
523       bool use_length_prefix, const ParsedQuicVersionVector& versions);
524 
525   // Returns a new IETF version negotiation packet.
526   static std::unique_ptr<QuicEncryptedPacket> BuildIetfVersionNegotiationPacket(
527       bool use_length_prefix, QuicConnectionId server_connection_id,
528       QuicConnectionId client_connection_id,
529       const ParsedQuicVersionVector& versions);
530 
531   // If header.version_flag is set, the version in the
532   // packet will be set -- but it will be set from version_ not
533   // header.versions.
534   bool AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
535                                 QuicDataWriter* writer);
536   bool AppendIetfPacketHeader(const QuicPacketHeader& header,
537                               QuicDataWriter* writer,
538                               size_t* length_field_offset);
539   bool WriteIetfLongHeaderLength(const QuicPacketHeader& header,
540                                  QuicDataWriter* writer,
541                                  size_t length_field_offset,
542                                  EncryptionLevel level);
543   bool AppendTypeByte(const QuicFrame& frame, bool last_frame_in_packet,
544                       QuicDataWriter* writer);
545   bool AppendIetfFrameType(const QuicFrame& frame, bool last_frame_in_packet,
546                            QuicDataWriter* writer);
547   size_t AppendIetfFrames(const QuicFrames& frames, QuicDataWriter* writer);
548   bool AppendStreamFrame(const QuicStreamFrame& frame,
549                          bool no_stream_frame_length, QuicDataWriter* writer);
550   bool AppendCryptoFrame(const QuicCryptoFrame& frame, QuicDataWriter* writer);
551   bool AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame,
552                                QuicDataWriter* writer);
553   bool AppendResetFrameAtFrame(const QuicResetStreamAtFrame& frame,
554                                QuicDataWriter& writer);
555 
556   // SetDecrypter sets the primary decrypter, replacing any that already exists.
557   // If an alternative decrypter is in place then the function QUICHE_DCHECKs.
558   // This is intended for cases where one knows that future packets will be
559   // using the new decrypter and the previous decrypter is now obsolete. |level|
560   // indicates the encryption level of the new decrypter.
561   void SetDecrypter(EncryptionLevel level,
562                     std::unique_ptr<QuicDecrypter> decrypter);
563 
564   // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
565   // future packets. |level| indicates the encryption level of the decrypter. If
566   // |latch_once_used| is true, then the first time that the decrypter is
567   // successful it will replace the primary decrypter.  Otherwise both
568   // decrypters will remain active and the primary decrypter will be the one
569   // last used.
570   void SetAlternativeDecrypter(EncryptionLevel level,
571                                std::unique_ptr<QuicDecrypter> decrypter,
572                                bool latch_once_used);
573 
574   void InstallDecrypter(EncryptionLevel level,
575                         std::unique_ptr<QuicDecrypter> decrypter);
576   void RemoveDecrypter(EncryptionLevel level);
577 
578   // Enables key update support.
579   void SetKeyUpdateSupportForConnection(bool enabled);
580   // Discard the decrypter for the previous key phase.
581   void DiscardPreviousOneRttKeys();
582   // Update the key phase.
583   bool DoKeyUpdate(KeyUpdateReason reason);
584   // Returns the count of packets received that appeared to attempt a key
585   // update but failed decryption which have been received since the last
586   // successfully decrypted packet.
587   QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const;
588 
589   const QuicDecrypter* GetDecrypter(EncryptionLevel level) const;
590   const QuicDecrypter* decrypter() const;
591   const QuicDecrypter* alternative_decrypter() const;
592 
593   // Changes the encrypter used for level |level| to |encrypter|.
594   void SetEncrypter(EncryptionLevel level,
595                     std::unique_ptr<QuicEncrypter> encrypter);
596 
597   // Called to remove encrypter of encryption |level|.
598   void RemoveEncrypter(EncryptionLevel level);
599 
600   // Sets the encrypter and decrypter for the ENCRYPTION_INITIAL level.
601   void SetInitialObfuscators(QuicConnectionId connection_id);
602 
603   // Encrypts a payload in |buffer|.  |ad_len| is the length of the associated
604   // data. |total_len| is the length of the associated data plus plaintext.
605   // |buffer_len| is the full length of the allocated buffer.
606   size_t EncryptInPlace(EncryptionLevel level, QuicPacketNumber packet_number,
607                         size_t ad_len, size_t total_len, size_t buffer_len,
608                         char* buffer);
609 
610   // Returns the length of the data encrypted into |buffer| if |buffer_len| is
611   // long enough, and otherwise 0.
612   size_t EncryptPayload(EncryptionLevel level, QuicPacketNumber packet_number,
613                         const QuicPacket& packet, char* buffer,
614                         size_t buffer_len);
615 
616   // Returns the length of the ciphertext that would be generated by encrypting
617   // to plaintext of size |plaintext_size| at the given level.
618   size_t GetCiphertextSize(EncryptionLevel level, size_t plaintext_size) const;
619 
620   // Returns the maximum length of plaintext that can be encrypted
621   // to ciphertext no larger than |ciphertext_size|.
622   size_t GetMaxPlaintextSize(size_t ciphertext_size);
623 
624   // Returns the maximum number of packets that can be safely encrypted with
625   // the active AEAD. 1-RTT keys must be set before calling this method.
626   QuicPacketCount GetOneRttEncrypterConfidentialityLimit() const;
627 
detailed_error()628   const std::string& detailed_error() { return detailed_error_; }
629 
630   // The minimum packet number length required to represent |packet_number|.
631   static QuicPacketNumberLength GetMinPacketNumberLength(
632       QuicPacketNumber packet_number);
633 
SetSupportedVersions(const ParsedQuicVersionVector & versions)634   void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
635     supported_versions_ = versions;
636     version_ = versions[0];
637   }
638 
639   // Returns true if |header| is considered as an stateless reset packet.
640   bool IsIetfStatelessResetPacket(const QuicPacketHeader& header) const;
641 
642   // Returns true if encrypter of |level| is available.
643   bool HasEncrypterOfEncryptionLevel(EncryptionLevel level) const;
644   // Returns true if decrypter of |level| is available.
645   bool HasDecrypterOfEncryptionLevel(EncryptionLevel level) const;
646 
647   // Returns true if an encrypter of |space| is available.
648   bool HasAnEncrypterForSpace(PacketNumberSpace space) const;
649 
650   // Returns the encryption level to send application data. This should be only
651   // called with available encrypter for application data.
652   EncryptionLevel GetEncryptionLevelToSendApplicationData() const;
653 
set_validate_flags(bool value)654   void set_validate_flags(bool value) { validate_flags_ = value; }
655 
perspective()656   Perspective perspective() const { return perspective_; }
657 
data_producer()658   QuicStreamFrameDataProducer* data_producer() const { return data_producer_; }
659 
set_data_producer(QuicStreamFrameDataProducer * data_producer)660   void set_data_producer(QuicStreamFrameDataProducer* data_producer) {
661     data_producer_ = data_producer;
662   }
663 
creation_time()664   QuicTime creation_time() const { return creation_time_; }
665 
first_sending_packet_number()666   QuicPacketNumber first_sending_packet_number() const {
667     return first_sending_packet_number_;
668   }
669 
current_received_frame_type()670   uint64_t current_received_frame_type() const {
671     return current_received_frame_type_;
672   }
673 
previously_received_frame_type()674   uint64_t previously_received_frame_type() const {
675     return previously_received_frame_type_;
676   }
677 
678   // The connection ID length the framer expects on incoming IETF short headers
679   // on the server.
GetExpectedServerConnectionIdLength()680   uint8_t GetExpectedServerConnectionIdLength() {
681     return expected_server_connection_id_length_;
682   }
683 
684   // Change the expected destination connection ID length for short headers on
685   // the client.
SetExpectedClientConnectionIdLength(uint8_t expected_client_connection_id_length)686   void SetExpectedClientConnectionIdLength(
687       uint8_t expected_client_connection_id_length) {
688     expected_client_connection_id_length_ =
689         expected_client_connection_id_length;
690   }
691 
692   void EnableMultiplePacketNumberSpacesSupport();
693 
694   // Writes an array of bytes that, if sent as a UDP datagram, will trigger
695   // IETF QUIC Version Negotiation on servers. The bytes will be written to
696   // |packet_bytes|, which must point to |packet_length| bytes of memory.
697   // |packet_length| must be in the range [1200, 65535].
698   // |destination_connection_id_bytes| will be sent as the destination
699   // connection ID, and must point to |destination_connection_id_length| bytes
700   // of memory. |destination_connection_id_length| must be in the range [8,18].
701   // When targeting Google servers, it is recommended to use a
702   // |destination_connection_id_length| of 8.
703   static bool WriteClientVersionNegotiationProbePacket(
704       char* packet_bytes, QuicByteCount packet_length,
705       const char* destination_connection_id_bytes,
706       uint8_t destination_connection_id_length);
707 
708   // Parses a packet which a QUIC server sent in response to a packet sent by
709   // WriteClientVersionNegotiationProbePacket. |packet_bytes| must point to
710   // |packet_length| bytes in memory which represent the response.
711   // |packet_length| must be greater or equal to 6. This method will fill in
712   // |source_connection_id_bytes| which must point to at least
713   // |*source_connection_id_length_out| bytes in memory.
714   // |*source_connection_id_length_out| must be at least 18.
715   // |*source_connection_id_length_out| will contain the length of the received
716   // source connection ID, which on success will match the contents of the
717   // destination connection ID passed in to
718   // WriteClientVersionNegotiationProbePacket. In the case of a failure,
719   // |detailed_error| will be filled in with an explanation of what failed.
720   static bool ParseServerVersionNegotiationProbeResponse(
721       const char* packet_bytes, QuicByteCount packet_length,
722       char* source_connection_id_bytes,
723       uint8_t* source_connection_id_length_out, std::string* detailed_error);
724 
set_local_ack_delay_exponent(uint32_t exponent)725   void set_local_ack_delay_exponent(uint32_t exponent) {
726     local_ack_delay_exponent_ = exponent;
727   }
local_ack_delay_exponent()728   uint32_t local_ack_delay_exponent() const {
729     return local_ack_delay_exponent_;
730   }
731 
set_peer_ack_delay_exponent(uint32_t exponent)732   void set_peer_ack_delay_exponent(uint32_t exponent) {
733     peer_ack_delay_exponent_ = exponent;
734   }
peer_ack_delay_exponent()735   uint32_t peer_ack_delay_exponent() const { return peer_ack_delay_exponent_; }
736 
set_drop_incoming_retry_packets(bool drop_incoming_retry_packets)737   void set_drop_incoming_retry_packets(bool drop_incoming_retry_packets) {
738     drop_incoming_retry_packets_ = drop_incoming_retry_packets;
739   }
740 
741  private:
742   friend class test::QuicFramerPeer;
743 
744   using NackRangeMap = std::map<QuicPacketNumber, uint8_t>;
745   using AssociatedDataStorage = absl::InlinedVector<char, 20>;
746 
747   // AckTimestampRange is a data structure derived from a QuicAckFrame. It is
748   // used to serialize timestamps in a IETF_ACK_RECEIVE_TIMESTAMPS frame.
749   struct QUICHE_EXPORT AckTimestampRange {
750     QuicPacketCount gap;
751     // |range_begin| and |range_end| are index(es) in
752     // QuicAckFrame.received_packet_times, representing a continuous range of
753     // packet numbers in descending order. |range_begin| >= |range_end|.
754     int64_t range_begin;  // Inclusive
755     int64_t range_end;    // Inclusive
756   };
757   absl::InlinedVector<AckTimestampRange, 2> GetAckTimestampRanges(
758       const QuicAckFrame& frame, std::string& detailed_error) const;
759   int64_t FrameAckTimestampRanges(
760       const QuicAckFrame& frame,
761       const absl::InlinedVector<AckTimestampRange, 2>& timestamp_ranges,
762       QuicDataWriter* writer) const;
763 
764   struct QUICHE_EXPORT AckFrameInfo {
765     AckFrameInfo();
766     AckFrameInfo(const AckFrameInfo& other);
767     ~AckFrameInfo();
768 
769     // The maximum ack block length.
770     QuicPacketCount max_block_length;
771     // Length of first ack block.
772     QuicPacketCount first_block_length;
773     // Number of ACK blocks needed for the ACK frame.
774     size_t num_ack_blocks;
775   };
776 
777   // Applies header protection to an IETF QUIC packet header in |buffer| using
778   // the encrypter for level |level|. The buffer has |buffer_len| bytes of data,
779   // with the first protected packet bytes starting at |ad_len|.
780   bool ApplyHeaderProtection(EncryptionLevel level, char* buffer,
781                              size_t buffer_len, size_t ad_len);
782 
783   // Removes header protection from an IETF QUIC packet header.
784   //
785   // The packet number from the header is read from |reader|, where the packet
786   // number is the next contents in |reader|. |reader| is only advanced by the
787   // length of the packet number, but it is also used to peek the sample needed
788   // for removing header protection.
789   //
790   // Properties needed for removing header protection are read from |header|.
791   // The packet number length and type byte are written to |header|.
792   //
793   // The packet number, after removing header protection and decoding it, is
794   // written to |full_packet_number|. Finally, the header, with header
795   // protection removed, is written to |associated_data| to be used in packet
796   // decryption. |packet| is used in computing the asociated data.
797   bool RemoveHeaderProtection(QuicDataReader* reader,
798                               const QuicEncryptedPacket& packet,
799                               QuicPacketHeader* header,
800                               uint64_t* full_packet_number,
801                               AssociatedDataStorage& associated_data);
802 
803   bool ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
804                              QuicPacketHeader* header,
805                              const QuicEncryptedPacket& packet,
806                              char* decrypted_buffer, size_t buffer_length);
807 
808   bool ProcessVersionNegotiationPacket(QuicDataReader* reader,
809                                        const QuicPacketHeader& header);
810 
811   bool ProcessRetryPacket(QuicDataReader* reader,
812                           const QuicPacketHeader& header);
813 
814   void MaybeProcessCoalescedPacket(const QuicDataReader& encrypted_reader,
815                                    uint64_t remaining_bytes_length,
816                                    const QuicPacketHeader& header);
817 
818   bool MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
819                               QuicPacketHeader* header);
820 
821   // Processes the version label in the packet header.
822   static bool ProcessVersionLabel(QuicDataReader* reader,
823                                   QuicVersionLabel* version_label);
824 
825   // Validates and updates |destination_connection_id_length| and
826   // |source_connection_id_length|. When
827   // |should_update_expected_server_connection_id_length| is true, length
828   // validation is disabled and |expected_server_connection_id_length| is set
829   // to the appropriate length.
830   // TODO(b/133873272) refactor this method.
831   static bool ProcessAndValidateIetfConnectionIdLength(
832       QuicDataReader* reader, ParsedQuicVersion version,
833       Perspective perspective,
834       bool should_update_expected_server_connection_id_length,
835       uint8_t* expected_server_connection_id_length,
836       uint8_t* destination_connection_id_length,
837       uint8_t* source_connection_id_length, std::string* detailed_error);
838 
839   bool ProcessIetfHeaderTypeByte(QuicDataReader* reader,
840                                  QuicPacketHeader* header);
841   bool ProcessIetfPacketHeader(QuicDataReader* reader,
842                                QuicPacketHeader* header);
843 
844   // First processes possibly truncated packet number. Calculates the full
845   // packet number from the truncated one and the last seen packet number, and
846   // stores it to |packet_number|.
847   bool ProcessAndCalculatePacketNumber(
848       QuicDataReader* reader, QuicPacketNumberLength packet_number_length,
849       QuicPacketNumber base_packet_number, uint64_t* packet_number);
850   bool ProcessFrameData(QuicDataReader* reader, const QuicPacketHeader& header);
851 
852   static bool IsIetfFrameTypeExpectedForEncryptionLevel(uint64_t frame_type,
853                                                         EncryptionLevel level);
854 
855   bool ProcessIetfFrameData(QuicDataReader* reader,
856                             const QuicPacketHeader& header,
857                             EncryptionLevel decrypted_level);
858   bool ProcessStreamFrame(QuicDataReader* reader, uint8_t frame_type,
859                           QuicStreamFrame* frame);
860   bool ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type);
861   bool ProcessTimestampsInAckFrame(uint8_t num_received_packets,
862                                    QuicPacketNumber largest_acked,
863                                    QuicDataReader* reader);
864   bool ProcessIetfAckFrame(QuicDataReader* reader, uint64_t frame_type,
865                            QuicAckFrame* ack_frame);
866   bool ProcessIetfTimestampsInAckFrame(QuicPacketNumber largest_acked,
867                                        QuicDataReader* reader);
868   bool ProcessStopWaitingFrame(QuicDataReader* reader,
869                                const QuicPacketHeader& header,
870                                QuicStopWaitingFrame* stop_waiting);
871   bool ProcessRstStreamFrame(QuicDataReader* reader, QuicRstStreamFrame* frame);
872   bool ProcessConnectionCloseFrame(QuicDataReader* reader,
873                                    QuicConnectionCloseFrame* frame);
874   bool ProcessGoAwayFrame(QuicDataReader* reader, QuicGoAwayFrame* frame);
875   bool ProcessWindowUpdateFrame(QuicDataReader* reader,
876                                 QuicWindowUpdateFrame* frame);
877   bool ProcessBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame);
878   void ProcessPaddingFrame(QuicDataReader* reader, QuicPaddingFrame* frame);
879   bool ProcessMessageFrame(QuicDataReader* reader, bool no_message_length,
880                            QuicMessageFrame* frame);
881 
882   bool DecryptPayload(size_t udp_packet_length, absl::string_view encrypted,
883                       absl::string_view associated_data,
884                       const QuicPacketHeader& header, char* decrypted_buffer,
885                       size_t buffer_length, size_t* decrypted_length,
886                       EncryptionLevel* decrypted_level);
887 
888   // Returns the full packet number from the truncated
889   // wire format version and the last seen packet number.
890   uint64_t CalculatePacketNumberFromWire(
891       QuicPacketNumberLength packet_number_length,
892       QuicPacketNumber base_packet_number, uint64_t packet_number) const;
893 
894   // Returns the QuicTime::Delta corresponding to the time from when the framer
895   // was created.
896   const QuicTime::Delta CalculateTimestampFromWire(uint32_t time_delta_us);
897 
898   // Computes the wire size in bytes of time stamps in |ack|.
899   size_t GetAckFrameTimeStampSize(const QuicAckFrame& ack);
900   size_t GetIetfAckFrameTimestampSize(const QuicAckFrame& ack);
901 
902   // Computes the wire size in bytes of the |ack| frame.
903   size_t GetAckFrameSize(const QuicAckFrame& ack,
904                          QuicPacketNumberLength packet_number_length);
905   // Computes the wire-size, in bytes, of the |frame| ack frame, for IETF Quic.
906   size_t GetIetfAckFrameSize(const QuicAckFrame& frame);
907 
908   // Computes the wire size in bytes of the |ack| frame.
909   size_t GetAckFrameSize(const QuicAckFrame& ack);
910 
911   // Computes the wire size in bytes of the payload of |frame|.
912   size_t ComputeFrameLength(const QuicFrame& frame, bool last_frame_in_packet,
913                             QuicPacketNumberLength packet_number_length);
914 
915   static bool AppendPacketNumber(QuicPacketNumberLength packet_number_length,
916                                  QuicPacketNumber packet_number,
917                                  QuicDataWriter* writer);
918   static bool AppendStreamId(size_t stream_id_length, QuicStreamId stream_id,
919                              QuicDataWriter* writer);
920   static bool AppendStreamOffset(size_t offset_length, QuicStreamOffset offset,
921                                  QuicDataWriter* writer);
922 
923   // Appends a single ACK block to |writer| and returns true if the block was
924   // successfully appended.
925   static bool AppendAckBlock(uint8_t gap, QuicPacketNumberLength length_length,
926                              uint64_t length, QuicDataWriter* writer);
927 
928   static uint8_t GetPacketNumberFlags(
929       QuicPacketNumberLength packet_number_length);
930 
931   static AckFrameInfo GetAckFrameInfo(const QuicAckFrame& frame);
932 
933   static QuicErrorCode ParsePublicHeaderGoogleQuic(
934       QuicDataReader* reader, uint8_t* first_byte, PacketHeaderFormat* format,
935       bool* version_present, QuicVersionLabel* version_label,
936       ParsedQuicVersion* parsed_version,
937       QuicConnectionId* destination_connection_id, std::string* detailed_error);
938 
939   bool ValidateReceivedConnectionIds(const QuicPacketHeader& header);
940 
941   // The Append* methods attempt to write the provided header or frame using the
942   // |writer|, and return true if successful.
943 
944   bool AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
945                                  QuicDataWriter* writer);
946   bool AppendTimestampsToAckFrame(const QuicAckFrame& frame,
947                                   QuicDataWriter* writer);
948 
949   // Append IETF format ACK frame.
950   //
951   // AppendIetfAckFrameAndTypeByte adds the IETF type byte and the body
952   // of the frame.
953   bool AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
954                                      QuicDataWriter* writer);
955   bool AppendIetfTimestampsToAckFrame(const QuicAckFrame& frame,
956                                       QuicDataWriter* writer);
957 
958   bool AppendStopWaitingFrame(const QuicPacketHeader& header,
959                               const QuicStopWaitingFrame& frame,
960                               QuicDataWriter* writer);
961   bool AppendRstStreamFrame(const QuicRstStreamFrame& frame,
962                             QuicDataWriter* writer);
963   bool AppendConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
964                                   QuicDataWriter* writer);
965   bool AppendGoAwayFrame(const QuicGoAwayFrame& frame, QuicDataWriter* writer);
966   bool AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
967                                QuicDataWriter* writer);
968   bool AppendBlockedFrame(const QuicBlockedFrame& frame,
969                           QuicDataWriter* writer);
970   bool AppendPaddingFrame(const QuicPaddingFrame& frame,
971                           QuicDataWriter* writer);
972   bool AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
973                                      bool last_frame_in_packet,
974                                      QuicDataWriter* writer);
975 
976   // IETF frame processing methods.
977   bool ProcessIetfStreamFrame(QuicDataReader* reader, uint8_t frame_type,
978                               QuicStreamFrame* frame);
979   bool ProcessIetfConnectionCloseFrame(QuicDataReader* reader,
980                                        QuicConnectionCloseType type,
981                                        QuicConnectionCloseFrame* frame);
982   bool ProcessPathChallengeFrame(QuicDataReader* reader,
983                                  QuicPathChallengeFrame* frame);
984   bool ProcessPathResponseFrame(QuicDataReader* reader,
985                                 QuicPathResponseFrame* frame);
986   bool ProcessIetfResetStreamFrame(QuicDataReader* reader,
987                                    QuicRstStreamFrame* frame);
988   bool ProcessStopSendingFrame(QuicDataReader* reader,
989                                QuicStopSendingFrame* stop_sending_frame);
990   bool ProcessCryptoFrame(QuicDataReader* reader,
991                           EncryptionLevel encryption_level,
992                           QuicCryptoFrame* frame);
993   bool ProcessAckFrequencyFrame(QuicDataReader* reader,
994                                 QuicAckFrequencyFrame* frame);
995   bool ProcessResetStreamAtFrame(QuicDataReader& reader,
996                                  QuicResetStreamAtFrame& frame);
997   // IETF frame appending methods.  All methods append the type byte as well.
998   bool AppendIetfStreamFrame(const QuicStreamFrame& frame,
999                              bool last_frame_in_packet, QuicDataWriter* writer);
1000   bool AppendIetfConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
1001                                       QuicDataWriter* writer);
1002   bool AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
1003                                 QuicDataWriter* writer);
1004   bool AppendPathResponseFrame(const QuicPathResponseFrame& frame,
1005                                QuicDataWriter* writer);
1006   bool AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
1007                                   QuicDataWriter* writer);
1008   bool AppendStopSendingFrame(const QuicStopSendingFrame& stop_sending_frame,
1009                               QuicDataWriter* writer);
1010 
1011   // Append/consume IETF-Format MAX_DATA and MAX_STREAM_DATA frames
1012   bool AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
1013                           QuicDataWriter* writer);
1014   bool AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
1015                                 QuicDataWriter* writer);
1016   bool ProcessMaxDataFrame(QuicDataReader* reader,
1017                            QuicWindowUpdateFrame* frame);
1018   bool ProcessMaxStreamDataFrame(QuicDataReader* reader,
1019                                  QuicWindowUpdateFrame* frame);
1020 
1021   bool AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
1022                              QuicDataWriter* writer);
1023   bool ProcessMaxStreamsFrame(QuicDataReader* reader,
1024                               QuicMaxStreamsFrame* frame, uint64_t frame_type);
1025 
1026   bool AppendDataBlockedFrame(const QuicBlockedFrame& frame,
1027                               QuicDataWriter* writer);
1028   bool ProcessDataBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame);
1029 
1030   bool AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame,
1031                                     QuicDataWriter* writer);
1032   bool ProcessStreamDataBlockedFrame(QuicDataReader* reader,
1033                                      QuicBlockedFrame* frame);
1034 
1035   bool AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
1036                                  QuicDataWriter* writer);
1037   bool ProcessStreamsBlockedFrame(QuicDataReader* reader,
1038                                   QuicStreamsBlockedFrame* frame,
1039                                   uint64_t frame_type);
1040 
1041   bool AppendNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame,
1042                                   QuicDataWriter* writer);
1043   bool ProcessNewConnectionIdFrame(QuicDataReader* reader,
1044                                    QuicNewConnectionIdFrame* frame);
1045   bool AppendRetireConnectionIdFrame(const QuicRetireConnectionIdFrame& frame,
1046                                      QuicDataWriter* writer);
1047   bool ProcessRetireConnectionIdFrame(QuicDataReader* reader,
1048                                       QuicRetireConnectionIdFrame* frame);
1049 
1050   bool AppendNewTokenFrame(const QuicNewTokenFrame& frame,
1051                            QuicDataWriter* writer);
1052   bool ProcessNewTokenFrame(QuicDataReader* reader, QuicNewTokenFrame* frame);
1053 
1054   bool RaiseError(QuicErrorCode error);
1055 
1056   // Returns true if |header| indicates a version negotiation packet.
1057   bool IsVersionNegotiation(const QuicPacketHeader& header) const;
1058 
1059   // Calculates and returns type byte of stream frame.
1060   uint8_t GetStreamFrameTypeByte(const QuicStreamFrame& frame,
1061                                  bool last_frame_in_packet) const;
1062   uint8_t GetIetfStreamFrameTypeByte(const QuicStreamFrame& frame,
1063                                      bool last_frame_in_packet) const;
1064 
set_error(QuicErrorCode error)1065   void set_error(QuicErrorCode error) { error_ = error; }
1066 
set_detailed_error(const char * error)1067   void set_detailed_error(const char* error) { detailed_error_ = error; }
set_detailed_error(std::string error)1068   void set_detailed_error(std::string error) { detailed_error_ = error; }
1069 
1070   // Returns false if the reading fails.
1071   bool ReadUint32FromVarint62(QuicDataReader* reader, QuicIetfFrameType type,
1072                               QuicStreamId* id);
1073 
1074   bool ProcessPacketInternal(const QuicEncryptedPacket& packet);
1075 
1076   // Determine whether the given QuicAckFrame should be serialized with a
1077   // IETF_ACK_RECEIVE_TIMESTAMPS frame type.
UseIetfAckWithReceiveTimestamp(const QuicAckFrame & frame)1078   bool UseIetfAckWithReceiveTimestamp(const QuicAckFrame& frame) const {
1079     return VersionHasIetfQuicFrames(version_.transport_version) &&
1080            process_timestamps_ &&
1081            std::min<uint64_t>(max_receive_timestamps_per_ack_,
1082                               frame.received_packet_times.size()) > 0;
1083   }
1084 
1085   std::string detailed_error_;
1086   QuicFramerVisitorInterface* visitor_;
1087   QuicErrorCode error_;
1088   // Updated by ProcessPacketHeader when it succeeds decrypting a larger packet.
1089   QuicPacketNumber largest_packet_number_;
1090   // Largest successfully decrypted packet number per packet number space. Only
1091   // used when supports_multiple_packet_number_spaces_ is true.
1092   QuicPacketNumber largest_decrypted_packet_numbers_[NUM_PACKET_NUMBER_SPACES];
1093   // Last server connection ID seen on the wire.
1094   QuicConnectionId last_serialized_server_connection_id_;
1095   // Version of the protocol being used.
1096   ParsedQuicVersion version_;
1097   // This vector contains QUIC versions which we currently support.
1098   // This should be ordered such that the highest supported version is the first
1099   // element, with subsequent elements in descending order (versions can be
1100   // skipped as necessary).
1101   ParsedQuicVersionVector supported_versions_;
1102   // Decrypters used to decrypt packets during parsing.
1103   std::unique_ptr<QuicDecrypter> decrypter_[NUM_ENCRYPTION_LEVELS];
1104   // The encryption level of the primary decrypter to use in |decrypter_|.
1105   EncryptionLevel decrypter_level_;
1106   // The encryption level of the alternative decrypter to use in |decrypter_|.
1107   // When set to NUM_ENCRYPTION_LEVELS, indicates that there is no alternative
1108   // decrypter.
1109   EncryptionLevel alternative_decrypter_level_;
1110   // |alternative_decrypter_latch_| is true if, when the decrypter at
1111   // |alternative_decrypter_level_| successfully decrypts a packet, we should
1112   // install it as the only decrypter.
1113   bool alternative_decrypter_latch_;
1114   // Encrypters used to encrypt packets via EncryptPayload().
1115   std::unique_ptr<QuicEncrypter> encrypter_[NUM_ENCRYPTION_LEVELS];
1116   // Tracks if the framer is being used by the entity that received the
1117   // connection or the entity that initiated it.
1118   Perspective perspective_;
1119   // If false, skip validation that the public flags are set to legal values.
1120   bool validate_flags_;
1121   // The diversification nonce from the last received packet.
1122   DiversificationNonce last_nonce_;
1123   // If true, send and process timestamps in the ACK frame.
1124   // TODO(ianswett): Remove the mutables once set_process_timestamps and
1125   // set_receive_timestamp_exponent_ aren't const.
1126   mutable bool process_timestamps_;
1127   // The max number of receive timestamps to send per ACK frame.
1128   mutable uint32_t max_receive_timestamps_per_ack_;
1129   // The exponent to use when writing/reading ACK receive timestamps.
1130   mutable uint32_t receive_timestamps_exponent_;
1131   // If true, process RESET_STREAM_AT frames.
1132   bool process_reset_stream_at_;
1133   // The creation time of the connection, used to calculate timestamps.
1134   QuicTime creation_time_;
1135   // The last timestamp received if process_timestamps_ is true.
1136   QuicTime::Delta last_timestamp_;
1137 
1138   // Whether IETF QUIC Key Update is supported on this connection.
1139   bool support_key_update_for_connection_;
1140   // The value of the current key phase bit, which is toggled when the keys are
1141   // changed.
1142   bool current_key_phase_bit_;
1143   // Whether we have performed a key update at least once.
1144   bool key_update_performed_ = false;
1145   // Tracks the first packet received in the current key phase. Will be
1146   // uninitialized before the first one-RTT packet has been received or after a
1147   // locally initiated key update but before the first packet from the peer in
1148   // the new key phase is received.
1149   QuicPacketNumber current_key_phase_first_received_packet_number_;
1150   // Counts the number of packets received that might have been failed key
1151   // update attempts. Reset to zero every time a packet is successfully
1152   // decrypted.
1153   QuicPacketCount potential_peer_key_update_attempt_count_;
1154   // Decrypter for the previous key phase. Will be null if in the first key
1155   // phase or previous keys have been discarded.
1156   std::unique_ptr<QuicDecrypter> previous_decrypter_;
1157   // Decrypter for the next key phase. May be null if next keys haven't been
1158   // generated yet.
1159   std::unique_ptr<QuicDecrypter> next_decrypter_;
1160 
1161   // If this is a framer of a connection, this is the packet number of first
1162   // sending packet. If this is a framer of a framer of dispatcher, this is the
1163   // packet number of sent packets (for those which have packet number).
1164   const QuicPacketNumber first_sending_packet_number_;
1165 
1166   // If not null, framer asks data_producer_ to write stream frame data. Not
1167   // owned. TODO(fayang): Consider add data producer to framer's constructor.
1168   QuicStreamFrameDataProducer* data_producer_;
1169 
1170   // Whether we are in the middle of a call to this->ProcessPacket.
1171   bool is_processing_packet_ = false;
1172 
1173   // IETF short headers contain a destination connection ID but do not
1174   // encode its length. These variables contains the length we expect to read.
1175   // This is also used to validate the long header destination connection ID
1176   // lengths in older versions of QUIC.
1177   uint8_t expected_server_connection_id_length_;
1178   uint8_t expected_client_connection_id_length_;
1179 
1180   // Indicates whether this framer supports multiple packet number spaces.
1181   bool supports_multiple_packet_number_spaces_;
1182 
1183   // Indicates whether received RETRY packets should be dropped.
1184   bool drop_incoming_retry_packets_ = false;
1185 
1186   // The length in bytes of the last packet number written to an IETF-framed
1187   // packet.
1188   size_t last_written_packet_number_length_;
1189 
1190   // The amount to shift the ack timestamp in ACK frames. The default is 3.
1191   // Local_ is the amount this node shifts timestamps in ACK frames it
1192   // generates. it is sent to the peer in a transport parameter negotiation.
1193   // Peer_ is the amount the peer shifts timestamps when it sends ACK frames to
1194   // this node. This node "unshifts" by this amount. The value is received from
1195   // the peer in the transport parameter negotiation. IETF QUIC only.
1196   uint32_t peer_ack_delay_exponent_;
1197   uint32_t local_ack_delay_exponent_;
1198 
1199   // The type of received IETF frame currently being processed.  0 when not
1200   // processing a frame or when processing Google QUIC frames.  Used to populate
1201   // the Transport Connection Close when there is an error during frame
1202   // processing.
1203   uint64_t current_received_frame_type_;
1204 
1205   // TODO(haoyuewang) Remove this debug utility.
1206   // The type of the IETF frame preceding the frame currently being processed. 0
1207   // when not processing a frame or only 1 frame has been processed.
1208   uint64_t previously_received_frame_type_;
1209 };
1210 
1211 // Look for and parse the error code from the "<quic_error_code>:" text that
1212 // may be present at the start of the CONNECTION_CLOSE error details string.
1213 // This text, inserted by the peer if it's using Google's QUIC implementation,
1214 // contains additional error information that narrows down the exact error. The
1215 // extracted error code and (possibly updated) error_details string are returned
1216 // in |*frame|. If an error code is not found in the error details, then
1217 // frame->quic_error_code is set to
1218 // QuicErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING.  If there is an error code in
1219 // the string then it is removed from the string.
1220 QUICHE_EXPORT void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame);
1221 
1222 }  // namespace quic
1223 
1224 #endif  // QUICHE_QUIC_CORE_QUIC_FRAMER_H_
1225