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,
242 SpdyPriority priority,
246 // Called when a WINDOW_UPDATE frame has been parsed.
247 virtual void OnWindowUpdate(SpdyStreamId stream_id,
248 uint32 delta_window_size) = 0;
250 // Called when a goaway frame opaque data is available.
251 // |goaway_data| A buffer containing the opaque GOAWAY data chunk received.
252 // |len| The length of the header data buffer. A length of zero indicates
253 // that the header data block has been completely sent.
254 // When this function returns true the visitor indicates that it accepted
255 // all of the data. Returning false indicates that that an error has
256 // occurred while processing the data. Default implementation returns true.
257 virtual bool OnGoAwayFrameData(const char* goaway_data, size_t len);
259 // Called when rst_stream frame opaque data is available.
260 // |rst_stream_data| A buffer containing the opaque RST_STREAM
261 // data chunk received.
262 // |len| The length of the header data buffer. A length of zero indicates
263 // that the opaque data has been completely sent.
264 // When this function returns true the visitor indicates that it accepted
265 // all of the data. Returning false indicates that that an error has
266 // occurred while processing the data. Default implementation returns true.
267 virtual bool OnRstStreamFrameData(const char* rst_stream_data, size_t len);
269 // Called when a BLOCKED frame has been parsed.
270 virtual void OnBlocked(SpdyStreamId stream_id) {}
272 // Called when a PUSH_PROMISE frame is received.
273 // Note that header block data is not included. See
274 // OnControlFrameHeaderData().
275 virtual void OnPushPromise(SpdyStreamId stream_id,
276 SpdyStreamId promised_stream_id,
279 // Called when a CONTINUATION frame is received.
280 // Note that header block data is not included. See
281 // OnControlFrameHeaderData().
282 virtual void OnContinuation(SpdyStreamId stream_id, bool end) = 0;
284 // Called when an ALTSVC frame has been parsed.
285 virtual void OnAltSvc(SpdyStreamId stream_id,
288 base::StringPiece protocol_id,
289 base::StringPiece host,
290 base::StringPiece origin) {}
292 // Called when a PRIORITY frame is received.
293 virtual void OnPriority(SpdyStreamId stream_id,
294 SpdyStreamId parent_stream_id,
298 // Called when a frame type we don't recognize is received.
299 // Return true if this appears to be a valid extension frame, false otherwise.
300 // We distinguish between extension frames and nonsense by checking
301 // whether the stream id is valid.
302 virtual bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) = 0;
305 // Optionally, and in addition to SpdyFramerVisitorInterface, a class supporting
306 // SpdyFramerDebugVisitorInterface may be used in conjunction with SpdyFramer in
307 // order to extract debug/internal information about the SpdyFramer as it
310 // Most SPDY implementations need not bother with this interface at all.
311 class NET_EXPORT_PRIVATE SpdyFramerDebugVisitorInterface {
313 virtual ~SpdyFramerDebugVisitorInterface() {}
315 // Called after compressing a frame with a payload of
316 // a list of name-value pairs.
317 // |payload_len| is the uncompressed payload size.
318 // |frame_len| is the compressed frame size.
319 virtual void OnSendCompressedFrame(SpdyStreamId stream_id,
324 // Called when a frame containing a compressed payload of
325 // name-value pairs is received.
326 // |frame_len| is the compressed frame size.
327 virtual void OnReceiveCompressedFrame(SpdyStreamId stream_id,
332 class NET_EXPORT_PRIVATE SpdyFramer {
335 // TODO(mbelshe): Can we move these into the implementation
336 // and avoid exposing through the header. (Needed for test)
341 SPDY_READING_COMMON_HEADER,
342 SPDY_CONTROL_FRAME_PAYLOAD,
343 SPDY_READ_DATA_FRAME_PADDING_LENGTH,
344 SPDY_CONSUME_PADDING,
345 SPDY_IGNORE_REMAINING_PAYLOAD,
346 SPDY_FORWARD_STREAM_FRAME,
347 SPDY_CONTROL_FRAME_BEFORE_HEADER_BLOCK,
348 SPDY_CONTROL_FRAME_HEADER_BLOCK,
349 SPDY_GOAWAY_FRAME_PAYLOAD,
350 SPDY_RST_STREAM_FRAME_PAYLOAD,
351 SPDY_SETTINGS_FRAME_PAYLOAD,
352 SPDY_ALTSVC_FRAME_PAYLOAD,
358 SPDY_INVALID_CONTROL_FRAME, // Control frame is mal-formatted.
359 SPDY_CONTROL_PAYLOAD_TOO_LARGE, // Control frame payload was too large.
360 SPDY_ZLIB_INIT_FAILURE, // The Zlib library could not initialize.
361 SPDY_UNSUPPORTED_VERSION, // Control frame has unsupported version.
362 SPDY_DECOMPRESS_FAILURE, // There was an error decompressing.
363 SPDY_COMPRESS_FAILURE, // There was an error compressing.
364 SPDY_GOAWAY_FRAME_CORRUPT, // GOAWAY frame could not be parsed.
365 SPDY_RST_STREAM_FRAME_CORRUPT, // RST_STREAM frame could not be parsed.
366 SPDY_INVALID_DATA_FRAME_FLAGS, // Data frame has invalid flags.
367 SPDY_INVALID_CONTROL_FRAME_FLAGS, // Control frame has invalid flags.
368 SPDY_UNEXPECTED_FRAME, // Frame received out of order.
370 LAST_ERROR, // Must be the last entry in the enum.
373 // Constant for invalid (or unknown) stream IDs.
374 static const SpdyStreamId kInvalidStream;
376 // The maximum size of header data chunks delivered to the framer visitor
377 // through OnControlFrameHeaderData. (It is exposed here for unit test
379 static const size_t kHeaderDataChunkMaxSize;
381 // Serializes a SpdyHeaderBlock.
382 static void WriteHeaderBlock(SpdyFrameBuilder* frame,
383 const SpdyMajorVersion spdy_version,
384 const SpdyHeaderBlock* headers);
386 // Retrieve serialized length of SpdyHeaderBlock.
387 // TODO(hkhalil): Remove, or move to quic code.
388 static size_t GetSerializedLength(
389 const SpdyMajorVersion spdy_version,
390 const SpdyHeaderBlock* headers);
392 // Create a new Framer, provided a SPDY version.
393 explicit SpdyFramer(SpdyMajorVersion version);
394 virtual ~SpdyFramer();
396 // Set callbacks to be called from the framer. A visitor must be set, or
397 // else the framer will likely crash. It is acceptable for the visitor
398 // to do nothing. If this is called multiple times, only the last visitor
400 void set_visitor(SpdyFramerVisitorInterface* visitor) {
404 // Set debug callbacks to be called from the framer. The debug visitor is
405 // completely optional and need not be set in order for normal operation.
406 // If this is called multiple times, only the last visitor will be used.
407 void set_debug_visitor(SpdyFramerDebugVisitorInterface* debug_visitor) {
408 debug_visitor_ = debug_visitor;
411 // Pass data into the framer for parsing.
412 // Returns the number of bytes consumed. It is safe to pass more bytes in
413 // than may be consumed.
414 size_t ProcessInput(const char* data, size_t len);
416 // Resets the framer state after a frame has been successfully decoded.
417 // TODO(mbelshe): can we make this private?
420 // Check the state of the framer.
421 SpdyError error_code() const { return error_code_; }
422 SpdyState state() const { return state_; }
423 bool HasError() const { return state_ == SPDY_ERROR; }
425 // Given a buffer containing a decompressed header block in SPDY
426 // serialized format, parse out a SpdyHeaderBlock, putting the results
427 // in the given header block.
428 // Returns number of bytes consumed if successfully parsed, 0 otherwise.
429 size_t ParseHeaderBlockInBuffer(const char* header_data,
430 size_t header_length,
431 SpdyHeaderBlock* block) const;
433 // Serialize a data frame.
434 SpdySerializedFrame* SerializeData(const SpdyDataIR& data) const;
435 // Serializes the data frame header and optionally padding length fields,
436 // excluding actual data payload and padding.
437 SpdySerializedFrame* SerializeDataFrameHeaderWithPaddingLengthField(
438 const SpdyDataIR& data) const;
440 // Serializes a SYN_STREAM frame.
441 SpdySerializedFrame* SerializeSynStream(const SpdySynStreamIR& syn_stream);
443 // Serialize a SYN_REPLY SpdyFrame.
444 SpdySerializedFrame* SerializeSynReply(const SpdySynReplyIR& syn_reply);
446 SpdySerializedFrame* SerializeRstStream(
447 const SpdyRstStreamIR& rst_stream) const;
449 // Serializes a SETTINGS frame. The SETTINGS frame is
450 // used to communicate name/value pairs relevant to the communication channel.
451 SpdySerializedFrame* SerializeSettings(const SpdySettingsIR& settings) const;
453 // Serializes a PING frame. The unique_id is used to
454 // identify the ping request/response.
455 SpdySerializedFrame* SerializePing(const SpdyPingIR& ping) const;
457 // Serializes a GOAWAY frame. The GOAWAY frame is used
458 // prior to the shutting down of the TCP connection, and includes the
459 // stream_id of the last stream the sender of the frame is willing to process
461 SpdySerializedFrame* SerializeGoAway(const SpdyGoAwayIR& goaway) const;
463 // Serializes a HEADERS frame. The HEADERS frame is used
464 // for sending additional headers outside of a SYN_STREAM/SYN_REPLY.
465 SpdySerializedFrame* SerializeHeaders(const SpdyHeadersIR& headers);
467 // Serializes a WINDOW_UPDATE frame. The WINDOW_UPDATE
468 // frame is used to implement per stream flow control in SPDY.
469 SpdySerializedFrame* SerializeWindowUpdate(
470 const SpdyWindowUpdateIR& window_update) const;
472 // Serializes a BLOCKED frame. The BLOCKED frame is used to
473 // indicate to the remote endpoint that this endpoint believes itself to be
474 // flow-control blocked but otherwise ready to send data. The BLOCKED frame
475 // is purely advisory and optional.
476 SpdySerializedFrame* SerializeBlocked(const SpdyBlockedIR& blocked) const;
478 // Serializes a PUSH_PROMISE frame. The PUSH_PROMISE frame is used
479 // to inform the client that it will be receiving an additional stream
480 // in response to the original request. The frame includes synthesized
481 // headers to explain the upcoming data.
482 SpdySerializedFrame* SerializePushPromise(
483 const SpdyPushPromiseIR& push_promise);
485 // Serializes a CONTINUATION frame. The CONTINUATION frame is used
486 // to continue a sequence of header block fragments.
487 // TODO(jgraettinger): This implementation is incorrect. The continuation
488 // frame continues a previously-begun HPACK encoding; it doesn't begin a
489 // new one. Figure out whether it makes sense to keep SerializeContinuation().
490 SpdySerializedFrame* SerializeContinuation(
491 const SpdyContinuationIR& continuation);
493 // Serializes an ALTSVC frame. The ALTSVC frame advertises the
494 // availability of an alternative service to the client.
495 SpdySerializedFrame* SerializeAltSvc(const SpdyAltSvcIR& altsvc);
497 // Serializes a PRIORITY frame. The PRIORITY frame advises a change in
498 // the relative priority of the given stream.
499 SpdySerializedFrame* SerializePriority(const SpdyPriorityIR& priority);
501 // Serialize a frame of unknown type.
502 SpdySerializedFrame* SerializeFrame(const SpdyFrameIR& frame);
504 // NOTES about frame compression.
505 // We want spdy to compress headers across the entire session. As long as
506 // the session is over TCP, frames are sent serially. The client & server
507 // can each compress frames in the same order and then compress them in that
508 // order, and the remote can do the reverse. However, we ultimately want
509 // the creation of frames to be less sensitive to order so that they can be
510 // placed over a UDP based protocol and yet still benefit from some
511 // compression. We don't know of any good compression protocol which does
512 // not build its state in a serial (stream based) manner.... For now, we're
513 // using zlib anyway.
515 // Compresses a SpdyFrame.
516 // On success, returns a new SpdyFrame with the payload compressed.
517 // Compression state is maintained as part of the SpdyFramer.
518 // Returned frame must be freed with "delete".
519 // On failure, returns NULL.
520 SpdyFrame* CompressFrame(const SpdyFrame& frame);
522 // For ease of testing and experimentation we can tweak compression on/off.
523 void set_enable_compression(bool value) {
524 enable_compression_ = value;
527 // Used only in log messages.
528 void set_display_protocol(const std::string& protocol) {
529 display_protocol_ = protocol;
532 // Returns the (minimum) size of frames (sans variable-length portions).
533 size_t GetDataFrameMinimumSize() const;
534 size_t GetControlFrameHeaderSize() const;
535 size_t GetSynStreamMinimumSize() const;
536 size_t GetSynReplyMinimumSize() const;
537 size_t GetRstStreamMinimumSize() const;
538 size_t GetSettingsMinimumSize() const;
539 size_t GetPingSize() const;
540 size_t GetGoAwayMinimumSize() const;
541 size_t GetHeadersMinimumSize() const;
542 size_t GetWindowUpdateSize() const;
543 size_t GetBlockedSize() const;
544 size_t GetPushPromiseMinimumSize() const;
545 size_t GetContinuationMinimumSize() const;
546 size_t GetAltSvcMinimumSize() const;
547 size_t GetPrioritySize() const;
549 // Returns the minimum size a frame can be (data or control).
550 size_t GetFrameMinimumSize() const;
552 // Returns the maximum size a frame can be (data or control).
553 size_t GetFrameMaximumSize() const;
555 // Returns the maximum size that a control frame can be.
556 size_t GetControlFrameMaximumSize() const;
558 // Returns the maximum payload size of a DATA frame.
559 size_t GetDataFrameMaximumPayload() const;
561 // Returns the prefix length for the given frame type.
562 size_t GetPrefixLength(SpdyFrameType type) const;
565 static const char* StateToString(int state);
566 static const char* ErrorCodeToString(int error_code);
567 static const char* StatusCodeToString(int status_code);
568 static const char* FrameTypeToString(SpdyFrameType type);
570 SpdyMajorVersion protocol_version() const { return spdy_version_; }
572 bool probable_http_response() const { return probable_http_response_; }
574 SpdyStreamId expect_continuation() const { return expect_continuation_; }
576 SpdyPriority GetLowestPriority() const {
577 return spdy_version_ < SPDY3 ? 3 : 7;
580 SpdyPriority GetHighestPriority() const { return 0; }
582 // Interpolates SpdyPriority values into SPDY4/HTTP2 priority weights,
584 uint8 MapPriorityToWeight(SpdyPriority priority);
585 SpdyPriority MapWeightToPriority(uint8 weight);
587 // Deliver the given control frame's compressed headers block to the visitor
588 // in decompressed form, in chunks. Returns true if the visitor has
589 // accepted all of the chunks.
590 bool IncrementallyDecompressControlFrameHeaderData(
591 SpdyStreamId stream_id,
596 // TODO(jgraettinger): Switch to test peer pattern.
597 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, BasicCompression);
598 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameSizesAreValidated);
599 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, HeaderCompression);
600 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, DecompressUncompressedFrame);
601 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ExpandBuffer_HeapSmash);
602 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, HugeHeaderBlock);
603 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, UnclosedStreamDataCompressors);
604 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
605 UnclosedStreamDataCompressorsOneByteAtATime);
606 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
607 UncompressLargerThanFrameBufferInitialSize);
608 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
609 CreatePushPromiseThenContinuationUncompressed);
610 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ReadLargeSettingsFrame);
611 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
612 ReadLargeSettingsFrameInSmallChunks);
613 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameAtMaxSizeLimit);
614 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest, ControlFrameTooLarge);
615 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
616 TooLargeHeadersFrameUsesContinuation);
617 FRIEND_TEST_ALL_PREFIXES(SpdyFramerTest,
618 TooLargePushPromiseFrameUsesContinuation);
619 friend class net::HttpNetworkLayer; // This is temporary for the server.
620 friend class net::HttpNetworkTransactionTest;
621 friend class net::HttpProxyClientSocketPoolTest;
622 friend class net::SpdyHttpStreamTest;
623 friend class net::SpdyNetworkTransactionTest;
624 friend class net::SpdyProxyClientSocketTest;
625 friend class net::SpdySessionTest;
626 friend class net::SpdyStreamTest;
627 friend class net::SpdyWebSocketStreamTest;
628 friend class net::WebSocketJobTest;
629 friend class test::TestSpdyVisitor;
632 // Internal breakouts from ProcessInput. Each returns the number of bytes
633 // consumed from the data.
634 size_t ProcessCommonHeader(const char* data, size_t len);
635 size_t ProcessControlFramePayload(const char* data, size_t len);
636 size_t ProcessControlFrameBeforeHeaderBlock(const char* data, size_t len);
637 // HPACK data is re-encoded as SPDY3 and re-entrantly delivered through
638 // |ProcessControlFrameHeaderBlock()|. |is_hpack_header_block| controls
639 // whether data is treated as HPACK- vs SPDY3-encoded.
640 size_t ProcessControlFrameHeaderBlock(const char* data,
642 bool is_hpack_header_block);
643 size_t ProcessDataFramePaddingLength(const char* data, size_t len);
644 size_t ProcessFramePadding(const char* data, size_t len);
645 size_t ProcessDataFramePayload(const char* data, size_t len);
646 size_t ProcessGoAwayFramePayload(const char* data, size_t len);
647 size_t ProcessRstStreamFramePayload(const char* data, size_t len);
648 size_t ProcessSettingsFramePayload(const char* data, size_t len);
649 size_t ProcessAltSvcFramePayload(const char* data, size_t len);
650 size_t ProcessIgnoredControlFramePayload(/*const char* data,*/ size_t len);
652 // TODO(jgraettinger): To be removed with migration to
653 // SpdyHeadersHandlerInterface.
654 // Serializes the last-processed header block of |hpack_decoder_| as
655 // a SPDY3 format block, and delivers it to the visitor via reentrant
656 // call to ProcessControlFrameHeaderBlock().
657 void DeliverHpackBlockAsSpdy3Block();
659 // Helpers for above internal breakouts from ProcessInput.
660 void ProcessControlFrameHeader(uint16 control_frame_type_field);
661 // Always passed exactly 1 setting's worth of data.
662 bool ProcessSetting(const char* data);
664 // Retrieve serialized length of SpdyHeaderBlock. If compression is enabled, a
665 // maximum estimate is returned.
666 size_t GetSerializedLength(const SpdyHeaderBlock& headers);
668 // Get (and lazily initialize) the ZLib state.
669 z_stream* GetHeaderCompressor();
670 z_stream* GetHeaderDecompressor();
672 // Get (and lazily initialize) the HPACK state.
673 HpackEncoder* GetHpackEncoder();
674 HpackDecoder* GetHpackDecoder();
676 size_t GetNumberRequiredContinuationFrames(size_t size);
678 void WritePayloadWithContinuation(SpdyFrameBuilder* builder,
679 const std::string& hpack_encoding,
680 SpdyStreamId stream_id,
682 int padding_payload_len);
685 // Deliver the given control frame's uncompressed headers block to the
686 // visitor in chunks. Returns true if the visitor has accepted all of the
688 bool IncrementallyDeliverControlFrameHeaderData(SpdyStreamId stream_id,
692 // Utility to copy the given data block to the current frame buffer, up
693 // to the given maximum number of bytes, and update the buffer
694 // data (pointer and length). Returns the number of bytes
696 // *data is advanced the number of bytes read.
697 // *len is reduced by the number of bytes read.
698 size_t UpdateCurrentFrameBuffer(const char** data, size_t* len,
701 void WriteHeaderBlockToZ(const SpdyHeaderBlock* headers,
702 z_stream* out) const;
704 void SerializeNameValueBlockWithoutCompression(
705 SpdyFrameBuilder* builder,
706 const SpdyNameValueBlock& name_value_block) const;
708 // Compresses automatically according to enable_compression_.
709 void SerializeNameValueBlock(
710 SpdyFrameBuilder* builder,
711 const SpdyFrameWithNameValueBlockIR& frame);
713 // Set the error code and moves the framer into the error state.
714 void set_error(SpdyError error);
716 // The size of the control frame buffer.
717 // Since this is only used for control frame headers, the maximum control
718 // frame header size (SYN_STREAM) is sufficient; all remaining control
719 // frame data is streamed to the visitor.
720 static const size_t kControlFrameBufferSize;
722 // The maximum size of the control frames that we support.
723 // This limit is arbitrary. We can enforce it here or at the application
724 // layer. We chose the framing layer, but this can be changed (or removed)
725 // if necessary later down the line.
726 static const size_t kMaxControlFrameSize;
729 SpdyState previous_state_;
730 SpdyError error_code_;
732 // Note that for DATA frame, remaining_data_length_ is sum of lengths of
733 // frame header, padding length field (optional), data payload (optional) and
734 // padding payload (optional).
735 size_t remaining_data_length_;
737 // The length (in bytes) of the padding payload to be processed.
738 size_t remaining_padding_payload_length_;
740 // The number of bytes remaining to read from the current control frame's
741 // headers. Note that header data blocks (for control types that have them)
742 // are part of the frame's payload, and not the frame's headers.
743 size_t remaining_control_header_;
745 scoped_ptr<char[]> current_frame_buffer_;
746 // Number of bytes read into the current_frame_buffer_.
747 size_t current_frame_buffer_length_;
749 // The type of the frame currently being read.
750 SpdyFrameType current_frame_type_;
752 // The flags field of the frame currently being read.
753 uint8 current_frame_flags_;
755 // The total length of the frame currently being read, including frame header.
756 uint32 current_frame_length_;
758 // The stream ID field of the frame currently being read, if applicable.
759 SpdyStreamId current_frame_stream_id_;
761 // Scratch space for handling SETTINGS frames.
762 // TODO(hkhalil): Unify memory for this scratch space with
763 // current_frame_buffer_.
764 SpdySettingsScratch settings_scratch_;
766 SpdyAltSvcScratch altsvc_scratch_;
768 bool enable_compression_; // Controls all compression
769 // SPDY header compressors.
770 scoped_ptr<z_stream> header_compressor_;
771 scoped_ptr<z_stream> header_decompressor_;
773 scoped_ptr<HpackEncoder> hpack_encoder_;
774 scoped_ptr<HpackDecoder> hpack_decoder_;
776 SpdyFramerVisitorInterface* visitor_;
777 SpdyFramerDebugVisitorInterface* debug_visitor_;
779 std::string display_protocol_;
781 // The major SPDY version to be spoken/understood by this framer.
782 const SpdyMajorVersion spdy_version_;
784 // Tracks if we've ever gotten far enough in framing to see a control frame of
785 // type SYN_STREAM or SYN_REPLY.
787 // If we ever get something which looks like a data frame before we've had a
788 // SYN, we explicitly check to see if it looks like we got an HTTP response
789 // to a SPDY request. This boolean lets us do that.
790 bool syn_frame_processed_;
792 // If we ever get a data frame before a SYN frame, we check to see if it
793 // starts with HTTP. If it does, we likely have an HTTP response. This
794 // isn't guaranteed though: we could have gotten a settings frame and then
795 // corrupt data that just looks like HTTP, but deterministic checking requires
797 bool probable_http_response_;
799 // Set this to the current stream when we receive a HEADERS, PUSH_PROMISE, or
800 // CONTINUATION frame without the END_HEADERS(0x4) bit set. These frames must
801 // be followed by a CONTINUATION frame, or else we throw a PROTOCOL_ERROR.
802 // A value of 0 indicates that we are not expecting a CONTINUATION frame.
803 SpdyStreamId expect_continuation_;
805 // If a HEADERS frame is followed by a CONTINUATION frame, the FIN/END_STREAM
806 // flag is still carried in the HEADERS frame. If it's set, flip this so that
807 // we know to terminate the stream when the entire header block has been
809 bool end_stream_when_done_;
814 #endif // NET_SPDY_SPDY_FRAMER_H_