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