blob: efe46a63fcb1de4c97b5287c1fbf458cce834a8f [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// 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.
4
5// The base class for client/server QUIC streams.
6
7// It does not contain the entire interface needed by an application to interact
8// with a QUIC stream. Some parts of the interface must be obtained by
9// accessing the owning session object. A subclass of QuicStream
10// connects the object and the application that generates and consumes the data
11// of the stream.
12
13// The QuicStream object has a dependent QuicStreamSequencer object,
14// which is given the stream frames as they arrive, and provides stream data in
15// order by invoking ProcessRawData().
16
17#ifndef QUICHE_QUIC_CORE_QUIC_STREAM_H_
18#define QUICHE_QUIC_CORE_QUIC_STREAM_H_
19
20#include <cstddef>
21#include <cstdint>
22#include <list>
vasilvv872e7a32019-03-12 16:42:44 -070023#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050024
QUICHE teama6ef0a62019-03-07 20:34:33 -050025#include "net/third_party/quiche/src/quic/core/quic_flow_controller.h"
26#include "net/third_party/quiche/src/quic/core/quic_packets.h"
27#include "net/third_party/quiche/src/quic/core/quic_stream_send_buffer.h"
28#include "net/third_party/quiche/src/quic/core/quic_stream_sequencer.h"
29#include "net/third_party/quiche/src/quic/core/quic_types.h"
30#include "net/third_party/quiche/src/quic/core/session_notifier_interface.h"
31#include "net/third_party/quiche/src/quic/platform/api/quic_export.h"
32#include "net/third_party/quiche/src/quic/platform/api/quic_mem_slice_span.h"
33#include "net/third_party/quiche/src/quic/platform/api/quic_reference_counted.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050034#include "net/third_party/quiche/src/quic/platform/api/quic_string_piece.h"
35#include "net/third_party/quiche/src/spdy/core/spdy_protocol.h"
36
37namespace quic {
38
39namespace test {
40class QuicStreamPeer;
41} // namespace test
42
43class QuicSession;
44class QuicStream;
45
46// Buffers frames for a stream until the first byte of that frame arrives.
47class QUIC_EXPORT_PRIVATE PendingStream
48 : public QuicStreamSequencer::StreamInterface {
49 public:
50 PendingStream(QuicStreamId id, QuicSession* session);
51 PendingStream(const PendingStream&) = delete;
52 PendingStream(PendingStream&&) = default;
53 ~PendingStream() override = default;
54
55 // QuicStreamSequencer::StreamInterface
56 void OnDataAvailable() override;
57 void OnFinRead() override;
58 void AddBytesConsumed(QuicByteCount bytes) override;
59 void Reset(QuicRstStreamErrorCode error) override;
60 void CloseConnectionWithDetails(QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -070061 const std::string& details) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -050062 QuicStreamId id() const override;
63 const QuicSocketAddress& PeerAddressOfLatestPacket() const override;
64
65 // Buffers the contents of |frame|. Frame must have a non-zero offset.
66 // If the data violates flow control, the connection will be closed.
67 void OnStreamFrame(const QuicStreamFrame& frame);
68
69 // Stores the final byte offset from |frame|.
70 // If the final offset violates flow control, the connection will be closed.
71 void OnRstStreamFrame(const QuicRstStreamFrame& frame);
72
73 // Returns the number of bytes read on this stream.
74 uint64_t stream_bytes_read() { return stream_bytes_read_; }
75
renjietang0c558862019-05-08 13:26:23 -070076 const QuicStreamSequencer* sequencer() const { return &sequencer_; }
77
QUICHE teama6ef0a62019-03-07 20:34:33 -050078 private:
79 friend class QuicStream;
80
81 bool MaybeIncreaseHighestReceivedOffset(QuicStreamOffset new_offset);
82
83 // ID of this stream.
84 QuicStreamId id_;
85
86 // Session which owns this.
87 QuicSession* session_;
88
89 // Bytes read refers to payload bytes only: they do not include framing,
90 // encryption overhead etc.
91 uint64_t stream_bytes_read_;
92
93 // True if a frame containing a fin has been received.
94 bool fin_received_;
95
96 // Connection-level flow controller. Owned by the session.
97 QuicFlowController* connection_flow_controller_;
98 // Stream-level flow controller.
99 QuicFlowController flow_controller_;
100 // Stores the buffered frames.
101 QuicStreamSequencer sequencer_;
102};
103
104class QUIC_EXPORT_PRIVATE QuicStream
105 : public QuicStreamSequencer::StreamInterface {
106 public:
107 // This is somewhat arbitrary. It's possible, but unlikely, we will either
108 // fail to set a priority client-side, or cancel a stream before stripping the
109 // priority from the wire server-side. In either case, start out with a
110 // priority in the middle.
111 static const spdy::SpdyPriority kDefaultPriority = 3;
112 static_assert(kDefaultPriority ==
113 (spdy::kV3LowestPriority + spdy::kV3HighestPriority) / 2,
114 "Unexpected value of kDefaultPriority");
115
116 // Creates a new stream with stream_id |id| associated with |session|. If
117 // |is_static| is true, then the stream will be given precedence
118 // over other streams when determing what streams should write next.
119 // |type| indicates whether the stream is bidirectional, read unidirectional
120 // or write unidirectional.
121 // TODO(fayang): Remove |type| when IETF stream ID numbering fully kicks in.
122 QuicStream(QuicStreamId id,
123 QuicSession* session,
124 bool is_static,
125 StreamType type);
126 QuicStream(PendingStream pending, StreamType type);
127 QuicStream(const QuicStream&) = delete;
128 QuicStream& operator=(const QuicStream&) = delete;
129
130 virtual ~QuicStream();
131
132 // Not in use currently.
133 void SetFromConfig();
134
135 // QuicStreamSequencer::StreamInterface implementation.
136 QuicStreamId id() const override { return id_; }
137 // Called by the stream subclass after it has consumed the final incoming
138 // data.
139 void OnFinRead() override;
140
141 // Called by the subclass or the sequencer to reset the stream from this
142 // end.
143 void Reset(QuicRstStreamErrorCode error) override;
144
145 // Called by the subclass or the sequencer to close the entire connection from
146 // this end.
147 void CloseConnectionWithDetails(QuicErrorCode error,
vasilvvc48c8712019-03-11 13:38:16 -0700148 const std::string& details) override;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500149
QUICHE teama6ef0a62019-03-07 20:34:33 -0500150 // Get peer IP of the lastest packet which connection is dealing/delt with.
151 const QuicSocketAddress& PeerAddressOfLatestPacket() const override;
152
153 // Called by the session when a (potentially duplicate) stream frame has been
154 // received for this stream.
155 virtual void OnStreamFrame(const QuicStreamFrame& frame);
156
157 // Called by the session when the connection becomes writeable to allow the
158 // stream to write any pending data.
159 virtual void OnCanWrite();
160
161 // Called by the session just before the object is destroyed.
162 // The object should not be accessed after OnClose is called.
163 // Sends a RST_STREAM with code QUIC_RST_ACKNOWLEDGEMENT if neither a FIN nor
164 // a RST_STREAM has been sent.
165 virtual void OnClose();
166
167 // Called by the session when the endpoint receives a RST_STREAM from the
168 // peer.
169 virtual void OnStreamReset(const QuicRstStreamFrame& frame);
170
171 // Called by the session when the endpoint receives or sends a connection
172 // close, and should immediately close the stream.
173 virtual void OnConnectionClosed(QuicErrorCode error,
174 ConnectionCloseSource source);
175
176 spdy::SpdyPriority priority() const;
177
178 // Sets priority_ to priority. This should only be called before bytes are
179 // written to the server.
180 void SetPriority(spdy::SpdyPriority priority);
181
182 // Returns true if this stream is still waiting for acks of sent data.
183 // This will return false if all data has been acked, or if the stream
184 // is no longer interested in data being acked (which happens when
185 // a stream is reset because of an error).
186 bool IsWaitingForAcks() const;
187
188 // Number of bytes available to read.
189 size_t ReadableBytes() const;
190
191 QuicRstStreamErrorCode stream_error() const { return stream_error_; }
192 QuicErrorCode connection_error() const { return connection_error_; }
193
194 bool reading_stopped() const {
195 return sequencer_.ignore_read_data() || read_side_closed_;
196 }
197 bool write_side_closed() const { return write_side_closed_; }
198
199 bool rst_received() const { return rst_received_; }
200 bool rst_sent() const { return rst_sent_; }
201 bool fin_received() const { return fin_received_; }
202 bool fin_sent() const { return fin_sent_; }
203 bool fin_outstanding() const { return fin_outstanding_; }
204 bool fin_lost() const { return fin_lost_; }
205
206 uint64_t BufferedDataBytes() const;
207
208 uint64_t stream_bytes_read() const { return stream_bytes_read_; }
209 uint64_t stream_bytes_written() const;
210
211 size_t busy_counter() const { return busy_counter_; }
212 void set_busy_counter(size_t busy_counter) { busy_counter_ = busy_counter; }
213
214 void set_fin_sent(bool fin_sent) { fin_sent_ = fin_sent; }
215 void set_fin_received(bool fin_received) { fin_received_ = fin_received; }
216 void set_rst_sent(bool rst_sent) { rst_sent_ = rst_sent; }
217
218 void set_rst_received(bool rst_received) { rst_received_ = rst_received; }
219 void set_stream_error(QuicRstStreamErrorCode error) { stream_error_ = error; }
220
221 // Adjust the flow control window according to new offset in |frame|.
222 virtual void OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame);
223
224 int num_frames_received() const;
225 int num_duplicate_frames_received() const;
226
227 QuicFlowController* flow_controller() { return &flow_controller_; }
228
229 // Called when endpoint receives a frame which could increase the highest
230 // offset.
231 // Returns true if the highest offset did increase.
232 bool MaybeIncreaseHighestReceivedOffset(QuicStreamOffset new_offset);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500233
234 // Updates the flow controller's send window offset and calls OnCanWrite if
235 // it was blocked before.
236 void UpdateSendWindowOffset(QuicStreamOffset new_offset);
237
238 // Returns true if the stream has received either a RST_STREAM or a FIN -
239 // either of which gives a definitive number of bytes which the peer has
240 // sent. If this is not true on deletion of the stream object, the session
241 // must keep track of the stream's byte offset until a definitive final value
242 // arrives.
243 bool HasFinalReceivedByteOffset() const {
244 return fin_received_ || rst_received_;
245 }
246
247 // Returns true if the stream has queued data waiting to write.
248 bool HasBufferedData() const;
249
250 // Returns the version of QUIC being used for this stream.
251 QuicTransportVersion transport_version() const;
252
253 // Returns the crypto handshake protocol that was used on this stream's
254 // connection.
255 HandshakeProtocol handshake_protocol() const;
256
257 // Sets the sequencer to consume all incoming data itself and not call
258 // OnDataAvailable().
259 // When the FIN is received, the stream will be notified automatically (via
260 // OnFinRead()) (which may happen during the call of StopReading()).
261 // TODO(dworley): There should be machinery to send a RST_STREAM/NO_ERROR and
262 // stop sending stream-level flow-control updates when this end sends FIN.
263 virtual void StopReading();
264
265 // Sends as much of 'data' to the connection as the connection will consume,
266 // and then buffers any remaining data in queued_data_.
267 // If fin is true: if it is immediately passed on to the session,
268 // write_side_closed() becomes true, otherwise fin_buffered_ becomes true.
269 void WriteOrBufferData(
270 QuicStringPiece data,
271 bool fin,
272 QuicReferenceCountedPointer<QuicAckListenerInterface> ack_listener);
273
274 // Adds random padding after the fin is consumed for this stream.
275 void AddRandomPaddingAfterFin();
276
277 // Write |data_length| of data starts at |offset| from send buffer.
278 bool WriteStreamData(QuicStreamOffset offset,
279 QuicByteCount data_length,
280 QuicDataWriter* writer);
281
282 // Called when data [offset, offset + data_length) is acked. |fin_acked|
283 // indicates whether the fin is acked. Returns true and updates
284 // |newly_acked_length| if any new stream data (including fin) gets acked.
285 virtual bool OnStreamFrameAcked(QuicStreamOffset offset,
286 QuicByteCount data_length,
287 bool fin_acked,
288 QuicTime::Delta ack_delay_time,
289 QuicByteCount* newly_acked_length);
290
291 // Called when data [offset, offset + data_length) was retransmitted.
292 // |fin_retransmitted| indicates whether fin was retransmitted.
293 virtual void OnStreamFrameRetransmitted(QuicStreamOffset offset,
294 QuicByteCount data_length,
295 bool fin_retransmitted);
296
297 // Called when data [offset, offset + data_length) is considered as lost.
298 // |fin_lost| indicates whether the fin is considered as lost.
299 virtual void OnStreamFrameLost(QuicStreamOffset offset,
300 QuicByteCount data_length,
301 bool fin_lost);
302
303 // Called to retransmit outstanding portion in data [offset, offset +
304 // data_length) and |fin|. Returns true if all data gets retransmitted.
305 virtual bool RetransmitStreamData(QuicStreamOffset offset,
306 QuicByteCount data_length,
307 bool fin);
308
309 // Sets deadline of this stream to be now + |ttl|, returns true if the setting
310 // succeeds.
311 bool MaybeSetTtl(QuicTime::Delta ttl);
312
313 // Same as WritevData except data is provided in reference counted memory so
314 // that data copy is avoided.
315 QuicConsumedData WriteMemSlices(QuicMemSliceSpan span, bool fin);
316
317 // Returns true if any stream data is lost (including fin) and needs to be
318 // retransmitted.
319 virtual bool HasPendingRetransmission() const;
320
321 // Returns true if any portion of data [offset, offset + data_length) is
322 // outstanding or fin is outstanding (if |fin| is true). Returns false
323 // otherwise.
324 bool IsStreamFrameOutstanding(QuicStreamOffset offset,
325 QuicByteCount data_length,
326 bool fin) const;
327
328 StreamType type() const { return type_; }
329
330 // Creates and sends a STOP_SENDING frame. This can be called regardless of
331 // the version that has been negotiated. If not IETF QUIC/Version 99 then the
332 // method is a noop, relieving the application of the necessity of
333 // understanding the connection's QUIC version and knowing whether it can call
334 // this method or not.
335 void SendStopSending(uint16_t code);
336
337 // Invoked when QUIC receives a STOP_SENDING frame for this stream, informing
338 // the application that the peer has sent a STOP_SENDING. The default
339 // implementation is a noop. Is to be overridden by the application-specific
340 // QuicStream class.
341 virtual void OnStopSending(uint16_t code);
342
343 // Close the write side of the socket. Further writes will fail.
344 // Can be called by the subclass or internally.
345 // Does not send a FIN. May cause the stream to be closed.
346 virtual void CloseWriteSide();
347
renjietangfbeb5bf2019-04-19 15:06:20 -0700348 // Returns true if the stream is static.
349 bool is_static() const { return is_static_; }
350
QUICHE teama6ef0a62019-03-07 20:34:33 -0500351 protected:
352 // Sends as many bytes in the first |count| buffers of |iov| to the connection
353 // as the connection will consume. If FIN is consumed, the write side is
354 // immediately closed.
355 // Returns the number of bytes consumed by the connection.
356 // Please note: Returned consumed data is the amount of data saved in send
357 // buffer. The data is not necessarily consumed by the connection. So write
358 // side is closed when FIN is sent.
359 // TODO(fayang): Let WritevData return boolean.
360 QuicConsumedData WritevData(const struct iovec* iov, int iov_count, bool fin);
361
362 // Allows override of the session level writev, for the force HOL
363 // blocking experiment.
364 virtual QuicConsumedData WritevDataInner(size_t write_length,
365 QuicStreamOffset offset,
366 bool fin);
367
368 // Close the read side of the socket. May cause the stream to be closed.
369 // Subclasses and consumers should use StopReading to terminate reading early
370 // if expecting a FIN. Can be used directly by subclasses if not expecting a
371 // FIN.
372 void CloseReadSide();
373
374 // Called when data of [offset, offset + data_length] is buffered in send
375 // buffer.
376 virtual void OnDataBuffered(
377 QuicStreamOffset offset,
378 QuicByteCount data_length,
379 const QuicReferenceCountedPointer<QuicAckListenerInterface>&
380 ack_listener) {}
381
382 // True if buffered data in send buffer is below buffered_data_threshold_.
383 bool CanWriteNewData() const;
384
385 // True if buffered data in send buffer is still below
386 // buffered_data_threshold_ even after writing |length| bytes.
387 bool CanWriteNewDataAfterData(QuicByteCount length) const;
388
389 // Called when upper layer can write new data.
390 virtual void OnCanWriteNewData() {}
391
392 // Called when |bytes_consumed| bytes has been consumed.
393 virtual void OnStreamDataConsumed(size_t bytes_consumed);
394
ianswett93637202019-04-03 08:05:29 -0700395 // Called by the stream sequencer as bytes are consumed from the buffer.
396 // If the receive window has dropped below the threshold, then send a
397 // WINDOW_UPDATE frame.
398 void AddBytesConsumed(QuicByteCount bytes) override;
399
QUICHE teama6ef0a62019-03-07 20:34:33 -0500400 // Writes pending retransmissions if any.
401 virtual void WritePendingRetransmission();
402
403 // This is called when stream tries to retransmit data after deadline_. Make
404 // this virtual so that subclasses can implement their own logics.
405 virtual void OnDeadlinePassed();
406
407 bool fin_buffered() const { return fin_buffered_; }
408
409 const QuicSession* session() const { return session_; }
410 QuicSession* session() { return session_; }
411
412 const QuicStreamSequencer* sequencer() const { return &sequencer_; }
413 QuicStreamSequencer* sequencer() { return &sequencer_; }
414
415 void DisableConnectionFlowControlForThisStream() {
416 stream_contributes_to_connection_flow_control_ = false;
417 }
418
419 const QuicIntervalSet<QuicStreamOffset>& bytes_acked() const;
420
421 const QuicStreamSendBuffer& send_buffer() const { return send_buffer_; }
422
423 QuicStreamSendBuffer& send_buffer() { return send_buffer_; }
424
425 private:
426 friend class test::QuicStreamPeer;
427 friend class QuicStreamUtils;
428
429 QuicStream(QuicStreamId id,
430 QuicSession* session,
431 QuicStreamSequencer sequencer,
432 bool is_static,
433 StreamType type,
434 uint64_t stream_bytes_read,
435 bool fin_received,
436 QuicFlowController flow_controller,
437 QuicFlowController* connection_flow_controller);
438
439 // Subclasses and consumers should use reading_stopped.
440 bool read_side_closed() const { return read_side_closed_; }
441
442 // Calls MaybeSendBlocked on the stream's flow controller and the connection
443 // level flow controller. If the stream is flow control blocked by the
444 // connection-level flow controller but not by the stream-level flow
445 // controller, marks this stream as connection-level write blocked.
446 void MaybeSendBlocked();
447
448 // Write buffered data in send buffer. TODO(fayang): Consider combine
449 // WriteOrBufferData, Writev and WriteBufferedData.
450 void WriteBufferedData();
451
ianswett93637202019-04-03 08:05:29 -0700452 // Called when bytes are sent to the peer.
453 void AddBytesSent(QuicByteCount bytes);
454
QUICHE teama6ef0a62019-03-07 20:34:33 -0500455 // Returns true if deadline_ has passed.
456 bool HasDeadlinePassed() const;
457
458 QuicStreamSequencer sequencer_;
459 QuicStreamId id_;
460 // Pointer to the owning QuicSession object.
461 QuicSession* session_;
462 // The priority of the stream, once parsed.
463 spdy::SpdyPriority priority_;
464 // Bytes read refers to payload bytes only: they do not include framing,
465 // encryption overhead etc.
466 uint64_t stream_bytes_read_;
467
468 // Stream error code received from a RstStreamFrame or error code sent by the
469 // visitor or sequencer in the RstStreamFrame.
470 QuicRstStreamErrorCode stream_error_;
471 // Connection error code due to which the stream was closed. |stream_error_|
472 // is set to |QUIC_STREAM_CONNECTION_ERROR| when this happens and consumers
473 // should check |connection_error_|.
474 QuicErrorCode connection_error_;
475
476 // True if the read side is closed and further frames should be rejected.
477 bool read_side_closed_;
478 // True if the write side is closed, and further writes should fail.
479 bool write_side_closed_;
480
481 // True if the subclass has written a FIN with WriteOrBufferData, but it was
482 // buffered in queued_data_ rather than being sent to the session.
483 bool fin_buffered_;
484 // True if a FIN has been sent to the session.
485 bool fin_sent_;
486 // True if a FIN is waiting to be acked.
487 bool fin_outstanding_;
488 // True if a FIN is lost.
489 bool fin_lost_;
490
491 // True if this stream has received (and the sequencer has accepted) a
492 // StreamFrame with the FIN set.
493 bool fin_received_;
494
495 // True if an RST_STREAM has been sent to the session.
496 // In combination with fin_sent_, used to ensure that a FIN and/or a
497 // RST_STREAM is always sent to terminate the stream.
498 bool rst_sent_;
499
500 // True if this stream has received a RST_STREAM frame.
501 bool rst_received_;
502
503 // Tracks if the session this stream is running under was created by a
504 // server or a client.
505 Perspective perspective_;
506
507 QuicFlowController flow_controller_;
508
509 // The connection level flow controller. Not owned.
510 QuicFlowController* connection_flow_controller_;
511
512 // Special streams, such as the crypto and headers streams, do not respect
513 // connection level flow control limits (but are stream level flow control
514 // limited).
515 bool stream_contributes_to_connection_flow_control_;
516
517 // A counter incremented when OnCanWrite() is called and no progress is made.
518 // For debugging only.
519 size_t busy_counter_;
520
521 // Indicates whether paddings will be added after the fin is consumed for this
522 // stream.
523 bool add_random_padding_after_fin_;
524
525 // Send buffer of this stream. Send buffer is cleaned up when data gets acked
526 // or discarded.
527 QuicStreamSendBuffer send_buffer_;
528
529 // Latched value of FLAGS_quic_buffered_data_threshold.
530 const QuicByteCount buffered_data_threshold_;
531
532 // If true, then this stream has precedence over other streams for write
533 // scheduling.
534 const bool is_static_;
535
536 // If initialized, reset this stream at this deadline.
537 QuicTime deadline_;
538
539 // Indicates whether this stream is bidirectional, read unidirectional or
540 // write unidirectional.
541 const StreamType type_;
542};
543
544} // namespace quic
545
546#endif // QUICHE_QUIC_CORE_QUIC_STREAM_H_