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_
10 #include "base/basictypes.h"
11 #include "base/logging.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/strings/string_piece.h"
14 #include "net/base/net_export.h"
15 #include "net/quic/quic_protocol.h"
29 // Number of bytes reserved for the frame type preceding each frame.
30 const size_t kQuicFrameTypeSize
= 1;
31 // Number of bytes reserved for error code.
32 const size_t kQuicErrorCodeSize
= 4;
33 // Number of bytes reserved to denote the length of error details field.
34 const size_t kQuicErrorDetailsLengthSize
= 2;
36 // Maximum number of bytes reserved for stream id.
37 const size_t kQuicMaxStreamIdSize
= 4;
38 // Maximum number of bytes reserved for byte offset in stream frame.
39 const size_t kQuicMaxStreamOffsetSize
= 8;
40 // Number of bytes reserved to store payload length in stream frame.
41 const size_t kQuicStreamPayloadLengthSize
= 2;
43 // Size in bytes of the entropy hash sent in ack frames.
44 const size_t kQuicEntropyHashSize
= 1;
45 // Size in bytes reserved for the delta time of the largest observed
46 // sequence number in ack frames.
47 const size_t kQuicDeltaTimeLargestObservedSize
= 2;
48 // Size in bytes reserved for the number of missing packets in ack frames.
49 const size_t kNumberOfNackRangesSize
= 1;
50 // Maximum number of missing packet ranges that can fit within an ack frame.
51 const size_t kMaxNackRanges
=
52 (1 << (kNumberOfNackRangesSize
* 8)) - 1;
53 // Size in bytes reserved for the number of revived packets in ack frames.
54 const size_t kNumberOfRevivedPacketsSize
= 1;
55 // Maximum number of revived packets that can fit within an ack frame.
56 const size_t kMaxRevivedPackets
=
57 (1 << (kNumberOfRevivedPacketsSize
* 8)) - 1;
59 // This class receives callbacks from the framer when packets
61 class NET_EXPORT_PRIVATE QuicFramerVisitorInterface
{
63 virtual ~QuicFramerVisitorInterface() {}
65 // Called if an error is detected in the QUIC protocol.
66 virtual void OnError(QuicFramer
* framer
) = 0;
68 // Called only when |is_server_| is true and the the framer gets a packet with
69 // version flag true and the version on the packet doesn't match
70 // |quic_version_|. The visitor should return true after it updates the
71 // version of the |framer_| to |received_version| or false to stop processing
73 virtual bool OnProtocolVersionMismatch(QuicVersion received_version
) = 0;
75 // Called when a new packet has been received, before it
76 // has been validated or processed.
77 virtual void OnPacket() = 0;
79 // Called when a public reset packet has been parsed but has not yet
81 virtual void OnPublicResetPacket(
82 const QuicPublicResetPacket
& packet
) = 0;
84 // Called only when |is_server_| is false and a version negotiation packet has
86 virtual void OnVersionNegotiationPacket(
87 const QuicVersionNegotiationPacket
& packet
) = 0;
89 // Called when a lost packet has been recovered via FEC,
90 // before it has been processed.
91 virtual void OnRevivedPacket() = 0;
93 // Called when the public header has been parsed, but has not been
94 // authenticated. If it returns false, framing for this packet will cease.
95 virtual bool OnUnauthenticatedPublicHeader(
96 const QuicPacketPublicHeader
& header
) = 0;
98 // Called when the unauthenticated portion of the header has been parsed.
99 // If OnUnauthenticatedHeader returns false, framing for this packet will
101 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader
& header
) = 0;
103 // Called when a packet has been decrypted. |level| is the encryption level
105 virtual void OnDecryptedPacket(EncryptionLevel level
) = 0;
107 // Called when the complete header of a packet had been parsed.
108 // If OnPacketHeader returns false, framing for this packet will cease.
109 virtual bool OnPacketHeader(const QuicPacketHeader
& header
) = 0;
111 // Called when a data packet is parsed that is part of an FEC group.
112 // |payload| is the non-encrypted FEC protected payload of the packet.
113 virtual void OnFecProtectedPayload(base::StringPiece payload
) = 0;
115 // Called when a StreamFrame has been parsed.
116 virtual bool OnStreamFrame(const QuicStreamFrame
& frame
) = 0;
118 // Called when a AckFrame has been parsed. If OnAckFrame returns false,
119 // the framer will stop parsing the current packet.
120 virtual bool OnAckFrame(const QuicAckFrame
& frame
) = 0;
122 // Called when a CongestionFeedbackFrame has been parsed.
123 virtual bool OnCongestionFeedbackFrame(
124 const QuicCongestionFeedbackFrame
& frame
) = 0;
126 // Called when a StopWaitingFrame has been parsed.
127 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) = 0;
129 // Called when a PingFrame has been parsed.
130 virtual bool OnPingFrame(const QuicPingFrame
& frame
) = 0;
132 // Called when a RstStreamFrame has been parsed.
133 virtual bool OnRstStreamFrame(const QuicRstStreamFrame
& frame
) = 0;
135 // Called when a ConnectionCloseFrame has been parsed.
136 virtual bool OnConnectionCloseFrame(
137 const QuicConnectionCloseFrame
& frame
) = 0;
139 // Called when a GoAwayFrame has been parsed.
140 virtual bool OnGoAwayFrame(const QuicGoAwayFrame
& frame
) = 0;
142 // Called when a WindowUpdateFrame has been parsed.
143 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) = 0;
145 // Called when a BlockedFrame has been parsed.
146 virtual bool OnBlockedFrame(const QuicBlockedFrame
& frame
) = 0;
148 // Called when FEC data has been parsed.
149 virtual void OnFecData(const QuicFecData
& fec
) = 0;
151 // Called when a packet has been completely processed.
152 virtual void OnPacketComplete() = 0;
155 class NET_EXPORT_PRIVATE QuicFecBuilderInterface
{
157 virtual ~QuicFecBuilderInterface() {}
159 // Called when a data packet is constructed that is part of an FEC group.
160 // |payload| is the non-encrypted FEC protected payload of the packet.
161 virtual void OnBuiltFecProtectedPayload(const QuicPacketHeader
& header
,
162 base::StringPiece payload
) = 0;
165 // This class calculates the received entropy of the ack packet being
166 // framed, should it get truncated.
167 class NET_EXPORT_PRIVATE QuicReceivedEntropyHashCalculatorInterface
{
169 virtual ~QuicReceivedEntropyHashCalculatorInterface() {}
171 // When an ack frame gets truncated while being framed the received
172 // entropy of the ack frame needs to be calculated since the some of the
173 // missing packets are not added and the largest observed might be lowered.
174 // This should return the received entropy hash of the packets received up to
175 // and including |sequence_number|.
176 virtual QuicPacketEntropyHash
EntropyHash(
177 QuicPacketSequenceNumber sequence_number
) const = 0;
180 // Class for parsing and constructing QUIC packets. It has a
181 // QuicFramerVisitorInterface that is called when packets are parsed.
182 // It also has a QuicFecBuilder that is called when packets are constructed
183 // in order to generate FEC data for subsequently building FEC packets.
184 class NET_EXPORT_PRIVATE QuicFramer
{
186 // Constructs a new framer that installs a kNULL QuicEncrypter and
187 // QuicDecrypter for level ENCRYPTION_NONE. |supported_versions| specifies the
188 // list of supported QUIC versions. |quic_version_| is set to the maximum
189 // version in |supported_versions|.
190 QuicFramer(const QuicVersionVector
& supported_versions
,
191 QuicTime creation_time
,
194 virtual ~QuicFramer();
196 // Returns true if |version| is a supported protocol version.
197 bool IsSupportedVersion(const QuicVersion version
) const;
199 // Set callbacks to be called from the framer. A visitor must be set, or
200 // else the framer will likely crash. It is acceptable for the visitor
201 // to do nothing. If this is called multiple times, only the last visitor
203 void set_visitor(QuicFramerVisitorInterface
* visitor
) {
207 // Set a builder to be called from the framer when building FEC protected
208 // packets. If this is called multiple times, only the last builder
209 // will be used. The builder need not be set.
210 void set_fec_builder(QuicFecBuilderInterface
* builder
) {
211 fec_builder_
= builder
;
214 const QuicVersionVector
& supported_versions() const {
215 return supported_versions_
;
218 QuicVersion
version() const {
219 return quic_version_
;
222 void set_version(const QuicVersion version
);
224 // Does not DCHECK for supported version. Used by tests to set unsupported
225 // version to trigger version negotiation.
226 void set_version_for_tests(const QuicVersion version
) {
227 quic_version_
= version
;
230 // Set entropy calculator to be called from the framer when it needs the
231 // entropy of a truncated ack frame. An entropy calculator must be set or else
232 // the framer will likely crash. If this is called multiple times, only the
233 // last calculator will be used.
234 void set_received_entropy_calculator(
235 QuicReceivedEntropyHashCalculatorInterface
* entropy_calculator
) {
236 entropy_calculator_
= entropy_calculator
;
239 QuicErrorCode
error() const {
243 // Pass a UDP packet into the framer for parsing.
244 // Return true if the packet was processed succesfully. |packet| must be a
245 // single, complete UDP packet (not a frame of a packet). This packet
246 // might be null padded past the end of the payload, which will be correctly
248 bool ProcessPacket(const QuicEncryptedPacket
& packet
);
250 // Pass a data packet that was revived from FEC data into the framer
252 // Return true if the packet was processed succesfully. |payload| must be
253 // the complete DECRYPTED payload of the revived packet.
254 bool ProcessRevivedPacket(QuicPacketHeader
* header
,
255 base::StringPiece payload
);
257 // Largest size in bytes of all stream frame fields without the payload.
258 static size_t GetMinStreamFrameSize(QuicVersion version
,
259 QuicStreamId stream_id
,
260 QuicStreamOffset offset
,
261 bool last_frame_in_packet
,
262 InFecGroup is_in_fec_group
);
263 // Size in bytes of all ack frame fields without the missing packets.
264 static size_t GetMinAckFrameSize(
266 QuicSequenceNumberLength sequence_number_length
,
267 QuicSequenceNumberLength largest_observed_length
);
268 // Size in bytes of a stop waiting frame.
269 static size_t GetStopWaitingFrameSize(
270 QuicSequenceNumberLength sequence_number_length
);
271 // Size in bytes of all reset stream frame without the error details.
272 static size_t GetMinRstStreamFrameSize(QuicVersion quic_version
);
273 // Size in bytes of all connection close frame fields without the error
274 // details and the missing packets from the enclosed ack frame.
275 static size_t GetMinConnectionCloseFrameSize();
276 // Size in bytes of all GoAway frame fields without the reason phrase.
277 static size_t GetMinGoAwayFrameSize();
278 // Size in bytes of all WindowUpdate frame fields.
279 static size_t GetWindowUpdateFrameSize();
280 // Size in bytes of all Blocked frame fields.
281 static size_t GetBlockedFrameSize();
282 // Size in bytes required to serialize the stream id.
283 static size_t GetStreamIdSize(QuicStreamId stream_id
);
284 // Size in bytes required to serialize the stream offset.
285 static size_t GetStreamOffsetSize(QuicStreamOffset offset
);
286 // Size in bytes required for a serialized version negotiation packet
287 static size_t GetVersionNegotiationPacketSize(size_t number_versions
);
289 // Returns the number of bytes added to the packet for the specified frame,
290 // and 0 if the frame doesn't fit. Includes the header size for the first
292 size_t GetSerializedFrameLength(
293 const QuicFrame
& frame
,
295 bool first_frame_in_packet
,
296 bool last_frame_in_packet
,
297 InFecGroup is_in_fec_group
,
298 QuicSequenceNumberLength sequence_number_length
);
300 // Returns the associated data from the encrypted packet |encrypted| as a
302 static base::StringPiece
GetAssociatedDataFromEncryptedPacket(
303 const QuicEncryptedPacket
& encrypted
,
304 QuicConnectionIdLength connection_id_length
,
305 bool includes_version
,
306 QuicSequenceNumberLength sequence_number_length
);
308 // Returns a SerializedPacket whose |packet| member is owned by the caller,
309 // is created from the first |num_frames| frames, or is NULL if the packet
310 // could not be created. The packet must be of size |packet_size|.
311 SerializedPacket
BuildDataPacket(const QuicPacketHeader
& header
,
312 const QuicFrames
& frames
,
315 // Returns a SerializedPacket whose |packet| member is owned by the caller,
316 // and is populated with the fields in |header| and |fec|, or is NULL if the
317 // packet could not be created.
318 SerializedPacket
BuildFecPacket(const QuicPacketHeader
& header
,
319 const QuicFecData
& fec
);
321 // Returns a new public reset packet, owned by the caller.
322 static QuicEncryptedPacket
* BuildPublicResetPacket(
323 const QuicPublicResetPacket
& packet
);
325 QuicEncryptedPacket
* BuildVersionNegotiationPacket(
326 const QuicPacketPublicHeader
& header
,
327 const QuicVersionVector
& supported_versions
);
329 // SetDecrypter sets the primary decrypter, replacing any that already exists,
330 // and takes ownership. If an alternative decrypter is in place then the
331 // function DCHECKs. This is intended for cases where one knows that future
332 // packets will be using the new decrypter and the previous decrypter is now
333 // obsolete. |level| indicates the encryption level of the new decrypter.
334 void SetDecrypter(QuicDecrypter
* decrypter
, EncryptionLevel level
);
336 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
337 // future packets and takes ownership of it. |level| indicates the encryption
338 // level of the decrypter. If |latch_once_used| is true, then the first time
339 // that the decrypter is successful it will replace the primary decrypter.
340 // Otherwise both decrypters will remain active and the primary decrypter
341 // will be the one last used.
342 void SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
343 EncryptionLevel level
,
344 bool latch_once_used
);
346 const QuicDecrypter
* decrypter() const;
347 const QuicDecrypter
* alternative_decrypter() const;
349 // Changes the encrypter used for level |level| to |encrypter|. The function
350 // takes ownership of |encrypter|.
351 void SetEncrypter(EncryptionLevel level
, QuicEncrypter
* encrypter
);
352 const QuicEncrypter
* encrypter(EncryptionLevel level
) const;
354 // Returns a new encrypted packet, owned by the caller.
355 QuicEncryptedPacket
* EncryptPacket(EncryptionLevel level
,
356 QuicPacketSequenceNumber sequence_number
,
357 const QuicPacket
& packet
);
359 // Returns the maximum length of plaintext that can be encrypted
360 // to ciphertext no larger than |ciphertext_size|.
361 size_t GetMaxPlaintextSize(size_t ciphertext_size
);
363 const std::string
& detailed_error() { return detailed_error_
; }
365 // The minimum sequence number length required to represent |sequence_number|.
366 static QuicSequenceNumberLength
GetMinSequenceNumberLength(
367 QuicPacketSequenceNumber sequence_number
);
369 void SetSupportedVersions(const QuicVersionVector
& versions
) {
370 supported_versions_
= versions
;
371 quic_version_
= versions
[0];
374 void set_validate_flags(bool value
) { validate_flags_
= value
; }
376 bool is_server() const { return is_server_
; }
379 friend class test::QuicFramerPeer
;
381 typedef std::map
<QuicPacketSequenceNumber
, uint8
> NackRangeMap
;
383 struct AckFrameInfo
{
387 // The maximum delta between ranges.
388 QuicPacketSequenceNumber max_delta
;
389 // Nack ranges starting with start sequence numbers and lengths.
390 NackRangeMap nack_ranges
;
393 QuicPacketEntropyHash
GetPacketEntropyHash(
394 const QuicPacketHeader
& header
) const;
396 bool ProcessDataPacket(const QuicPacketPublicHeader
& public_header
,
397 const QuicEncryptedPacket
& packet
);
399 bool ProcessPublicResetPacket(const QuicPacketPublicHeader
& public_header
);
401 bool ProcessVersionNegotiationPacket(QuicPacketPublicHeader
* public_header
);
403 bool ProcessPublicHeader(QuicPacketPublicHeader
* header
);
405 bool ProcessPacketHeader(QuicPacketHeader
* header
,
406 const QuicEncryptedPacket
& packet
);
408 bool ProcessPacketSequenceNumber(
409 QuicSequenceNumberLength sequence_number_length
,
410 QuicPacketSequenceNumber
* sequence_number
);
411 bool ProcessFrameData(const QuicPacketHeader
& header
);
412 bool ProcessStreamFrame(uint8 frame_type
, QuicStreamFrame
* frame
);
413 bool ProcessAckFrame(const QuicPacketHeader
& header
,
415 QuicAckFrame
* frame
);
416 bool ProcessReceivedInfo(uint8 frame_type
, ReceivedPacketInfo
* received_info
);
417 bool ProcessStopWaitingFrame(const QuicPacketHeader
& public_header
,
418 QuicStopWaitingFrame
* stop_waiting
);
419 bool ProcessQuicCongestionFeedbackFrame(
420 QuicCongestionFeedbackFrame
* congestion_feedback
);
421 bool ProcessRstStreamFrame(QuicRstStreamFrame
* frame
);
422 bool ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
);
423 bool ProcessGoAwayFrame(QuicGoAwayFrame
* frame
);
424 bool ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
);
425 bool ProcessBlockedFrame(QuicBlockedFrame
* frame
);
427 bool DecryptPayload(const QuicPacketHeader
& header
,
428 const QuicEncryptedPacket
& packet
);
430 // Returns the full packet sequence number from the truncated
431 // wire format version and the last seen packet sequence number.
432 QuicPacketSequenceNumber
CalculatePacketSequenceNumberFromWire(
433 QuicSequenceNumberLength sequence_number_length
,
434 QuicPacketSequenceNumber packet_sequence_number
) const;
436 // Computes the wire size in bytes of the |ack| frame, assuming no truncation.
437 size_t GetAckFrameSize(const QuicAckFrame
& ack
,
438 QuicSequenceNumberLength sequence_number_length
);
440 // Computes the wire size in bytes of the payload of |frame|.
441 size_t ComputeFrameLength(const QuicFrame
& frame
,
442 bool last_frame_in_packet
,
443 InFecGroup is_in_fec_group
,
444 QuicSequenceNumberLength sequence_number_length
);
446 static bool AppendPacketSequenceNumber(
447 QuicSequenceNumberLength sequence_number_length
,
448 QuicPacketSequenceNumber packet_sequence_number
,
449 QuicDataWriter
* writer
);
451 static uint8
GetSequenceNumberFlags(
452 QuicSequenceNumberLength sequence_number_length
);
454 static AckFrameInfo
GetAckFrameInfo(const QuicAckFrame
& frame
);
456 // The Append* methods attempt to write the provided header or frame using the
457 // |writer|, and return true if successful.
458 bool AppendPacketHeader(const QuicPacketHeader
& header
,
459 QuicDataWriter
* writer
);
460 bool AppendTypeByte(const QuicFrame
& frame
,
461 bool last_frame_in_packet
,
462 QuicDataWriter
* writer
);
463 bool AppendStreamFrame(const QuicStreamFrame
& frame
,
464 bool last_frame_in_packet
,
465 QuicDataWriter
* builder
);
466 bool AppendAckFrameAndTypeByte(const QuicPacketHeader
& header
,
467 const QuicAckFrame
& frame
,
468 QuicDataWriter
* builder
);
469 bool AppendCongestionFeedbackFrame(const QuicCongestionFeedbackFrame
& frame
,
470 QuicDataWriter
* builder
);
471 bool AppendStopWaitingFrame(const QuicPacketHeader
& header
,
472 const QuicStopWaitingFrame
& frame
,
473 QuicDataWriter
* builder
);
474 bool AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
475 QuicDataWriter
* builder
);
476 bool AppendConnectionCloseFrame(const QuicConnectionCloseFrame
& frame
,
477 QuicDataWriter
* builder
);
478 bool AppendGoAwayFrame(const QuicGoAwayFrame
& frame
, QuicDataWriter
* writer
);
479 bool AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
480 QuicDataWriter
* writer
);
481 bool AppendBlockedFrame(const QuicBlockedFrame
& frame
,
482 QuicDataWriter
* writer
);
484 bool RaiseError(QuicErrorCode error
);
486 void set_error(QuicErrorCode error
) {
490 void set_detailed_error(const char* error
) {
491 detailed_error_
= error
;
494 std::string detailed_error_
;
495 scoped_ptr
<QuicDataReader
> reader_
;
496 QuicFramerVisitorInterface
* visitor_
;
497 QuicFecBuilderInterface
* fec_builder_
;
498 QuicReceivedEntropyHashCalculatorInterface
* entropy_calculator_
;
499 QuicErrorCode error_
;
500 // Updated by ProcessPacketHeader when it succeeds.
501 QuicPacketSequenceNumber last_sequence_number_
;
502 // Updated by WritePacketHeader.
503 QuicConnectionId last_serialized_connection_id_
;
504 // Buffer containing decrypted payload data during parsing.
505 scoped_ptr
<QuicData
> decrypted_
;
506 // Version of the protocol being used.
507 QuicVersion quic_version_
;
508 // This vector contains QUIC versions which we currently support.
509 // This should be ordered such that the highest supported version is the first
510 // element, with subsequent elements in descending order (versions can be
511 // skipped as necessary).
512 QuicVersionVector supported_versions_
;
513 // Primary decrypter used to decrypt packets during parsing.
514 scoped_ptr
<QuicDecrypter
> decrypter_
;
515 // Alternative decrypter that can also be used to decrypt packets.
516 scoped_ptr
<QuicDecrypter
> alternative_decrypter_
;
517 // The encryption level of |decrypter_|.
518 EncryptionLevel decrypter_level_
;
519 // The encryption level of |alternative_decrypter_|.
520 EncryptionLevel alternative_decrypter_level_
;
521 // |alternative_decrypter_latch_| is true if, when |alternative_decrypter_|
522 // successfully decrypts a packet, we should install it as the only
524 bool alternative_decrypter_latch_
;
525 // Encrypters used to encrypt packets via EncryptPacket().
526 scoped_ptr
<QuicEncrypter
> encrypter_
[NUM_ENCRYPTION_LEVELS
];
527 // Tracks if the framer is being used by the entity that received the
528 // connection or the entity that initiated it.
530 // If false, skip validation that the public flags are set to legal values.
531 bool validate_flags_
;
532 // The time this frames was created. Time written to the wire will be
533 // written as a delta from this value.
534 QuicTime creation_time_
;
536 DISALLOW_COPY_AND_ASSIGN(QuicFramer
);
541 #endif // NET_QUIC_QUIC_FRAMER_H_