[Password Autofill] Update bug number for fixing one click popup on Android.
[chromium-blink-merge.git] / net / quic / quic_framer.h
blob4cc51f11ed6f8f0ad9ee12d8e4632999195602c3
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_
8 #include <vector>
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"
17 namespace net {
19 namespace test {
20 class QuicFramerPeer;
21 } // namespace test
23 class QuicDataReader;
24 class QuicDataWriter;
25 class QuicDecrypter;
26 class QuicEncrypter;
27 class QuicFramer;
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
62 // are processed.
63 class NET_EXPORT_PRIVATE QuicFramerVisitorInterface {
64 public:
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
74 // this packet.
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
82 // been validated.
83 virtual void OnPublicResetPacket(
84 const QuicPublicResetPacket& packet) = 0;
86 // Called only when |is_server_| is false and a version negotiation packet has
87 // been parsed.
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
102 // cease.
103 virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) = 0;
105 // Called when a packet has been decrypted. |level| is the encryption level
106 // of the packet.
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 CongestionFeedbackFrame has been parsed.
125 virtual bool OnCongestionFeedbackFrame(
126 const QuicCongestionFeedbackFrame& frame) = 0;
128 // Called when a StopWaitingFrame has been parsed.
129 virtual bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) = 0;
131 // Called when a PingFrame has been parsed.
132 virtual bool OnPingFrame(const QuicPingFrame& frame) = 0;
134 // Called when a RstStreamFrame has been parsed.
135 virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0;
137 // Called when a ConnectionCloseFrame has been parsed.
138 virtual bool OnConnectionCloseFrame(
139 const QuicConnectionCloseFrame& frame) = 0;
141 // Called when a GoAwayFrame has been parsed.
142 virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) = 0;
144 // Called when a WindowUpdateFrame has been parsed.
145 virtual bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) = 0;
147 // Called when a BlockedFrame has been parsed.
148 virtual bool OnBlockedFrame(const QuicBlockedFrame& frame) = 0;
150 // Called when FEC data has been parsed.
151 virtual void OnFecData(const QuicFecData& fec) = 0;
153 // Called when a packet has been completely processed.
154 virtual void OnPacketComplete() = 0;
157 class NET_EXPORT_PRIVATE QuicFecBuilderInterface {
158 public:
159 virtual ~QuicFecBuilderInterface() {}
161 // Called when a data packet is constructed that is part of an FEC group.
162 // |payload| is the non-encrypted FEC protected payload of the packet.
163 virtual void OnBuiltFecProtectedPayload(const QuicPacketHeader& header,
164 base::StringPiece payload) = 0;
167 // This class calculates the received entropy of the ack packet being
168 // framed, should it get truncated.
169 class NET_EXPORT_PRIVATE QuicReceivedEntropyHashCalculatorInterface {
170 public:
171 virtual ~QuicReceivedEntropyHashCalculatorInterface() {}
173 // When an ack frame gets truncated while being framed the received
174 // entropy of the ack frame needs to be calculated since the some of the
175 // missing packets are not added and the largest observed might be lowered.
176 // This should return the received entropy hash of the packets received up to
177 // and including |sequence_number|.
178 virtual QuicPacketEntropyHash EntropyHash(
179 QuicPacketSequenceNumber sequence_number) const = 0;
182 // Class for parsing and constructing QUIC packets. It has a
183 // QuicFramerVisitorInterface that is called when packets are parsed.
184 // It also has a QuicFecBuilder that is called when packets are constructed
185 // in order to generate FEC data for subsequently building FEC packets.
186 class NET_EXPORT_PRIVATE QuicFramer {
187 public:
188 // Constructs a new framer that installs a kNULL QuicEncrypter and
189 // QuicDecrypter for level ENCRYPTION_NONE. |supported_versions| specifies the
190 // list of supported QUIC versions. |quic_version_| is set to the maximum
191 // version in |supported_versions|.
192 QuicFramer(const QuicVersionVector& supported_versions,
193 QuicTime creation_time,
194 bool is_server);
196 virtual ~QuicFramer();
198 // Returns true if |version| is a supported protocol version.
199 bool IsSupportedVersion(const QuicVersion version) const;
201 // Set callbacks to be called from the framer. A visitor must be set, or
202 // else the framer will likely crash. It is acceptable for the visitor
203 // to do nothing. If this is called multiple times, only the last visitor
204 // will be used.
205 void set_visitor(QuicFramerVisitorInterface* visitor) {
206 visitor_ = visitor;
209 // Set a builder to be called from the framer when building FEC protected
210 // packets. If this is called multiple times, only the last builder
211 // will be used. The builder need not be set.
212 void set_fec_builder(QuicFecBuilderInterface* builder) {
213 fec_builder_ = builder;
216 const QuicVersionVector& supported_versions() const {
217 return supported_versions_;
220 QuicVersion version() const {
221 return quic_version_;
224 void set_version(const QuicVersion version);
226 // Does not DCHECK for supported version. Used by tests to set unsupported
227 // version to trigger version negotiation.
228 void set_version_for_tests(const QuicVersion version) {
229 quic_version_ = version;
232 // Set entropy calculator to be called from the framer when it needs the
233 // entropy of a truncated ack frame. An entropy calculator must be set or else
234 // the framer will likely crash. If this is called multiple times, only the
235 // last calculator will be used.
236 void set_received_entropy_calculator(
237 QuicReceivedEntropyHashCalculatorInterface* entropy_calculator) {
238 entropy_calculator_ = entropy_calculator;
241 QuicErrorCode error() const {
242 return error_;
245 // Pass a UDP packet into the framer for parsing.
246 // Return true if the packet was processed succesfully. |packet| must be a
247 // single, complete UDP packet (not a frame of a packet). This packet
248 // might be null padded past the end of the payload, which will be correctly
249 // ignored.
250 bool ProcessPacket(const QuicEncryptedPacket& packet);
252 // Pass a data packet that was revived from FEC data into the framer
253 // for parsing.
254 // Return true if the packet was processed succesfully. |payload| must be
255 // the complete DECRYPTED payload of the revived packet.
256 bool ProcessRevivedPacket(QuicPacketHeader* header,
257 base::StringPiece payload);
259 // Largest size in bytes of all stream frame fields without the payload.
260 static size_t GetMinStreamFrameSize(QuicStreamId stream_id,
261 QuicStreamOffset offset,
262 bool last_frame_in_packet,
263 InFecGroup is_in_fec_group);
264 // Size in bytes of all ack frame fields without the missing packets.
265 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();
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
291 // frame.
292 size_t GetSerializedFrameLength(
293 const QuicFrame& frame,
294 size_t free_bytes,
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
301 // stringpiece.
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 nullptr 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,
313 size_t packet_size);
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 nullptr if
317 // the 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_; }
378 private:
379 friend class test::QuicFramerPeer;
381 typedef std::map<QuicPacketSequenceNumber, uint8> NackRangeMap;
383 struct AckFrameInfo {
384 AckFrameInfo();
385 ~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(uint8 frame_type, QuicAckFrame* frame);
414 bool ProcessTimestampsInAckFrame(QuicAckFrame* frame);
415 bool ProcessStopWaitingFrame(const QuicPacketHeader& public_header,
416 QuicStopWaitingFrame* stop_waiting);
417 bool ProcessCongestionFeedbackFrame(
418 QuicCongestionFeedbackFrame* congestion_feedback);
419 bool ProcessRstStreamFrame(QuicRstStreamFrame* frame);
420 bool ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame);
421 bool ProcessGoAwayFrame(QuicGoAwayFrame* frame);
422 bool ProcessWindowUpdateFrame(QuicWindowUpdateFrame* frame);
423 bool ProcessBlockedFrame(QuicBlockedFrame* frame);
425 bool DecryptPayload(const QuicPacketHeader& header,
426 const QuicEncryptedPacket& packet);
428 // Returns the full packet sequence number from the truncated
429 // wire format version and the last seen packet sequence number.
430 QuicPacketSequenceNumber CalculatePacketSequenceNumberFromWire(
431 QuicSequenceNumberLength sequence_number_length,
432 QuicPacketSequenceNumber packet_sequence_number) const;
434 // Returns the QuicTime::Delta corresponding to the time from when the framer
435 // was created.
436 const QuicTime::Delta CalculateTimestampFromWire(uint32 time_delta_us);
438 // Computes the wire size in bytes of the |ack| frame, assuming no truncation.
439 size_t GetAckFrameSize(const QuicAckFrame& ack,
440 QuicSequenceNumberLength sequence_number_length);
442 // Computes the wire size in bytes of the payload of |frame|.
443 size_t ComputeFrameLength(const QuicFrame& frame,
444 bool last_frame_in_packet,
445 InFecGroup is_in_fec_group,
446 QuicSequenceNumberLength sequence_number_length);
448 static bool AppendPacketSequenceNumber(
449 QuicSequenceNumberLength sequence_number_length,
450 QuicPacketSequenceNumber packet_sequence_number,
451 QuicDataWriter* writer);
453 static uint8 GetSequenceNumberFlags(
454 QuicSequenceNumberLength sequence_number_length);
456 static AckFrameInfo GetAckFrameInfo(const QuicAckFrame& frame);
458 // The Append* methods attempt to write the provided header or frame using the
459 // |writer|, and return true if successful.
460 bool AppendPacketHeader(const QuicPacketHeader& header,
461 QuicDataWriter* writer);
462 bool AppendTypeByte(const QuicFrame& frame,
463 bool last_frame_in_packet,
464 QuicDataWriter* writer);
465 bool AppendStreamFrame(const QuicStreamFrame& frame,
466 bool last_frame_in_packet,
467 QuicDataWriter* builder);
468 bool AppendAckFrameAndTypeByte(const QuicPacketHeader& header,
469 const QuicAckFrame& frame,
470 QuicDataWriter* builder);
471 bool AppendCongestionFeedbackFrame(const QuicCongestionFeedbackFrame& frame,
472 QuicDataWriter* builder);
473 bool AppendTimestampToAckFrame(const QuicAckFrame& frame,
474 QuicDataWriter* builder);
475 bool AppendStopWaitingFrame(const QuicPacketHeader& header,
476 const QuicStopWaitingFrame& frame,
477 QuicDataWriter* builder);
478 bool AppendRstStreamFrame(const QuicRstStreamFrame& frame,
479 QuicDataWriter* builder);
480 bool AppendConnectionCloseFrame(const QuicConnectionCloseFrame& frame,
481 QuicDataWriter* builder);
482 bool AppendGoAwayFrame(const QuicGoAwayFrame& frame, QuicDataWriter* writer);
483 bool AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame,
484 QuicDataWriter* writer);
485 bool AppendBlockedFrame(const QuicBlockedFrame& frame,
486 QuicDataWriter* writer);
488 bool RaiseError(QuicErrorCode error);
490 void set_error(QuicErrorCode error) {
491 error_ = error;
494 void set_detailed_error(const char* error) {
495 detailed_error_ = error;
498 std::string detailed_error_;
499 scoped_ptr<QuicDataReader> reader_;
500 QuicFramerVisitorInterface* visitor_;
501 QuicFecBuilderInterface* fec_builder_;
502 QuicReceivedEntropyHashCalculatorInterface* entropy_calculator_;
503 QuicErrorCode error_;
504 // Updated by ProcessPacketHeader when it succeeds.
505 QuicPacketSequenceNumber last_sequence_number_;
506 // Updated by WritePacketHeader.
507 QuicConnectionId last_serialized_connection_id_;
508 // Buffer containing decrypted payload data during parsing.
509 scoped_ptr<QuicData> decrypted_;
510 // Version of the protocol being used.
511 QuicVersion quic_version_;
512 // This vector contains QUIC versions which we currently support.
513 // This should be ordered such that the highest supported version is the first
514 // element, with subsequent elements in descending order (versions can be
515 // skipped as necessary).
516 QuicVersionVector supported_versions_;
517 // Primary decrypter used to decrypt packets during parsing.
518 scoped_ptr<QuicDecrypter> decrypter_;
519 // Alternative decrypter that can also be used to decrypt packets.
520 scoped_ptr<QuicDecrypter> alternative_decrypter_;
521 // The encryption level of |decrypter_|.
522 EncryptionLevel decrypter_level_;
523 // The encryption level of |alternative_decrypter_|.
524 EncryptionLevel alternative_decrypter_level_;
525 // |alternative_decrypter_latch_| is true if, when |alternative_decrypter_|
526 // successfully decrypts a packet, we should install it as the only
527 // decrypter.
528 bool alternative_decrypter_latch_;
529 // Encrypters used to encrypt packets via EncryptPacket().
530 scoped_ptr<QuicEncrypter> encrypter_[NUM_ENCRYPTION_LEVELS];
531 // Tracks if the framer is being used by the entity that received the
532 // connection or the entity that initiated it.
533 bool is_server_;
534 // If false, skip validation that the public flags are set to legal values.
535 bool validate_flags_;
536 // The time this framer was created. Time written to the wire will be
537 // written as a delta from this value.
538 QuicTime creation_time_;
539 // The time delta computed for the last timestamp frame. This is relative to
540 // the creation_time.
541 QuicTime::Delta last_timestamp_;
543 DISALLOW_COPY_AND_ASSIGN(QuicFramer);
546 } // namespace net
548 #endif // NET_QUIC_QUIC_FRAMER_H_