We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / net / spdy / spdy_stream.h
blobd68b2cfdecadee75918f4b4fb84cf199d3506279
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_STREAM_H_
6 #define NET_SPDY_SPDY_STREAM_H_
8 #include <deque>
9 #include <string>
10 #include <vector>
12 #include "base/basictypes.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/scoped_vector.h"
16 #include "base/memory/weak_ptr.h"
17 #include "net/base/io_buffer.h"
18 #include "net/base/net_export.h"
19 #include "net/base/request_priority.h"
20 #include "net/log/net_log.h"
21 #include "net/socket/ssl_client_socket.h"
22 #include "net/spdy/spdy_buffer.h"
23 #include "net/spdy/spdy_framer.h"
24 #include "net/spdy/spdy_header_block.h"
25 #include "net/spdy/spdy_protocol.h"
26 #include "net/ssl/ssl_client_cert_type.h"
27 #include "url/gurl.h"
29 namespace net {
31 class AddressList;
32 class IPEndPoint;
33 struct LoadTimingInfo;
34 class SSLCertRequestInfo;
35 class SSLInfo;
36 class SpdySession;
38 enum SpdyStreamType {
39 // The most general type of stream; there are no restrictions on
40 // when data can be sent and received.
41 SPDY_BIDIRECTIONAL_STREAM,
42 // A stream where the client sends a request with possibly a body,
43 // and the server then sends a response with a body.
44 SPDY_REQUEST_RESPONSE_STREAM,
45 // A server-initiated stream where the server just sends a response
46 // with a body and the client does not send anything.
47 SPDY_PUSH_STREAM
50 // Passed to some SpdyStream functions to indicate whether there's
51 // more data to send.
52 enum SpdySendStatus {
53 MORE_DATA_TO_SEND,
54 NO_MORE_DATA_TO_SEND
57 // Returned by SpdyStream::OnResponseHeadersUpdated() to indicate
58 // whether the current response headers are complete or not.
59 enum SpdyResponseHeadersStatus {
60 RESPONSE_HEADERS_ARE_INCOMPLETE,
61 RESPONSE_HEADERS_ARE_COMPLETE
64 // The SpdyStream is used by the SpdySession to represent each stream known
65 // on the SpdySession. This class provides interfaces for SpdySession to use.
66 // Streams can be created either by the client or by the server. When they
67 // are initiated by the client, both the SpdySession and client object (such as
68 // a SpdyNetworkTransaction) will maintain a reference to the stream. When
69 // initiated by the server, only the SpdySession will maintain any reference,
70 // until such a time as a client object requests a stream for the path.
71 class NET_EXPORT_PRIVATE SpdyStream {
72 public:
73 // Delegate handles protocol specific behavior of spdy stream.
74 class NET_EXPORT_PRIVATE Delegate {
75 public:
76 Delegate() {}
78 // Called when the request headers have been sent. Never called
79 // for push streams. Must not cause the stream to be closed.
80 virtual void OnRequestHeadersSent() = 0;
82 // WARNING: This function is complicated! Be sure to read the
83 // whole comment below if you're working with code that implements
84 // or calls this function.
86 // Called when the response headers are updated from the
87 // server. |response_headers| contains the set of all headers
88 // received up to this point; delegates can assume that any
89 // headers previously received remain unchanged.
91 // This is called at least once before any data is received. If
92 // RESPONSE_HEADERS_ARE_INCOMPLETE is returned, this will be
93 // called again when more headers are received until
94 // RESPONSE_HEADERS_ARE_COMPLETE is returned, and any data
95 // received before then will be treated as a protocol error.
97 // If RESPONSE_HEADERS_ARE_INCOMPLETE is returned, the delegate
98 // must not have closed the stream. Otherwise, if
99 // RESPONSE_HEADERS_ARE_COMPLETE is returned, the delegate has
100 // processed the headers successfully. However, it still may have
101 // closed the stream, e.g. if the headers indicated an error
102 // condition.
104 // Some type-specific behavior:
106 // - For bidirectional streams, this may be called even after
107 // data is received, but it is expected that
108 // RESPONSE_HEADERS_ARE_COMPLETE is always returned. If
109 // RESPONSE_HEADERS_ARE_INCOMPLETE is returned, this is
110 // treated as a protocol error.
112 // - For request/response streams, this function is called
113 // exactly once before data is received, and it is expected
114 // that RESPONSE_HEADERS_ARE_COMPLETE is returned. If
115 // RESPONSE_HEADERS_ARE_INCOMPLETE is returned, this is
116 // treated as a protocol error.
118 // - For push streams, it is expected that this function will be
119 // called until RESPONSE_HEADERS_ARE_COMPLETE is returned
120 // before any data is received; any deviation from this is
121 // treated as a protocol error.
123 // TODO(akalin): Treat headers received after data has been
124 // received as a protocol error for non-bidirectional streams.
125 // TODO(jgraettinger): This should be at the semantic (HTTP) rather
126 // than stream layer. Streams shouldn't have a notion of header
127 // completeness. Move to SpdyHttpStream/SpdyWebsocketStream.
128 virtual SpdyResponseHeadersStatus OnResponseHeadersUpdated(
129 const SpdyHeaderBlock& response_headers) = 0;
131 // Called when data is received after all required response
132 // headers have been received. |buffer| may be NULL, which signals
133 // EOF. Must return OK if the data was received successfully, or
134 // a network error code otherwise.
136 // May cause the stream to be closed.
137 virtual void OnDataReceived(scoped_ptr<SpdyBuffer> buffer) = 0;
139 // Called when data is sent. Must not cause the stream to be
140 // closed.
141 virtual void OnDataSent() = 0;
143 // Called when SpdyStream is closed. No other delegate functions
144 // will be called after this is called, and the delegate must not
145 // access the stream after this is called. Must not cause the
146 // stream to be be (re-)closed.
148 // TODO(akalin): Allow this function to re-close the stream and
149 // handle it gracefully.
150 virtual void OnClose(int status) = 0;
152 protected:
153 virtual ~Delegate() {}
155 private:
156 DISALLOW_COPY_AND_ASSIGN(Delegate);
159 // SpdyStream constructor
160 SpdyStream(SpdyStreamType type,
161 const base::WeakPtr<SpdySession>& session,
162 const GURL& url,
163 RequestPriority priority,
164 int32 initial_send_window_size,
165 int32 initial_recv_window_size,
166 const BoundNetLog& net_log);
168 ~SpdyStream();
170 // Set the delegate, which must not be NULL. Must not be called more
171 // than once. For push streams, calling this may cause buffered data
172 // to be sent to the delegate (from a posted task).
173 void SetDelegate(Delegate* delegate);
175 // Detach the delegate from the stream, which must not yet be
176 // closed, and cancel it.
177 void DetachDelegate();
179 // The time at which the first bytes of the response were received
180 // from the server, or null if the response hasn't been received
181 // yet.
182 base::Time response_time() const { return response_time_; }
184 SpdyStreamType type() const { return type_; }
186 SpdyStreamId stream_id() const { return stream_id_; }
187 void set_stream_id(SpdyStreamId stream_id) { stream_id_ = stream_id; }
189 const GURL& url() const { return url_; }
191 RequestPriority priority() const { return priority_; }
193 int32 send_window_size() const { return send_window_size_; }
195 int32 recv_window_size() const { return recv_window_size_; }
197 bool send_stalled_by_flow_control() const {
198 return send_stalled_by_flow_control_;
201 void set_send_stalled_by_flow_control(bool stalled) {
202 send_stalled_by_flow_control_ = stalled;
205 // Called by the session to adjust this stream's send window size by
206 // |delta_window_size|, which is the difference between the
207 // SETTINGS_INITIAL_WINDOW_SIZE in the most recent SETTINGS frame
208 // and the previous initial send window size, possibly unstalling
209 // this stream. Although |delta_window_size| may cause this stream's
210 // send window size to go negative, it must not cause it to wrap
211 // around in either direction. Does nothing if the stream is already
212 // closed.
214 // If stream flow control is turned off, this must not be called.
215 void AdjustSendWindowSize(int32 delta_window_size);
217 // Called when bytes are consumed from a SpdyBuffer for a DATA frame
218 // that is to be written or is being written. Increases the send
219 // window size accordingly if some or all of the SpdyBuffer is being
220 // discarded.
222 // If stream flow control is turned off, this must not be called.
223 void OnWriteBufferConsumed(size_t frame_payload_size,
224 size_t consume_size,
225 SpdyBuffer::ConsumeSource consume_source);
227 // Called by the session to increase this stream's send window size
228 // by |delta_window_size| (which must be at least 1) from a received
229 // WINDOW_UPDATE frame or from a dropped DATA frame that was
230 // intended to be sent, possibly unstalling this stream. If
231 // |delta_window_size| would cause this stream's send window size to
232 // overflow, calls into the session to reset this stream. Does
233 // nothing if the stream is already closed.
235 // If stream flow control is turned off, this must not be called.
236 void IncreaseSendWindowSize(int32 delta_window_size);
238 // If stream flow control is turned on, called by the session to
239 // decrease this stream's send window size by |delta_window_size|,
240 // which must be at least 0 and at most kMaxSpdyFrameChunkSize.
241 // |delta_window_size| must not cause this stream's send window size
242 // to go negative. Does nothing if the stream is already closed.
244 // If stream flow control is turned off, this must not be called.
245 void DecreaseSendWindowSize(int32 delta_window_size);
247 // Called when bytes are consumed by the delegate from a SpdyBuffer
248 // containing received data. Increases the receive window size
249 // accordingly.
251 // If stream flow control is turned off, this must not be called.
252 void OnReadBufferConsumed(size_t consume_size,
253 SpdyBuffer::ConsumeSource consume_source);
255 // Called by OnReadBufferConsume to increase this stream's receive
256 // window size by |delta_window_size|, which must be at least 1 and
257 // must not cause this stream's receive window size to overflow,
258 // possibly also sending a WINDOW_UPDATE frame. Does nothing if the
259 // stream is not active.
261 // If stream flow control is turned off, this must not be called.
262 void IncreaseRecvWindowSize(int32 delta_window_size);
264 // Called by OnDataReceived or OnPaddingConsumed (which are in turn called by
265 // the session) to decrease this stream's receive window size by
266 // |delta_window_size|, which must be at least 1 and must not cause
267 // this stream's receive window size to go negative.
269 // If stream flow control is turned off or the stream is not active,
270 // this must not be called.
271 void DecreaseRecvWindowSize(int32 delta_window_size);
273 int GetPeerAddress(IPEndPoint* address) const;
274 int GetLocalAddress(IPEndPoint* address) const;
276 // Returns true if the underlying transport socket ever had any reads or
277 // writes.
278 bool WasEverUsed() const;
280 const BoundNetLog& net_log() const { return net_log_; }
282 base::Time GetRequestTime() const;
283 void SetRequestTime(base::Time t);
285 // Called at most once by the SpdySession when the initial response
286 // headers have been received for this stream, i.e., a SYN_REPLY (or
287 // SYN_STREAM for push streams) frame has been received. Returns a status
288 // code; if it is an error, the stream was closed by this function.
289 int OnInitialResponseHeadersReceived(const SpdyHeaderBlock& response_headers,
290 base::Time response_time,
291 base::TimeTicks recv_first_byte_time);
293 // Called by the SpdySession (only after
294 // OnInitialResponseHeadersReceived() has been called) when
295 // late-bound headers are received for a stream. Returns a status
296 // code; if it is an error, the stream was closed by this function.
297 int OnAdditionalResponseHeadersReceived(
298 const SpdyHeaderBlock& additional_response_headers);
300 // Called by the SpdySession when a frame carrying request headers opening a
301 // push stream is received. Stream transits to STATE_RESERVED_REMOTE state.
302 void OnPushPromiseHeadersReceived(const SpdyHeaderBlock& headers);
304 // Called by the SpdySession when response data has been received
305 // for this stream. This callback may be called multiple times as
306 // data arrives from the network, and will never be called prior to
307 // OnResponseHeadersReceived.
309 // |buffer| contains the data received, or NULL if the stream is
310 // being closed. The stream must copy any data from this
311 // buffer before returning from this callback.
313 // |length| is the number of bytes received (at most 2^24 - 1) or 0 if
314 // the stream is being closed.
315 void OnDataReceived(scoped_ptr<SpdyBuffer> buffer);
317 // Called by the SpdySession when padding is consumed to allow for the stream
318 // receiving window to be updated.
319 void OnPaddingConsumed(size_t len);
321 // Called by the SpdySession when a frame has been successfully and
322 // completely written. |frame_size| is the total size of the frame
323 // in bytes, including framing overhead.
324 void OnFrameWriteComplete(SpdyFrameType frame_type, size_t frame_size);
326 // SYN_STREAM-specific write handler invoked by OnFrameWriteComplete().
327 int OnRequestHeadersSent();
329 // DATA-specific write handler invoked by OnFrameWriteComplete().
330 // If more data is already available to be written, the next write is
331 // queued and ERR_IO_PENDING is returned. Returns OK otherwise.
332 int OnDataSent(size_t frame_size);
334 // Called by the SpdySession when the request is finished. This callback
335 // will always be called at the end of the request and signals to the
336 // stream that the stream has no more network events. No further callbacks
337 // to the stream will be made after this call.
338 // |status| is an error code or OK.
339 void OnClose(int status);
341 // Called by the SpdySession to log stream related errors.
342 void LogStreamError(int status, const std::string& description);
344 // If this stream is active, reset it, and close it otherwise. In
345 // either case the stream is deleted.
346 void Cancel();
348 // Close this stream without sending a RST_STREAM and delete
349 // it.
350 void Close();
352 // Must be used only by |session_|.
353 base::WeakPtr<SpdyStream> GetWeakPtr();
355 // Interface for the delegate to use.
357 // Only one send can be in flight at a time, except for push
358 // streams, which must not send anything.
360 // Sends the request headers. The delegate is called back via
361 // OnRequestHeadersSent() when the request headers have completed
362 // sending. |send_status| must be MORE_DATA_TO_SEND for
363 // bidirectional streams; for request/response streams, it must be
364 // MORE_DATA_TO_SEND if the request has data to upload, or
365 // NO_MORE_DATA_TO_SEND if not.
366 int SendRequestHeaders(scoped_ptr<SpdyHeaderBlock> request_headers,
367 SpdySendStatus send_status);
369 // Sends a DATA frame. The delegate will be notified via
370 // OnDataSent() when the send is complete. |send_status| must be
371 // MORE_DATA_TO_SEND for bidirectional streams; for request/response
372 // streams, it must be MORE_DATA_TO_SEND if there is more data to
373 // upload, or NO_MORE_DATA_TO_SEND if not.
374 void SendData(IOBuffer* data, int length, SpdySendStatus send_status);
376 // Fills SSL info in |ssl_info| and returns true when SSL is in use.
377 bool GetSSLInfo(SSLInfo* ssl_info,
378 bool* was_npn_negotiated,
379 NextProto* protocol_negotiated);
381 // Fills SSL Certificate Request info |cert_request_info| and returns
382 // true when SSL is in use.
383 bool GetSSLCertRequestInfo(SSLCertRequestInfo* cert_request_info);
385 // If the stream is stalled on sending data, but the session is not
386 // stalled on sending data and |send_window_size_| is positive, then
387 // set |send_stalled_by_flow_control_| to false and unstall the data
388 // sending. Called by the session or by the stream itself. Must be
389 // called only when the stream is still open.
390 void PossiblyResumeIfSendStalled();
392 // Returns whether or not this stream is closed. Note that the only
393 // time a stream is closed and not deleted is in its delegate's
394 // OnClose() method.
395 bool IsClosed() const;
397 // Returns whether the streams local endpoint is closed.
398 // The remote endpoint may still be active.
399 bool IsLocallyClosed() const;
401 // Returns whether this stream is IDLE: request and response headers
402 // have neither been sent nor receieved.
403 bool IsIdle() const;
405 // Returns whether or not this stream is fully open: that request and
406 // response headers are complete, and it is not in a half-closed state.
407 bool IsOpen() const;
409 // Returns whether the stream is reserved by remote endpoint: server has sent
410 // intended request headers for a pushed stream, but haven't started response
411 // yet.
412 bool IsReservedRemote() const;
414 // Returns the protocol used by this stream. Always between
415 // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
416 NextProto GetProtocol() const;
418 int response_status() const { return response_status_; }
420 void IncrementRawReceivedBytes(size_t received_bytes) {
421 raw_received_bytes_ += received_bytes;
424 int64 raw_received_bytes() const { return raw_received_bytes_; }
426 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const;
428 // Get the URL from the appropriate stream headers, or the empty
429 // GURL() if it is unknown.
431 // TODO(akalin): Figure out if we really need this function,
432 // i.e. can we just use the URL this stream was created with and/or
433 // one we receive headers validate that the URL from them is the
434 // same.
435 GURL GetUrlFromHeaders() const;
437 // Returns whether the URL for this stream is known.
439 // TODO(akalin): Remove this, as it's only used in tests.
440 bool HasUrlFromHeaders() const;
442 SpdyMajorVersion GetProtocolVersion() const;
444 private:
445 class SynStreamBufferProducer;
446 class HeaderBufferProducer;
448 // SpdyStream states and transitions are modeled
449 // on the HTTP/2 stream state machine. All states and transitions
450 // are modeled, with the exceptions of RESERVED_LOCAL (the client
451 // cannot initate push streams), and the transition to OPEN due to
452 // a remote SYN_STREAM (the client can only initate streams).
453 enum State {
454 STATE_IDLE,
455 STATE_OPEN,
456 STATE_HALF_CLOSED_LOCAL_UNCLAIMED,
457 STATE_HALF_CLOSED_LOCAL,
458 STATE_HALF_CLOSED_REMOTE,
459 STATE_RESERVED_REMOTE,
460 STATE_CLOSED,
463 // Update the histograms. Can safely be called repeatedly, but should only
464 // be called after the stream has completed.
465 void UpdateHistograms();
467 // When a server-push stream is claimed by SetDelegate(), this function is
468 // posted on the current MessageLoop to replay everything the server has sent.
469 // From the perspective of SpdyStream's state machine, headers, data, and
470 // FIN states received prior to the delegate being attached have not yet been
471 // read. While buffered by |pending_recv_data_| it's not until
472 // PushedStreamReplay() is invoked that reads are considered
473 // to have occurred, driving the state machine forward.
474 void PushedStreamReplay();
476 // Produces the SYN_STREAM frame for the stream. The stream must
477 // already be activated.
478 scoped_ptr<SpdyFrame> ProduceSynStreamFrame();
480 // Produce the initial HEADER frame for the stream with the given
481 // block. The stream must already be activated.
482 scoped_ptr<SpdyFrame> ProduceHeaderFrame(
483 scoped_ptr<SpdyHeaderBlock> header_block);
485 // Queues the send for next frame of the remaining data in
486 // |pending_send_data_|. Must be called only when
487 // |pending_send_data_| is set.
488 void QueueNextDataFrame();
490 // Merge the given headers into |response_headers_| and calls
491 // OnResponseHeadersUpdated() on the delegate (if attached).
492 // Returns a status code; if it is an error, the stream was closed
493 // by this function.
494 int MergeWithResponseHeaders(const SpdyHeaderBlock& new_response_headers);
496 static std::string DescribeState(State state);
498 const SpdyStreamType type_;
500 SpdyStreamId stream_id_;
501 const GURL url_;
502 const RequestPriority priority_;
504 // Flow control variables.
505 bool send_stalled_by_flow_control_;
506 int32 send_window_size_;
507 int32 recv_window_size_;
508 int32 unacked_recv_window_bytes_;
510 const base::WeakPtr<SpdySession> session_;
512 // The transaction should own the delegate.
513 SpdyStream::Delegate* delegate_;
515 // The headers for the request to send.
517 // TODO(akalin): Hang onto this only until we send it. This
518 // necessitates stashing the URL separately.
519 scoped_ptr<SpdyHeaderBlock> request_headers_;
521 // Data waiting to be sent, and the close state of the local endpoint
522 // after the data is fully written.
523 scoped_refptr<DrainableIOBuffer> pending_send_data_;
524 SpdySendStatus pending_send_status_;
526 // Data waiting to be received, and the close state of the remote endpoint
527 // after the data is fully read. Specifically, data received before the
528 // delegate is attached must be buffered and later replayed. A remote FIN
529 // is represented by a final, zero-length buffer.
530 ScopedVector<SpdyBuffer> pending_recv_data_;
532 // The time at which the request was made that resulted in this response.
533 // For cached responses, this time could be "far" in the past.
534 base::Time request_time_;
536 SpdyHeaderBlock response_headers_;
537 SpdyResponseHeadersStatus response_headers_status_;
538 base::Time response_time_;
540 State io_state_;
542 // Since we buffer the response, we also buffer the response status.
543 // Not valid until the stream is closed.
544 int response_status_;
546 BoundNetLog net_log_;
548 base::TimeTicks send_time_;
549 base::TimeTicks recv_first_byte_time_;
550 base::TimeTicks recv_last_byte_time_;
552 // Number of bytes that have been received on this stream, including frame
553 // overhead and headers.
554 int64 raw_received_bytes_;
556 // Number of data bytes that have been sent/received on this stream, not
557 // including frame overhead. Note that this does not count headers.
558 int send_bytes_;
559 int recv_bytes_;
561 // Guards calls of delegate write handlers ensuring |this| is not destroyed.
562 // TODO(jgraettinger): Consider removing after crbug.com/35511 is tracked
563 // down.
564 bool write_handler_guard_;
566 base::WeakPtrFactory<SpdyStream> weak_ptr_factory_;
568 DISALLOW_COPY_AND_ASSIGN(SpdyStream);
571 } // namespace net
573 #endif // NET_SPDY_SPDY_STREAM_H_