Don't show supervised user as "already on this device" while they're being imported.
[chromium-blink-merge.git] / net / spdy / spdy_stream.h
blob73288ce9ba1490f915fd018a5d2187e9815d3556
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 SSLInfo;
35 class SpdySession;
37 enum SpdyStreamType {
38 // The most general type of stream; there are no restrictions on
39 // when data can be sent and received.
40 SPDY_BIDIRECTIONAL_STREAM,
41 // A stream where the client sends a request with possibly a body,
42 // and the server then sends a response with a body.
43 SPDY_REQUEST_RESPONSE_STREAM,
44 // A server-initiated stream where the server just sends a response
45 // with a body and the client does not send anything.
46 SPDY_PUSH_STREAM
49 // Passed to some SpdyStream functions to indicate whether there's
50 // more data to send.
51 enum SpdySendStatus {
52 MORE_DATA_TO_SEND,
53 NO_MORE_DATA_TO_SEND
56 // Returned by SpdyStream::OnResponseHeadersUpdated() to indicate
57 // whether the current response headers are complete or not.
58 enum SpdyResponseHeadersStatus {
59 RESPONSE_HEADERS_ARE_INCOMPLETE,
60 RESPONSE_HEADERS_ARE_COMPLETE
63 // The SpdyStream is used by the SpdySession to represent each stream known
64 // on the SpdySession. This class provides interfaces for SpdySession to use.
65 // Streams can be created either by the client or by the server. When they
66 // are initiated by the client, both the SpdySession and client object (such as
67 // a SpdyNetworkTransaction) will maintain a reference to the stream. When
68 // initiated by the server, only the SpdySession will maintain any reference,
69 // until such a time as a client object requests a stream for the path.
70 class NET_EXPORT_PRIVATE SpdyStream {
71 public:
72 // Delegate handles protocol specific behavior of spdy stream.
73 class NET_EXPORT_PRIVATE Delegate {
74 public:
75 Delegate() {}
77 // Called when the request headers have been sent. Never called
78 // for push streams. Must not cause the stream to be closed.
79 virtual void OnRequestHeadersSent() = 0;
81 // WARNING: This function is complicated! Be sure to read the
82 // whole comment below if you're working with code that implements
83 // or calls this function.
85 // Called when the response headers are updated from the
86 // server. |response_headers| contains the set of all headers
87 // received up to this point; delegates can assume that any
88 // headers previously received remain unchanged.
90 // This is called at least once before any data is received. If
91 // RESPONSE_HEADERS_ARE_INCOMPLETE is returned, this will be
92 // called again when more headers are received until
93 // RESPONSE_HEADERS_ARE_COMPLETE is returned, and any data
94 // received before then will be treated as a protocol error.
96 // If RESPONSE_HEADERS_ARE_INCOMPLETE is returned, the delegate
97 // must not have closed the stream. Otherwise, if
98 // RESPONSE_HEADERS_ARE_COMPLETE is returned, the delegate has
99 // processed the headers successfully. However, it still may have
100 // closed the stream, e.g. if the headers indicated an error
101 // condition.
103 // Some type-specific behavior:
105 // - For bidirectional streams, this may be called even after
106 // data is received, but it is expected that
107 // RESPONSE_HEADERS_ARE_COMPLETE is always returned. If
108 // RESPONSE_HEADERS_ARE_INCOMPLETE is returned, this is
109 // treated as a protocol error.
111 // - For request/response streams, this function is called
112 // exactly once before data is received, and it is expected
113 // that RESPONSE_HEADERS_ARE_COMPLETE is returned. If
114 // RESPONSE_HEADERS_ARE_INCOMPLETE is returned, this is
115 // treated as a protocol error.
117 // - For push streams, it is expected that this function will be
118 // called until RESPONSE_HEADERS_ARE_COMPLETE is returned
119 // before any data is received; any deviation from this is
120 // treated as a protocol error.
122 // TODO(akalin): Treat headers received after data has been
123 // received as a protocol error for non-bidirectional streams.
124 // TODO(jgraettinger): This should be at the semantic (HTTP) rather
125 // than stream layer. Streams shouldn't have a notion of header
126 // completeness. Move to SpdyHttpStream/SpdyWebsocketStream.
127 virtual SpdyResponseHeadersStatus OnResponseHeadersUpdated(
128 const SpdyHeaderBlock& response_headers) = 0;
130 // Called when data is received after all required response
131 // headers have been received. |buffer| may be NULL, which signals
132 // EOF. Must return OK if the data was received successfully, or
133 // a network error code otherwise.
135 // May cause the stream to be closed.
136 virtual void OnDataReceived(scoped_ptr<SpdyBuffer> buffer) = 0;
138 // Called when data is sent. Must not cause the stream to be
139 // closed.
140 virtual void OnDataSent() = 0;
142 // Called when SpdyStream is closed. No other delegate functions
143 // will be called after this is called, and the delegate must not
144 // access the stream after this is called. Must not cause the
145 // stream to be be (re-)closed.
147 // TODO(akalin): Allow this function to re-close the stream and
148 // handle it gracefully.
149 virtual void OnClose(int status) = 0;
151 protected:
152 virtual ~Delegate() {}
154 private:
155 DISALLOW_COPY_AND_ASSIGN(Delegate);
158 // SpdyStream constructor
159 SpdyStream(SpdyStreamType type,
160 const base::WeakPtr<SpdySession>& session,
161 const GURL& url,
162 RequestPriority priority,
163 int32 initial_send_window_size,
164 int32 max_recv_window_size,
165 const BoundNetLog& net_log);
167 ~SpdyStream();
169 // Set the delegate, which must not be NULL. Must not be called more
170 // than once. For push streams, calling this may cause buffered data
171 // to be sent to the delegate (from a posted task).
172 void SetDelegate(Delegate* delegate);
174 // Detach the delegate from the stream, which must not yet be
175 // closed, and cancel it.
176 void DetachDelegate();
178 // The time at which the first bytes of the response were received
179 // from the server, or null if the response hasn't been received
180 // yet.
181 base::Time response_time() const { return response_time_; }
183 SpdyStreamType type() const { return type_; }
185 SpdyStreamId stream_id() const { return stream_id_; }
186 void set_stream_id(SpdyStreamId stream_id) { stream_id_ = stream_id; }
188 const GURL& url() const { return url_; }
190 RequestPriority priority() const { return priority_; }
192 int32 send_window_size() const { return send_window_size_; }
194 int32 recv_window_size() const { return recv_window_size_; }
196 bool send_stalled_by_flow_control() const {
197 return send_stalled_by_flow_control_;
200 void set_send_stalled_by_flow_control(bool stalled) {
201 send_stalled_by_flow_control_ = stalled;
204 // Called by the session to adjust this stream's send window size by
205 // |delta_window_size|, which is the difference between the
206 // SETTINGS_INITIAL_WINDOW_SIZE in the most recent SETTINGS frame
207 // and the previous initial send window size, possibly unstalling
208 // this stream. Although |delta_window_size| may cause this stream's
209 // send window size to go negative, it must not cause it to wrap
210 // around in either direction. Does nothing if the stream is already
211 // closed.
213 // If stream flow control is turned off, this must not be called.
214 void AdjustSendWindowSize(int32 delta_window_size);
216 // Called when bytes are consumed from a SpdyBuffer for a DATA frame
217 // that is to be written or is being written. Increases the send
218 // window size accordingly if some or all of the SpdyBuffer is being
219 // discarded.
221 // If stream flow control is turned off, this must not be called.
222 void OnWriteBufferConsumed(size_t frame_payload_size,
223 size_t consume_size,
224 SpdyBuffer::ConsumeSource consume_source);
226 // Called by the session to increase this stream's send window size
227 // by |delta_window_size| (which must be at least 1) from a received
228 // WINDOW_UPDATE frame or from a dropped DATA frame that was
229 // intended to be sent, possibly unstalling this stream. If
230 // |delta_window_size| would cause this stream's send window size to
231 // overflow, calls into the session to reset this stream. Does
232 // nothing if the stream is already closed.
234 // If stream flow control is turned off, this must not be called.
235 void IncreaseSendWindowSize(int32 delta_window_size);
237 // If stream flow control is turned on, called by the session to
238 // decrease this stream's send window size by |delta_window_size|,
239 // which must be at least 0 and at most kMaxSpdyFrameChunkSize.
240 // |delta_window_size| must not cause this stream's send window size
241 // to go negative. Does nothing if the stream is already closed.
243 // If stream flow control is turned off, this must not be called.
244 void DecreaseSendWindowSize(int32 delta_window_size);
246 // Called when bytes are consumed by the delegate from a SpdyBuffer
247 // containing received data. Increases the receive window size
248 // accordingly.
250 // If stream flow control is turned off, this must not be called.
251 void OnReadBufferConsumed(size_t consume_size,
252 SpdyBuffer::ConsumeSource consume_source);
254 // Called by OnReadBufferConsume to increase this stream's receive
255 // window size by |delta_window_size|, which must be at least 1 and
256 // must not cause this stream's receive window size to overflow,
257 // possibly also sending a WINDOW_UPDATE frame. Does nothing if the
258 // stream is not active.
260 // If stream flow control is turned off, this must not be called.
261 void IncreaseRecvWindowSize(int32 delta_window_size);
263 // Called by OnDataReceived or OnPaddingConsumed (which are in turn called by
264 // the session) to decrease this stream's receive window size by
265 // |delta_window_size|, which must be at least 1. May close the stream on
266 // flow control error.
268 // If stream flow control is turned off or the stream is not active,
269 // this must not be called.
270 void DecreaseRecvWindowSize(int32 delta_window_size);
272 int GetPeerAddress(IPEndPoint* address) const;
273 int GetLocalAddress(IPEndPoint* address) const;
275 // Returns true if the underlying transport socket ever had any reads or
276 // writes.
277 bool WasEverUsed() const;
279 const BoundNetLog& net_log() const { return net_log_; }
281 base::Time GetRequestTime() const;
282 void SetRequestTime(base::Time t);
284 // Called at most once by the SpdySession when the initial response
285 // headers have been received for this stream, i.e., a SYN_REPLY (or
286 // SYN_STREAM for push streams) frame has been received. Returns a status
287 // code; if it is an error, the stream was closed by this function.
288 int OnInitialResponseHeadersReceived(const SpdyHeaderBlock& response_headers,
289 base::Time response_time,
290 base::TimeTicks recv_first_byte_time);
292 // Called by the SpdySession (only after
293 // OnInitialResponseHeadersReceived() has been called) when
294 // late-bound headers are received for a stream. Returns a status
295 // code; if it is an error, the stream was closed by this function.
296 int OnAdditionalResponseHeadersReceived(
297 const SpdyHeaderBlock& additional_response_headers);
299 // Called by the SpdySession when a frame carrying request headers opening a
300 // push stream is received. Stream transits to STATE_RESERVED_REMOTE state.
301 void OnPushPromiseHeadersReceived(const SpdyHeaderBlock& headers);
303 // Called by the SpdySession when response data has been received
304 // for this stream. This callback may be called multiple times as
305 // data arrives from the network, and will never be called prior to
306 // OnResponseHeadersReceived.
308 // |buffer| contains the data received, or NULL if the stream is
309 // being closed. The stream must copy any data from this
310 // buffer before returning from this callback.
312 // |length| is the number of bytes received (at most 2^24 - 1) or 0 if
313 // the stream is being closed.
314 void OnDataReceived(scoped_ptr<SpdyBuffer> buffer);
316 // Called by the SpdySession when padding is consumed to allow for the stream
317 // receiving window to be updated.
318 void OnPaddingConsumed(size_t len);
320 // Called by the SpdySession when a frame has been successfully and
321 // completely written. |frame_size| is the total size of the frame
322 // in bytes, including framing overhead.
323 void OnFrameWriteComplete(SpdyFrameType frame_type, size_t frame_size);
325 // SYN_STREAM-specific write handler invoked by OnFrameWriteComplete().
326 int OnRequestHeadersSent();
328 // DATA-specific write handler invoked by OnFrameWriteComplete().
329 // If more data is already available to be written, the next write is
330 // queued and ERR_IO_PENDING is returned. Returns OK otherwise.
331 int OnDataSent(size_t frame_size);
333 // Called by the SpdySession when the request is finished. This callback
334 // will always be called at the end of the request and signals to the
335 // stream that the stream has no more network events. No further callbacks
336 // to the stream will be made after this call.
337 // |status| is an error code or OK.
338 void OnClose(int status);
340 // Called by the SpdySession to log stream related errors.
341 void LogStreamError(int status, const std::string& description);
343 // If this stream is active, reset it, and close it otherwise. In
344 // either case the stream is deleted.
345 void Cancel();
347 // Close this stream without sending a RST_STREAM and delete
348 // it.
349 void Close();
351 // Must be used only by |session_|.
352 base::WeakPtr<SpdyStream> GetWeakPtr();
354 // Interface for the delegate to use.
356 // Only one send can be in flight at a time, except for push
357 // streams, which must not send anything.
359 // Sends the request headers. The delegate is called back via
360 // OnRequestHeadersSent() when the request headers have completed
361 // sending. |send_status| must be MORE_DATA_TO_SEND for
362 // bidirectional streams; for request/response streams, it must be
363 // MORE_DATA_TO_SEND if the request has data to upload, or
364 // NO_MORE_DATA_TO_SEND if not.
365 int SendRequestHeaders(scoped_ptr<SpdyHeaderBlock> request_headers,
366 SpdySendStatus send_status);
368 // Sends a DATA frame. The delegate will be notified via
369 // OnDataSent() when the send is complete. |send_status| must be
370 // MORE_DATA_TO_SEND for bidirectional streams; for request/response
371 // streams, it must be MORE_DATA_TO_SEND if there is more data to
372 // upload, or NO_MORE_DATA_TO_SEND if not.
373 void SendData(IOBuffer* data, int length, SpdySendStatus send_status);
375 // Fills SSL info in |ssl_info| and returns true when SSL is in use.
376 bool GetSSLInfo(SSLInfo* ssl_info,
377 bool* was_npn_negotiated,
378 NextProto* protocol_negotiated);
380 // If the stream is stalled on sending data, but the session is not
381 // stalled on sending data and |send_window_size_| is positive, then
382 // set |send_stalled_by_flow_control_| to false and unstall the data
383 // sending. Called by the session or by the stream itself. Must be
384 // called only when the stream is still open.
385 void PossiblyResumeIfSendStalled();
387 // Returns whether or not this stream is closed. Note that the only
388 // time a stream is closed and not deleted is in its delegate's
389 // OnClose() method.
390 bool IsClosed() const;
392 // Returns whether the streams local endpoint is closed.
393 // The remote endpoint may still be active.
394 bool IsLocallyClosed() const;
396 // Returns whether this stream is IDLE: request and response headers
397 // have neither been sent nor receieved.
398 bool IsIdle() const;
400 // Returns whether or not this stream is fully open: that request and
401 // response headers are complete, and it is not in a half-closed state.
402 bool IsOpen() const;
404 // Returns whether the stream is reserved by remote endpoint: server has sent
405 // intended request headers for a pushed stream, but haven't started response
406 // yet.
407 bool IsReservedRemote() const;
409 // Returns the protocol used by this stream. Always between
410 // kProtoSPDYMinimumVersion and kProtoSPDYMaximumVersion.
411 NextProto GetProtocol() const;
413 int response_status() const { return response_status_; }
415 void IncrementRawReceivedBytes(size_t received_bytes) {
416 raw_received_bytes_ += received_bytes;
419 int64 raw_received_bytes() const { return raw_received_bytes_; }
421 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const;
423 // Get the URL from the appropriate stream headers, or the empty
424 // GURL() if it is unknown.
426 // TODO(akalin): Figure out if we really need this function,
427 // i.e. can we just use the URL this stream was created with and/or
428 // one we receive headers validate that the URL from them is the
429 // same.
430 GURL GetUrlFromHeaders() const;
432 // Returns whether the URL for this stream is known.
434 // TODO(akalin): Remove this, as it's only used in tests.
435 bool HasUrlFromHeaders() const;
437 SpdyMajorVersion GetProtocolVersion() const;
439 private:
440 class SynStreamBufferProducer;
441 class HeaderBufferProducer;
443 // SpdyStream states and transitions are modeled
444 // on the HTTP/2 stream state machine. All states and transitions
445 // are modeled, with the exceptions of RESERVED_LOCAL (the client
446 // cannot initate push streams), and the transition to OPEN due to
447 // a remote SYN_STREAM (the client can only initate streams).
448 enum State {
449 STATE_IDLE,
450 STATE_OPEN,
451 STATE_HALF_CLOSED_LOCAL_UNCLAIMED,
452 STATE_HALF_CLOSED_LOCAL,
453 STATE_HALF_CLOSED_REMOTE,
454 STATE_RESERVED_REMOTE,
455 STATE_CLOSED,
458 // Update the histograms. Can safely be called repeatedly, but should only
459 // be called after the stream has completed.
460 void UpdateHistograms();
462 // When a server-push stream is claimed by SetDelegate(), this function is
463 // posted on the current MessageLoop to replay everything the server has sent.
464 // From the perspective of SpdyStream's state machine, headers, data, and
465 // FIN states received prior to the delegate being attached have not yet been
466 // read. While buffered by |pending_recv_data_| it's not until
467 // PushedStreamReplay() is invoked that reads are considered
468 // to have occurred, driving the state machine forward.
469 void PushedStreamReplay();
471 // Produces the SYN_STREAM frame for the stream. The stream must
472 // already be activated.
473 scoped_ptr<SpdyFrame> ProduceSynStreamFrame();
475 // Produce the initial HEADER frame for the stream with the given
476 // block. The stream must already be activated.
477 scoped_ptr<SpdyFrame> ProduceHeaderFrame(
478 scoped_ptr<SpdyHeaderBlock> header_block);
480 // Queues the send for next frame of the remaining data in
481 // |pending_send_data_|. Must be called only when
482 // |pending_send_data_| is set.
483 void QueueNextDataFrame();
485 // Merge the given headers into |response_headers_| and calls
486 // OnResponseHeadersUpdated() on the delegate (if attached).
487 // Returns a status code; if it is an error, the stream was closed
488 // by this function.
489 int MergeWithResponseHeaders(const SpdyHeaderBlock& new_response_headers);
491 static std::string DescribeState(State state);
493 const SpdyStreamType type_;
495 SpdyStreamId stream_id_;
496 const GURL url_;
497 const RequestPriority priority_;
499 bool send_stalled_by_flow_control_;
501 // Current send window size.
502 int32 send_window_size_;
504 // Maximum receive window size. Each time a WINDOW_UPDATE is sent, it
505 // restores the receive window size to this value.
506 int32 max_recv_window_size_;
508 // Sum of |session_unacked_recv_window_bytes_| and current receive window
509 // size.
510 // TODO(bnc): Rename or change semantics so that |window_size_| is actual
511 // window size.
512 int32 recv_window_size_;
514 // When bytes are consumed, SpdyIOBuffer destructor calls back to SpdySession,
515 // and this member keeps count of them until the corresponding WINDOW_UPDATEs
516 // are sent.
517 int32 unacked_recv_window_bytes_;
519 const base::WeakPtr<SpdySession> session_;
521 // The transaction should own the delegate.
522 SpdyStream::Delegate* delegate_;
524 // The headers for the request to send.
526 // TODO(akalin): Hang onto this only until we send it. This
527 // necessitates stashing the URL separately.
528 scoped_ptr<SpdyHeaderBlock> request_headers_;
530 // Data waiting to be sent, and the close state of the local endpoint
531 // after the data is fully written.
532 scoped_refptr<DrainableIOBuffer> pending_send_data_;
533 SpdySendStatus pending_send_status_;
535 // Data waiting to be received, and the close state of the remote endpoint
536 // after the data is fully read. Specifically, data received before the
537 // delegate is attached must be buffered and later replayed. A remote FIN
538 // is represented by a final, zero-length buffer.
539 ScopedVector<SpdyBuffer> pending_recv_data_;
541 // The time at which the request was made that resulted in this response.
542 // For cached responses, this time could be "far" in the past.
543 base::Time request_time_;
545 SpdyHeaderBlock response_headers_;
546 SpdyResponseHeadersStatus response_headers_status_;
547 base::Time response_time_;
549 State io_state_;
551 // Since we buffer the response, we also buffer the response status.
552 // Not valid until the stream is closed.
553 int response_status_;
555 BoundNetLog net_log_;
557 base::TimeTicks send_time_;
558 base::TimeTicks recv_first_byte_time_;
559 base::TimeTicks recv_last_byte_time_;
561 // Number of bytes that have been received on this stream, including frame
562 // overhead and headers.
563 int64 raw_received_bytes_;
565 // Number of data bytes that have been sent/received on this stream, not
566 // including frame overhead. Note that this does not count headers.
567 int send_bytes_;
568 int recv_bytes_;
570 // Guards calls of delegate write handlers ensuring |this| is not destroyed.
571 // TODO(jgraettinger): Consider removing after crbug.com/35511 is tracked
572 // down.
573 bool write_handler_guard_;
575 base::WeakPtrFactory<SpdyStream> weak_ptr_factory_;
577 DISALLOW_COPY_AND_ASSIGN(SpdyStream);
580 } // namespace net
582 #endif // NET_SPDY_SPDY_STREAM_H_