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) {}
288 // Called when a PRIORITY frame is received.
289 virtual void OnPriority(SpdyStreamId stream_id,
290 SpdyStreamId parent_stream_id,
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
300 // Most SPDY implementations need not bother with this interface at all.
301 class NET_EXPORT_PRIVATE SpdyFramerDebugVisitorInterface {
303 virtual ~SpdyFramerDebugVisitorInterface() {}
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,
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,
322 class NET_EXPORT_PRIVATE SpdyFramer {
325 // TODO(mbelshe): Can we move these into the implementation
326 // and avoid exposing through the header. (Needed for test)
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,
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.
360 LAST_ERROR, // Must be the last entry in the enum.
363 // Constant for invalid (or unknown) stream IDs.
364 static const SpdyStreamId kInvalidStream;
366 // The maximum size of header data chunks delivered to the framer visitor
367 // through OnControlFrameHeaderData. (It is exposed here for unit test
369 static const size_t kHeaderDataChunkMaxSize;
371 // Serializes a SpdyHeaderBlock.
372 static void WriteHeaderBlock(SpdyFrameBuilder* frame,
373 const SpdyMajorVersion spdy_version,
374 const SpdyHeaderBlock* headers);
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);
382 // Create a new Framer, provided a SPDY version.
383 explicit SpdyFramer(SpdyMajorVersion version);
384 virtual ~SpdyFramer();
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
390 void set_visitor(SpdyFramerVisitorInterface* visitor) {
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;
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);
406 // Resets the framer state after a frame has been successfully decoded.
407 // TODO(mbelshe): can we make this private?
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; }
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;
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;
430 // Serializes a SYN_STREAM frame.
431 SpdySerializedFrame* SerializeSynStream(const SpdySynStreamIR& syn_stream);
433 // Serialize a SYN_REPLY SpdyFrame.
434 SpdySerializedFrame* SerializeSynReply(const SpdySynReplyIR& syn_reply);
436 SpdySerializedFrame* SerializeRstStream(
437 const SpdyRstStreamIR& rst_stream) const;
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;
443 // Serializes a PING frame. The unique_id is used to
444 // identify the ping request/response.
445 SpdySerializedFrame* SerializePing(const SpdyPingIR& ping) const;
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
451 SpdySerializedFrame* SerializeGoAway(const SpdyGoAwayIR& goaway) const;
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);
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;
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;
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);
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);
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);
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);
491 // Serialize a frame of unknown type.
492 SpdySerializedFrame* SerializeFrame(const SpdyFrameIR& frame);
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.
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);
512 // For ease of testing and experimentation we can tweak compression on/off.
513 void set_enable_compression(bool value) {
514 enable_compression_ = value;
517 // Used only in log messages.
518 void set_display_protocol(const std::string& protocol) {
519 display_protocol_ = protocol;
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;
539 // Returns the minimum size a frame can be (data or control).
540 size_t GetFrameMinimumSize() const;
542 // Returns the maximum size a frame can be (data or control).
543 size_t GetFrameMaximumSize() const;
545 // Returns the maximum size that a control frame can be.
546 size_t GetControlFrameMaximumSize() const;
548 // Returns the maximum payload size of a DATA frame.
549 size_t GetDataFrameMaximumPayload() const;
551 // Returns the prefix length for the given frame type.
552 size_t GetPrefixLength(SpdyFrameType type) const;
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);
560 SpdyMajorVersion protocol_version() const { return spdy_version_; }
562 bool probable_http_response() const { return probable_http_response_; }
564 SpdyStreamId expect_continuation() const { return expect_continuation_; }
566 SpdyPriority GetLowestPriority() const {
567 return spdy_version_ < SPDY3 ? 3 : 7;
570 SpdyPriority GetHighestPriority() const { return 0; }
572 // Interpolates SpdyPriority values into SPDY4/HTTP2 priority weights,
574 uint8 MapPriorityToWeight(SpdyPriority priority);
575 SpdyPriority MapWeightToPriority(uint8 weight);
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,
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;
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,
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);
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();
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);
652 // Retrieve serialized length of SpdyHeaderBlock. If compression is enabled, a
653 // maximum estimate is returned.
654 size_t GetSerializedLength(const SpdyHeaderBlock& headers);
656 // Get (and lazily initialize) the ZLib state.
657 z_stream* GetHeaderCompressor();
658 z_stream* GetHeaderDecompressor();
660 // Get (and lazily initialize) the HPACK state.
661 HpackEncoder* GetHpackEncoder();
662 HpackDecoder* GetHpackDecoder();
664 size_t GetNumberRequiredContinuationFrames(size_t size);
666 void WritePayloadWithContinuation(SpdyFrameBuilder* builder,
667 const std::string& hpack_encoding,
668 SpdyStreamId stream_id,
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
675 bool IncrementallyDeliverControlFrameHeaderData(SpdyStreamId stream_id,
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
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,
688 void WriteHeaderBlockToZ(const SpdyHeaderBlock* headers,
689 z_stream* out) const;
691 void SerializeNameValueBlockWithoutCompression(
692 SpdyFrameBuilder* builder,
693 const SpdyNameValueBlock& name_value_block) const;
695 // Compresses automatically according to enable_compression_.
696 void SerializeNameValueBlock(
697 SpdyFrameBuilder* builder,
698 const SpdyFrameWithNameValueBlockIR& frame);
700 // Set the error code and moves the framer into the error state.
701 void set_error(SpdyError error);
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
711 if (spdy_version_ == SPDY2) {
714 if (spdy_version_ == SPDY3) {
715 return 16 * 1024 * 1024;
717 // Absolute maximum size of HTTP2 frame payload (section 4.2 "Frame size").
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.
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;
734 SpdyState previous_state_;
735 SpdyError error_code_;
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_;
742 // The length (in bytes) of the padding payload to be processed.
743 size_t remaining_padding_payload_length_;
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_;
750 scoped_ptr<char[]> current_frame_buffer_;
751 // Number of bytes read into the current_frame_buffer_.
752 size_t current_frame_buffer_length_;
754 // The type of the frame currently being read.
755 SpdyFrameType current_frame_type_;
757 // The flags field of the frame currently being read.
758 uint8 current_frame_flags_;
760 // The total length of the frame currently being read, including frame header.
761 uint32 current_frame_length_;
763 // The stream ID field of the frame currently being read, if applicable.
764 SpdyStreamId current_frame_stream_id_;
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_;
771 SpdyAltSvcScratch altsvc_scratch_;
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_;
778 scoped_ptr<HpackEncoder> hpack_encoder_;
779 scoped_ptr<HpackDecoder> hpack_decoder_;
781 SpdyFramerVisitorInterface* visitor_;
782 SpdyFramerDebugVisitorInterface* debug_visitor_;
784 std::string display_protocol_;
786 // The major SPDY version to be spoken/understood by this framer.
787 const SpdyMajorVersion spdy_version_;
789 // Tracks if we've ever gotten far enough in framing to see a control frame of
790 // type SYN_STREAM or SYN_REPLY.
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_;
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
802 bool probable_http_response_;
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_;
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
814 bool end_stream_when_done_;
819 #endif // NET_SPDY_SPDY_FRAMER_H_