• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #ifndef NET_QUIC_QUIC_FRAMER_H_
6 #define NET_QUIC_QUIC_FRAMER_H_
7 
8 #include <vector>
9 
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"
16 
17 namespace net {
18 
19 namespace test {
20 class QuicFramerPeer;
21 }  // namespace test
22 
23 class QuicDataReader;
24 class QuicDataWriter;
25 class QuicDecrypter;
26 class QuicEncrypter;
27 class QuicFramer;
28 
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;
35 
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;
42 
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 kNumberOfMissingPacketsSize = 1;
50 
51 // This class receives callbacks from the framer when packets
52 // are processed.
53 class NET_EXPORT_PRIVATE QuicFramerVisitorInterface {
54  public:
~QuicFramerVisitorInterface()55   virtual ~QuicFramerVisitorInterface() {}
56 
57   // Called if an error is detected in the QUIC protocol.
58   virtual void OnError(QuicFramer* framer) = 0;
59 
60   // Called only when |is_server_| is true and the the framer gets a packet with
61   // version flag true and the version on the packet doesn't match
62   // |quic_version_|. The visitor should return true after it updates the
63   // version of the |framer_| to |received_version| or false to stop processing
64   // this packet.
65   virtual bool OnProtocolVersionMismatch(QuicVersion received_version) = 0;
66 
67   // Called when a new packet has been received, before it
68   // has been validated or processed.
69   virtual void OnPacket() = 0;
70 
71   // Called when a public reset packet has been parsed but has not yet
72   // been validated.
73   virtual void OnPublicResetPacket(
74       const QuicPublicResetPacket& packet) = 0;
75 
76   // Called only when |is_server_| is false and a version negotiation packet has
77   // been parsed.
78   virtual void OnVersionNegotiationPacket(
79       const QuicVersionNegotiationPacket& packet) = 0;
80 
81   // Called when a lost packet has been recovered via FEC,
82   // before it has been processed.
83   virtual void OnRevivedPacket() = 0;
84 
85   // Called when the unauthenticated portion of the header has been parsed.
86   // If OnUnauthenticatedHeader returns false, framing for this packet will
87   // cease.
88   virtual bool OnUnauthenticatedHeader(const QuicPacketHeader& header) = 0;
89 
90   // Called when the complete header of a packet had been parsed.
91   // If OnPacketHeader returns false, framing for this packet will cease.
92   virtual bool OnPacketHeader(const QuicPacketHeader& header) = 0;
93 
94   // Called when a data packet is parsed that is part of an FEC group.
95   // |payload| is the non-encrypted FEC protected payload of the packet.
96   virtual void OnFecProtectedPayload(base::StringPiece payload) = 0;
97 
98   // Called when a StreamFrame has been parsed.
99   virtual bool OnStreamFrame(const QuicStreamFrame& frame) = 0;
100 
101   // Called when a AckFrame has been parsed.  If OnAckFrame returns false,
102   // the framer will stop parsing the current packet.
103   virtual bool OnAckFrame(const QuicAckFrame& frame) = 0;
104 
105   // Called when a CongestionFeedbackFrame has been parsed.
106   virtual bool OnCongestionFeedbackFrame(
107       const QuicCongestionFeedbackFrame& frame) = 0;
108 
109   // Called when a RstStreamFrame has been parsed.
110   virtual bool OnRstStreamFrame(const QuicRstStreamFrame& frame) = 0;
111 
112   // Called when a ConnectionCloseFrame has been parsed.
113   virtual bool OnConnectionCloseFrame(
114       const QuicConnectionCloseFrame& frame) = 0;
115 
116   // Called when a GoAwayFrame has been parsed.
117   virtual bool OnGoAwayFrame(const QuicGoAwayFrame& frame) = 0;
118 
119   // Called when FEC data has been parsed.
120   virtual void OnFecData(const QuicFecData& fec) = 0;
121 
122   // Called when a packet has been completely processed.
123   virtual void OnPacketComplete() = 0;
124 };
125 
126 class NET_EXPORT_PRIVATE QuicFecBuilderInterface {
127  public:
~QuicFecBuilderInterface()128   virtual ~QuicFecBuilderInterface() {}
129 
130   // Called when a data packet is constructed that is part of an FEC group.
131   // |payload| is the non-encrypted FEC protected payload of the packet.
132   virtual void OnBuiltFecProtectedPayload(const QuicPacketHeader& header,
133                                           base::StringPiece payload) = 0;
134 };
135 
136 // This class calculates the received entropy of the ack packet being
137 // framed, should it get truncated.
138 class NET_EXPORT_PRIVATE QuicReceivedEntropyHashCalculatorInterface {
139  public:
~QuicReceivedEntropyHashCalculatorInterface()140   virtual ~QuicReceivedEntropyHashCalculatorInterface() {}
141 
142   // When an ack frame gets truncated while being framed the received
143   // entropy of the ack frame needs to be calculated since the some of the
144   // missing packets are not added and the largest observed might be lowered.
145   // This should return the received entropy hash of the packets received up to
146   // and including |sequence_number|.
147   virtual QuicPacketEntropyHash EntropyHash(
148       QuicPacketSequenceNumber sequence_number) const = 0;
149 };
150 
151 // Class for parsing and constructing QUIC packets.  It has a
152 // QuicFramerVisitorInterface that is called when packets are parsed.
153 // It also has a QuicFecBuilder that is called when packets are constructed
154 // in order to generate FEC data for subsequently building FEC packets.
155 class NET_EXPORT_PRIVATE QuicFramer {
156  public:
157   // Constructs a new framer that installs a kNULL QuicEncrypter and
158   // QuicDecrypter for level ENCRYPTION_NONE. |supported_versions| specifies the
159   // list of supported QUIC versions. |quic_version_| is set to the maximum
160   // version in |supported_versions|.
161   QuicFramer(const QuicVersionVector& supported_versions,
162              QuicTime creation_time,
163              bool is_server);
164 
165   virtual ~QuicFramer();
166 
167   // Returns true if |version| is a supported protocol version.
168   bool IsSupportedVersion(const QuicVersion version) const;
169 
170   // Returns true if the version flag is set in the public flags.
171   static bool HasVersionFlag(const QuicEncryptedPacket& packet);
172 
173   // Calculates the largest observed packet to advertise in the case an Ack
174   // Frame was truncated.  last_written in this case is the iterator for the
175   // last missing packet which fit in the outgoing ack.
176   static QuicPacketSequenceNumber CalculateLargestObserved(
177       const SequenceNumberSet& missing_packets,
178       SequenceNumberSet::const_iterator last_written);
179 
180   // Set callbacks to be called from the framer.  A visitor must be set, or
181   // else the framer will likely crash.  It is acceptable for the visitor
182   // to do nothing.  If this is called multiple times, only the last visitor
183   // will be used.
set_visitor(QuicFramerVisitorInterface * visitor)184   void set_visitor(QuicFramerVisitorInterface* visitor) {
185     visitor_ = visitor;
186   }
187 
188   // Set a builder to be called from the framer when building FEC protected
189   // packets.  If this is called multiple times, only the last builder
190   // will be used.  The builder need not be set.
set_fec_builder(QuicFecBuilderInterface * builder)191   void set_fec_builder(QuicFecBuilderInterface* builder) {
192     fec_builder_ = builder;
193   }
194 
supported_versions()195   const QuicVersionVector& supported_versions() const {
196     return supported_versions_;
197   }
198 
version()199   QuicVersion version() const {
200     return quic_version_;
201   }
202 
203   void set_version(const QuicVersion version);
204 
205   // Does not DCHECK for supported version. Used by tests to set unsupported
206   // version to trigger version negotiation.
set_version_for_tests(const QuicVersion version)207   void set_version_for_tests(const QuicVersion version) {
208     quic_version_ = version;
209   }
210 
211   // Set entropy calculator to be called from the framer when it needs the
212   // entropy of a truncated ack frame. An entropy calculator must be set or else
213   // the framer will likely crash. If this is called multiple times, only the
214   // last calculator will be used.
set_received_entropy_calculator(QuicReceivedEntropyHashCalculatorInterface * entropy_calculator)215   void set_received_entropy_calculator(
216       QuicReceivedEntropyHashCalculatorInterface* entropy_calculator) {
217     entropy_calculator_ = entropy_calculator;
218   }
219 
error()220   QuicErrorCode error() const {
221     return error_;
222   }
223 
224   // Pass a UDP packet into the framer for parsing.
225   // Return true if the packet was processed succesfully. |packet| must be a
226   // single, complete UDP packet (not a frame of a packet).  This packet
227   // might be null padded past the end of the payload, which will be correctly
228   // ignored.
229   bool ProcessPacket(const QuicEncryptedPacket& packet);
230 
231   // Pass a data packet that was revived from FEC data into the framer
232   // for parsing.
233   // Return true if the packet was processed succesfully. |payload| must be
234   // the complete DECRYPTED payload of the revived packet.
235   bool ProcessRevivedPacket(QuicPacketHeader* header,
236                             base::StringPiece payload);
237 
238   // Largest size in bytes of all stream frame fields without the payload.
239   static size_t GetMinStreamFrameSize(QuicVersion version,
240                                       QuicStreamId stream_id,
241                                       QuicStreamOffset offset,
242                                       bool last_frame_in_packet);
243   // Size in bytes of all ack frame fields without the missing packets.
244   static size_t GetMinAckFrameSize(
245       QuicVersion version,
246       QuicSequenceNumberLength sequence_number_length,
247       QuicSequenceNumberLength largest_observed_length);
248   // Size in bytes of all reset stream frame without the error details.
249   static size_t GetMinRstStreamFrameSize();
250   // Size in bytes of all connection close frame fields without the error
251   // details and the missing packets from the enclosed ack frame.
252   static size_t GetMinConnectionCloseFrameSize();
253   // Size in bytes of all GoAway frame fields without the reason phrase.
254   static size_t GetMinGoAwayFrameSize();
255   // The maximum number of nacks which can be transmitted in a single ack packet
256   // without exceeding kDefaultMaxPacketSize.
257   static size_t GetMaxUnackedPackets(QuicPacketHeader header);
258   // Size in bytes required to serialize the stream id.
259   static size_t GetStreamIdSize(QuicStreamId stream_id);
260   // Size in bytes required to serialize the stream offset.
261   static size_t GetStreamOffsetSize(QuicStreamOffset offset);
262   // Size in bytes required for a serialized version negotiation packet
263   static size_t GetVersionNegotiationPacketSize(size_t number_versions);
264 
265 
266   static bool CanTruncate(
267       QuicVersion version, const QuicFrame& frame, size_t free_bytes);
268 
269   // Returns the number of bytes added to the packet for the specified frame,
270   // and 0 if the frame doesn't fit.  Includes the header size for the first
271   // frame.
272   size_t GetSerializedFrameLength(
273       const QuicFrame& frame,
274       size_t free_bytes,
275       bool first_frame,
276       bool last_frame,
277       QuicSequenceNumberLength sequence_number_length);
278 
279   // Returns the associated data from the encrypted packet |encrypted| as a
280   // stringpiece.
281   static base::StringPiece GetAssociatedDataFromEncryptedPacket(
282       const QuicEncryptedPacket& encrypted,
283       QuicGuidLength guid_length,
284       bool includes_version,
285       QuicSequenceNumberLength sequence_number_length);
286 
287   // Returns a SerializedPacket whose |packet| member is owned by the caller,
288   // and is populated with the fields in |header| and |frames|, or is NULL if
289   // the packet could not be created.
290   // TODO(ianswett): Used for testing only.
291   SerializedPacket BuildUnsizedDataPacket(const QuicPacketHeader& header,
292                                           const QuicFrames& frames);
293 
294   // Returns a SerializedPacket whose |packet| member is owned by the caller,
295   // is created from the first |num_frames| frames, or is NULL if the packet
296   // could not be created.  The packet must be of size |packet_size|.
297   SerializedPacket BuildDataPacket(const QuicPacketHeader& header,
298                                    const QuicFrames& frames,
299                                    size_t packet_size);
300 
301   // Returns a SerializedPacket whose |packet| member is owned by the caller,
302   // and is populated with the fields in |header| and |fec|, or is NULL if the
303   // packet could not be created.
304   SerializedPacket BuildFecPacket(const QuicPacketHeader& header,
305                                   const QuicFecData& fec);
306 
307   // Returns a new public reset packet, owned by the caller.
308   static QuicEncryptedPacket* BuildPublicResetPacket(
309       const QuicPublicResetPacket& packet);
310 
311   QuicEncryptedPacket* BuildVersionNegotiationPacket(
312       const QuicPacketPublicHeader& header,
313       const QuicVersionVector& supported_versions);
314 
315   // SetDecrypter sets the primary decrypter, replacing any that already exists,
316   // and takes ownership. If an alternative decrypter is in place then the
317   // function DCHECKs. This is intended for cases where one knows that future
318   // packets will be using the new decrypter and the previous decrypter is not
319   // obsolete.
320   void SetDecrypter(QuicDecrypter* decrypter);
321 
322   // SetAlternativeDecrypter sets a decrypter that may be used to decrypt
323   // future packets and takes ownership of it. If |latch_once_used| is true,
324   // then the first time that the decrypter is successful it will replace the
325   // primary decrypter. Otherwise both decrypters will remain active and the
326   // primary decrypter will be the one last used.
327   void SetAlternativeDecrypter(QuicDecrypter* decrypter,
328                                bool latch_once_used);
329 
330   const QuicDecrypter* decrypter() const;
331   const QuicDecrypter* alternative_decrypter() const;
332 
333   // Changes the encrypter used for level |level| to |encrypter|. The function
334   // takes ownership of |encrypter|.
335   void SetEncrypter(EncryptionLevel level, QuicEncrypter* encrypter);
336   const QuicEncrypter* encrypter(EncryptionLevel level) const;
337 
338   // SwapCryptersForTest exchanges the state of the crypters with |other|. To
339   // be used in tests only.
340   void SwapCryptersForTest(QuicFramer* other);
341 
342   // Returns a new encrypted packet, owned by the caller.
343   QuicEncryptedPacket* EncryptPacket(EncryptionLevel level,
344                                      QuicPacketSequenceNumber sequence_number,
345                                      const QuicPacket& packet);
346 
347   // Returns the maximum length of plaintext that can be encrypted
348   // to ciphertext no larger than |ciphertext_size|.
349   size_t GetMaxPlaintextSize(size_t ciphertext_size);
350 
detailed_error()351   const std::string& detailed_error() { return detailed_error_; }
352 
353   // Read the full 8 byte guid from a packet header.
354   // Return true on success, else false.
355   static bool ReadGuidFromPacket(const QuicEncryptedPacket& packet,
356                                  QuicGuid* guid);
357 
358   static QuicSequenceNumberLength ReadSequenceNumberLength(uint8 flags);
359 
360   // The minimum sequence number length required to represent |sequence_number|.
361   static QuicSequenceNumberLength GetMinSequenceNumberLength(
362       QuicPacketSequenceNumber sequence_number);
363 
364  private:
365   friend class test::QuicFramerPeer;
366 
367   typedef std::map<QuicPacketSequenceNumber, uint8> NackRangeMap;
368 
369   struct AckFrameInfo {
370     AckFrameInfo();
371     ~AckFrameInfo();
372 
373     // The maximum delta between ranges.
374     QuicPacketSequenceNumber max_delta;
375     // Nack ranges starting with start sequence numbers and lengths.
376     NackRangeMap nack_ranges;
377   };
378 
379   QuicPacketEntropyHash GetPacketEntropyHash(
380       const QuicPacketHeader& header) const;
381 
382   bool ProcessDataPacket(const QuicPacketPublicHeader& public_header,
383                          const QuicEncryptedPacket& packet);
384 
385   bool ProcessPublicResetPacket(const QuicPacketPublicHeader& public_header);
386 
387   bool ProcessVersionNegotiationPacket(QuicPacketPublicHeader* public_header);
388 
389   bool ProcessPublicHeader(QuicPacketPublicHeader* header);
390 
391   bool ProcessPacketHeader(QuicPacketHeader* header,
392                            const QuicEncryptedPacket& packet);
393 
394   bool ProcessPacketSequenceNumber(
395       QuicSequenceNumberLength sequence_number_length,
396       QuicPacketSequenceNumber* sequence_number);
397   bool ProcessFrameData(const QuicPacketHeader& header);
398   bool ProcessStreamFrame(uint8 frame_type, QuicStreamFrame* frame);
399   bool ProcessAckFrame(const QuicPacketHeader& header,
400                        uint8 frame_type,
401                        QuicAckFrame* frame);
402   bool ProcessReceivedInfo(uint8 frame_type, ReceivedPacketInfo* received_info);
403   bool ProcessSentInfo(const QuicPacketHeader& public_header,
404                        SentPacketInfo* sent_info);
405   bool ProcessQuicCongestionFeedbackFrame(
406       QuicCongestionFeedbackFrame* congestion_feedback);
407   bool ProcessRstStreamFrame(QuicRstStreamFrame* frame);
408   bool ProcessConnectionCloseFrame(QuicConnectionCloseFrame* frame);
409   bool ProcessGoAwayFrame(QuicGoAwayFrame* frame);
410 
411   bool DecryptPayload(const QuicPacketHeader& header,
412                       const QuicEncryptedPacket& packet);
413 
414   // Returns the full packet sequence number from the truncated
415   // wire format version and the last seen packet sequence number.
416   QuicPacketSequenceNumber CalculatePacketSequenceNumberFromWire(
417       QuicSequenceNumberLength sequence_number_length,
418       QuicPacketSequenceNumber packet_sequence_number) const;
419 
420   // Computes the wire size in bytes of the |ack| frame, assuming no truncation.
421   size_t GetAckFrameSize(const QuicAckFrame& ack,
422                          QuicSequenceNumberLength sequence_number_length);
423 
424   // Computes the wire size in bytes of the payload of |frame|.
425   size_t ComputeFrameLength(const QuicFrame& frame,
426                             bool last_frame_in_packet,
427                             QuicSequenceNumberLength sequence_number_length);
428 
429   static bool AppendPacketSequenceNumber(
430       QuicSequenceNumberLength sequence_number_length,
431       QuicPacketSequenceNumber packet_sequence_number,
432       QuicDataWriter* writer);
433 
434   static uint8 GetSequenceNumberFlags(
435       QuicSequenceNumberLength sequence_number_length);
436 
437   static AckFrameInfo GetAckFrameInfo(const QuicAckFrame& frame);
438 
439   bool AppendPacketHeader(const QuicPacketHeader& header,
440                           QuicDataWriter* writer);
441   bool AppendTypeByte(const QuicFrame& frame,
442                       bool last_frame_in_packet,
443                       QuicDataWriter* writer);
444   bool AppendStreamFramePayload(const QuicStreamFrame& frame,
445                                 bool last_frame_in_packet,
446                                 QuicDataWriter* builder);
447   bool AppendAckFramePayloadAndTypeByte(const QuicPacketHeader& header,
448                                         const QuicAckFrame& frame,
449                                         QuicDataWriter* builder);
450   bool AppendQuicCongestionFeedbackFramePayload(
451       const QuicCongestionFeedbackFrame& frame,
452       QuicDataWriter* builder);
453   bool AppendRstStreamFramePayload(const QuicRstStreamFrame& frame,
454                                    QuicDataWriter* builder);
455   bool AppendConnectionCloseFramePayload(
456       const QuicConnectionCloseFrame& frame,
457       QuicDataWriter* builder);
458   bool AppendGoAwayFramePayload(const QuicGoAwayFrame& frame,
459                                 QuicDataWriter* writer);
460   bool RaiseError(QuicErrorCode error);
461 
set_error(QuicErrorCode error)462   void set_error(QuicErrorCode error) {
463     error_ = error;
464   }
465 
set_detailed_error(const char * error)466   void set_detailed_error(const char* error) {
467     detailed_error_ = error;
468   }
469 
470   std::string detailed_error_;
471   scoped_ptr<QuicDataReader> reader_;
472   QuicFramerVisitorInterface* visitor_;
473   QuicFecBuilderInterface* fec_builder_;
474   QuicReceivedEntropyHashCalculatorInterface* entropy_calculator_;
475   QuicErrorCode error_;
476   // Updated by ProcessPacketHeader when it succeeds.
477   QuicPacketSequenceNumber last_sequence_number_;
478   // Updated by WritePacketHeader.
479   QuicGuid last_serialized_guid_;
480   // Buffer containing decrypted payload data during parsing.
481   scoped_ptr<QuicData> decrypted_;
482   // Version of the protocol being used.
483   QuicVersion quic_version_;
484   // This vector contains QUIC versions which we currently support.
485   // This should be ordered such that the highest supported version is the first
486   // element, with subsequent elements in descending order (versions can be
487   // skipped as necessary).
488   QuicVersionVector supported_versions_;
489   // Primary decrypter used to decrypt packets during parsing.
490   scoped_ptr<QuicDecrypter> decrypter_;
491   // Alternative decrypter that can also be used to decrypt packets.
492   scoped_ptr<QuicDecrypter> alternative_decrypter_;
493   // alternative_decrypter_latch_is true if, when |alternative_decrypter_|
494   // successfully decrypts a packet, we should install it as the only
495   // decrypter.
496   bool alternative_decrypter_latch_;
497   // Encrypters used to encrypt packets via EncryptPacket().
498   scoped_ptr<QuicEncrypter> encrypter_[NUM_ENCRYPTION_LEVELS];
499   // Tracks if the framer is being used by the entity that received the
500   // connection or the entity that initiated it.
501   bool is_server_;
502   // The time this frames was created.  Time written to the wire will be
503   // written as a delta from this value.
504   QuicTime creation_time_;
505 
506   DISALLOW_COPY_AND_ASSIGN(QuicFramer);
507 };
508 
509 }  // namespace net
510 
511 #endif  // NET_QUIC_QUIC_FRAMER_H_
512