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.
5 #ifndef NET_QUIC_QUIC_FRAMER_H_
6 #define NET_QUIC_QUIC_FRAMER_H_
11 #include "base/basictypes.h"
12 #include "base/logging.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/strings/string_piece.h"
15 #include "net/base/net_export.h"
16 #include "net/quic/quic_protocol.h"
30 // Number of bytes reserved for the frame type preceding each frame.
31 const size_t kQuicFrameTypeSize
= 1;
32 // Number of bytes reserved for error code.
33 const size_t kQuicErrorCodeSize
= 4;
34 // Number of bytes reserved to denote the length of error details field.
35 const size_t kQuicErrorDetailsLengthSize
= 2;
37 // Maximum number of bytes reserved for stream id.
38 const size_t kQuicMaxStreamIdSize
= 4;
39 // Maximum number of bytes reserved for byte offset in stream frame.
40 const size_t kQuicMaxStreamOffsetSize
= 8;
41 // Number of bytes reserved to store payload length in stream frame.
42 const size_t kQuicStreamPayloadLengthSize
= 2;
44 // Size in bytes of the entropy hash sent in ack frames.
45 const size_t kQuicEntropyHashSize
= 1;
46 // Size in bytes reserved for the delta time of the largest observed
47 // packet number in ack frames.
48 const size_t kQuicDeltaTimeLargestObservedSize
= 2;
49 // Size in bytes reserved for the number of received packets with timestamps.
50 const size_t kQuicNumTimestampsSize
= 1;
51 // Size in bytes reserved for the number of missing packets in ack frames.
52 const size_t kNumberOfNackRangesSize
= 1;
53 // Maximum number of missing packet ranges that can fit within an ack frame.
54 const size_t kMaxNackRanges
=
55 (1 << (kNumberOfNackRangesSize
* 8)) - 1;
56 // Size in bytes reserved for the number of revived packets in ack frames.
57 const size_t kNumberOfRevivedPacketsSize
= 1;
58 // Maximum number of revived packets that can fit within an ack frame.
59 const size_t kMaxRevivedPackets
=
60 (1 << (kNumberOfRevivedPacketsSize
* 8)) - 1;
62 // This class receives callbacks from the framer when packets
64 class NET_EXPORT_PRIVATE QuicFramerVisitorInterface
{
66 virtual ~QuicFramerVisitorInterface() {}
68 // Called if an error is detected in the QUIC protocol.
69 virtual void OnError(QuicFramer
* framer
) = 0;
71 // Called only when |perspective_| is IS_SERVER and the the framer gets a
72 // packet with version flag true and the version on the packet doesn't match
73 // |quic_version_|. The visitor should return true after it updates the
74 // version of the |framer_| to |received_version| or false to stop processing
76 virtual bool OnProtocolVersionMismatch(QuicVersion received_version
) = 0;
78 // Called when a new packet has been received, before it
79 // has been validated or processed.
80 virtual void OnPacket() = 0;
82 // Called when a public reset packet has been parsed but has not yet
84 virtual void OnPublicResetPacket(
85 const QuicPublicResetPacket
& packet
) = 0;
87 // Called only when |perspective_| is IS_CLIENT and a version negotiation
88 // packet has been parsed.
89 virtual void OnVersionNegotiationPacket(
90 const QuicVersionNegotiationPacket
& packet
) = 0;
92 // Called when a lost packet has been recovered via FEC,
93 // before it has been processed.
94 virtual void OnRevivedPacket() = 0;
96 // Called when the public header has been parsed, but has not been
97 // authenticated. If it returns false, framing for this packet will cease.
98 virtual bool OnUnauthenticatedPublicHeader(
99 const QuicPacketPublicHeader
& header
) = 0;
101 // Called when the unauthenticated portion of the header has been parsed.
102 // If OnUnauthenticatedHeader returns false, framing for this packet will
104 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader
& header
) = 0;
106 // Called when a packet has been decrypted. |level| is the encryption level
108 virtual void OnDecryptedPacket(EncryptionLevel level
) = 0;
110 // Called when the complete header of a packet had been parsed.
111 // If OnPacketHeader returns false, framing for this packet will cease.
112 virtual bool OnPacketHeader(const QuicPacketHeader
& header
) = 0;
114 // Called when a data packet is parsed that is part of an FEC group.
115 // |payload| is the non-encrypted FEC protected payload of the packet.
116 virtual void OnFecProtectedPayload(base::StringPiece payload
) = 0;
118 // Called when a StreamFrame has been parsed.
119 virtual bool OnStreamFrame(const QuicStreamFrame
& frame
) = 0;
121 // Called when a AckFrame has been parsed. If OnAckFrame returns false,
122 // the framer will stop parsing the current packet.
123 virtual bool OnAckFrame(const QuicAckFrame
& frame
) = 0;
125 // Called when a StopWaitingFrame has been parsed.
126 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) = 0;
128 // Called when a PingFrame has been parsed.
129 virtual bool OnPingFrame(const QuicPingFrame
& frame
) = 0;
131 // Called when a RstStreamFrame has been parsed.
132 virtual bool OnRstStreamFrame(const QuicRstStreamFrame
& frame
) = 0;
134 // Called when a ConnectionCloseFrame has been parsed.
135 virtual bool OnConnectionCloseFrame(
136 const QuicConnectionCloseFrame
& frame
) = 0;
138 // Called when a GoAwayFrame has been parsed.
139 virtual bool OnGoAwayFrame(const QuicGoAwayFrame
& frame
) = 0;
141 // Called when a WindowUpdateFrame has been parsed.
142 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) = 0;
144 // Called when a BlockedFrame has been parsed.
145 virtual bool OnBlockedFrame(const QuicBlockedFrame
& frame
) = 0;
147 // Called when FEC data has been parsed.
148 virtual void OnFecData(const QuicFecData
& fec
) = 0;
150 // Called when a packet has been completely processed.
151 virtual void OnPacketComplete() = 0;
154 // This class calculates the received entropy of the ack packet being
155 // framed, should it get truncated.
156 class NET_EXPORT_PRIVATE QuicReceivedEntropyHashCalculatorInterface
{
158 virtual ~QuicReceivedEntropyHashCalculatorInterface() {}
160 // When an ack frame gets truncated while being framed the received
161 // entropy of the ack frame needs to be calculated since the some of the
162 // missing packets are not added and the largest observed might be lowered.
163 // This should return the received entropy hash of the packets received up to
164 // and including |packet_number|.
165 virtual QuicPacketEntropyHash
EntropyHash(
166 QuicPacketNumber packet_number
) const = 0;
169 // Class for parsing and constructing QUIC packets. It has a
170 // QuicFramerVisitorInterface that is called when packets are parsed.
171 // It also has a QuicFecBuilder that is called when packets are constructed
172 // in order to generate FEC data for subsequently building FEC packets.
173 class NET_EXPORT_PRIVATE QuicFramer
{
175 // Constructs a new framer that installs a kNULL QuicEncrypter and
176 // QuicDecrypter for level ENCRYPTION_NONE. |supported_versions| specifies the
177 // list of supported QUIC versions. |quic_version_| is set to the maximum
178 // version in |supported_versions|.
179 QuicFramer(const QuicVersionVector
& supported_versions
,
180 QuicTime creation_time
,
181 Perspective perspective
);
183 virtual ~QuicFramer();
185 // Returns true if |version| is a supported protocol version.
186 bool IsSupportedVersion(const QuicVersion version
) const;
188 // Set callbacks to be called from the framer. A visitor must be set, or
189 // else the framer will likely crash. It is acceptable for the visitor
190 // to do nothing. If this is called multiple times, only the last visitor
192 void set_visitor(QuicFramerVisitorInterface
* visitor
) {
196 const QuicVersionVector
& supported_versions() const {
197 return supported_versions_
;
200 QuicVersion
version() const {
201 return quic_version_
;
204 void set_version(const QuicVersion version
);
206 // Does not DCHECK for supported version. Used by tests to set unsupported
207 // version to trigger version negotiation.
208 void set_version_for_tests(const QuicVersion version
) {
209 quic_version_
= version
;
212 // Set entropy calculator to be called from the framer when it needs the
213 // entropy of a truncated ack frame. An entropy calculator must be set or else
214 // the framer will likely crash. If this is called multiple times, only the
215 // last calculator will be used.
216 void set_received_entropy_calculator(
217 QuicReceivedEntropyHashCalculatorInterface
* entropy_calculator
) {
218 entropy_calculator_
= entropy_calculator
;
221 QuicErrorCode
error() const {
225 // Pass a UDP packet into the framer for parsing.
226 // Return true if the packet was processed succesfully. |packet| must be a
227 // single, complete UDP packet (not a frame of a packet). This packet
228 // might be null padded past the end of the payload, which will be correctly
230 bool ProcessPacket(const QuicEncryptedPacket
& packet
);
232 // Pass a data packet that was revived from FEC data into the framer
234 // Return true if the packet was processed succesfully. |payload| must be
235 // the complete DECRYPTED payload of the revived packet.
236 bool ProcessRevivedPacket(QuicPacketHeader
* header
,
237 base::StringPiece payload
);
239 // Largest size in bytes of all stream frame fields without the payload.
240 static size_t GetMinStreamFrameSize(QuicStreamId stream_id
,
241 QuicStreamOffset offset
,
242 bool last_frame_in_packet
,
243 InFecGroup is_in_fec_group
);
244 // Size in bytes of all ack frame fields without the missing packets.
245 static size_t GetMinAckFrameSize(
246 QuicPacketNumberLength largest_observed_length
);
247 // Size in bytes of a stop waiting frame.
248 static size_t GetStopWaitingFrameSize(
249 QuicPacketNumberLength packet_number_length
);
250 // Size in bytes of all reset stream frame without the error details.
251 // Used before QUIC_VERSION_25.
252 static size_t GetMinRstStreamFrameSize();
253 // Size in bytes of all reset stream frame fields.
254 static size_t GetRstStreamFrameSize();
255 // Size in bytes of all connection close frame fields without the error
256 // details and the missing packets from the enclosed ack frame.
257 static size_t GetMinConnectionCloseFrameSize();
258 // Size in bytes of all GoAway frame fields without the reason phrase.
259 static size_t GetMinGoAwayFrameSize();
260 // Size in bytes of all WindowUpdate frame fields.
261 static size_t GetWindowUpdateFrameSize();
262 // Size in bytes of all Blocked frame fields.
263 static size_t GetBlockedFrameSize();
264 // Size in bytes required to serialize the stream id.
265 static size_t GetStreamIdSize(QuicStreamId stream_id
);
266 // Size in bytes required to serialize the stream offset.
267 static size_t GetStreamOffsetSize(QuicStreamOffset offset
);
268 // Size in bytes required for a serialized version negotiation packet
269 static size_t GetVersionNegotiationPacketSize(size_t number_versions
);
271 // Returns the number of bytes added to the packet for the specified frame,
272 // and 0 if the frame doesn't fit. Includes the header size for the first
274 size_t GetSerializedFrameLength(const QuicFrame
& frame
,
276 bool first_frame_in_packet
,
277 bool last_frame_in_packet
,
278 InFecGroup is_in_fec_group
,
279 QuicPacketNumberLength packet_number_length
);
281 // Returns the associated data from the encrypted packet |encrypted| as a
283 static base::StringPiece
GetAssociatedDataFromEncryptedPacket(
284 const QuicEncryptedPacket
& encrypted
,
285 QuicConnectionIdLength connection_id_length
,
286 bool includes_version
,
287 QuicPacketNumberLength packet_number_length
);
289 // Returns a QuicPacket* that is owned by the caller, is created from
290 // |frames|. Returns nullptr if the packet could not be created.
291 // The packet must be of size |packet_size|.
292 QuicPacket
* BuildDataPacket(const QuicPacketHeader
& header
,
293 const QuicFrames
& frames
,
295 size_t packet_length
);
297 // Returns a QuicPacket* that is owned by the caller, and is populated with
298 // the fields in |header| and |fec|. Returns nullptr if the packet could
300 QuicPacket
* BuildFecPacket(const QuicPacketHeader
& header
,
301 const QuicFecData
& fec
);
303 // Returns a new public reset packet, owned by the caller.
304 static QuicEncryptedPacket
* BuildPublicResetPacket(
305 const QuicPublicResetPacket
& packet
);
307 QuicEncryptedPacket
* BuildVersionNegotiationPacket(
308 const QuicPacketPublicHeader
& header
,
309 const QuicVersionVector
& supported_versions
);
311 // SetDecrypter sets the primary decrypter, replacing any that already exists,
312 // and takes ownership. If an alternative decrypter is in place then the
313 // function DCHECKs. This is intended for cases where one knows that future
314 // packets will be using the new decrypter and the previous decrypter is now
315 // obsolete. |level| indicates the encryption level of the new decrypter.
316 void SetDecrypter(EncryptionLevel level
, QuicDecrypter
* decrypter
);
318 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
319 // future packets and takes ownership of it. |level| indicates the encryption
320 // level of the decrypter. If |latch_once_used| is true, then the first time
321 // that the decrypter is successful it will replace the primary decrypter.
322 // Otherwise both decrypters will remain active and the primary decrypter
323 // will be the one last used.
324 void SetAlternativeDecrypter(EncryptionLevel level
,
325 QuicDecrypter
* decrypter
,
326 bool latch_once_used
);
328 const QuicDecrypter
* decrypter() const;
329 const QuicDecrypter
* alternative_decrypter() const;
331 // Changes the encrypter used for level |level| to |encrypter|. The function
332 // takes ownership of |encrypter|.
333 void SetEncrypter(EncryptionLevel level
, QuicEncrypter
* encrypter
);
335 // Returns a new encrypted packet, owned by the caller.
336 // Encrypts into |buffer| if |buffer_len| is long enough, and otherwise
337 // constructs a new buffer owned by the EncryptedPacket.
338 QuicEncryptedPacket
* EncryptPayload(EncryptionLevel level
,
339 QuicPacketNumber packet_number
,
340 const QuicPacket
& packet
,
344 // Returns the maximum length of plaintext that can be encrypted
345 // to ciphertext no larger than |ciphertext_size|.
346 size_t GetMaxPlaintextSize(size_t ciphertext_size
);
348 const std::string
& detailed_error() { return detailed_error_
; }
350 // The minimum packet number length required to represent |packet_number|.
351 static QuicPacketNumberLength
GetMinSequenceNumberLength(
352 QuicPacketNumber packet_number
);
354 void SetSupportedVersions(const QuicVersionVector
& versions
) {
355 supported_versions_
= versions
;
356 quic_version_
= versions
[0];
359 void set_validate_flags(bool value
) { validate_flags_
= value
; }
361 Perspective
perspective() const { return perspective_
; }
363 static QuicPacketEntropyHash
GetPacketEntropyHash(
364 const QuicPacketHeader
& header
);
367 friend class test::QuicFramerPeer
;
369 typedef std::map
<QuicPacketNumber
, uint8
> NackRangeMap
;
371 struct AckFrameInfo
{
375 // The maximum delta between ranges.
376 QuicPacketNumber max_delta
;
377 // Nack ranges starting with start packet numbers and lengths.
378 NackRangeMap nack_ranges
;
381 bool ProcessDataPacket(QuicDataReader
* reader
,
382 const QuicPacketPublicHeader
& public_header
,
383 const QuicEncryptedPacket
& packet
,
384 char* decrypted_buffer
,
385 size_t buffer_length
);
387 bool ProcessPublicResetPacket(QuicDataReader
* reader
,
388 const QuicPacketPublicHeader
& public_header
);
390 bool ProcessVersionNegotiationPacket(QuicDataReader
* reader
,
391 QuicPacketPublicHeader
* public_header
);
393 bool ProcessPublicHeader(QuicDataReader
* reader
,
394 QuicPacketPublicHeader
* header
);
396 // Processes the unauthenticated portion of the header into |header| from
397 // the current QuicDataReader. Returns true on success, false on failure.
398 bool ProcessUnauthenticatedHeader(QuicDataReader
* encrypted_reader
,
399 QuicPacketHeader
* header
);
401 // Processes the authenticated portion of the header into |header| from
402 // the current QuicDataReader. Returns true on success, false on failure.
403 bool ProcessAuthenticatedHeader(QuicDataReader
* reader
,
404 QuicPacketHeader
* header
);
406 bool ProcessPacketSequenceNumber(QuicDataReader
* reader
,
407 QuicPacketNumberLength packet_number_length
,
408 QuicPacketNumber
* packet_number
);
409 bool ProcessFrameData(QuicDataReader
* reader
, const QuicPacketHeader
& header
);
410 bool ProcessStreamFrame(QuicDataReader
* reader
,
412 QuicStreamFrame
* frame
);
413 bool ProcessAckFrame(QuicDataReader
* reader
,
415 QuicAckFrame
* frame
);
416 bool ProcessTimestampsInAckFrame(QuicDataReader
* reader
, QuicAckFrame
* frame
);
417 bool ProcessStopWaitingFrame(QuicDataReader
* reader
,
418 const QuicPacketHeader
& public_header
,
419 QuicStopWaitingFrame
* stop_waiting
);
420 bool ProcessRstStreamFrame(QuicDataReader
* reader
, QuicRstStreamFrame
* frame
);
421 bool ProcessConnectionCloseFrame(QuicDataReader
* reader
,
422 QuicConnectionCloseFrame
* frame
);
423 bool ProcessGoAwayFrame(QuicDataReader
* reader
, QuicGoAwayFrame
* frame
);
424 bool ProcessWindowUpdateFrame(QuicDataReader
* reader
,
425 QuicWindowUpdateFrame
* frame
);
426 bool ProcessBlockedFrame(QuicDataReader
* reader
, QuicBlockedFrame
* frame
);
428 bool DecryptPayload(QuicDataReader
* encrypted_reader
,
429 const QuicPacketHeader
& header
,
430 const QuicEncryptedPacket
& packet
,
431 char* decrypted_buffer
,
432 size_t buffer_length
,
433 size_t* decrypted_length
);
435 // Returns the full packet number from the truncated
436 // wire format version and the last seen packet number.
437 QuicPacketNumber
CalculatePacketNumberFromWire(
438 QuicPacketNumberLength packet_number_length
,
439 QuicPacketNumber packet_packet_number
) const;
441 // Returns the QuicTime::Delta corresponding to the time from when the framer
443 const QuicTime::Delta
CalculateTimestampFromWire(uint32 time_delta_us
);
445 // Computes the wire size in bytes of the |ack| frame, assuming no truncation.
446 size_t GetAckFrameSize(const QuicAckFrame
& ack
,
447 QuicPacketNumberLength packet_number_length
);
449 // Computes the wire size in bytes of the payload of |frame|.
450 size_t ComputeFrameLength(const QuicFrame
& frame
,
451 bool last_frame_in_packet
,
452 InFecGroup is_in_fec_group
,
453 QuicPacketNumberLength packet_number_length
);
455 static bool AppendPacketSequenceNumber(
456 QuicPacketNumberLength packet_number_length
,
457 QuicPacketNumber packet_packet_number
,
458 QuicDataWriter
* writer
);
460 static uint8
GetSequenceNumberFlags(
461 QuicPacketNumberLength packet_number_length
);
463 static AckFrameInfo
GetAckFrameInfo(const QuicAckFrame
& frame
);
465 // The Append* methods attempt to write the provided header or frame using the
466 // |writer|, and return true if successful.
468 // If header.public_header.version_flag is set, the version in the
469 // packet will be set -- but it will be set from quic_version_ not
470 // header.public_header.versions.
471 bool AppendPacketHeader(const QuicPacketHeader
& header
,
472 QuicDataWriter
* writer
);
473 bool AppendTypeByte(const QuicFrame
& frame
,
474 bool last_frame_in_packet
,
475 QuicDataWriter
* writer
);
476 bool AppendStreamFrame(const QuicStreamFrame
& frame
,
477 bool last_frame_in_packet
,
478 QuicDataWriter
* builder
);
479 bool AppendAckFrameAndTypeByte(const QuicPacketHeader
& header
,
480 const QuicAckFrame
& frame
,
481 QuicDataWriter
* builder
);
482 bool AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
483 QuicDataWriter
* builder
);
484 bool AppendStopWaitingFrame(const QuicPacketHeader
& header
,
485 const QuicStopWaitingFrame
& frame
,
486 QuicDataWriter
* builder
);
487 bool AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
488 QuicDataWriter
* builder
);
489 bool AppendConnectionCloseFrame(const QuicConnectionCloseFrame
& frame
,
490 QuicDataWriter
* builder
);
491 bool AppendGoAwayFrame(const QuicGoAwayFrame
& frame
, QuicDataWriter
* writer
);
492 bool AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
493 QuicDataWriter
* writer
);
494 bool AppendBlockedFrame(const QuicBlockedFrame
& frame
,
495 QuicDataWriter
* writer
);
497 bool RaiseError(QuicErrorCode error
);
499 void set_error(QuicErrorCode error
) {
503 void set_detailed_error(const char* error
) {
504 detailed_error_
= error
;
507 std::string detailed_error_
;
508 QuicFramerVisitorInterface
* visitor_
;
509 QuicReceivedEntropyHashCalculatorInterface
* entropy_calculator_
;
510 QuicErrorCode error_
;
511 // Updated by ProcessPacketHeader when it succeeds.
512 QuicPacketNumber last_packet_number_
;
513 // Updated by WritePacketHeader.
514 QuicConnectionId last_serialized_connection_id_
;
515 // Version of the protocol being used.
516 QuicVersion quic_version_
;
517 // This vector contains QUIC versions which we currently support.
518 // This should be ordered such that the highest supported version is the first
519 // element, with subsequent elements in descending order (versions can be
520 // skipped as necessary).
521 QuicVersionVector supported_versions_
;
522 // Primary decrypter used to decrypt packets during parsing.
523 scoped_ptr
<QuicDecrypter
> decrypter_
;
524 // Alternative decrypter that can also be used to decrypt packets.
525 scoped_ptr
<QuicDecrypter
> alternative_decrypter_
;
526 // The encryption level of |decrypter_|.
527 EncryptionLevel decrypter_level_
;
528 // The encryption level of |alternative_decrypter_|.
529 EncryptionLevel alternative_decrypter_level_
;
530 // |alternative_decrypter_latch_| is true if, when |alternative_decrypter_|
531 // successfully decrypts a packet, we should install it as the only
533 bool alternative_decrypter_latch_
;
534 // Encrypters used to encrypt packets via EncryptPayload().
535 scoped_ptr
<QuicEncrypter
> encrypter_
[NUM_ENCRYPTION_LEVELS
];
536 // Tracks if the framer is being used by the entity that received the
537 // connection or the entity that initiated it.
538 Perspective perspective_
;
539 // If false, skip validation that the public flags are set to legal values.
540 bool validate_flags_
;
541 // The time this framer was created. Time written to the wire will be
542 // written as a delta from this value.
543 QuicTime creation_time_
;
544 // The time delta computed for the last timestamp frame. This is relative to
545 // the creation_time.
546 QuicTime::Delta last_timestamp_
;
548 DISALLOW_COPY_AND_ASSIGN(QuicFramer
);
553 #endif // NET_QUIC_QUIC_FRAMER_H_