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 received packets with timestamps.
49 const size_t kQuicNumTimestampsSize
= 1;
50 // Size in bytes reserved for the number of missing packets in ack frames.
51 const size_t kNumberOfNackRangesSize
= 1;
52 // Maximum number of missing packet ranges that can fit within an ack frame.
53 const size_t kMaxNackRanges
=
54 (1 << (kNumberOfNackRangesSize
* 8)) - 1;
55 // Size in bytes reserved for the number of revived packets in ack frames.
56 const size_t kNumberOfRevivedPacketsSize
= 1;
57 // Maximum number of revived packets that can fit within an ack frame.
58 const size_t kMaxRevivedPackets
=
59 (1 << (kNumberOfRevivedPacketsSize
* 8)) - 1;
61 // This class receives callbacks from the framer when packets
63 class NET_EXPORT_PRIVATE QuicFramerVisitorInterface
{
65 virtual ~QuicFramerVisitorInterface() {}
67 // Called if an error is detected in the QUIC protocol.
68 virtual void OnError(QuicFramer
* framer
) = 0;
70 // Called only when |is_server_| is true and the the framer gets a packet with
71 // version flag true and the version on the packet doesn't match
72 // |quic_version_|. The visitor should return true after it updates the
73 // version of the |framer_| to |received_version| or false to stop processing
75 virtual bool OnProtocolVersionMismatch(QuicVersion received_version
) = 0;
77 // Called when a new packet has been received, before it
78 // has been validated or processed.
79 virtual void OnPacket() = 0;
81 // Called when a public reset packet has been parsed but has not yet
83 virtual void OnPublicResetPacket(
84 const QuicPublicResetPacket
& packet
) = 0;
86 // Called only when |is_server_| is false and a version negotiation packet has
88 virtual void OnVersionNegotiationPacket(
89 const QuicVersionNegotiationPacket
& packet
) = 0;
91 // Called when a lost packet has been recovered via FEC,
92 // before it has been processed.
93 virtual void OnRevivedPacket() = 0;
95 // Called when the public header has been parsed, but has not been
96 // authenticated. If it returns false, framing for this packet will cease.
97 virtual bool OnUnauthenticatedPublicHeader(
98 const QuicPacketPublicHeader
& header
) = 0;
100 // Called when the unauthenticated portion of the header has been parsed.
101 // If OnUnauthenticatedHeader returns false, framing for this packet will
103 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader
& header
) = 0;
105 // Called when a packet has been decrypted. |level| is the encryption level
107 virtual void OnDecryptedPacket(EncryptionLevel level
) = 0;
109 // Called when the complete header of a packet had been parsed.
110 // If OnPacketHeader returns false, framing for this packet will cease.
111 virtual bool OnPacketHeader(const QuicPacketHeader
& header
) = 0;
113 // Called when a data packet is parsed that is part of an FEC group.
114 // |payload| is the non-encrypted FEC protected payload of the packet.
115 virtual void OnFecProtectedPayload(base::StringPiece payload
) = 0;
117 // Called when a StreamFrame has been parsed.
118 virtual bool OnStreamFrame(const QuicStreamFrame
& frame
) = 0;
120 // Called when a AckFrame has been parsed. If OnAckFrame returns false,
121 // the framer will stop parsing the current packet.
122 virtual bool OnAckFrame(const QuicAckFrame
& frame
) = 0;
124 // Called when a StopWaitingFrame has been parsed.
125 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame
& frame
) = 0;
127 // Called when a PingFrame has been parsed.
128 virtual bool OnPingFrame(const QuicPingFrame
& frame
) = 0;
130 // Called when a RstStreamFrame has been parsed.
131 virtual bool OnRstStreamFrame(const QuicRstStreamFrame
& frame
) = 0;
133 // Called when a ConnectionCloseFrame has been parsed.
134 virtual bool OnConnectionCloseFrame(
135 const QuicConnectionCloseFrame
& frame
) = 0;
137 // Called when a GoAwayFrame has been parsed.
138 virtual bool OnGoAwayFrame(const QuicGoAwayFrame
& frame
) = 0;
140 // Called when a WindowUpdateFrame has been parsed.
141 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
) = 0;
143 // Called when a BlockedFrame has been parsed.
144 virtual bool OnBlockedFrame(const QuicBlockedFrame
& frame
) = 0;
146 // Called when FEC data has been parsed.
147 virtual void OnFecData(const QuicFecData
& fec
) = 0;
149 // Called when a packet has been completely processed.
150 virtual void OnPacketComplete() = 0;
153 class NET_EXPORT_PRIVATE QuicFecBuilderInterface
{
155 virtual ~QuicFecBuilderInterface() {}
157 // Called when a data packet is constructed that is part of an FEC group.
158 // |payload| is the non-encrypted FEC protected payload of the packet.
159 virtual void OnBuiltFecProtectedPayload(const QuicPacketHeader
& header
,
160 base::StringPiece payload
) = 0;
163 // This class calculates the received entropy of the ack packet being
164 // framed, should it get truncated.
165 class NET_EXPORT_PRIVATE QuicReceivedEntropyHashCalculatorInterface
{
167 virtual ~QuicReceivedEntropyHashCalculatorInterface() {}
169 // When an ack frame gets truncated while being framed the received
170 // entropy of the ack frame needs to be calculated since the some of the
171 // missing packets are not added and the largest observed might be lowered.
172 // This should return the received entropy hash of the packets received up to
173 // and including |sequence_number|.
174 virtual QuicPacketEntropyHash
EntropyHash(
175 QuicPacketSequenceNumber sequence_number
) const = 0;
178 // Class for parsing and constructing QUIC packets. It has a
179 // QuicFramerVisitorInterface that is called when packets are parsed.
180 // It also has a QuicFecBuilder that is called when packets are constructed
181 // in order to generate FEC data for subsequently building FEC packets.
182 class NET_EXPORT_PRIVATE QuicFramer
{
184 // Constructs a new framer that installs a kNULL QuicEncrypter and
185 // QuicDecrypter for level ENCRYPTION_NONE. |supported_versions| specifies the
186 // list of supported QUIC versions. |quic_version_| is set to the maximum
187 // version in |supported_versions|.
188 QuicFramer(const QuicVersionVector
& supported_versions
,
189 QuicTime creation_time
,
192 virtual ~QuicFramer();
194 // Returns true if |version| is a supported protocol version.
195 bool IsSupportedVersion(const QuicVersion version
) const;
197 // Set callbacks to be called from the framer. A visitor must be set, or
198 // else the framer will likely crash. It is acceptable for the visitor
199 // to do nothing. If this is called multiple times, only the last visitor
201 void set_visitor(QuicFramerVisitorInterface
* visitor
) {
205 // Set a builder to be called from the framer when building FEC protected
206 // packets. If this is called multiple times, only the last builder
207 // will be used. The builder need not be set.
208 void set_fec_builder(QuicFecBuilderInterface
* builder
) {
209 fec_builder_
= builder
;
212 const QuicVersionVector
& supported_versions() const {
213 return supported_versions_
;
216 QuicVersion
version() const {
217 return quic_version_
;
220 void set_version(const QuicVersion version
);
222 // Does not DCHECK for supported version. Used by tests to set unsupported
223 // version to trigger version negotiation.
224 void set_version_for_tests(const QuicVersion version
) {
225 quic_version_
= version
;
228 // Set entropy calculator to be called from the framer when it needs the
229 // entropy of a truncated ack frame. An entropy calculator must be set or else
230 // the framer will likely crash. If this is called multiple times, only the
231 // last calculator will be used.
232 void set_received_entropy_calculator(
233 QuicReceivedEntropyHashCalculatorInterface
* entropy_calculator
) {
234 entropy_calculator_
= entropy_calculator
;
237 QuicErrorCode
error() const {
241 // Pass a UDP packet into the framer for parsing.
242 // Return true if the packet was processed succesfully. |packet| must be a
243 // single, complete UDP packet (not a frame of a packet). This packet
244 // might be null padded past the end of the payload, which will be correctly
246 bool ProcessPacket(const QuicEncryptedPacket
& packet
);
248 // Pass a data packet that was revived from FEC data into the framer
250 // Return true if the packet was processed succesfully. |payload| must be
251 // the complete DECRYPTED payload of the revived packet.
252 bool ProcessRevivedPacket(QuicPacketHeader
* header
,
253 base::StringPiece payload
);
255 // Largest size in bytes of all stream frame fields without the payload.
256 static size_t GetMinStreamFrameSize(QuicStreamId stream_id
,
257 QuicStreamOffset offset
,
258 bool last_frame_in_packet
,
259 InFecGroup is_in_fec_group
);
260 // Size in bytes of all ack frame fields without the missing packets.
261 static size_t GetMinAckFrameSize(
262 QuicSequenceNumberLength sequence_number_length
,
263 QuicSequenceNumberLength largest_observed_length
);
264 // Size in bytes of a stop waiting frame.
265 static size_t GetStopWaitingFrameSize(
266 QuicSequenceNumberLength sequence_number_length
);
267 // Size in bytes of all reset stream frame without the error details.
268 static size_t GetMinRstStreamFrameSize();
269 // Size in bytes of all connection close frame fields without the error
270 // details and the missing packets from the enclosed ack frame.
271 static size_t GetMinConnectionCloseFrameSize();
272 // Size in bytes of all GoAway frame fields without the reason phrase.
273 static size_t GetMinGoAwayFrameSize();
274 // Size in bytes of all WindowUpdate frame fields.
275 static size_t GetWindowUpdateFrameSize();
276 // Size in bytes of all Blocked frame fields.
277 static size_t GetBlockedFrameSize();
278 // Size in bytes required to serialize the stream id.
279 static size_t GetStreamIdSize(QuicStreamId stream_id
);
280 // Size in bytes required to serialize the stream offset.
281 static size_t GetStreamOffsetSize(QuicStreamOffset offset
);
282 // Size in bytes required for a serialized version negotiation packet
283 static size_t GetVersionNegotiationPacketSize(size_t number_versions
);
285 // Returns the number of bytes added to the packet for the specified frame,
286 // and 0 if the frame doesn't fit. Includes the header size for the first
288 size_t GetSerializedFrameLength(
289 const QuicFrame
& frame
,
291 bool first_frame_in_packet
,
292 bool last_frame_in_packet
,
293 InFecGroup is_in_fec_group
,
294 QuicSequenceNumberLength sequence_number_length
);
296 // Returns the associated data from the encrypted packet |encrypted| as a
298 static base::StringPiece
GetAssociatedDataFromEncryptedPacket(
299 const QuicEncryptedPacket
& encrypted
,
300 QuicConnectionIdLength connection_id_length
,
301 bool includes_version
,
302 QuicSequenceNumberLength sequence_number_length
);
304 // Returns a QuicPacket* that is owned by the caller, is created from
305 // |frames|. Returns nullptr if the packet could not be created.
306 // The packet must be of size |packet_size|.
307 QuicPacket
* BuildDataPacket(const QuicPacketHeader
& header
,
308 const QuicFrames
& frames
,
310 size_t packet_length
);
312 // Returns a QuicPacket* that is owned by the caller, and is populated with
313 // the fields in |header| and |fec|. Returns nullptr if the packet could
315 QuicPacket
* BuildFecPacket(const QuicPacketHeader
& header
,
316 const QuicFecData
& fec
);
318 // Returns a new public reset packet, owned by the caller.
319 static QuicEncryptedPacket
* BuildPublicResetPacket(
320 const QuicPublicResetPacket
& packet
);
322 QuicEncryptedPacket
* BuildVersionNegotiationPacket(
323 const QuicPacketPublicHeader
& header
,
324 const QuicVersionVector
& supported_versions
);
326 // SetDecrypter sets the primary decrypter, replacing any that already exists,
327 // and takes ownership. If an alternative decrypter is in place then the
328 // function DCHECKs. This is intended for cases where one knows that future
329 // packets will be using the new decrypter and the previous decrypter is now
330 // obsolete. |level| indicates the encryption level of the new decrypter.
331 void SetDecrypter(QuicDecrypter
* decrypter
, EncryptionLevel level
);
333 // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
334 // future packets and takes ownership of it. |level| indicates the encryption
335 // level of the decrypter. If |latch_once_used| is true, then the first time
336 // that the decrypter is successful it will replace the primary decrypter.
337 // Otherwise both decrypters will remain active and the primary decrypter
338 // will be the one last used.
339 void SetAlternativeDecrypter(QuicDecrypter
* decrypter
,
340 EncryptionLevel level
,
341 bool latch_once_used
);
343 const QuicDecrypter
* decrypter() const;
344 const QuicDecrypter
* alternative_decrypter() const;
346 // Changes the encrypter used for level |level| to |encrypter|. The function
347 // takes ownership of |encrypter|.
348 void SetEncrypter(EncryptionLevel level
, QuicEncrypter
* encrypter
);
349 const QuicEncrypter
* encrypter(EncryptionLevel level
) const;
351 // Returns a new encrypted packet, owned by the caller.
352 QuicEncryptedPacket
* EncryptPacket(EncryptionLevel level
,
353 QuicPacketSequenceNumber sequence_number
,
354 const QuicPacket
& packet
);
356 // Returns the maximum length of plaintext that can be encrypted
357 // to ciphertext no larger than |ciphertext_size|.
358 size_t GetMaxPlaintextSize(size_t ciphertext_size
);
360 const std::string
& detailed_error() { return detailed_error_
; }
362 // The minimum sequence number length required to represent |sequence_number|.
363 static QuicSequenceNumberLength
GetMinSequenceNumberLength(
364 QuicPacketSequenceNumber sequence_number
);
366 void SetSupportedVersions(const QuicVersionVector
& versions
) {
367 supported_versions_
= versions
;
368 quic_version_
= versions
[0];
371 void set_validate_flags(bool value
) { validate_flags_
= value
; }
373 bool is_server() const { return is_server_
; }
375 static QuicPacketEntropyHash
GetPacketEntropyHash(
376 const QuicPacketHeader
& header
);
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 bool ProcessDataPacket(const QuicPacketPublicHeader
& public_header
,
394 const QuicEncryptedPacket
& packet
,
395 char* decrypted_buffer
,
396 size_t buffer_length
);
398 bool ProcessPublicResetPacket(const QuicPacketPublicHeader
& public_header
);
400 bool ProcessVersionNegotiationPacket(QuicPacketPublicHeader
* public_header
);
402 bool ProcessPublicHeader(QuicPacketPublicHeader
* header
);
404 // |decrypted_buffer| must be allocated to be large enough to hold the
405 // unencrypted contents of |packet|.
406 bool ProcessPacketHeader(QuicPacketHeader
* header
,
407 const QuicEncryptedPacket
& packet
,
408 char* decrypted_buffer
,
409 size_t buffer_length
);
411 bool ProcessPacketSequenceNumber(
412 QuicSequenceNumberLength sequence_number_length
,
413 QuicPacketSequenceNumber
* sequence_number
);
414 bool ProcessFrameData(const QuicPacketHeader
& header
);
415 bool ProcessStreamFrame(uint8 frame_type
, QuicStreamFrame
* frame
);
416 bool ProcessAckFrame(uint8 frame_type
, QuicAckFrame
* frame
);
417 bool ProcessTimestampsInAckFrame(QuicAckFrame
* frame
);
418 bool ProcessStopWaitingFrame(const QuicPacketHeader
& public_header
,
419 QuicStopWaitingFrame
* stop_waiting
);
420 bool ProcessRstStreamFrame(QuicRstStreamFrame
* frame
);
421 bool ProcessConnectionCloseFrame(QuicConnectionCloseFrame
* frame
);
422 bool ProcessGoAwayFrame(QuicGoAwayFrame
* frame
);
423 bool ProcessWindowUpdateFrame(QuicWindowUpdateFrame
* frame
);
424 bool ProcessBlockedFrame(QuicBlockedFrame
* frame
);
426 bool DecryptPayload(const QuicPacketHeader
& header
,
427 const QuicEncryptedPacket
& packet
,
428 char* decrypted_buffer
,
429 size_t buffer_length
);
431 // Returns the full packet sequence number from the truncated
432 // wire format version and the last seen packet sequence number.
433 QuicPacketSequenceNumber
CalculatePacketSequenceNumberFromWire(
434 QuicSequenceNumberLength sequence_number_length
,
435 QuicPacketSequenceNumber packet_sequence_number
) const;
437 // Returns the QuicTime::Delta corresponding to the time from when the framer
439 const QuicTime::Delta
CalculateTimestampFromWire(uint32 time_delta_us
);
441 // Computes the wire size in bytes of the |ack| frame, assuming no truncation.
442 size_t GetAckFrameSize(const QuicAckFrame
& ack
,
443 QuicSequenceNumberLength sequence_number_length
);
445 // Computes the wire size in bytes of the payload of |frame|.
446 size_t ComputeFrameLength(const QuicFrame
& frame
,
447 bool last_frame_in_packet
,
448 InFecGroup is_in_fec_group
,
449 QuicSequenceNumberLength sequence_number_length
);
451 static bool AppendPacketSequenceNumber(
452 QuicSequenceNumberLength sequence_number_length
,
453 QuicPacketSequenceNumber packet_sequence_number
,
454 QuicDataWriter
* writer
);
456 static uint8
GetSequenceNumberFlags(
457 QuicSequenceNumberLength sequence_number_length
);
459 static AckFrameInfo
GetAckFrameInfo(const QuicAckFrame
& frame
);
461 // The Append* methods attempt to write the provided header or frame using the
462 // |writer|, and return true if successful.
463 bool AppendPacketHeader(const QuicPacketHeader
& header
,
464 QuicDataWriter
* writer
);
465 bool AppendTypeByte(const QuicFrame
& frame
,
466 bool last_frame_in_packet
,
467 QuicDataWriter
* writer
);
468 bool AppendStreamFrame(const QuicStreamFrame
& frame
,
469 bool last_frame_in_packet
,
470 QuicDataWriter
* builder
);
471 bool AppendAckFrameAndTypeByte(const QuicPacketHeader
& header
,
472 const QuicAckFrame
& frame
,
473 QuicDataWriter
* builder
);
474 bool AppendTimestampToAckFrame(const QuicAckFrame
& frame
,
475 QuicDataWriter
* builder
);
476 bool AppendStopWaitingFrame(const QuicPacketHeader
& header
,
477 const QuicStopWaitingFrame
& frame
,
478 QuicDataWriter
* builder
);
479 bool AppendRstStreamFrame(const QuicRstStreamFrame
& frame
,
480 QuicDataWriter
* builder
);
481 bool AppendConnectionCloseFrame(const QuicConnectionCloseFrame
& frame
,
482 QuicDataWriter
* builder
);
483 bool AppendGoAwayFrame(const QuicGoAwayFrame
& frame
, QuicDataWriter
* writer
);
484 bool AppendWindowUpdateFrame(const QuicWindowUpdateFrame
& frame
,
485 QuicDataWriter
* writer
);
486 bool AppendBlockedFrame(const QuicBlockedFrame
& frame
,
487 QuicDataWriter
* writer
);
489 bool RaiseError(QuicErrorCode error
);
491 void set_error(QuicErrorCode error
) {
495 void set_detailed_error(const char* error
) {
496 detailed_error_
= error
;
499 std::string detailed_error_
;
500 scoped_ptr
<QuicDataReader
> reader_
;
501 QuicFramerVisitorInterface
* visitor_
;
502 QuicFecBuilderInterface
* fec_builder_
;
503 QuicReceivedEntropyHashCalculatorInterface
* entropy_calculator_
;
504 QuicErrorCode error_
;
505 // Updated by ProcessPacketHeader when it succeeds.
506 QuicPacketSequenceNumber last_sequence_number_
;
507 // Updated by WritePacketHeader.
508 QuicConnectionId last_serialized_connection_id_
;
509 // Version of the protocol being used.
510 QuicVersion quic_version_
;
511 // This vector contains QUIC versions which we currently support.
512 // This should be ordered such that the highest supported version is the first
513 // element, with subsequent elements in descending order (versions can be
514 // skipped as necessary).
515 QuicVersionVector supported_versions_
;
516 // Primary decrypter used to decrypt packets during parsing.
517 scoped_ptr
<QuicDecrypter
> decrypter_
;
518 // Alternative decrypter that can also be used to decrypt packets.
519 scoped_ptr
<QuicDecrypter
> alternative_decrypter_
;
520 // The encryption level of |decrypter_|.
521 EncryptionLevel decrypter_level_
;
522 // The encryption level of |alternative_decrypter_|.
523 EncryptionLevel alternative_decrypter_level_
;
524 // |alternative_decrypter_latch_| is true if, when |alternative_decrypter_|
525 // successfully decrypts a packet, we should install it as the only
527 bool alternative_decrypter_latch_
;
528 // Encrypters used to encrypt packets via EncryptPacket().
529 scoped_ptr
<QuicEncrypter
> encrypter_
[NUM_ENCRYPTION_LEVELS
];
530 // Tracks if the framer is being used by the entity that received the
531 // connection or the entity that initiated it.
533 // If false, skip validation that the public flags are set to legal values.
534 bool validate_flags_
;
535 // The time this framer was created. Time written to the wire will be
536 // written as a delta from this value.
537 QuicTime creation_time_
;
538 // The time delta computed for the last timestamp frame. This is relative to
539 // the creation_time.
540 QuicTime::Delta last_timestamp_
;
542 DISALLOW_COPY_AND_ASSIGN(QuicFramer
);
547 #endif // NET_QUIC_QUIC_FRAMER_H_