blob: 2920db351c457203e48d350608e93c9c68dad9e5 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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>
vasilvv872e7a32019-03-12 16:42:44 -070011#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050012
vasilvvc872ee42020-10-07 19:50:22 -070013#include "absl/strings/string_view.h"
QUICHE team5be974e2020-12-29 18:35:24 -050014#include "quic/core/crypto/quic_decrypter.h"
15#include "quic/core/crypto/quic_encrypter.h"
16#include "quic/core/crypto/quic_random.h"
17#include "quic/core/quic_connection_id.h"
18#include "quic/core/quic_packets.h"
19#include "quic/core/quic_types.h"
20#include "quic/platform/api/quic_export.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050021
22namespace quic {
23
24namespace test {
25class QuicFramerPeer;
26} // namespace test
27
28class QuicDataReader;
29class QuicDataWriter;
30class QuicFramer;
31class QuicStreamFrameDataProducer;
32
33// Number of bytes reserved for the frame type preceding each frame.
34const size_t kQuicFrameTypeSize = 1;
35// Number of bytes reserved for error code.
36const size_t kQuicErrorCodeSize = 4;
37// Number of bytes reserved to denote the length of error details field.
38const size_t kQuicErrorDetailsLengthSize = 2;
39
40// Maximum number of bytes reserved for stream id.
41const size_t kQuicMaxStreamIdSize = 4;
42// Maximum number of bytes reserved for byte offset in stream frame.
43const size_t kQuicMaxStreamOffsetSize = 8;
44// Number of bytes reserved to store payload length in stream frame.
45const size_t kQuicStreamPayloadLengthSize = 2;
46// Number of bytes to reserve for IQ Error codes (for the Connection Close,
47// Application Close, and Reset Stream frames).
48const size_t kQuicIetfQuicErrorCodeSize = 2;
49// Minimum size of the IETF QUIC Error Phrase's length field
50const size_t kIetfQuicMinErrorPhraseLengthSize = 1;
51
52// Size in bytes reserved for the delta time of the largest observed
53// packet number in ack frames.
54const size_t kQuicDeltaTimeLargestObservedSize = 2;
55// Size in bytes reserved for the number of received packets with timestamps.
56const size_t kQuicNumTimestampsSize = 1;
57// Size in bytes reserved for the number of missing packets in ack frames.
58const size_t kNumberOfNackRangesSize = 1;
59// Size in bytes reserved for the number of ack blocks in ack frames.
60const size_t kNumberOfAckBlocksSize = 1;
61// Maximum number of missing packet ranges that can fit within an ack frame.
62const size_t kMaxNackRanges = (1 << (kNumberOfNackRangesSize * 8)) - 1;
63// Maximum number of ack blocks that can fit within an ack frame.
64const size_t kMaxAckBlocks = (1 << (kNumberOfAckBlocksSize * 8)) - 1;
65
66// This class receives callbacks from the framer when packets
67// are processed.
68class QUIC_EXPORT_PRIVATE QuicFramerVisitorInterface {
69 public:
70 virtual ~QuicFramerVisitorInterface() {}
71
72 // Called if an error is detected in the QUIC protocol.
73 virtual void OnError(QuicFramer* framer) = 0;
74
75 // Called only when |perspective_| is IS_SERVER and the framer gets a
76 // packet with version flag true and the version on the packet doesn't match
77 // |quic_version_|. The visitor should return true after it updates the
78 // version of the |framer_| to |received_version| or false to stop processing
79 // this packet.
fayang8aba1ff2019-06-21 12:00:54 -070080 virtual bool OnProtocolVersionMismatch(
81 ParsedQuicVersion received_version) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -050082
83 // Called when a new packet has been received, before it
84 // has been validated or processed.
85 virtual void OnPacket() = 0;
86
87 // Called when a public reset packet has been parsed but has not yet
88 // been validated.
89 virtual void OnPublicResetPacket(const QuicPublicResetPacket& packet) = 0;
90
91 // Called only when |perspective_| is IS_CLIENT and a version negotiation
92 // packet has been parsed.
93 virtual void OnVersionNegotiationPacket(
94 const QuicVersionNegotiationPacket& packet) = 0;
95
dschinazi244f6dc2019-05-06 15:45:16 -070096 // Called only when |perspective_| is IS_CLIENT and a retry packet has been
dschinazi278efae2020-01-28 17:03:09 -080097 // parsed. |new_connection_id| contains the value of the Source Connection
98 // ID field, and |retry_token| contains the value of the Retry Token field.
dschinazi1f6aca82020-12-04 13:20:08 -080099 // On versions where UsesTls() is false,
dschinazi278efae2020-01-28 17:03:09 -0800100 // |original_connection_id| contains the value of the Original Destination
101 // Connection ID field, and both |retry_integrity_tag| and
102 // |retry_without_tag| are empty.
dschinazi1f6aca82020-12-04 13:20:08 -0800103 // On versions where UsesTls() is true,
dschinazi278efae2020-01-28 17:03:09 -0800104 // |original_connection_id| is empty, |retry_integrity_tag| contains the
105 // value of the Retry Integrity Tag field, and |retry_without_tag| contains
106 // the entire RETRY packet except the Retry Integrity Tag field.
dschinazi244f6dc2019-05-06 15:45:16 -0700107 virtual void OnRetryPacket(QuicConnectionId original_connection_id,
108 QuicConnectionId new_connection_id,
vasilvvc872ee42020-10-07 19:50:22 -0700109 absl::string_view retry_token,
110 absl::string_view retry_integrity_tag,
111 absl::string_view retry_without_tag) = 0;
dschinazi244f6dc2019-05-06 15:45:16 -0700112
QUICHE teama6ef0a62019-03-07 20:34:33 -0500113 // Called when all fields except packet number has been parsed, but has not
114 // been authenticated. If it returns false, framing for this packet will
115 // cease.
116 virtual bool OnUnauthenticatedPublicHeader(
117 const QuicPacketHeader& header) = 0;
118
119 // Called when the unauthenticated portion of the header has been parsed.
120 // If OnUnauthenticatedHeader returns false, framing for this packet will
121 // cease.
122 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) = 0;
123
fayang93b4e4d2020-11-25 07:56:47 -0800124 // Called when a packet has been decrypted. |length| is the packet length,
125 // and |level| is the encryption level of the packet.
126 virtual void OnDecryptedPacket(size_t length, EncryptionLevel level) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500127
128 // Called when the complete header of a packet had been parsed.
129 // If OnPacketHeader returns false, framing for this packet will cease.
130 virtual bool OnPacketHeader(const QuicPacketHeader& header) = 0;
131
132 // Called when the packet being processed contains multiple IETF QUIC packets,
133 // which is due to there being more data after what is covered by the length
134 // field. |packet| contains the remaining data which can be processed.
135 // Note that this is called when the framer parses the length field, before
136 // it attempts to decrypt the first payload. It is the visitor's
137 // responsibility to buffer the packet and call ProcessPacket on it
138 // after the framer is done parsing the current payload. |packet| does not
139 // own its internal buffer, the visitor should make a copy of it.
140 virtual void OnCoalescedPacket(const QuicEncryptedPacket& packet) = 0;
141
dschinazi4b5a68a2019-08-15 15:45:36 -0700142 // Called when the packet being processed failed to decrypt.
143 // |has_decryption_key| indicates whether the framer knew which decryption
144 // key to use for this packet and already had a suitable key.
145 virtual void OnUndecryptablePacket(const QuicEncryptedPacket& packet,
146 EncryptionLevel decryption_level,
147 bool has_decryption_key) = 0;
148
QUICHE teama6ef0a62019-03-07 20:34:33 -0500149 // Called when a StreamFrame has been parsed.
150 virtual bool OnStreamFrame(const QuicStreamFrame& frame) = 0;
151
152 // Called when a CRYPTO frame has been parsed.
153 virtual bool OnCryptoFrame(const QuicCryptoFrame& frame) = 0;
154
155 // Called when largest acked of an AckFrame has been parsed.
156 virtual bool OnAckFrameStart(QuicPacketNumber largest_acked,
157 QuicTime::Delta ack_delay_time) = 0;
158
159 // Called when ack range [start, end) of an AckFrame has been parsed.
160 virtual bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) = 0;
161
162 // Called when a timestamp in the AckFrame has been parsed.
163 virtual bool OnAckTimestamp(QuicPacketNumber packet_number,
164 QuicTime timestamp) = 0;
165
166 // Called after the last ack range in an AckFrame has been parsed.
167 // |start| is the starting value of the last ack range.
168 virtual bool OnAckFrameEnd(QuicPacketNumber start) = 0;
169
170 // Called when a StopWaitingFrame has been parsed.
171 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) = 0;
172
173 // Called when a QuicPaddingFrame has been parsed.
174 virtual bool OnPaddingFrame(const QuicPaddingFrame& frame) = 0;
175
176 // Called when a PingFrame has been parsed.
177 virtual bool OnPingFrame(const QuicPingFrame& frame) = 0;
178
179 // Called when a RstStreamFrame has been parsed.
180 virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0;
181
fkastenholz04bd4f32019-04-16 12:24:38 -0700182 // Called when a ConnectionCloseFrame, of any type, has been parsed.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500183 virtual bool OnConnectionCloseFrame(
184 const QuicConnectionCloseFrame& frame) = 0;
185
QUICHE teama6ef0a62019-03-07 20:34:33 -0500186 // Called when a StopSendingFrame has been parsed.
187 virtual bool OnStopSendingFrame(const QuicStopSendingFrame& frame) = 0;
188
189 // Called when a PathChallengeFrame has been parsed.
190 virtual bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) = 0;
191
192 // Called when a PathResponseFrame has been parsed.
193 virtual bool OnPathResponseFrame(const QuicPathResponseFrame& frame) = 0;
194
195 // Called when a GoAwayFrame has been parsed.
196 virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) = 0;
197
198 // Called when a WindowUpdateFrame has been parsed.
199 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0;
200
201 // Called when a BlockedFrame has been parsed.
202 virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) = 0;
203
204 // Called when a NewConnectionIdFrame has been parsed.
205 virtual bool OnNewConnectionIdFrame(
206 const QuicNewConnectionIdFrame& frame) = 0;
207
208 // Called when a RetireConnectionIdFrame has been parsed.
209 virtual bool OnRetireConnectionIdFrame(
210 const QuicRetireConnectionIdFrame& frame) = 0;
211
212 // Called when a NewTokenFrame has been parsed.
213 virtual bool OnNewTokenFrame(const QuicNewTokenFrame& frame) = 0;
214
215 // Called when a message frame has been parsed.
216 virtual bool OnMessageFrame(const QuicMessageFrame& frame) = 0;
217
fayang01062942020-01-22 07:23:23 -0800218 // Called when a handshake done frame has been parsed.
219 virtual bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) = 0;
220
haoyuewang6a6a0ff2020-06-23 16:32:26 -0700221 // Called when an AckFrequencyFrame has been parsed.
222 virtual bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) = 0;
223
QUICHE teama6ef0a62019-03-07 20:34:33 -0500224 // Called when a packet has been completely processed.
225 virtual void OnPacketComplete() = 0;
226
227 // Called to check whether |token| is a valid stateless reset token.
bnc1ccd0bc2021-04-07 10:20:17 -0700228 virtual bool IsValidStatelessResetToken(
229 const StatelessResetToken& token) const = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500230
231 // Called when an IETF stateless reset packet has been parsed and validated
232 // with the stateless reset token.
233 virtual void OnAuthenticatedIetfStatelessResetPacket(
234 const QuicIetfStatelessResetPacket& packet) = 0;
235
fkastenholz3c4eabf2019-04-22 07:49:59 -0700236 // Called when an IETF MaxStreams frame has been parsed.
237 virtual bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500238
fkastenholz3c4eabf2019-04-22 07:49:59 -0700239 // Called when an IETF StreamsBlocked frame has been parsed.
240 virtual bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) = 0;
mattm072a7e32020-10-09 16:16:56 -0700241
242 // Called when a Key Phase Update has been initiated. This is called for both
243 // locally and peer initiated key updates. If the key update was locally
244 // initiated, this does not indicate the peer has received the key update yet.
mattm5c7090d2020-10-19 10:36:43 -0700245 virtual void OnKeyUpdate(KeyUpdateReason reason) = 0;
mattm072a7e32020-10-09 16:16:56 -0700246
247 // Called on the first decrypted packet in each key phase (including the
248 // first key phase.)
249 virtual void OnDecryptedFirstPacketInKeyPhase() = 0;
250
251 // Called when the framer needs to generate a decrypter for the next key
252 // phase. Each call should generate the key for phase n+1.
253 virtual std::unique_ptr<QuicDecrypter>
254 AdvanceKeysAndCreateCurrentOneRttDecrypter() = 0;
255
256 // Called when the framer needs to generate an encrypter. The key corresponds
257 // to the key phase of the last decrypter returned by
258 // AdvanceKeysAndCreateCurrentOneRttDecrypter().
259 virtual std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() = 0;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500260};
261
262// Class for parsing and constructing QUIC packets. It has a
263// QuicFramerVisitorInterface that is called when packets are parsed.
264class QUIC_EXPORT_PRIVATE QuicFramer {
265 public:
266 // Constructs a new framer that installs a kNULL QuicEncrypter and
QUICHE team6987b4a2019-03-15 16:23:04 -0700267 // QuicDecrypter for level ENCRYPTION_INITIAL. |supported_versions| specifies
268 // the list of supported QUIC versions. |quic_version_| is set to the maximum
QUICHE teama6ef0a62019-03-07 20:34:33 -0500269 // version in |supported_versions|.
270 QuicFramer(const ParsedQuicVersionVector& supported_versions,
271 QuicTime creation_time,
272 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700273 uint8_t expected_server_connection_id_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500274 QuicFramer(const QuicFramer&) = delete;
275 QuicFramer& operator=(const QuicFramer&) = delete;
276
277 virtual ~QuicFramer();
278
279 // Returns true if |version| is a supported transport version.
280 bool IsSupportedTransportVersion(const QuicTransportVersion version) const;
281
282 // Returns true if |version| is a supported protocol version.
283 bool IsSupportedVersion(const ParsedQuicVersion version) const;
284
285 // Set callbacks to be called from the framer. A visitor must be set, or
286 // else the framer will likely crash. It is acceptable for the visitor
287 // to do nothing. If this is called multiple times, only the last visitor
288 // will be used.
289 void set_visitor(QuicFramerVisitorInterface* visitor) { visitor_ = visitor; }
290
291 const ParsedQuicVersionVector& supported_versions() const {
292 return supported_versions_;
293 }
294
295 QuicTransportVersion transport_version() const {
296 return version_.transport_version;
297 }
298
299 ParsedQuicVersion version() const { return version_; }
300
301 void set_version(const ParsedQuicVersion version);
302
vasilvv5cef78e2021-01-30 11:11:14 -0800303 // Does not QUICHE_DCHECK for supported version. Used by tests to set
304 // unsupported version to trigger version negotiation.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500305 void set_version_for_tests(const ParsedQuicVersion version) {
306 version_ = version;
307 }
308
309 QuicErrorCode error() const { return error_; }
310
311 // Allows enabling or disabling of timestamp processing and serialization.
312 void set_process_timestamps(bool process_timestamps) {
313 process_timestamps_ = process_timestamps;
314 }
315
316 // Pass a UDP packet into the framer for parsing.
dschinazi244f6dc2019-05-06 15:45:16 -0700317 // Return true if the packet was processed successfully. |packet| must be a
QUICHE teama6ef0a62019-03-07 20:34:33 -0500318 // single, complete UDP packet (not a frame of a packet). This packet
319 // might be null padded past the end of the payload, which will be correctly
320 // ignored.
321 bool ProcessPacket(const QuicEncryptedPacket& packet);
322
wub28ecbba2020-10-16 16:13:47 -0700323 // Whether we are in the middle of a call to this->ProcessPacket.
324 bool is_processing_packet() const { return is_processing_packet_; }
325
QUICHE teama6ef0a62019-03-07 20:34:33 -0500326 // Largest size in bytes of all stream frame fields without the payload.
327 static size_t GetMinStreamFrameSize(QuicTransportVersion version,
328 QuicStreamId stream_id,
329 QuicStreamOffset offset,
330 bool last_frame_in_packet,
fkastenholzabfd9ec2019-10-31 07:59:12 -0700331 size_t data_length);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500332 // Returns the overhead of framing a CRYPTO frame with the specific offset and
333 // data length provided, but not counting the size of the data payload.
334 static size_t GetMinCryptoFrameSize(QuicStreamOffset offset,
335 QuicPacketLength data_length);
336 static size_t GetMessageFrameSize(QuicTransportVersion version,
337 bool last_frame_in_packet,
338 QuicByteCount length);
339 // Size in bytes of all ack frame fields without the missing packets or ack
340 // blocks.
fayang43697fd2020-04-21 11:13:43 -0700341 static size_t GetMinAckFrameSize(QuicTransportVersion version,
342 const QuicAckFrame& ack_frame,
343 uint32_t local_ack_delay_exponent);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500344 // Size in bytes of a stop waiting frame.
345 static size_t GetStopWaitingFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500346 QuicPacketNumberLength packet_number_length);
347 // Size in bytes of all reset stream frame fields.
348 static size_t GetRstStreamFrameSize(QuicTransportVersion version,
349 const QuicRstStreamFrame& frame);
haoyuewang6a6a0ff2020-06-23 16:32:26 -0700350 // Size in bytes of all ack frenquency frame fields.
351 static size_t GetAckFrequencyFrameSize(const QuicAckFrequencyFrame& frame);
fkastenholza037b8b2019-05-07 06:00:05 -0700352 // Size in bytes of all connection close frame fields, including the error
353 // details.
354 static size_t GetConnectionCloseFrameSize(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500355 QuicTransportVersion version,
356 const QuicConnectionCloseFrame& frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500357 // Size in bytes of all GoAway frame fields without the reason phrase.
358 static size_t GetMinGoAwayFrameSize();
359 // Size in bytes of all WindowUpdate frame fields.
360 // For version 99, determines whether a MAX DATA or MAX STREAM DATA frame will
361 // be generated and calculates the appropriate size.
362 static size_t GetWindowUpdateFrameSize(QuicTransportVersion version,
363 const QuicWindowUpdateFrame& frame);
364 // Size in bytes of all MaxStreams frame fields.
365 static size_t GetMaxStreamsFrameSize(QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700366 const QuicMaxStreamsFrame& frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500367 // Size in bytes of all StreamsBlocked frame fields.
368 static size_t GetStreamsBlockedFrameSize(
369 QuicTransportVersion version,
fkastenholz3c4eabf2019-04-22 07:49:59 -0700370 const QuicStreamsBlockedFrame& frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500371 // Size in bytes of all Blocked frame fields.
372 static size_t GetBlockedFrameSize(QuicTransportVersion version,
373 const QuicBlockedFrame& frame);
374 // Size in bytes of PathChallenge frame.
375 static size_t GetPathChallengeFrameSize(const QuicPathChallengeFrame& frame);
376 // Size in bytes of PathResponse frame.
377 static size_t GetPathResponseFrameSize(const QuicPathResponseFrame& frame);
378 // Size in bytes required to serialize the stream id.
379 static size_t GetStreamIdSize(QuicStreamId stream_id);
380 // Size in bytes required to serialize the stream offset.
renjietang488201d2019-12-17 13:40:49 -0800381 static size_t GetStreamOffsetSize(QuicStreamOffset offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500382 // Size in bytes for a serialized new connection id frame
383 static size_t GetNewConnectionIdFrameSize(
384 const QuicNewConnectionIdFrame& frame);
385
386 // Size in bytes for a serialized retire connection id frame
387 static size_t GetRetireConnectionIdFrameSize(
388 const QuicRetireConnectionIdFrame& frame);
389
390 // Size in bytes for a serialized new token frame
391 static size_t GetNewTokenFrameSize(const QuicNewTokenFrame& frame);
392
393 // Size in bytes required for a serialized stop sending frame.
394 static size_t GetStopSendingFrameSize(const QuicStopSendingFrame& frame);
395
396 // Size in bytes required for a serialized retransmittable control |frame|.
397 static size_t GetRetransmittableControlFrameSize(QuicTransportVersion version,
398 const QuicFrame& frame);
399
400 // Returns the number of bytes added to the packet for the specified frame,
401 // and 0 if the frame doesn't fit. Includes the header size for the first
402 // frame.
403 size_t GetSerializedFrameLength(const QuicFrame& frame,
404 size_t free_bytes,
405 bool first_frame_in_packet,
406 bool last_frame_in_packet,
407 QuicPacketNumberLength packet_number_length);
408
409 // Returns the associated data from the encrypted packet |encrypted| as a
410 // stringpiece.
vasilvvc872ee42020-10-07 19:50:22 -0700411 static absl::string_view GetAssociatedDataFromEncryptedPacket(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500412 QuicTransportVersion version,
413 const QuicEncryptedPacket& encrypted,
414 QuicConnectionIdLength destination_connection_id_length,
415 QuicConnectionIdLength source_connection_id_length,
416 bool includes_version,
417 bool includes_diversification_nonce,
418 QuicPacketNumberLength packet_number_length,
419 QuicVariableLengthIntegerLength retry_token_length_length,
420 uint64_t retry_token_length,
421 QuicVariableLengthIntegerLength length_length);
422
dschinazi9d3ba8d2020-10-07 16:18:07 -0700423 // Parses the unencrypted fields in a QUIC header using |reader| as input,
dschinazi48ac9192019-07-31 00:07:26 -0700424 // stores the result in the other parameters.
425 // |expected_destination_connection_id_length| is only used for short headers.
426 static QuicErrorCode ParsePublicHeader(
427 QuicDataReader* reader,
428 uint8_t expected_destination_connection_id_length,
429 bool ietf_format,
430 uint8_t* first_byte,
431 PacketHeaderFormat* format,
432 bool* version_present,
433 bool* has_length_prefix,
434 QuicVersionLabel* version_label,
435 ParsedQuicVersion* parsed_version,
436 QuicConnectionId* destination_connection_id,
437 QuicConnectionId* source_connection_id,
438 QuicLongHeaderType* long_packet_type,
439 QuicVariableLengthIntegerLength* retry_token_length_length,
vasilvvc872ee42020-10-07 19:50:22 -0700440 absl::string_view* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -0700441 std::string* detailed_error);
442
dschinazi9d3ba8d2020-10-07 16:18:07 -0700443 // Parses the unencrypted fields in |packet| and stores them in the other
dschinazi48ac9192019-07-31 00:07:26 -0700444 // parameters. This can only be called on the server.
445 // |expected_destination_connection_id_length| is only used for short headers.
446 static QuicErrorCode ParsePublicHeaderDispatcher(
447 const QuicEncryptedPacket& packet,
448 uint8_t expected_destination_connection_id_length,
449 PacketHeaderFormat* format,
fayange3f2f7b2019-09-19 17:01:57 -0700450 QuicLongHeaderType* long_packet_type,
dschinazi48ac9192019-07-31 00:07:26 -0700451 bool* version_present,
452 bool* has_length_prefix,
453 QuicVersionLabel* version_label,
454 ParsedQuicVersion* parsed_version,
455 QuicConnectionId* destination_connection_id,
456 QuicConnectionId* source_connection_id,
457 bool* retry_token_present,
vasilvvc872ee42020-10-07 19:50:22 -0700458 absl::string_view* retry_token,
dschinazi48ac9192019-07-31 00:07:26 -0700459 std::string* detailed_error);
460
QUICHE teama6ef0a62019-03-07 20:34:33 -0500461 // Serializes a packet containing |frames| into |buffer|.
462 // Returns the length of the packet, which must not be longer than
463 // |packet_length|. Returns 0 if it fails to serialize.
464 size_t BuildDataPacket(const QuicPacketHeader& header,
465 const QuicFrames& frames,
466 char* buffer,
467 size_t packet_length,
468 EncryptionLevel level);
469
QUICHE teama6ef0a62019-03-07 20:34:33 -0500470 // Returns a new public reset packet.
471 static std::unique_ptr<QuicEncryptedPacket> BuildPublicResetPacket(
472 const QuicPublicResetPacket& packet);
473
fayang11cdc522021-03-15 13:54:05 -0700474 // Returns the minimal stateless reset packet length.
475 static size_t GetMinStatelessResetPacketLength();
476
QUICHE teama6ef0a62019-03-07 20:34:33 -0500477 // Returns a new IETF stateless reset packet.
478 static std::unique_ptr<QuicEncryptedPacket> BuildIetfStatelessResetPacket(
479 QuicConnectionId connection_id,
fayang11cdc522021-03-15 13:54:05 -0700480 size_t received_packet_length,
bnc1ccd0bc2021-04-07 10:20:17 -0700481 StatelessResetToken stateless_reset_token);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500482
483 // Returns a new version negotiation packet.
484 static std::unique_ptr<QuicEncryptedPacket> BuildVersionNegotiationPacket(
dschinazib417d602019-05-29 13:08:45 -0700485 QuicConnectionId server_connection_id,
486 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500487 bool ietf_quic,
dschinazi48ac9192019-07-31 00:07:26 -0700488 bool use_length_prefix,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500489 const ParsedQuicVersionVector& versions);
490
491 // Returns a new IETF version negotiation packet.
492 static std::unique_ptr<QuicEncryptedPacket> BuildIetfVersionNegotiationPacket(
dschinazi48ac9192019-07-31 00:07:26 -0700493 bool use_length_prefix,
dschinazib417d602019-05-29 13:08:45 -0700494 QuicConnectionId server_connection_id,
495 QuicConnectionId client_connection_id,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500496 const ParsedQuicVersionVector& versions);
497
498 // If header.version_flag is set, the version in the
499 // packet will be set -- but it will be set from version_ not
500 // header.versions.
501 bool AppendPacketHeader(const QuicPacketHeader& header,
502 QuicDataWriter* writer,
503 size_t* length_field_offset);
504 bool AppendIetfHeaderTypeByte(const QuicPacketHeader& header,
505 QuicDataWriter* writer);
506 bool AppendIetfPacketHeader(const QuicPacketHeader& header,
507 QuicDataWriter* writer,
508 size_t* length_field_offset);
509 bool WriteIetfLongHeaderLength(const QuicPacketHeader& header,
510 QuicDataWriter* writer,
511 size_t length_field_offset,
512 EncryptionLevel level);
513 bool AppendTypeByte(const QuicFrame& frame,
514 bool last_frame_in_packet,
515 QuicDataWriter* writer);
haoyuewangbe38a7d2020-06-23 10:18:35 -0700516 bool AppendIetfFrameType(const QuicFrame& frame,
517 bool last_frame_in_packet,
518 QuicDataWriter* writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500519 size_t AppendIetfFrames(const QuicFrames& frames, QuicDataWriter* writer);
520 bool AppendStreamFrame(const QuicStreamFrame& frame,
521 bool last_frame_in_packet,
522 QuicDataWriter* writer);
523 bool AppendCryptoFrame(const QuicCryptoFrame& frame, QuicDataWriter* writer);
haoyuewang6a6a0ff2020-06-23 16:32:26 -0700524 bool AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame,
525 QuicDataWriter* writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500526
527 // SetDecrypter sets the primary decrypter, replacing any that already exists.
vasilvv5cef78e2021-01-30 11:11:14 -0800528 // If an alternative decrypter is in place then the function QUICHE_DCHECKs.
529 // This is intended for cases where one knows that future packets will be
530 // using the new decrypter and the previous decrypter is now obsolete. |level|
531 // indicates the encryption level of the new decrypter.
QUICHE teama6ef0a62019-03-07 20:34:33 -0500532 void SetDecrypter(EncryptionLevel level,
533 std::unique_ptr<QuicDecrypter> decrypter);
534
535 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
536 // future packets. |level| indicates the encryption level of the decrypter. If
537 // |latch_once_used| is true, then the first time that the decrypter is
538 // successful it will replace the primary decrypter. Otherwise both
539 // decrypters will remain active and the primary decrypter will be the one
540 // last used.
541 void SetAlternativeDecrypter(EncryptionLevel level,
542 std::unique_ptr<QuicDecrypter> decrypter,
543 bool latch_once_used);
544
zhongyi546cc452019-04-12 15:27:49 -0700545 void InstallDecrypter(EncryptionLevel level,
546 std::unique_ptr<QuicDecrypter> decrypter);
547 void RemoveDecrypter(EncryptionLevel level);
548
mattm072a7e32020-10-09 16:16:56 -0700549 // Enables key update support.
550 void SetKeyUpdateSupportForConnection(bool enabled);
551 // Discard the decrypter for the previous key phase.
552 void DiscardPreviousOneRttKeys();
553 // Update the key phase.
mattm5c7090d2020-10-19 10:36:43 -0700554 bool DoKeyUpdate(KeyUpdateReason reason);
mattmd061ef12020-10-23 11:21:31 -0700555 // Returns the count of packets received that appeared to attempt a key
556 // update but failed decryption which have been received since the last
557 // successfully decrypted packet.
558 QuicPacketCount PotentialPeerKeyUpdateAttemptCount() const;
mattm072a7e32020-10-09 16:16:56 -0700559
zhongyi546cc452019-04-12 15:27:49 -0700560 const QuicDecrypter* GetDecrypter(EncryptionLevel level) const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500561 const QuicDecrypter* decrypter() const;
562 const QuicDecrypter* alternative_decrypter() const;
563
564 // Changes the encrypter used for level |level| to |encrypter|.
565 void SetEncrypter(EncryptionLevel level,
566 std::unique_ptr<QuicEncrypter> encrypter);
567
fayangb296fb82020-02-11 08:14:28 -0800568 // Called to remove encrypter of encryption |level|.
569 void RemoveEncrypter(EncryptionLevel level);
570
nharper4a5a76c2019-09-13 13:44:37 -0700571 // Sets the encrypter and decrypter for the ENCRYPTION_INITIAL level.
572 void SetInitialObfuscators(QuicConnectionId connection_id);
573
QUICHE teama6ef0a62019-03-07 20:34:33 -0500574 // Encrypts a payload in |buffer|. |ad_len| is the length of the associated
575 // data. |total_len| is the length of the associated data plus plaintext.
576 // |buffer_len| is the full length of the allocated buffer.
577 size_t EncryptInPlace(EncryptionLevel level,
578 QuicPacketNumber packet_number,
579 size_t ad_len,
580 size_t total_len,
581 size_t buffer_len,
582 char* buffer);
583
584 // Returns the length of the data encrypted into |buffer| if |buffer_len| is
585 // long enough, and otherwise 0.
586 size_t EncryptPayload(EncryptionLevel level,
587 QuicPacketNumber packet_number,
588 const QuicPacket& packet,
589 char* buffer,
590 size_t buffer_len);
591
592 // Returns the length of the ciphertext that would be generated by encrypting
593 // to plaintext of size |plaintext_size| at the given level.
594 size_t GetCiphertextSize(EncryptionLevel level, size_t plaintext_size) const;
595
596 // Returns the maximum length of plaintext that can be encrypted
597 // to ciphertext no larger than |ciphertext_size|.
598 size_t GetMaxPlaintextSize(size_t ciphertext_size);
599
mattmd0744852020-10-16 14:42:01 -0700600 // Returns the maximum number of packets that can be safely encrypted with
601 // the active AEAD. 1-RTT keys must be set before calling this method.
602 QuicPacketCount GetOneRttEncrypterConfidentialityLimit() const;
603
vasilvvc48c8712019-03-11 13:38:16 -0700604 const std::string& detailed_error() { return detailed_error_; }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500605
606 // The minimum packet number length required to represent |packet_number|.
607 static QuicPacketNumberLength GetMinPacketNumberLength(
QUICHE teama6ef0a62019-03-07 20:34:33 -0500608 QuicPacketNumber packet_number);
609
610 void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
611 supported_versions_ = versions;
612 version_ = versions[0];
613 }
614
615 // Tell framer to infer packet header type from version_.
616 void InferPacketHeaderTypeFromVersion();
617
QUICHE teama6ef0a62019-03-07 20:34:33 -0500618 // Returns true if |header| is considered as an stateless reset packet.
619 bool IsIetfStatelessResetPacket(const QuicPacketHeader& header) const;
620
621 // Returns true if encrypter of |level| is available.
622 bool HasEncrypterOfEncryptionLevel(EncryptionLevel level) const;
fayang750b54f2020-06-18 06:26:54 -0700623 // Returns true if decrypter of |level| is available.
624 bool HasDecrypterOfEncryptionLevel(EncryptionLevel level) const;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500625
fayangd01e9962020-09-24 11:29:31 -0700626 // Returns true if an encrypter of |space| is available.
627 bool HasAnEncrypterForSpace(PacketNumberSpace space) const;
628
fayang9c41f8b2020-10-30 13:13:06 -0700629 // Returns the encryption level to send application data. This should be only
630 // called with available encrypter for application data.
631 EncryptionLevel GetEncryptionLevelToSendApplicationData() const;
632
QUICHE teama6ef0a62019-03-07 20:34:33 -0500633 void set_validate_flags(bool value) { validate_flags_ = value; }
634
635 Perspective perspective() const { return perspective_; }
636
dschinazicb6b5102021-04-28 08:16:40 -0700637 QuicStreamFrameDataProducer* data_producer() const { return data_producer_; }
638
QUICHE teama6ef0a62019-03-07 20:34:33 -0500639 void set_data_producer(QuicStreamFrameDataProducer* data_producer) {
640 data_producer_ = data_producer;
641 }
642
QUICHE teama6ef0a62019-03-07 20:34:33 -0500643 QuicTime creation_time() const { return creation_time_; }
644
645 QuicPacketNumber first_sending_packet_number() const {
646 return first_sending_packet_number_;
647 }
648
fkastenholza3660102019-08-28 05:19:24 -0700649 uint64_t current_received_frame_type() const {
650 return current_received_frame_type_;
651 }
652
dschinazi8ff74822019-05-28 16:37:20 -0700653 // The connection ID length the framer expects on incoming IETF short headers
654 // on the server.
655 uint8_t GetExpectedServerConnectionIdLength() {
656 return expected_server_connection_id_length_;
QUICHE team8e2e4532019-03-14 14:37:56 -0700657 }
658
dschinazi346b7ce2019-06-05 01:38:18 -0700659 // Change the expected destination connection ID length for short headers on
660 // the client.
661 void SetExpectedClientConnectionIdLength(
662 uint8_t expected_client_connection_id_length) {
663 expected_client_connection_id_length_ =
664 expected_client_connection_id_length;
665 }
666
QUICHE team10b22a12019-03-21 15:31:42 -0700667 void EnableMultiplePacketNumberSpacesSupport();
668
dschinazide0f6dc2019-05-15 16:10:11 -0700669 // Writes an array of bytes that, if sent as a UDP datagram, will trigger
670 // IETF QUIC Version Negotiation on servers. The bytes will be written to
671 // |packet_bytes|, which must point to |packet_length| bytes of memory.
672 // |packet_length| must be in the range [1200, 65535].
673 // |destination_connection_id_bytes| will be sent as the destination
674 // connection ID, and must point to |destination_connection_id_length| bytes
dschinazi19dc2b52019-07-17 19:54:43 -0700675 // of memory. |destination_connection_id_length| must be in the range [8,18].
676 // When targeting Google servers, it is recommended to use a
dschinazide0f6dc2019-05-15 16:10:11 -0700677 // |destination_connection_id_length| of 8.
678 static bool WriteClientVersionNegotiationProbePacket(
679 char* packet_bytes,
680 QuicByteCount packet_length,
681 const char* destination_connection_id_bytes,
682 uint8_t destination_connection_id_length);
683
684 // Parses a packet which a QUIC server sent in response to a packet sent by
685 // WriteClientVersionNegotiationProbePacket. |packet_bytes| must point to
686 // |packet_length| bytes in memory which represent the response.
687 // |packet_length| must be greater or equal to 6. This method will fill in
dschinazi9d3ba8d2020-10-07 16:18:07 -0700688 // |source_connection_id_bytes| which must point to at least
689 // |*source_connection_id_length_out| bytes in memory.
690 // |*source_connection_id_length_out| must be at least 18.
691 // |*source_connection_id_length_out| will contain the length of the received
692 // source connection ID, which on success will match the contents of the
693 // destination connection ID passed in to
dschinazide0f6dc2019-05-15 16:10:11 -0700694 // WriteClientVersionNegotiationProbePacket. In the case of a failure,
695 // |detailed_error| will be filled in with an explanation of what failed.
696 static bool ParseServerVersionNegotiationProbeResponse(
697 const char* packet_bytes,
698 QuicByteCount packet_length,
699 char* source_connection_id_bytes,
700 uint8_t* source_connection_id_length_out,
701 std::string* detailed_error);
702
fkastenholz4dc4ba32019-07-30 09:55:25 -0700703 void set_local_ack_delay_exponent(uint32_t exponent) {
704 local_ack_delay_exponent_ = exponent;
705 }
706 uint32_t local_ack_delay_exponent() const {
707 return local_ack_delay_exponent_;
708 }
709
710 void set_peer_ack_delay_exponent(uint32_t exponent) {
711 peer_ack_delay_exponent_ = exponent;
712 }
713 uint32_t peer_ack_delay_exponent() const { return peer_ack_delay_exponent_; }
714
dschinazi8ea59422020-12-15 10:44:03 -0800715 void set_drop_incoming_retry_packets(bool drop_incoming_retry_packets) {
716 drop_incoming_retry_packets_ = drop_incoming_retry_packets;
717 }
718
QUICHE teama6ef0a62019-03-07 20:34:33 -0500719 private:
720 friend class test::QuicFramerPeer;
721
renjietang58b3af32020-11-11 15:48:58 -0800722 using NackRangeMap = std::map<QuicPacketNumber, uint8_t>;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500723
dschinazif25169a2019-10-23 08:12:18 -0700724 struct QUIC_EXPORT_PRIVATE AckFrameInfo {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500725 AckFrameInfo();
726 AckFrameInfo(const AckFrameInfo& other);
727 ~AckFrameInfo();
728
729 // The maximum ack block length.
730 QuicPacketCount max_block_length;
731 // Length of first ack block.
732 QuicPacketCount first_block_length;
733 // Number of ACK blocks needed for the ACK frame.
734 size_t num_ack_blocks;
735 };
736
nharper55fa6132019-05-07 19:37:21 -0700737 // Applies header protection to an IETF QUIC packet header in |buffer| using
738 // the encrypter for level |level|. The buffer has |buffer_len| bytes of data,
739 // with the first protected packet bytes starting at |ad_len|.
740 bool ApplyHeaderProtection(EncryptionLevel level,
741 char* buffer,
742 size_t buffer_len,
743 size_t ad_len);
744
745 // Removes header protection from an IETF QUIC packet header.
746 //
747 // The packet number from the header is read from |reader|, where the packet
748 // number is the next contents in |reader|. |reader| is only advanced by the
749 // length of the packet number, but it is also used to peek the sample needed
750 // for removing header protection.
751 //
752 // Properties needed for removing header protection are read from |header|.
753 // The packet number length and type byte are written to |header|.
754 //
755 // The packet number, after removing header protection and decoding it, is
756 // written to |full_packet_number|. Finally, the header, with header
757 // protection removed, is written to |associated_data| to be used in packet
758 // decryption. |packet| is used in computing the asociated data.
759 bool RemoveHeaderProtection(QuicDataReader* reader,
760 const QuicEncryptedPacket& packet,
761 QuicPacketHeader* header,
762 uint64_t* full_packet_number,
763 std::vector<char>* associated_data);
764
QUICHE teama6ef0a62019-03-07 20:34:33 -0500765 bool ProcessDataPacket(QuicDataReader* reader,
766 QuicPacketHeader* header,
767 const QuicEncryptedPacket& packet,
768 char* decrypted_buffer,
769 size_t buffer_length);
770
771 bool ProcessIetfDataPacket(QuicDataReader* encrypted_reader,
772 QuicPacketHeader* header,
773 const QuicEncryptedPacket& packet,
774 char* decrypted_buffer,
775 size_t buffer_length);
776
777 bool ProcessPublicResetPacket(QuicDataReader* reader,
778 const QuicPacketHeader& header);
779
780 bool ProcessVersionNegotiationPacket(QuicDataReader* reader,
781 const QuicPacketHeader& header);
782
dschinazi244f6dc2019-05-06 15:45:16 -0700783 bool ProcessRetryPacket(QuicDataReader* reader,
784 const QuicPacketHeader& header);
785
QUICHE teama6ef0a62019-03-07 20:34:33 -0500786 void MaybeProcessCoalescedPacket(const QuicDataReader& encrypted_reader,
787 uint64_t remaining_bytes_length,
788 const QuicPacketHeader& header);
789
790 bool MaybeProcessIetfLength(QuicDataReader* encrypted_reader,
791 QuicPacketHeader* header);
792
793 bool ProcessPublicHeader(QuicDataReader* reader,
794 bool packet_has_ietf_packet_header,
795 QuicPacketHeader* header);
796
797 // Processes the unauthenticated portion of the header into |header| from
798 // the current QuicDataReader. Returns true on success, false on failure.
799 bool ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader,
800 QuicPacketHeader* header);
801
fayang40315542019-05-09 09:19:09 -0700802 // Processes the version label in the packet header.
803 static bool ProcessVersionLabel(QuicDataReader* reader,
804 QuicVersionLabel* version_label);
805
806 // Validates and updates |destination_connection_id_length| and
dschinazi334f0232019-05-29 16:08:53 -0700807 // |source_connection_id_length|. When
808 // |should_update_expected_server_connection_id_length| is true, length
809 // validation is disabled and |expected_server_connection_id_length| is set
810 // to the appropriate length.
811 // TODO(b/133873272) refactor this method.
fayangccbab732019-05-13 10:11:25 -0700812 static bool ProcessAndValidateIetfConnectionIdLength(
813 QuicDataReader* reader,
fayang40315542019-05-09 09:19:09 -0700814 ParsedQuicVersion version,
dschinazi334f0232019-05-29 16:08:53 -0700815 Perspective perspective,
dschinazi8ff74822019-05-28 16:37:20 -0700816 bool should_update_expected_server_connection_id_length,
817 uint8_t* expected_server_connection_id_length,
fayang40315542019-05-09 09:19:09 -0700818 uint8_t* destination_connection_id_length,
fayangccbab732019-05-13 10:11:25 -0700819 uint8_t* source_connection_id_length,
820 std::string* detailed_error);
fayang40315542019-05-09 09:19:09 -0700821
QUICHE teama6ef0a62019-03-07 20:34:33 -0500822 bool ProcessIetfHeaderTypeByte(QuicDataReader* reader,
823 QuicPacketHeader* header);
824 bool ProcessIetfPacketHeader(QuicDataReader* reader,
825 QuicPacketHeader* header);
826
827 // First processes possibly truncated packet number. Calculates the full
828 // packet number from the truncated one and the last seen packet number, and
829 // stores it to |packet_number|.
830 bool ProcessAndCalculatePacketNumber(
831 QuicDataReader* reader,
832 QuicPacketNumberLength packet_number_length,
833 QuicPacketNumber base_packet_number,
834 uint64_t* packet_number);
835 bool ProcessFrameData(QuicDataReader* reader, const QuicPacketHeader& header);
haoyuewangfef3e302021-03-03 10:31:12 -0800836
837 static bool IsIetfFrameTypeExpectedForEncryptionLevel(uint64_t frame_type,
838 EncryptionLevel level);
839
QUICHE teama6ef0a62019-03-07 20:34:33 -0500840 bool ProcessIetfFrameData(QuicDataReader* reader,
haoyuewangfef3e302021-03-03 10:31:12 -0800841 const QuicPacketHeader& header,
842 EncryptionLevel decrypted_level);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500843 bool ProcessStreamFrame(QuicDataReader* reader,
844 uint8_t frame_type,
845 QuicStreamFrame* frame);
846 bool ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type);
847 bool ProcessTimestampsInAckFrame(uint8_t num_received_packets,
848 QuicPacketNumber largest_acked,
849 QuicDataReader* reader);
850 bool ProcessIetfAckFrame(QuicDataReader* reader,
851 uint64_t frame_type,
852 QuicAckFrame* ack_frame);
853 bool ProcessStopWaitingFrame(QuicDataReader* reader,
854 const QuicPacketHeader& header,
855 QuicStopWaitingFrame* stop_waiting);
856 bool ProcessRstStreamFrame(QuicDataReader* reader, QuicRstStreamFrame* frame);
857 bool ProcessConnectionCloseFrame(QuicDataReader* reader,
858 QuicConnectionCloseFrame* frame);
859 bool ProcessGoAwayFrame(QuicDataReader* reader, QuicGoAwayFrame* frame);
860 bool ProcessWindowUpdateFrame(QuicDataReader* reader,
861 QuicWindowUpdateFrame* frame);
862 bool ProcessBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame);
863 void ProcessPaddingFrame(QuicDataReader* reader, QuicPaddingFrame* frame);
864 bool ProcessMessageFrame(QuicDataReader* reader,
865 bool no_message_length,
866 QuicMessageFrame* frame);
867
fayang93b4e4d2020-11-25 07:56:47 -0800868 bool DecryptPayload(size_t udp_packet_length,
869 absl::string_view encrypted,
vasilvvc872ee42020-10-07 19:50:22 -0700870 absl::string_view associated_data,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500871 const QuicPacketHeader& header,
872 char* decrypted_buffer,
873 size_t buffer_length,
QUICHE team10b22a12019-03-21 15:31:42 -0700874 size_t* decrypted_length,
875 EncryptionLevel* decrypted_level);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500876
877 // Returns the full packet number from the truncated
878 // wire format version and the last seen packet number.
879 uint64_t CalculatePacketNumberFromWire(
880 QuicPacketNumberLength packet_number_length,
881 QuicPacketNumber base_packet_number,
882 uint64_t packet_number) const;
883
884 // Returns the QuicTime::Delta corresponding to the time from when the framer
885 // was created.
886 const QuicTime::Delta CalculateTimestampFromWire(uint32_t time_delta_us);
887
888 // Computes the wire size in bytes of time stamps in |ack|.
889 size_t GetAckFrameTimeStampSize(const QuicAckFrame& ack);
890
891 // Computes the wire size in bytes of the |ack| frame.
892 size_t GetAckFrameSize(const QuicAckFrame& ack,
893 QuicPacketNumberLength packet_number_length);
894 // Computes the wire-size, in bytes, of the |frame| ack frame, for IETF Quic.
895 size_t GetIetfAckFrameSize(const QuicAckFrame& frame);
896
897 // Computes the wire size in bytes of the |ack| frame.
898 size_t GetAckFrameSize(const QuicAckFrame& ack);
899
900 // Computes the wire size in bytes of the payload of |frame|.
901 size_t ComputeFrameLength(const QuicFrame& frame,
902 bool last_frame_in_packet,
903 QuicPacketNumberLength packet_number_length);
904
905 static bool AppendPacketNumber(QuicPacketNumberLength packet_number_length,
906 QuicPacketNumber packet_number,
907 QuicDataWriter* writer);
908 static bool AppendStreamId(size_t stream_id_length,
909 QuicStreamId stream_id,
910 QuicDataWriter* writer);
911 static bool AppendStreamOffset(size_t offset_length,
912 QuicStreamOffset offset,
913 QuicDataWriter* writer);
914
915 // Appends a single ACK block to |writer| and returns true if the block was
916 // successfully appended.
917 static bool AppendAckBlock(uint8_t gap,
918 QuicPacketNumberLength length_length,
919 uint64_t length,
920 QuicDataWriter* writer);
921
922 static uint8_t GetPacketNumberFlags(
923 QuicPacketNumberLength packet_number_length);
924
925 static AckFrameInfo GetAckFrameInfo(const QuicAckFrame& frame);
926
dschinazi48ac9192019-07-31 00:07:26 -0700927 static QuicErrorCode ParsePublicHeaderGoogleQuic(
928 QuicDataReader* reader,
929 uint8_t* first_byte,
930 PacketHeaderFormat* format,
931 bool* version_present,
932 QuicVersionLabel* version_label,
dschinazi243eabc2019-08-05 16:15:29 -0700933 ParsedQuicVersion* parsed_version,
dschinazi48ac9192019-07-31 00:07:26 -0700934 QuicConnectionId* destination_connection_id,
935 std::string* detailed_error);
936
dschinazib953d022019-08-01 18:05:58 -0700937 bool ValidateReceivedConnectionIds(const QuicPacketHeader& header);
938
QUICHE teama6ef0a62019-03-07 20:34:33 -0500939 // The Append* methods attempt to write the provided header or frame using the
940 // |writer|, and return true if successful.
941
942 bool AppendAckFrameAndTypeByte(const QuicAckFrame& frame,
943 QuicDataWriter* builder);
944 bool AppendTimestampsToAckFrame(const QuicAckFrame& frame,
945 QuicDataWriter* writer);
946
947 // Append IETF format ACK frame.
948 //
949 // AppendIetfAckFrameAndTypeByte adds the IETF type byte and the body
950 // of the frame.
951 bool AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame,
952 QuicDataWriter* writer);
953
QUICHE teama6ef0a62019-03-07 20:34:33 -0500954 bool AppendStopWaitingFrame(const QuicPacketHeader& header,
955 const QuicStopWaitingFrame& frame,
956 QuicDataWriter* builder);
957 bool AppendRstStreamFrame(const QuicRstStreamFrame& frame,
958 QuicDataWriter* builder);
959 bool AppendConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
960 QuicDataWriter* builder);
961 bool AppendGoAwayFrame(const QuicGoAwayFrame& frame, QuicDataWriter* writer);
962 bool AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
963 QuicDataWriter* writer);
964 bool AppendBlockedFrame(const QuicBlockedFrame& frame,
965 QuicDataWriter* writer);
966 bool AppendPaddingFrame(const QuicPaddingFrame& frame,
967 QuicDataWriter* writer);
968 bool AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame,
969 bool last_frame_in_packet,
970 QuicDataWriter* writer);
971
972 // IETF frame processing methods.
973 bool ProcessIetfStreamFrame(QuicDataReader* reader,
974 uint8_t frame_type,
975 QuicStreamFrame* frame);
976 bool ProcessIetfConnectionCloseFrame(QuicDataReader* reader,
fkastenholze9d71a82019-04-09 05:12:13 -0700977 QuicConnectionCloseType type,
QUICHE teama6ef0a62019-03-07 20:34:33 -0500978 QuicConnectionCloseFrame* frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500979 bool ProcessPathChallengeFrame(QuicDataReader* reader,
980 QuicPathChallengeFrame* frame);
981 bool ProcessPathResponseFrame(QuicDataReader* reader,
982 QuicPathResponseFrame* frame);
983 bool ProcessIetfResetStreamFrame(QuicDataReader* reader,
984 QuicRstStreamFrame* frame);
985 bool ProcessStopSendingFrame(QuicDataReader* reader,
986 QuicStopSendingFrame* stop_sending_frame);
renjietang15dfaa82020-01-03 16:13:38 -0800987 bool ProcessCryptoFrame(QuicDataReader* reader,
988 EncryptionLevel encryption_level,
989 QuicCryptoFrame* frame);
haoyuewang6a6a0ff2020-06-23 16:32:26 -0700990 bool ProcessAckFrequencyFrame(QuicDataReader* reader,
991 QuicAckFrequencyFrame* frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500992 // IETF frame appending methods. All methods append the type byte as well.
993 bool AppendIetfStreamFrame(const QuicStreamFrame& frame,
994 bool last_frame_in_packet,
995 QuicDataWriter* writer);
996 bool AppendIetfConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
997 QuicDataWriter* writer);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500998 bool AppendPathChallengeFrame(const QuicPathChallengeFrame& frame,
999 QuicDataWriter* writer);
1000 bool AppendPathResponseFrame(const QuicPathResponseFrame& frame,
1001 QuicDataWriter* writer);
1002 bool AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame,
1003 QuicDataWriter* writer);
1004 bool AppendStopSendingFrame(const QuicStopSendingFrame& stop_sending_frame,
1005 QuicDataWriter* writer);
1006
1007 // Append/consume IETF-Format MAX_DATA and MAX_STREAM_DATA frames
1008 bool AppendMaxDataFrame(const QuicWindowUpdateFrame& frame,
1009 QuicDataWriter* writer);
1010 bool AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame,
1011 QuicDataWriter* writer);
1012 bool ProcessMaxDataFrame(QuicDataReader* reader,
1013 QuicWindowUpdateFrame* frame);
1014 bool ProcessMaxStreamDataFrame(QuicDataReader* reader,
1015 QuicWindowUpdateFrame* frame);
1016
fkastenholz3c4eabf2019-04-22 07:49:59 -07001017 bool AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001018 QuicDataWriter* writer);
1019 bool ProcessMaxStreamsFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07001020 QuicMaxStreamsFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001021 uint64_t frame_type);
1022
renjietangf8a9c8c2020-03-19 16:47:03 -07001023 bool AppendDataBlockedFrame(const QuicBlockedFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001024 QuicDataWriter* writer);
renjietangf8a9c8c2020-03-19 16:47:03 -07001025 bool ProcessDataBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001026
renjietangf8a9c8c2020-03-19 16:47:03 -07001027 bool AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame,
1028 QuicDataWriter* writer);
1029 bool ProcessStreamDataBlockedFrame(QuicDataReader* reader,
1030 QuicBlockedFrame* frame);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001031
fkastenholz3c4eabf2019-04-22 07:49:59 -07001032 bool AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001033 QuicDataWriter* writer);
1034 bool ProcessStreamsBlockedFrame(QuicDataReader* reader,
fkastenholz3c4eabf2019-04-22 07:49:59 -07001035 QuicStreamsBlockedFrame* frame,
QUICHE teama6ef0a62019-03-07 20:34:33 -05001036 uint64_t frame_type);
1037
1038 bool AppendNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame,
1039 QuicDataWriter* writer);
1040 bool ProcessNewConnectionIdFrame(QuicDataReader* reader,
1041 QuicNewConnectionIdFrame* frame);
1042 bool AppendRetireConnectionIdFrame(const QuicRetireConnectionIdFrame& frame,
1043 QuicDataWriter* writer);
1044 bool ProcessRetireConnectionIdFrame(QuicDataReader* reader,
1045 QuicRetireConnectionIdFrame* frame);
1046
1047 bool AppendNewTokenFrame(const QuicNewTokenFrame& frame,
1048 QuicDataWriter* writer);
1049 bool ProcessNewTokenFrame(QuicDataReader* reader, QuicNewTokenFrame* frame);
1050
1051 bool RaiseError(QuicErrorCode error);
1052
1053 // Returns true if |header| indicates a version negotiation packet.
1054 bool IsVersionNegotiation(const QuicPacketHeader& header,
1055 bool packet_has_ietf_packet_header) const;
1056
1057 // Calculates and returns type byte of stream frame.
1058 uint8_t GetStreamFrameTypeByte(const QuicStreamFrame& frame,
1059 bool last_frame_in_packet) const;
1060 uint8_t GetIetfStreamFrameTypeByte(const QuicStreamFrame& frame,
1061 bool last_frame_in_packet) const;
1062
1063 void set_error(QuicErrorCode error) { error_ = error; }
1064
1065 void set_detailed_error(const char* error) { detailed_error_ = error; }
dschinazi48ac9192019-07-31 00:07:26 -07001066 void set_detailed_error(std::string error) { detailed_error_ = error; }
QUICHE teama6ef0a62019-03-07 20:34:33 -05001067
renjietangd077f8c2020-03-23 17:22:09 -07001068 // Returns false if the reading fails.
1069 bool ReadUint32FromVarint62(QuicDataReader* reader,
1070 QuicIetfFrameType type,
1071 QuicStreamId* id);
1072
wub28ecbba2020-10-16 16:13:47 -07001073 bool ProcessPacketInternal(const QuicEncryptedPacket& packet);
1074
vasilvvc48c8712019-03-11 13:38:16 -07001075 std::string detailed_error_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001076 QuicFramerVisitorInterface* visitor_;
1077 QuicErrorCode error_;
1078 // Updated by ProcessPacketHeader when it succeeds decrypting a larger packet.
1079 QuicPacketNumber largest_packet_number_;
QUICHE team10b22a12019-03-21 15:31:42 -07001080 // Largest successfully decrypted packet number per packet number space. Only
1081 // used when supports_multiple_packet_number_spaces_ is true.
1082 QuicPacketNumber largest_decrypted_packet_numbers_[NUM_PACKET_NUMBER_SPACES];
dschinazi7b9278c2019-05-20 07:36:21 -07001083 // Last server connection ID seen on the wire.
1084 QuicConnectionId last_serialized_server_connection_id_;
dschinazi346b7ce2019-06-05 01:38:18 -07001085 // Last client connection ID seen on the wire.
1086 QuicConnectionId last_serialized_client_connection_id_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001087 // Version of the protocol being used.
1088 ParsedQuicVersion version_;
1089 // This vector contains QUIC versions which we currently support.
1090 // This should be ordered such that the highest supported version is the first
1091 // element, with subsequent elements in descending order (versions can be
1092 // skipped as necessary).
1093 ParsedQuicVersionVector supported_versions_;
QUICHE team76086e42019-03-25 15:12:29 -07001094 // Decrypters used to decrypt packets during parsing.
1095 std::unique_ptr<QuicDecrypter> decrypter_[NUM_ENCRYPTION_LEVELS];
1096 // The encryption level of the primary decrypter to use in |decrypter_|.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001097 EncryptionLevel decrypter_level_;
QUICHE team76086e42019-03-25 15:12:29 -07001098 // The encryption level of the alternative decrypter to use in |decrypter_|.
1099 // When set to NUM_ENCRYPTION_LEVELS, indicates that there is no alternative
QUICHE teama6ef0a62019-03-07 20:34:33 -05001100 // decrypter.
QUICHE team76086e42019-03-25 15:12:29 -07001101 EncryptionLevel alternative_decrypter_level_;
1102 // |alternative_decrypter_latch_| is true if, when the decrypter at
1103 // |alternative_decrypter_level_| successfully decrypts a packet, we should
1104 // install it as the only decrypter.
QUICHE teama6ef0a62019-03-07 20:34:33 -05001105 bool alternative_decrypter_latch_;
1106 // Encrypters used to encrypt packets via EncryptPayload().
1107 std::unique_ptr<QuicEncrypter> encrypter_[NUM_ENCRYPTION_LEVELS];
1108 // Tracks if the framer is being used by the entity that received the
1109 // connection or the entity that initiated it.
1110 Perspective perspective_;
1111 // If false, skip validation that the public flags are set to legal values.
1112 bool validate_flags_;
1113 // The diversification nonce from the last received packet.
1114 DiversificationNonce last_nonce_;
1115 // If true, send and process timestamps in the ACK frame.
1116 bool process_timestamps_;
1117 // The creation time of the connection, used to calculate timestamps.
1118 QuicTime creation_time_;
1119 // The last timestamp received if process_timestamps_ is true.
1120 QuicTime::Delta last_timestamp_;
1121
mattm072a7e32020-10-09 16:16:56 -07001122 // Whether IETF QUIC Key Update is supported on this connection.
1123 bool support_key_update_for_connection_;
1124 // The value of the current key phase bit, which is toggled when the keys are
1125 // changed.
1126 bool current_key_phase_bit_;
dschinazi947c8cf2021-03-03 16:20:39 -08001127 // Whether we have performed a key update at least once.
1128 bool key_update_performed_ = false;
mattm072a7e32020-10-09 16:16:56 -07001129 // Tracks the first packet received in the current key phase. Will be
1130 // uninitialized before the first one-RTT packet has been received or after a
1131 // locally initiated key update but before the first packet from the peer in
1132 // the new key phase is received.
1133 QuicPacketNumber current_key_phase_first_received_packet_number_;
mattmd061ef12020-10-23 11:21:31 -07001134 // Counts the number of packets received that might have been failed key
1135 // update attempts. Reset to zero every time a packet is successfully
1136 // decrypted.
1137 QuicPacketCount potential_peer_key_update_attempt_count_;
mattm072a7e32020-10-09 16:16:56 -07001138 // Decrypter for the previous key phase. Will be null if in the first key
1139 // phase or previous keys have been discarded.
1140 std::unique_ptr<QuicDecrypter> previous_decrypter_;
1141 // Decrypter for the next key phase. May be null if next keys haven't been
1142 // generated yet.
1143 std::unique_ptr<QuicDecrypter> next_decrypter_;
1144
QUICHE teama6ef0a62019-03-07 20:34:33 -05001145 // If this is a framer of a connection, this is the packet number of first
1146 // sending packet. If this is a framer of a framer of dispatcher, this is the
1147 // packet number of sent packets (for those which have packet number).
1148 const QuicPacketNumber first_sending_packet_number_;
1149
1150 // If not null, framer asks data_producer_ to write stream frame data. Not
1151 // owned. TODO(fayang): Consider add data producer to framer's constructor.
1152 QuicStreamFrameDataProducer* data_producer_;
1153
wub28ecbba2020-10-16 16:13:47 -07001154 // Whether we are in the middle of a call to this->ProcessPacket.
1155 bool is_processing_packet_ = false;
1156
QUICHE teama6ef0a62019-03-07 20:34:33 -05001157 // If true, framer infers packet header type (IETF/GQUIC) from version_.
1158 // Otherwise, framer infers packet header type from first byte of a received
1159 // packet.
1160 bool infer_packet_header_type_from_version_;
1161
1162 // IETF short headers contain a destination connection ID but do not
dschinazi346b7ce2019-06-05 01:38:18 -07001163 // encode its length. These variables contains the length we expect to read.
1164 // This is also used to validate the long header destination connection ID
1165 // lengths in older versions of QUIC.
dschinazi8ff74822019-05-28 16:37:20 -07001166 uint8_t expected_server_connection_id_length_;
dschinazi346b7ce2019-06-05 01:38:18 -07001167 uint8_t expected_client_connection_id_length_;
QUICHE team4d9d6292019-03-11 14:25:33 -07001168
QUICHE team10b22a12019-03-21 15:31:42 -07001169 // Indicates whether this framer supports multiple packet number spaces.
1170 bool supports_multiple_packet_number_spaces_;
nharper55fa6132019-05-07 19:37:21 -07001171
dschinazi8ea59422020-12-15 10:44:03 -08001172 // Indicates whether received RETRY packets should be dropped.
1173 bool drop_incoming_retry_packets_ = false;
1174
nharper55fa6132019-05-07 19:37:21 -07001175 // The length in bytes of the last packet number written to an IETF-framed
1176 // packet.
1177 size_t last_written_packet_number_length_;
fkastenholz4dc4ba32019-07-30 09:55:25 -07001178
1179 // The amount to shift the ack timestamp in ACK frames. The default is 3.
1180 // Local_ is the amount this node shifts timestamps in ACK frames it
1181 // generates. it is sent to the peer in a transport parameter negotiation.
1182 // Peer_ is the amount the peer shifts timestamps when it sends ACK frames to
1183 // this node. This node "unshifts" by this amount. The value is received from
1184 // the peer in the transport parameter negotiation. IETF QUIC only.
1185 uint32_t peer_ack_delay_exponent_;
1186 uint32_t local_ack_delay_exponent_;
fkastenholza3660102019-08-28 05:19:24 -07001187
1188 // The type of received IETF frame currently being processed. 0 when not
1189 // processing a frame or when processing Google QUIC frames. Used to populate
1190 // the Transport Connection Close when there is an error during frame
1191 // processing.
1192 uint64_t current_received_frame_type_;
QUICHE teama6ef0a62019-03-07 20:34:33 -05001193};
1194
fkastenholzb4dade72019-08-05 06:54:20 -07001195// Look for and parse the error code from the "<quic_error_code>:" text that
1196// may be present at the start of the CONNECTION_CLOSE error details string.
1197// This text, inserted by the peer if it's using Google's QUIC implementation,
fkastenholz488a4622019-08-26 06:24:46 -07001198// contains additional error information that narrows down the exact error. The
1199// extracted error code and (possibly updated) error_details string are returned
bnc77e77b82020-04-05 10:36:49 -07001200// in |*frame|. If an error code is not found in the error details, then
1201// frame->quic_error_code is set to
1202// QuicErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING. If there is an error code in
1203// the string then it is removed from the string.
fkastenholz488a4622019-08-26 06:24:46 -07001204QUIC_EXPORT_PRIVATE void MaybeExtractQuicErrorCode(
1205 QuicConnectionCloseFrame* frame);
fkastenholzb4dade72019-08-05 06:54:20 -07001206
QUICHE teama6ef0a62019-03-07 20:34:33 -05001207} // namespace quic
1208
1209#endif // QUICHE_QUIC_CORE_QUIC_FRAMER_H_