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