Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / net / spdy / spdy_framer.h
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_SPDY_SPDY_FRAMER_H_
6 #define NET_SPDY_SPDY_FRAMER_H_
7
8 #include <list>
9 #include <map>
10 #include <memory>
11 #include <string>
12 #include <utility>
13 #include <vector>
14
15 #include "base/basictypes.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/strings/string_piece.h"
19 #include "base/sys_byteorder.h"
20 #include "net/base/net_export.h"
21 #include "net/spdy/hpack_decoder.h"
22 #include "net/spdy/hpack_encoder.h"
23 #include "net/spdy/spdy_header_block.h"
24 #include "net/spdy/spdy_protocol.h"
25
26 // TODO(akalin): Remove support for CREDENTIAL frames.
27
28 typedef struct z_stream_s z_stream;  // Forward declaration for zlib.
29
30 namespace net {
31
32 class HttpProxyClientSocketPoolTest;
33 class HttpNetworkLayer;
34 class HttpNetworkTransactionTest;
35 class SpdyHttpStreamTest;
36 class SpdyNetworkTransactionTest;
37 class SpdyProxyClientSocketTest;
38 class SpdySessionTest;
39 class SpdyStreamTest;
40 class SpdyWebSocketStreamTest;
41 class WebSocketJobTest;
42
43 class SpdyFramer;
44 class SpdyFrameBuilder;
45 class SpdyFramerTest;
46
47 namespace test {
48
49 class TestSpdyVisitor;
50
51 }  // namespace test
52
53 // A datastructure for holding a set of headers from a HEADERS, PUSH_PROMISE,
54 // SYN_STREAM, or SYN_REPLY frame.
55 typedef std::map<std::string, std::string> SpdyHeaderBlock;
56
57 // A datastructure for holding the ID and flag fields for SETTINGS.
58 // Conveniently handles converstion to/from wire format.
59 class NET_EXPORT_PRIVATE SettingsFlagsAndId {
60  public:
61   static SettingsFlagsAndId FromWireFormat(SpdyMajorVersion version,
62                                            uint32 wire);
63
64   SettingsFlagsAndId() : flags_(0), id_(0) {}
65
66   // TODO(hkhalil): restrict to enums instead of free-form ints.
67   SettingsFlagsAndId(uint8 flags, uint32 id);
68
69   uint32 GetWireFormat(SpdyMajorVersion version) const;
70
71   uint32 id() const { return id_; }
72   uint8 flags() const { return flags_; }
73
74  private:
75   static void ConvertFlagsAndIdForSpdy2(uint32* val);
76
77   uint8 flags_;
78   uint32 id_;
79 };
80
81 // SettingsMap has unique (flags, value) pair for given SpdySettingsIds ID.
82 typedef std::pair<SpdySettingsFlags, uint32> SettingsFlagsAndValue;
83 typedef std::map<SpdySettingsIds, SettingsFlagsAndValue> SettingsMap;
84
85 // Scratch space necessary for processing SETTINGS frames.
86 struct NET_EXPORT_PRIVATE SpdySettingsScratch {
87   SpdySettingsScratch() { Reset(); }
88
89   void Reset() {
90     setting_buf_len = 0;
91     last_setting_id = -1;
92   }
93
94   // Buffer contains up to one complete key/value pair.
95   char setting_buf[8];
96
97   // The amount of the buffer that is filled with valid data.
98   size_t setting_buf_len;
99
100   // The ID of the last setting that was processed in the current SETTINGS
101   // frame. Used for detecting out-of-order or duplicate keys within a settings
102   // frame. Set to -1 before first key/value pair is processed.
103   int last_setting_id;
104 };
105
106 // Scratch space necessary for processing ALTSVC frames.
107 struct NET_EXPORT_PRIVATE SpdyAltSvcScratch {
108   SpdyAltSvcScratch();
109   ~SpdyAltSvcScratch();
110
111   void Reset() {
112     max_age = 0;
113     port = 0;
114     pid_len = 0;
115     host_len = 0;
116     origin_len = 0;
117     pid_buf_len = 0;
118     host_buf_len = 0;
119     origin_buf_len = 0;
120     protocol_id.reset();
121     host.reset();
122     origin.reset();
123   }
124
125   uint32 max_age;
126   uint16 port;
127   uint8 pid_len;
128   uint8 host_len;
129   size_t origin_len;
130   size_t pid_buf_len;
131   size_t host_buf_len;
132   size_t origin_buf_len;
133   scoped_ptr<char[]> protocol_id;
134   scoped_ptr<char[]> host;
135   scoped_ptr<char[]> origin;
136 };
137
138 // SpdyFramerVisitorInterface is a set of callbacks for the SpdyFramer.
139 // Implement this interface to receive event callbacks as frames are
140 // decoded from the framer.
141 //
142 // Control frames that contain SPDY header blocks (SYN_STREAM, SYN_REPLY,
143 // HEADER, and PUSH_PROMISE) are processed in fashion that allows the
144 // decompressed header block to be delivered in chunks to the visitor.
145 // The following steps are followed:
146 //   1. OnSynStream, OnSynReply, OnHeaders, or OnPushPromise is called.
147 //   2. Repeated: OnControlFrameHeaderData is called with chunks of the
148 //      decompressed header block. In each call the len parameter is greater
149 //      than zero.
150 //   3. OnControlFrameHeaderData is called with len set to zero, indicating
151 //      that the full header block has been delivered for the control frame.
152 // During step 2 the visitor may return false, indicating that the chunk of
153 // header data could not be handled by the visitor (typically this indicates
154 // resource exhaustion). If this occurs the framer will discontinue
155 // delivering chunks to the visitor, set a SPDY_CONTROL_PAYLOAD_TOO_LARGE
156 // error, and clean up appropriately. Note that this will cause the header
157 // decompressor to lose synchronization with the sender's header compressor,
158 // making the SPDY session unusable for future work. The visitor's OnError
159 // function should deal with this condition by closing the SPDY connection.
160 class NET_EXPORT_PRIVATE SpdyFramerVisitorInterface {
161  public:
162   virtual ~SpdyFramerVisitorInterface() {}
163
164   // Called if an error is detected in the SpdyFrame protocol.
165   virtual void OnError(SpdyFramer* framer) = 0;
166
167   // Called when a data frame header is received. The frame's data
168   // payload will be provided via subsequent calls to
169   // OnStreamFrameData().
170   virtual void OnDataFrameHeader(SpdyStreamId stream_id,
171                                  size_t length,
172                                  bool fin) = 0;
173
174   // Called when data is received.
175   // |stream_id| The stream receiving data.
176   // |data| A buffer containing the data received.
177   // |len| The length of the data buffer.
178   // When the other side has finished sending data on this stream,
179   // this method will be called with a zero-length buffer.
180   virtual void OnStreamFrameData(SpdyStreamId stream_id,
181                                  const char* data,
182                                  size_t len,
183                                  bool fin) = 0;
184
185   // Called when a chunk of header data is available. This is called
186   // after OnSynStream, OnSynReply, OnHeaders(), or OnPushPromise.
187   // |stream_id| The stream receiving the header data.
188   // |header_data| A buffer containing the header data chunk received.
189   // |len| The length of the header data buffer. A length of zero indicates
190   //       that the header data block has been completely sent.
191   // When this function returns true the visitor indicates that it accepted
192   // all of the data. Returning false indicates that that an unrecoverable
193   // error has occurred, such as bad header data or resource exhaustion.
194   virtual bool OnControlFrameHeaderData(SpdyStreamId stream_id,
195                                         const char* header_data,
196                                         size_t len) = 0;
197
198   // Called when a SYN_STREAM frame is received.
199   // Note that header block data is not included. See
200   // OnControlFrameHeaderData().
201   virtual void OnSynStream(SpdyStreamId stream_id,
202                            SpdyStreamId associated_stream_id,
203                            SpdyPriority priority,
204                            bool fin,
205                            bool unidirectional) = 0;
206
207   // Called when a SYN_REPLY frame is received.
208   // Note that header block data is not included. See
209   // OnControlFrameHeaderData().
210   virtual void OnSynReply(SpdyStreamId stream_id, bool fin) = 0;
211
212   // Called when a RST_STREAM frame has been parsed.
213   virtual void OnRstStream(SpdyStreamId stream_id,
214                            SpdyRstStreamStatus status) = 0;
215
216   // Called when a SETTINGS frame is received.
217   // |clear_persisted| True if the respective flag is set on the SETTINGS frame.
218   virtual void OnSettings(bool clear_persisted) {}
219
220   // Called when a complete setting within a SETTINGS frame has been parsed and
221   // validated.
222   virtual void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) = 0;
223
224   // Called when a SETTINGS frame is received with the ACK flag set.
225   virtual void OnSettingsAck() {}
226
227   // Called before and after parsing SETTINGS id and value tuples.
228   virtual void OnSettingsEnd() = 0;
229
230   // Called when a PING frame has been parsed.
231   virtual void OnPing(SpdyPingId unique_id, bool is_ack) = 0;
232
233   // Called when a GOAWAY frame has been parsed.
234   virtual void OnGoAway(SpdyStreamId last_accepted_stream_id,
235                         SpdyGoAwayStatus status) = 0;
236
237   // Called when a HEADERS frame is received.
238   // Note that header block data is not included. See
239   // OnControlFrameHeaderData().
240   virtual void OnHeaders(SpdyStreamId stream_id, bool fin, bool end) = 0;
241
242   // Called when a WINDOW_UPDATE frame has been parsed.
243   virtual void OnWindowUpdate(SpdyStreamId stream_id,
244                               uint32 delta_window_size) = 0;
245
246   // Called when a goaway frame opaque data is available.
247   // |goaway_data| A buffer containing the opaque GOAWAY data chunk received.
248   // |len| The length of the header data buffer. A length of zero indicates
249   //       that the header data block has been completely sent.
250   // When this function returns true the visitor indicates that it accepted
251   // all of the data. Returning false indicates that that an error has
252   // occurred while processing the data. Default implementation returns true.
253   virtual bool OnGoAwayFrameData(const char* goaway_data, size_t len);
254
255   // Called when rst_stream frame opaque data is available.
256   // |rst_stream_data| A buffer containing the opaque RST_STREAM
257   // data chunk received.
258   // |len| The length of the header data buffer. A length of zero indicates
259   //       that the opaque data has been completely sent.
260   // When this function returns true the visitor indicates that it accepted
261   // all of the data. Returning false indicates that that an error has
262   // occurred while processing the data. Default implementation returns true.
263   virtual bool OnRstStreamFrameData(const char* rst_stream_data, size_t len);
264
265   // Called when a BLOCKED frame has been parsed.
266   virtual void OnBlocked(SpdyStreamId stream_id) {}
267
268   // Called when a PUSH_PROMISE frame is received.
269   // Note that header block data is not included. See
270   // OnControlFrameHeaderData().
271   virtual void OnPushPromise(SpdyStreamId stream_id,
272                              SpdyStreamId promised_stream_id,
273                              bool end) = 0;
274
275   // Called when a CONTINUATION frame is received.
276   // Note that header block data is not included. See
277   // OnControlFrameHeaderData().
278   virtual void OnContinuation(SpdyStreamId stream_id, bool end) = 0;
279
280   // Called when an ALTSVC frame has been parsed.
281   virtual void OnAltSvc(SpdyStreamId stream_id,
282                         uint32 max_age,
283                         uint16 port,
284                         base::StringPiece protocol_id,
285                         base::StringPiece host,
286                         base::StringPiece origin) {}
287
288   // Called when a PRIORITY frame is received.
289   virtual void OnPriority(SpdyStreamId stream_id,
290                           SpdyStreamId parent_stream_id,
291                           uint8 weight,
292                           bool exclusive) {};
293 };
294
295 // Optionally, and in addition to SpdyFramerVisitorInterface, a class supporting
296 // SpdyFramerDebugVisitorInterface may be used in conjunction with SpdyFramer in
297 // order to extract debug/internal information about the SpdyFramer as it
298 // operates.
299 //
300 // Most SPDY implementations need not bother with this interface at all.
301 class NET_EXPORT_PRIVATE SpdyFramerDebugVisitorInterface {
302  public:
303   virtual ~SpdyFramerDebugVisitorInterface() {}
304
305   // Called after compressing a frame with a payload of
306   // a list of name-value pairs.
307   // |payload_len| is the uncompressed payload size.
308   // |frame_len| is the compressed frame size.
309   virtual void OnSendCompressedFrame(SpdyStreamId stream_id,
310                                      SpdyFrameType type,
311                                      size_t payload_len,
312                                      size_t frame_len) {}
313
314   // Called when a frame containing a compressed payload of
315   // name-value pairs is received.
316   // |frame_len| is the compressed frame size.
317   virtual void OnReceiveCompressedFrame(SpdyStreamId stream_id,
318                                         SpdyFrameType type,
319                                         size_t frame_len) {}
320 };
321
322 class NET_EXPORT_PRIVATE SpdyFramer {
323  public:
324   // SPDY states.
325   // TODO(mbelshe): Can we move these into the implementation
326   //                and avoid exposing through the header.  (Needed for test)
327   enum SpdyState {
328     SPDY_ERROR,
329     SPDY_RESET,
330     SPDY_AUTO_RESET,
331     SPDY_READING_COMMON_HEADER,
332     SPDY_CONTROL_FRAME_PAYLOAD,
333     SPDY_READ_PADDING_LENGTH,
334     SPDY_CONSUME_PADDING,
335     SPDY_IGNORE_REMAINING_PAYLOAD,
336     SPDY_FORWARD_STREAM_FRAME,
337     SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK,
338     SPDY_CONTROL_FRAME_HEADER_BLOCK,
339     SPDY_GOAWAY_FRAME_PAYLOAD,
340     SPDY_RST_STREAM_FRAME_PAYLOAD,
341     SPDY_SETTINGS_FRAME_PAYLOAD,
342     SPDY_ALTSVC_FRAME_PAYLOAD,
343   };
344
345   // SPDY error codes.
346   enum SpdyError {
347     SPDY_NO_ERROR,
348     SPDY_INVALID_CONTROL_FRAME,        // Control frame is mal-formatted.
349     SPDY_CONTROL_PAYLOAD_TOO_LARGE,    // Control frame payload was too large.
350     SPDY_ZLIB_INIT_FAILURE,            // The Zlib library could not initialize.
351     SPDY_UNSUPPORTED_VERSION,          // Control frame has unsupported version.
352     SPDY_DECOMPRESS_FAILURE,           // There was an error decompressing.
353     SPDY_COMPRESS_FAILURE,             // There was an error compressing.
354     SPDY_GOAWAY_FRAME_CORRUPT,         // GOAWAY frame could not be parsed.
355     SPDY_RST_STREAM_FRAME_CORRUPT,     // RST_STREAM frame could not be parsed.
356     SPDY_INVALID_DATA_FRAME_FLAGS,     // Data frame has invalid flags.
357     SPDY_INVALID_CONTROL_FRAME_FLAGS,  // Control frame has invalid flags.
358     SPDY_UNEXPECTED_FRAME,             // Frame received out of order.
359
360     LAST_ERROR,  // Must be the last entry in the enum.
361   };
362
363   // Constant for invalid (or unknown) stream IDs.
364   static const SpdyStreamId kInvalidStream;
365
366   // The maximum size of header data chunks delivered to the framer visitor
367   // through OnControlFrameHeaderData. (It is exposed here for unit test
368   // purposes.)
369   static const size_t kHeaderDataChunkMaxSize;
370
371   // Serializes a SpdyHeaderBlock.
372   static void WriteHeaderBlock(SpdyFrameBuilder* frame,
373                                const SpdyMajorVersion spdy_version,
374                                const SpdyHeaderBlock* headers);
375
376   // Retrieve serialized length of SpdyHeaderBlock.
377   // TODO(hkhalil): Remove, or move to quic code.
378   static size_t GetSerializedLength(
379       const SpdyMajorVersion spdy_version,
380       const SpdyHeaderBlock* headers);
381
382   // Create a new Framer, provided a SPDY version.
383   explicit SpdyFramer(SpdyMajorVersion version);
384   virtual ~SpdyFramer();
385
386   // Set callbacks to be called from the framer.  A visitor must be set, or
387   // else the framer will likely crash.  It is acceptable for the visitor
388   // to do nothing.  If this is called multiple times, only the last visitor
389   // will be used.
390   void set_visitor(SpdyFramerVisitorInterface* visitor) {
391     visitor_ = visitor;
392   }
393
394   // Set debug callbacks to be called from the framer. The debug visitor is
395   // completely optional and need not be set in order for normal operation.
396   // If this is called multiple times, only the last visitor will be used.
397   void set_debug_visitor(SpdyFramerDebugVisitorInterface* debug_visitor) {
398     debug_visitor_ = debug_visitor;
399   }
400
401   // Pass data into the framer for parsing.
402   // Returns the number of bytes consumed. It is safe to pass more bytes in
403   // than may be consumed.
404   size_t ProcessInput(const char* data, size_t len);
405
406   // Resets the framer state after a frame has been successfully decoded.
407   // TODO(mbelshe): can we make this private?
408   void Reset();
409
410   // Check the state of the framer.
411   SpdyError error_code() const { return error_code_; }
412   SpdyState state() const { return state_; }
413   bool HasError() const { return state_ == SPDY_ERROR; }
414
415   // Given a buffer containing a decompressed header block in SPDY
416   // serialized format, parse out a SpdyHeaderBlock, putting the results
417   // in the given header block.
418   // Returns number of bytes consumed if successfully parsed, 0 otherwise.
419   size_t ParseHeaderBlockInBuffer(const char* header_data,
420                                 size_t header_length,
421                                 SpdyHeaderBlock* block) const;
422
423   // Serialize a data frame.
424   SpdySerializedFrame* SerializeData(const SpdyDataIR& data) const;
425   // Serializes the data frame header and optionally padding length fields,
426   // excluding actual data payload and padding.
427   SpdySerializedFrame* SerializeDataFrameHeaderWithPaddingLengthField(
428       const SpdyDataIR& data) const;
429
430   // Serializes a SYN_STREAM frame.
431   SpdySerializedFrame* SerializeSynStream(const SpdySynStreamIR& syn_stream);
432
433   // Serialize a SYN_REPLY SpdyFrame.
434   SpdySerializedFrame* SerializeSynReply(const SpdySynReplyIR& syn_reply);
435
436   SpdySerializedFrame* SerializeRstStream(
437       const SpdyRstStreamIR& rst_stream) const;
438
439   // Serializes a SETTINGS frame. The SETTINGS frame is
440   // used to communicate name/value pairs relevant to the communication channel.
441   SpdySerializedFrame* SerializeSettings(const SpdySettingsIR& settings) const;
442
443   // Serializes a PING frame. The unique_id is used to
444   // identify the ping request/response.
445   SpdySerializedFrame* SerializePing(const SpdyPingIR& ping) const;
446
447   // Serializes a GOAWAY frame. The GOAWAY frame is used
448   // prior to the shutting down of the TCP connection, and includes the
449   // stream_id of the last stream the sender of the frame is willing to process
450   // to completion.
451   SpdySerializedFrame* SerializeGoAway(const SpdyGoAwayIR& goaway) const;
452
453   // Serializes a HEADERS frame. The HEADERS frame is used
454   // for sending additional headers outside of a SYN_STREAM/SYN_REPLY.
455   SpdySerializedFrame* SerializeHeaders(const SpdyHeadersIR& headers);
456
457   // Serializes a WINDOW_UPDATE frame. The WINDOW_UPDATE
458   // frame is used to implement per stream flow control in SPDY.
459   SpdySerializedFrame* SerializeWindowUpdate(
460       const SpdyWindowUpdateIR& window_update) const;
461
462   // Serializes a BLOCKED frame. The BLOCKED frame is used to
463   // indicate to the remote endpoint that this endpoint believes itself to be
464   // flow-control blocked but otherwise ready to send data. The BLOCKED frame
465   // is purely advisory and optional.
466   SpdySerializedFrame* SerializeBlocked(const SpdyBlockedIR& blocked) const;
467
468   // Serializes a PUSH_PROMISE frame. The PUSH_PROMISE frame is used
469   // to inform the client that it will be receiving an additional stream
470   // in response to the original request. The frame includes synthesized
471   // headers to explain the upcoming data.
472   SpdySerializedFrame* SerializePushPromise(
473       const SpdyPushPromiseIR& push_promise);
474
475   // Serializes a CONTINUATION frame. The CONTINUATION frame is used
476   // to continue a sequence of header block fragments.
477   // TODO(jgraettinger): This implementation is incorrect. The continuation
478   // frame continues a previously-begun HPACK encoding; it doesn't begin a
479   // new one. Figure out whether it makes sense to keep SerializeContinuation().
480   SpdySerializedFrame* SerializeContinuation(
481       const SpdyContinuationIR& continuation);
482
483   // Serializes an ALTSVC frame. The ALTSVC frame advertises the
484   // availability of an alternative service to the client.
485   SpdySerializedFrame* SerializeAltSvc(const SpdyAltSvcIR& altsvc);
486
487   // Serializes a PRIORITY frame. The PRIORITY frame advises a change in
488   // the relative priority of the given stream.
489   SpdySerializedFrame* SerializePriority(const SpdyPriorityIR& priority);
490
491   // Serialize a frame of unknown type.
492   SpdySerializedFrame* SerializeFrame(const SpdyFrameIR& frame);
493
494   // NOTES about frame compression.
495   // We want spdy to compress headers across the entire session.  As long as
496   // the session is over TCP, frames are sent serially.  The client & server
497   // can each compress frames in the same order and then compress them in that
498   // order, and the remote can do the reverse.  However, we ultimately want
499   // the creation of frames to be less sensitive to order so that they can be
500   // placed over a UDP based protocol and yet still benefit from some
501   // compression.  We don't know of any good compression protocol which does
502   // not build its state in a serial (stream based) manner....  For now, we're
503   // using zlib anyway.
504
505   // Compresses a SpdyFrame.
506   // On success, returns a new SpdyFrame with the payload compressed.
507   // Compression state is maintained as part of the SpdyFramer.
508   // Returned frame must be freed with "delete".
509   // On failure, returns NULL.
510   SpdyFrame* CompressFrame(const SpdyFrame& frame);
511
512   // For ease of testing and experimentation we can tweak compression on/off.
513   void set_enable_compression(bool value) {
514     enable_compression_ = value;
515   }
516
517   // Used only in log messages.
518   void set_display_protocol(const std::string& protocol) {
519     display_protocol_ = protocol;
520   }
521
522   // Returns the (minimum) size of frames (sans variable-length portions).
523   size_t GetDataFrameMinimumSize() const;
524   size_t GetControlFrameHeaderSize() const;
525   size_t GetSynStreamMinimumSize() const;
526   size_t GetSynReplyMinimumSize() const;
527   size_t GetRstStreamMinimumSize() const;
528   size_t GetSettingsMinimumSize() const;
529   size_t GetPingSize() const;
530   size_t GetGoAwayMinimumSize() const;
531   size_t GetHeadersMinimumSize() const;
532   size_t GetWindowUpdateSize() const;
533   size_t GetBlockedSize() const;
534   size_t GetPushPromiseMinimumSize() const;
535   size_t GetContinuationMinimumSize() const;
536   size_t GetAltSvcMinimumSize() const;
537   size_t GetPrioritySize() const;
538
539   // Returns the minimum size a frame can be (data or control).
540   size_t GetFrameMinimumSize() const;
541
542   // Returns the maximum size a frame can be (data or control).
543   size_t GetFrameMaximumSize() const;
544
545   // Returns the maximum size that a control frame can be.
546   size_t GetControlFrameMaximumSize() const;
547
548   // Returns the maximum payload size of a DATA frame.
549   size_t GetDataFrameMaximumPayload() const;
550
551   // Returns the prefix length for the given frame type.
552   size_t GetPrefixLength(SpdyFrameType type) const;
553
554   // For debugging.
555   static const char* StateToString(int state);
556   static const char* ErrorCodeToString(int error_code);
557   static const char* StatusCodeToString(int status_code);
558   static const char* FrameTypeToString(SpdyFrameType type);
559
560   SpdyMajorVersion protocol_version() const { return spdy_version_; }
561
562   bool probable_http_response() const { return probable_http_response_; }
563
564   SpdyStreamId expect_continuation() const { return expect_continuation_; }
565
566   SpdyPriority GetLowestPriority() const {
567     return spdy_version_ < SPDY3 ? 3 : 7;
568   }
569
570   SpdyPriority GetHighestPriority() const { return 0; }
571
572   // Interpolates SpdyPriority values into SPDY4/HTTP2 priority weights,
573   // and vice versa.
574   uint8 MapPriorityToWeight(SpdyPriority priority);
575   SpdyPriority MapWeightToPriority(uint8 weight);
576
577   // Deliver the given control frame's compressed headers block to the visitor
578   // in decompressed form, in chunks. Returns true if the visitor has
579   // accepted all of the chunks.
580   bool IncrementallyDecompressControlFrameHeaderData(
581       SpdyStreamId stream_id,
582       const char* data,
583       size_t len);
584
585  protected:
586   // TODO(jgraettinger): Switch to test peer pattern.
587   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, BasicCompression);
588   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameSizesAreValidated);
589   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, HeaderCompression);
590   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, DecompressUncompressedFrame);
591   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ExpandBuffer_HeapSmash);
592   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, HugeHeaderBlock);
593   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, UnclosedStreamDataCompressors);
594   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
595                            UnclosedStreamDataCompressorsOneByteAtATime);
596   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
597                            UncompressLargerThanFrameBufferInitialSize);
598   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ReadLargeSettingsFrame);
599   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
600                            ReadLargeSettingsFrameInSmallChunks);
601   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameAtMaxSizeLimit);
602   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameTooLarge);
603   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
604                            TooLargeHeadersFrameUsesContinuation);
605   FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
606                            TooLargePushPromiseFrameUsesContinuation);
607   friend class net::HttpNetworkLayer;  // This is temporary for the server.
608   friend class net::HttpNetworkTransactionTest;
609   friend class net::HttpProxyClientSocketPoolTest;
610   friend class net::SpdyHttpStreamTest;
611   friend class net::SpdyNetworkTransactionTest;
612   friend class net::SpdyProxyClientSocketTest;
613   friend class net::SpdySessionTest;
614   friend class net::SpdyStreamTest;
615   friend class net::SpdyWebSocketStreamTest;
616   friend class net::WebSocketJobTest;
617   friend class test::TestSpdyVisitor;
618
619  private:
620   // Internal breakouts from ProcessInput. Each returns the number of bytes
621   // consumed from the data.
622   size_t ProcessCommonHeader(const char* data, size_t len);
623   size_t ProcessControlFramePayload(const char* data, size_t len);
624   size_t ProcessControlFrameBeforeHeaderBlock(const char* data, size_t len);
625   // HPACK data is re-encoded as SPDY3 and re-entrantly delivered through
626   // |ProcessControlFrameHeaderBlock()|. |is_hpack_header_block| controls
627   // whether data is treated as HPACK- vs SPDY3-encoded.
628   size_t ProcessControlFrameHeaderBlock(const char* data,
629                                         size_t len,
630                                         bool is_hpack_header_block);
631   size_t ProcessFramePaddingLength(const char* data, size_t len);
632   size_t ProcessFramePadding(const char* data, size_t len);
633   size_t ProcessDataFramePayload(const char* data, size_t len);
634   size_t ProcessGoAwayFramePayload(const char* data, size_t len);
635   size_t ProcessRstStreamFramePayload(const char* data, size_t len);
636   size_t ProcessSettingsFramePayload(const char* data, size_t len);
637   size_t ProcessAltSvcFramePayload(const char* data, size_t len);
638   size_t ProcessIgnoredControlFramePayload(/*const char* data,*/ size_t len);
639
640   // TODO(jgraettinger): To be removed with migration to
641   // SpdyHeadersHandlerInterface.
642   // Serializes the last-processed header block of |hpack_decoder_| as
643   // a SPDY3 format block, and delivers it to the visitor via reentrant
644   // call to ProcessControlFrameHeaderBlock().
645   void DeliverHpackBlockAsSpdy3Block();
646
647   // Helpers for above internal breakouts from ProcessInput.
648   void ProcessControlFrameHeader(uint16 control_frame_type_field);
649   // Always passed exactly 1 setting's worth of data.
650   bool ProcessSetting(const char* data);
651
652   // Retrieve serialized length of SpdyHeaderBlock. If compression is enabled, a
653   // maximum estimate is returned.
654   size_t GetSerializedLength(const SpdyHeaderBlock& headers);
655
656   // Get (and lazily initialize) the ZLib state.
657   z_stream* GetHeaderCompressor();
658   z_stream* GetHeaderDecompressor();
659
660   // Get (and lazily initialize) the HPACK state.
661   HpackEncoder* GetHpackEncoder();
662   HpackDecoder* GetHpackDecoder();
663
664   size_t GetNumberRequiredContinuationFrames(size_t size);
665
666   void WritePayloadWithContinuation(SpdyFrameBuilder* builder,
667                                     const std::string& hpack_encoding,
668                                     SpdyStreamId stream_id,
669                                     SpdyFrameType type);
670
671  private:
672   // Deliver the given control frame's uncompressed headers block to the
673   // visitor in chunks. Returns true if the visitor has accepted all of the
674   // chunks.
675   bool IncrementallyDeliverControlFrameHeaderData(SpdyStreamId stream_id,
676                                                   const char* data,
677                                                   size_t len);
678
679   // Utility to copy the given data block to the current frame buffer, up
680   // to the given maximum number of bytes, and update the buffer
681   // data (pointer and length). Returns the number of bytes
682   // read, and:
683   //   *data is advanced the number of bytes read.
684   //   *len is reduced by the number of bytes read.
685   size_t UpdateCurrentFrameBuffer(const char** data, size_t* len,
686                                   size_t max_bytes);
687
688   void WriteHeaderBlockToZ(const SpdyHeaderBlock* headers,
689                            z_stream* out) const;
690
691   void SerializeNameValueBlockWithoutCompression(
692       SpdyFrameBuilder* builder,
693       const SpdyNameValueBlock& name_value_block) const;
694
695   // Compresses automatically according to enable_compression_.
696   void SerializeNameValueBlock(
697       SpdyFrameBuilder* builder,
698       const SpdyFrameWithNameValueBlockIR& frame);
699
700   // Set the error code and moves the framer into the error state.
701   void set_error(SpdyError error);
702
703   // The maximum size of the control frames that we support.
704   // This limit is arbitrary. We can enforce it here or at the application
705   // layer. We chose the framing layer, but this can be changed (or removed)
706   // if necessary later down the line.
707   size_t GetControlFrameBufferMaxSize() const {
708     // The theoretical maximum for SPDY3 and earlier is (2^24 - 1) +
709     // 8, since the length field does not count the size of the
710     // header.
711     if (spdy_version_ == SPDY2) {
712       return 64 * 1024;
713     }
714     if (spdy_version_ == SPDY3) {
715       return 16 * 1024 * 1024;
716     }
717     // Absolute maximum size of HTTP2 frame payload (section 4.2 "Frame size").
718     return (1<<14) - 1;
719   }
720
721   // TODO(jgraettinger): For h2-13 interop testing coverage,
722   // fragment at smaller payload boundaries.
723   size_t GetHeaderFragmentMaxSize() const {
724     return GetControlFrameBufferMaxSize() >> 4;  // 1023 bytes.
725   }
726
727   // The size of the control frame buffer.
728   // Since this is only used for control frame headers, the maximum control
729   // frame header size (SYN_STREAM) is sufficient; all remaining control
730   // frame data is streamed to the visitor.
731   static const size_t kControlFrameBufferSize;
732
733   SpdyState state_;
734   SpdyState previous_state_;
735   SpdyError error_code_;
736
737   // Note that for DATA frame, remaining_data_length_ is sum of lengths of
738   // frame header, padding length field (optional), data payload (optional) and
739   // padding payload (optional).
740   size_t remaining_data_length_;
741
742   // The length (in bytes) of the padding payload to be processed.
743   size_t remaining_padding_payload_length_;
744
745   // The number of bytes remaining to read from the current control frame's
746   // headers. Note that header data blocks (for control types that have them)
747   // are part of the frame's payload, and not the frame's headers.
748   size_t remaining_control_header_;
749
750   scoped_ptr<char[]> current_frame_buffer_;
751   // Number of bytes read into the current_frame_buffer_.
752   size_t current_frame_buffer_length_;
753
754   // The type of the frame currently being read.
755   SpdyFrameType current_frame_type_;
756
757   // The flags field of the frame currently being read.
758   uint8 current_frame_flags_;
759
760   // The total length of the frame currently being read, including frame header.
761   uint32 current_frame_length_;
762
763   // The stream ID field of the frame currently being read, if applicable.
764   SpdyStreamId current_frame_stream_id_;
765
766   // Scratch space for handling SETTINGS frames.
767   // TODO(hkhalil): Unify memory for this scratch space with
768   // current_frame_buffer_.
769   SpdySettingsScratch settings_scratch_;
770
771   SpdyAltSvcScratch altsvc_scratch_;
772
773   bool enable_compression_;  // Controls all compression
774   // SPDY header compressors.
775   scoped_ptr<z_stream> header_compressor_;
776   scoped_ptr<z_stream> header_decompressor_;
777
778   scoped_ptr<HpackEncoder> hpack_encoder_;
779   scoped_ptr<HpackDecoder> hpack_decoder_;
780
781   SpdyFramerVisitorInterface* visitor_;
782   SpdyFramerDebugVisitorInterface* debug_visitor_;
783
784   std::string display_protocol_;
785
786   // The major SPDY version to be spoken/understood by this framer.
787   const SpdyMajorVersion spdy_version_;
788
789   // Tracks if we've ever gotten far enough in framing to see a control frame of
790   // type SYN_STREAM or SYN_REPLY.
791   //
792   // If we ever get something which looks like a data frame before we've had a
793   // SYN, we explicitly check to see if it looks like we got an HTTP response
794   // to a SPDY request.  This boolean lets us do that.
795   bool syn_frame_processed_;
796
797   // If we ever get a data frame before a SYN frame, we check to see if it
798   // starts with HTTP.  If it does, we likely have an HTTP response.   This
799   // isn't guaranteed though: we could have gotten a settings frame and then
800   // corrupt data that just looks like HTTP, but deterministic checking requires
801   // a lot more state.
802   bool probable_http_response_;
803
804   // Set this to the current stream when we receive a HEADERS, PUSH_PROMISE, or
805   // CONTINUATION frame without the END_HEADERS(0x4) bit set. These frames must
806   // be followed by a CONTINUATION frame, or else we throw a PROTOCOL_ERROR.
807   // A value of 0 indicates that we are not expecting a CONTINUATION frame.
808   SpdyStreamId expect_continuation_;
809
810   // If a HEADERS frame is followed by a CONTINUATION frame, the FIN/END_STREAM
811   // flag is still carried in the HEADERS frame. If it's set, flip this so that
812   // we know to terminate the stream when the entire header block has been
813   // processed.
814   bool end_stream_when_done_;
815 };
816
817 }  // namespace net
818
819 #endif  // NET_SPDY_SPDY_FRAMER_H_