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