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_SPDY_SPDY_FRAMER_H_
6 #define NET_SPDY_SPDY_FRAMER_H_
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"
26 // TODO(akalin): Remove support for CREDENTIAL frames.
28 typedef struct z_stream_s z_stream
; // Forward declaration for zlib.
32 class HttpProxyClientSocketPoolTest
;
33 class HttpNetworkLayer
;
34 class HttpNetworkTransactionTest
;
35 class SpdyHttpStreamTest
;
36 class SpdyNetworkTransactionTest
;
37 class SpdyProxyClientSocketTest
;
38 class SpdySessionTest
;
40 class SpdyWebSocketStreamTest
;
41 class WebSocketJobTest
;
44 class SpdyFrameBuilder
;
49 class TestSpdyVisitor
;
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
;
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
{
61 static SettingsFlagsAndId
FromWireFormat(SpdyMajorVersion version
,
64 SettingsFlagsAndId() : flags_(0), id_(0) {}
66 // TODO(hkhalil): restrict to enums instead of free-form ints.
67 SettingsFlagsAndId(uint8 flags
, uint32 id
);
69 uint32
GetWireFormat(SpdyMajorVersion version
) const;
71 uint32
id() const { return id_
; }
72 uint8
flags() const { return flags_
; }
75 static void ConvertFlagsAndIdForSpdy2(uint32
* val
);
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
;
85 // Scratch space necessary for processing SETTINGS frames.
86 struct NET_EXPORT_PRIVATE SpdySettingsScratch
{
87 SpdySettingsScratch() { Reset(); }
94 // Buffer contains up to one complete key/value pair.
97 // The amount of the buffer that is filled with valid data.
98 size_t setting_buf_len
;
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.
106 // Scratch space necessary for processing ALTSVC frames.
107 struct NET_EXPORT_PRIVATE SpdyAltSvcScratch
{
109 ~SpdyAltSvcScratch();
132 size_t origin_buf_len
;
133 scoped_ptr
<char[]> protocol_id
;
134 scoped_ptr
<char[]> host
;
135 scoped_ptr
<char[]> origin
;
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.
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
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
{
162 virtual ~SpdyFramerVisitorInterface() {}
164 // Called if an error is detected in the SpdyFrame protocol.
165 virtual void OnError(SpdyFramer
* framer
) = 0;
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
,
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
,
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
,
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
,
205 bool unidirectional
) = 0;
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;
212 // Called when a RST_STREAM frame has been parsed.
213 virtual void OnRstStream(SpdyStreamId stream_id
,
214 SpdyRstStreamStatus status
) = 0;
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
) {}
220 // Called when a complete setting within a SETTINGS frame has been parsed and
222 virtual void OnSetting(SpdySettingsIds id
, uint8 flags
, uint32 value
) = 0;
224 // Called when a SETTINGS frame is received with the ACK flag set.
225 virtual void OnSettingsAck() {}
227 // Called before and after parsing SETTINGS id and value tuples.
228 virtual void OnSettingsEnd() = 0;
230 // Called when a PING frame has been parsed.
231 virtual void OnPing(SpdyPingId unique_id
, bool is_ack
) = 0;
233 // Called when a GOAWAY frame has been parsed.
234 virtual void OnGoAway(SpdyStreamId last_accepted_stream_id
,
235 SpdyGoAwayStatus status
) = 0;
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;
242 // Called when a WINDOW_UPDATE frame has been parsed.
243 virtual void OnWindowUpdate(SpdyStreamId stream_id
,
244 uint32 delta_window_size
) = 0;
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
);
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
);
265 // Called when a BLOCKED frame has been parsed.
266 virtual void OnBlocked(SpdyStreamId stream_id
) {}
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
,
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;
280 // Called when an ALTSVC frame has been parsed.
281 virtual void OnAltSvc(SpdyStreamId stream_id
,
284 base::StringPiece protocol_id
,
285 base::StringPiece host
,
286 base::StringPiece origin
) {}
289 // Optionally, and in addition to SpdyFramerVisitorInterface, a class supporting
290 // SpdyFramerDebugVisitorInterface may be used in conjunction with SpdyFramer in
291 // order to extract debug/internal information about the SpdyFramer as it
294 // Most SPDY implementations need not bother with this interface at all.
295 class NET_EXPORT_PRIVATE SpdyFramerDebugVisitorInterface
{
297 virtual ~SpdyFramerDebugVisitorInterface() {}
299 // Called after compressing a frame with a payload of
300 // a list of name-value pairs.
301 // |payload_len| is the uncompressed payload size.
302 // |frame_len| is the compressed frame size.
303 virtual void OnSendCompressedFrame(SpdyStreamId stream_id
,
308 // Called when a frame containing a compressed payload of
309 // name-value pairs is received.
310 // |frame_len| is the compressed frame size.
311 virtual void OnReceiveCompressedFrame(SpdyStreamId stream_id
,
316 class NET_EXPORT_PRIVATE SpdyFramer
{
319 // TODO(mbelshe): Can we move these into the implementation
320 // and avoid exposing through the header. (Needed for test)
325 SPDY_READING_COMMON_HEADER
,
326 SPDY_CONTROL_FRAME_PAYLOAD
,
327 SPDY_READ_PADDING_LENGTH
,
328 SPDY_CONSUME_PADDING
,
329 SPDY_IGNORE_REMAINING_PAYLOAD
,
330 SPDY_FORWARD_STREAM_FRAME
,
331 SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK
,
332 SPDY_CONTROL_FRAME_HEADER_BLOCK
,
333 SPDY_GOAWAY_FRAME_PAYLOAD
,
334 SPDY_RST_STREAM_FRAME_PAYLOAD
,
335 SPDY_SETTINGS_FRAME_PAYLOAD
,
336 SPDY_ALTSVC_FRAME_PAYLOAD
,
342 SPDY_INVALID_CONTROL_FRAME
, // Control frame is mal-formatted.
343 SPDY_CONTROL_PAYLOAD_TOO_LARGE
, // Control frame payload was too large.
344 SPDY_ZLIB_INIT_FAILURE
, // The Zlib library could not initialize.
345 SPDY_UNSUPPORTED_VERSION
, // Control frame has unsupported version.
346 SPDY_DECOMPRESS_FAILURE
, // There was an error decompressing.
347 SPDY_COMPRESS_FAILURE
, // There was an error compressing.
348 SPDY_GOAWAY_FRAME_CORRUPT
, // GOAWAY frame could not be parsed.
349 SPDY_RST_STREAM_FRAME_CORRUPT
, // RST_STREAM frame could not be parsed.
350 SPDY_INVALID_DATA_FRAME_FLAGS
, // Data frame has invalid flags.
351 SPDY_INVALID_CONTROL_FRAME_FLAGS
, // Control frame has invalid flags.
352 SPDY_UNEXPECTED_FRAME
, // Frame received out of order.
354 LAST_ERROR
, // Must be the last entry in the enum.
357 // Constant for invalid (or unknown) stream IDs.
358 static const SpdyStreamId kInvalidStream
;
360 // The maximum size of header data chunks delivered to the framer visitor
361 // through OnControlFrameHeaderData. (It is exposed here for unit test
363 static const size_t kHeaderDataChunkMaxSize
;
365 // Serializes a SpdyHeaderBlock.
366 static void WriteHeaderBlock(SpdyFrameBuilder
* frame
,
367 const SpdyMajorVersion spdy_version
,
368 const SpdyHeaderBlock
* headers
);
370 // Retrieve serialized length of SpdyHeaderBlock.
371 // TODO(hkhalil): Remove, or move to quic code.
372 static size_t GetSerializedLength(
373 const SpdyMajorVersion spdy_version
,
374 const SpdyHeaderBlock
* headers
);
376 // Create a new Framer, provided a SPDY version.
377 explicit SpdyFramer(SpdyMajorVersion version
);
378 virtual ~SpdyFramer();
380 // Set callbacks to be called from the framer. A visitor must be set, or
381 // else the framer will likely crash. It is acceptable for the visitor
382 // to do nothing. If this is called multiple times, only the last visitor
384 void set_visitor(SpdyFramerVisitorInterface
* visitor
) {
388 // Set debug callbacks to be called from the framer. The debug visitor is
389 // completely optional and need not be set in order for normal operation.
390 // If this is called multiple times, only the last visitor will be used.
391 void set_debug_visitor(SpdyFramerDebugVisitorInterface
* debug_visitor
) {
392 debug_visitor_
= debug_visitor
;
395 // Pass data into the framer for parsing.
396 // Returns the number of bytes consumed. It is safe to pass more bytes in
397 // than may be consumed.
398 size_t ProcessInput(const char* data
, size_t len
);
400 // Resets the framer state after a frame has been successfully decoded.
401 // TODO(mbelshe): can we make this private?
404 // Check the state of the framer.
405 SpdyError
error_code() const { return error_code_
; }
406 SpdyState
state() const { return state_
; }
407 bool HasError() const { return state_
== SPDY_ERROR
; }
409 // Given a buffer containing a decompressed header block in SPDY
410 // serialized format, parse out a SpdyHeaderBlock, putting the results
411 // in the given header block.
412 // Returns number of bytes consumed if successfully parsed, 0 otherwise.
413 size_t ParseHeaderBlockInBuffer(const char* header_data
,
414 size_t header_length
,
415 SpdyHeaderBlock
* block
) const;
417 // Serialize a data frame.
418 SpdySerializedFrame
* SerializeData(const SpdyDataIR
& data
) const;
419 // Serializes the data frame header and optionally padding length fields,
420 // excluding actual data payload and padding.
421 SpdySerializedFrame
* SerializeDataFrameHeaderWithPaddingLengthField(
422 const SpdyDataIR
& data
) const;
424 // Serializes a SYN_STREAM frame.
425 SpdySerializedFrame
* SerializeSynStream(const SpdySynStreamIR
& syn_stream
);
427 // Serialize a SYN_REPLY SpdyFrame.
428 SpdySerializedFrame
* SerializeSynReply(const SpdySynReplyIR
& syn_reply
);
430 SpdySerializedFrame
* SerializeRstStream(
431 const SpdyRstStreamIR
& rst_stream
) const;
433 // Serializes a SETTINGS frame. The SETTINGS frame is
434 // used to communicate name/value pairs relevant to the communication channel.
435 SpdySerializedFrame
* SerializeSettings(const SpdySettingsIR
& settings
) const;
437 // Serializes a PING frame. The unique_id is used to
438 // identify the ping request/response.
439 SpdySerializedFrame
* SerializePing(const SpdyPingIR
& ping
) const;
441 // Serializes a GOAWAY frame. The GOAWAY frame is used
442 // prior to the shutting down of the TCP connection, and includes the
443 // stream_id of the last stream the sender of the frame is willing to process
445 SpdySerializedFrame
* SerializeGoAway(const SpdyGoAwayIR
& goaway
) const;
447 // Serializes a HEADERS frame. The HEADERS frame is used
448 // for sending additional headers outside of a SYN_STREAM/SYN_REPLY.
449 SpdySerializedFrame
* SerializeHeaders(const SpdyHeadersIR
& headers
);
451 // Serializes a WINDOW_UPDATE frame. The WINDOW_UPDATE
452 // frame is used to implement per stream flow control in SPDY.
453 SpdySerializedFrame
* SerializeWindowUpdate(
454 const SpdyWindowUpdateIR
& window_update
) const;
456 // Serializes a BLOCKED frame. The BLOCKED frame is used to
457 // indicate to the remote endpoint that this endpoint believes itself to be
458 // flow-control blocked but otherwise ready to send data. The BLOCKED frame
459 // is purely advisory and optional.
460 SpdySerializedFrame
* SerializeBlocked(const SpdyBlockedIR
& blocked
) const;
462 // Serializes a PUSH_PROMISE frame. The PUSH_PROMISE frame is used
463 // to inform the client that it will be receiving an additional stream
464 // in response to the original request. The frame includes synthesized
465 // headers to explain the upcoming data.
466 SpdySerializedFrame
* SerializePushPromise(
467 const SpdyPushPromiseIR
& push_promise
);
469 // Serializes a CONTINUATION frame. The CONTINUATION frame is used
470 // to continue a sequence of header block fragments.
471 // TODO(jgraettinger): This implementation is incorrect. The continuation
472 // frame continues a previously-begun HPACK encoding; it doesn't begin a
473 // new one. Figure out whether it makes sense to keep SerializeContinuation().
474 SpdySerializedFrame
* SerializeContinuation(
475 const SpdyContinuationIR
& continuation
);
477 // Serializes an ALTSVC frame. The ALTSVC frame advertises the
478 // availability of an alternative service to the client.
479 SpdySerializedFrame
* SerializeAltSvc(const SpdyAltSvcIR
& altsvc
);
481 // Serialize a frame of unknown type.
482 SpdySerializedFrame
* SerializeFrame(const SpdyFrameIR
& frame
);
484 // NOTES about frame compression.
485 // We want spdy to compress headers across the entire session. As long as
486 // the session is over TCP, frames are sent serially. The client & server
487 // can each compress frames in the same order and then compress them in that
488 // order, and the remote can do the reverse. However, we ultimately want
489 // the creation of frames to be less sensitive to order so that they can be
490 // placed over a UDP based protocol and yet still benefit from some
491 // compression. We don't know of any good compression protocol which does
492 // not build its state in a serial (stream based) manner.... For now, we're
493 // using zlib anyway.
495 // Compresses a SpdyFrame.
496 // On success, returns a new SpdyFrame with the payload compressed.
497 // Compression state is maintained as part of the SpdyFramer.
498 // Returned frame must be freed with "delete".
499 // On failure, returns NULL.
500 SpdyFrame
* CompressFrame(const SpdyFrame
& frame
);
502 // For ease of testing and experimentation we can tweak compression on/off.
503 void set_enable_compression(bool value
) {
504 enable_compression_
= value
;
507 // Used only in log messages.
508 void set_display_protocol(const std::string
& protocol
) {
509 display_protocol_
= protocol
;
512 // Returns the (minimum) size of frames (sans variable-length portions).
513 size_t GetDataFrameMinimumSize() const;
514 size_t GetControlFrameHeaderSize() const;
515 size_t GetSynStreamMinimumSize() const;
516 size_t GetSynReplyMinimumSize() const;
517 size_t GetRstStreamMinimumSize() const;
518 size_t GetSettingsMinimumSize() const;
519 size_t GetPingSize() const;
520 size_t GetGoAwayMinimumSize() const;
521 size_t GetHeadersMinimumSize() const;
522 size_t GetWindowUpdateSize() const;
523 size_t GetBlockedSize() const;
524 size_t GetPushPromiseMinimumSize() const;
525 size_t GetContinuationMinimumSize() const;
526 size_t GetAltSvcMinimumSize() const;
527 size_t GetPrioritySize() const;
529 // Returns the minimum size a frame can be (data or control).
530 size_t GetFrameMinimumSize() const;
532 // Returns the maximum size a frame can be (data or control).
533 size_t GetFrameMaximumSize() const;
535 // Returns the maximum size that a control frame can be.
536 size_t GetControlFrameMaximumSize() const;
538 // Returns the maximum payload size of a DATA frame.
539 size_t GetDataFrameMaximumPayload() const;
541 // Returns the prefix length for the given frame type.
542 size_t GetPrefixLength(SpdyFrameType type
) const;
545 static const char* StateToString(int state
);
546 static const char* ErrorCodeToString(int error_code
);
547 static const char* StatusCodeToString(int status_code
);
548 static const char* FrameTypeToString(SpdyFrameType type
);
550 SpdyMajorVersion
protocol_version() const { return spdy_version_
; }
552 bool probable_http_response() const { return probable_http_response_
; }
554 SpdyStreamId
expect_continuation() const { return expect_continuation_
; }
556 SpdyPriority
GetLowestPriority() const {
557 return spdy_version_
< SPDY3
? 3 : 7;
560 SpdyPriority
GetHighestPriority() const { return 0; }
562 // Interpolates SpdyPriority values into SPDY4/HTTP2 priority weights,
564 uint8
MapPriorityToWeight(SpdyPriority priority
);
565 SpdyPriority
MapWeightToPriority(uint8 weight
);
567 // Deliver the given control frame's compressed headers block to the visitor
568 // in decompressed form, in chunks. Returns true if the visitor has
569 // accepted all of the chunks.
570 bool IncrementallyDecompressControlFrameHeaderData(
571 SpdyStreamId stream_id
,
576 // TODO(jgraettinger): Switch to test peer pattern.
577 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, BasicCompression
);
578 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, ControlFrameSizesAreValidated
);
579 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, HeaderCompression
);
580 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, DecompressUncompressedFrame
);
581 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, ExpandBuffer_HeapSmash
);
582 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, HugeHeaderBlock
);
583 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, UnclosedStreamDataCompressors
);
584 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
,
585 UnclosedStreamDataCompressorsOneByteAtATime
);
586 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
,
587 UncompressLargerThanFrameBufferInitialSize
);
588 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, ReadLargeSettingsFrame
);
589 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
,
590 ReadLargeSettingsFrameInSmallChunks
);
591 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, ControlFrameAtMaxSizeLimit
);
592 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
, ControlFrameTooLarge
);
593 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
,
594 TooLargeHeadersFrameUsesContinuation
);
595 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest
,
596 TooLargePushPromiseFrameUsesContinuation
);
597 friend class net::HttpNetworkLayer
; // This is temporary for the server.
598 friend class net::HttpNetworkTransactionTest
;
599 friend class net::HttpProxyClientSocketPoolTest
;
600 friend class net::SpdyHttpStreamTest
;
601 friend class net::SpdyNetworkTransactionTest
;
602 friend class net::SpdyProxyClientSocketTest
;
603 friend class net::SpdySessionTest
;
604 friend class net::SpdyStreamTest
;
605 friend class net::SpdyWebSocketStreamTest
;
606 friend class net::WebSocketJobTest
;
607 friend class test::TestSpdyVisitor
;
610 // Internal breakouts from ProcessInput. Each returns the number of bytes
611 // consumed from the data.
612 size_t ProcessCommonHeader(const char* data
, size_t len
);
613 size_t ProcessControlFramePayload(const char* data
, size_t len
);
614 size_t ProcessControlFrameBeforeHeaderBlock(const char* data
, size_t len
);
615 // HPACK data is re-encoded as SPDY3 and re-entrantly delivered through
616 // |ProcessControlFrameHeaderBlock()|. |is_hpack_header_block| controls
617 // whether data is treated as HPACK- vs SPDY3-encoded.
618 size_t ProcessControlFrameHeaderBlock(const char* data
,
620 bool is_hpack_header_block
);
621 size_t ProcessFramePaddingLength(const char* data
, size_t len
);
622 size_t ProcessFramePadding(const char* data
, size_t len
);
623 size_t ProcessDataFramePayload(const char* data
, size_t len
);
624 size_t ProcessGoAwayFramePayload(const char* data
, size_t len
);
625 size_t ProcessRstStreamFramePayload(const char* data
, size_t len
);
626 size_t ProcessSettingsFramePayload(const char* data
, size_t len
);
627 size_t ProcessAltSvcFramePayload(const char* data
, size_t len
);
628 size_t ProcessIgnoredControlFramePayload(/*const char* data,*/ size_t len
);
630 // TODO(jgraettinger): To be removed with migration to
631 // SpdyHeadersHandlerInterface.
632 // Serializes the last-processed header block of |hpack_decoder_| as
633 // a SPDY3 format block, and delivers it to the visitor via reentrant
634 // call to ProcessControlFrameHeaderBlock().
635 void DeliverHpackBlockAsSpdy3Block();
637 // Helpers for above internal breakouts from ProcessInput.
638 void ProcessControlFrameHeader(uint16 control_frame_type_field
);
639 // Always passed exactly 1 setting's worth of data.
640 bool ProcessSetting(const char* data
);
642 // Retrieve serialized length of SpdyHeaderBlock. If compression is enabled, a
643 // maximum estimate is returned.
644 size_t GetSerializedLength(const SpdyHeaderBlock
& headers
);
646 // Get (and lazily initialize) the ZLib state.
647 z_stream
* GetHeaderCompressor();
648 z_stream
* GetHeaderDecompressor();
650 // Get (and lazily initialize) the HPACK state.
651 HpackEncoder
* GetHpackEncoder();
652 HpackDecoder
* GetHpackDecoder();
654 size_t GetNumberRequiredContinuationFrames(size_t size
);
656 void WritePayloadWithContinuation(SpdyFrameBuilder
* builder
,
657 const std::string
& hpack_encoding
,
658 SpdyStreamId stream_id
,
662 // Deliver the given control frame's uncompressed headers block to the
663 // visitor in chunks. Returns true if the visitor has accepted all of the
665 bool IncrementallyDeliverControlFrameHeaderData(SpdyStreamId stream_id
,
669 // Utility to copy the given data block to the current frame buffer, up
670 // to the given maximum number of bytes, and update the buffer
671 // data (pointer and length). Returns the number of bytes
673 // *data is advanced the number of bytes read.
674 // *len is reduced by the number of bytes read.
675 size_t UpdateCurrentFrameBuffer(const char** data
, size_t* len
,
678 void WriteHeaderBlockToZ(const SpdyHeaderBlock
* headers
,
679 z_stream
* out
) const;
681 void SerializeNameValueBlockWithoutCompression(
682 SpdyFrameBuilder
* builder
,
683 const SpdyNameValueBlock
& name_value_block
) const;
685 // Compresses automatically according to enable_compression_.
686 void SerializeNameValueBlock(
687 SpdyFrameBuilder
* builder
,
688 const SpdyFrameWithNameValueBlockIR
& frame
);
690 // Set the error code and moves the framer into the error state.
691 void set_error(SpdyError error
);
693 // The maximum size of the control frames that we support.
694 // This limit is arbitrary. We can enforce it here or at the application
695 // layer. We chose the framing layer, but this can be changed (or removed)
696 // if necessary later down the line.
697 size_t GetControlFrameBufferMaxSize() const {
698 // The theoretical maximum for SPDY3 and earlier is (2^24 - 1) +
699 // 8, since the length field does not count the size of the
701 if (spdy_version_
== SPDY2
) {
704 if (spdy_version_
== SPDY3
) {
705 return 16 * 1024 * 1024;
707 // Absolute maximum size of HTTP2 frame payload (section 4.2 "Frame size").
711 // The size of the control frame buffer.
712 // Since this is only used for control frame headers, the maximum control
713 // frame header size (SYN_STREAM) is sufficient; all remaining control
714 // frame data is streamed to the visitor.
715 static const size_t kControlFrameBufferSize
;
718 SpdyState previous_state_
;
719 SpdyError error_code_
;
721 // Note that for DATA frame, remaining_data_length_ is sum of lengths of
722 // frame header, padding length field (optional), data payload (optional) and
723 // padding payload (optional).
724 size_t remaining_data_length_
;
726 // The length (in bytes) of the padding payload to be processed.
727 size_t remaining_padding_payload_length_
;
729 // The length (in bytes) of the padding length field to be processed.
730 size_t remaining_padding_length_fields_
;
732 // The number of bytes remaining to read from the current control frame's
733 // headers. Note that header data blocks (for control types that have them)
734 // are part of the frame's payload, and not the frame's headers.
735 size_t remaining_control_header_
;
737 scoped_ptr
<char[]> current_frame_buffer_
;
738 // Number of bytes read into the current_frame_buffer_.
739 size_t current_frame_buffer_length_
;
741 // The type of the frame currently being read.
742 SpdyFrameType current_frame_type_
;
744 // The flags field of the frame currently being read.
745 uint8 current_frame_flags_
;
747 // The total length of the frame currently being read, including frame header.
748 uint32 current_frame_length_
;
750 // The stream ID field of the frame currently being read, if applicable.
751 SpdyStreamId current_frame_stream_id_
;
753 // Scratch space for handling SETTINGS frames.
754 // TODO(hkhalil): Unify memory for this scratch space with
755 // current_frame_buffer_.
756 SpdySettingsScratch settings_scratch_
;
758 SpdyAltSvcScratch altsvc_scratch_
;
760 bool enable_compression_
; // Controls all compression
761 // SPDY header compressors.
762 scoped_ptr
<z_stream
> header_compressor_
;
763 scoped_ptr
<z_stream
> header_decompressor_
;
765 scoped_ptr
<HpackEncoder
> hpack_encoder_
;
766 scoped_ptr
<HpackDecoder
> hpack_decoder_
;
768 SpdyFramerVisitorInterface
* visitor_
;
769 SpdyFramerDebugVisitorInterface
* debug_visitor_
;
771 std::string display_protocol_
;
773 // The major SPDY version to be spoken/understood by this framer.
774 const SpdyMajorVersion spdy_version_
;
776 // Tracks if we've ever gotten far enough in framing to see a control frame of
777 // type SYN_STREAM or SYN_REPLY.
779 // If we ever get something which looks like a data frame before we've had a
780 // SYN, we explicitly check to see if it looks like we got an HTTP response
781 // to a SPDY request. This boolean lets us do that.
782 bool syn_frame_processed_
;
784 // If we ever get a data frame before a SYN frame, we check to see if it
785 // starts with HTTP. If it does, we likely have an HTTP response. This
786 // isn't guaranteed though: we could have gotten a settings frame and then
787 // corrupt data that just looks like HTTP, but deterministic checking requires
789 bool probable_http_response_
;
791 // Set this to the current stream when we receive a HEADERS, PUSH_PROMISE, or
792 // CONTINUATION frame without the END_HEADERS(0x4) bit set. These frames must
793 // be followed by a CONTINUATION frame, or else we throw a PROTOCOL_ERROR.
794 // A value of 0 indicates that we are not expecting a CONTINUATION frame.
795 SpdyStreamId expect_continuation_
;
797 // If a HEADERS frame is followed by a CONTINUATION frame, the FIN/END_STREAM
798 // flag is still carried in the HEADERS frame. If it's set, flip this so that
799 // we know to terminate the stream when the entire header block has been
801 bool end_stream_when_done_
;
806 #endif // NET_SPDY_SPDY_FRAMER_H_