• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 //
5 // NOTE: This code is not shared between Google and Chrome.
6 
7 #ifndef NET_QUIC_QUIC_CHROMIUM_CLIENT_STREAM_H_
8 #define NET_QUIC_QUIC_CHROMIUM_CLIENT_STREAM_H_
9 
10 #include <stddef.h>
11 
12 #include <memory>
13 #include <vector>
14 
15 #include "base/containers/circular_deque.h"
16 #include "base/functional/callback_forward.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/time/time.h"
19 #include "net/base/completion_once_callback.h"
20 #include "net/base/idempotency.h"
21 #include "net/base/ip_endpoint.h"
22 #include "net/base/net_export.h"
23 #include "net/base/upload_data_stream.h"
24 #include "net/http/http_request_info.h"
25 #include "net/http/http_response_info.h"
26 #include "net/http/http_stream.h"
27 #include "net/log/net_log_with_source.h"
28 #include "net/third_party/quiche/src/quiche/quic/core/http/quic_spdy_stream.h"
29 #include "net/third_party/quiche/src/quiche/spdy/core/http2_header_block.h"
30 #include "net/traffic_annotation/network_traffic_annotation.h"
31 
32 namespace quic {
33 class QuicSpdyClientSessionBase;
34 }  // namespace quic
35 namespace net {
36 
37 // A client-initiated ReliableQuicStream.  Instances of this class
38 // are owned by the QuicClientSession which created them.
39 class NET_EXPORT_PRIVATE QuicChromiumClientStream
40     : public quic::QuicSpdyStream {
41  public:
42   // Wrapper for interacting with the session in a restricted fashion.
43   class NET_EXPORT_PRIVATE Handle {
44    public:
45     Handle(const Handle&) = delete;
46     Handle& operator=(const Handle&) = delete;
47 
48     ~Handle();
49 
50     // Returns true if the stream is still connected.
IsOpen()51     bool IsOpen() { return stream_ != nullptr; }
52 
53     // Reads initial or 103 Early Hints headers into |header_block| and returns
54     // the length of the HEADERS frame which contained them. If headers are not
55     // available, returns ERR_IO_PENDING and will invoke |callback|
56     // asynchronously when the headers arrive.
57     // TODO(rch): Invoke |callback| when there is a stream or connection error
58     // instead of calling OnClose() or OnError().
59     int ReadInitialHeaders(spdy::Http2HeaderBlock* header_block,
60                            CompletionOnceCallback callback);
61 
62     // Reads at most |buffer_len| bytes of body into |buffer| and returns the
63     // number of bytes read. If body is not available, returns ERR_IO_PENDING
64     // and will invoke |callback| asynchronously when data arrive.
65     // TODO(rch): Invoke |callback| when there is a stream or connection error
66     // instead of calling OnClose() or OnError().
67     int ReadBody(IOBuffer* buffer,
68                  int buffer_len,
69                  CompletionOnceCallback callback);
70 
71     // Reads trailing headers into |header_block| and returns the length of
72     // the HEADERS frame which contained them. If headers are not available,
73     // returns ERR_IO_PENDING and will invoke |callback| asynchronously when
74     // the headers arrive.
75     // TODO(rch): Invoke |callback| when there is a stream or connection error
76     // instead of calling OnClose() or OnError().
77     int ReadTrailingHeaders(spdy::Http2HeaderBlock* header_block,
78                             CompletionOnceCallback callback);
79 
80     // Writes |header_block| to the peer. Closes the write side if |fin| is
81     // true. If non-null, |ack_notifier_delegate| will be notified when the
82     // headers are ACK'd by the peer. Returns a net error code if there is
83     // an error writing the headers, or the number of bytes written on
84     // success. Will not return ERR_IO_PENDING.
85     int WriteHeaders(
86         spdy::Http2HeaderBlock header_block,
87         bool fin,
88         quiche::QuicheReferenceCountedPointer<quic::QuicAckListenerInterface>
89             ack_notifier_delegate);
90 
91     // Writes |data| to the peer. Closes the write side if |fin| is true.
92     // If the data could not be written immediately, returns ERR_IO_PENDING
93     // and invokes |callback| asynchronously when the write completes.
94     int WriteStreamData(base::StringPiece data,
95                         bool fin,
96                         CompletionOnceCallback callback);
97 
98     // Same as WriteStreamData except it writes data from a vector of IOBuffers,
99     // with the length of each buffer at the corresponding index in |lengths|.
100     int WritevStreamData(const std::vector<scoped_refptr<IOBuffer>>& buffers,
101                          const std::vector<int>& lengths,
102                          bool fin,
103                          CompletionOnceCallback callback);
104 
105     // Reads at most |buf_len| bytes into |buf|. Returns the number of bytes
106     // read.
107     int Read(IOBuffer* buf, int buf_len);
108 
109     // Called to notify the stream when the final incoming data is read.
110     void OnFinRead();
111 
112     // Prevents the connection from migrating to a cellular network while this
113     // stream is open.
114     void DisableConnectionMigrationToCellularNetwork();
115 
116     // Sets the precedence of the stream to |priority|.
117     void SetPriority(const quic::QuicStreamPriority& priority);
118 
119     // Sends a RST_STREAM frame to the peer and closes the streams.
120     void Reset(quic::QuicRstStreamErrorCode error_code);
121 
122     quic::QuicStreamId id() const;
123     quic::QuicErrorCode connection_error() const;
124     quic::QuicRstStreamErrorCode stream_error() const;
125     bool fin_sent() const;
126     bool fin_received() const;
127     uint64_t stream_bytes_read() const;
128     uint64_t stream_bytes_written() const;
129     size_t NumBytesConsumed() const;
130     bool HasBytesToRead() const;
131     bool IsDoneReading() const;
132     bool IsFirstStream() const;
133 
first_early_hints_time()134     base::TimeTicks first_early_hints_time() const {
135       return first_early_hints_time_;
136     }
137 
headers_received_start_time()138     base::TimeTicks headers_received_start_time() const {
139       return headers_received_start_time_;
140     }
141 
142     // TODO(rch): Move this test-only method to a peer, or else remove.
143     bool can_migrate_to_cellular_network();
144 
145     const NetLogWithSource& net_log() const;
146 
147     // Sets the idempotency of the request.
148     void SetRequestIdempotency(Idempotency idempotency);
149     // Returns the idempotency of the request.
150     Idempotency GetRequestIdempotency() const;
151 
152    private:
153     friend class QuicChromiumClientStream;
154 
155     // Constucts a new Handle for |stream|.
156     explicit Handle(QuicChromiumClientStream* stream);
157 
158     // Methods invoked by the stream.
159     void OnEarlyHintsAvailable();
160     void OnInitialHeadersAvailable();
161     void OnTrailingHeadersAvailable();
162     void OnDataAvailable();
163     void OnCanWrite();
164     void OnClose();
165     void OnError(int error);
166 
167     // Invokes async IO callbacks because of |error|.
168     void InvokeCallbacksOnClose(int error);
169 
170     // Saves various fields from the stream before the stream goes away.
171     void SaveState();
172 
173     void SetCallback(CompletionOnceCallback new_callback,
174                      CompletionOnceCallback* callback);
175 
176     void ResetAndRun(CompletionOnceCallback callback, int rv);
177 
178     int HandleIOComplete(int rv);
179 
180     raw_ptr<QuicChromiumClientStream> stream_;  // Unowned.
181 
182     bool may_invoke_callbacks_ = true;  // True when callbacks may be invoked.
183 
184     // Callback to be invoked when ReadInitialHeaders completes asynchronously.
185     CompletionOnceCallback read_headers_callback_;
186     // Provided by the owner of this handle when ReadInitialHeaders is called.
187     raw_ptr<spdy::Http2HeaderBlock> read_headers_buffer_ = nullptr;
188 
189     // Callback to be invoked when ReadBody completes asynchronously.
190     CompletionOnceCallback read_body_callback_;
191     raw_ptr<IOBuffer, DanglingUntriaged> read_body_buffer_;
192     int read_body_buffer_len_ = 0;
193 
194     // Callback to be invoked when WriteStreamData or WritevStreamData completes
195     // asynchronously.
196     CompletionOnceCallback write_callback_;
197 
198     quic::QuicStreamId id_;
199     quic::QuicErrorCode connection_error_;
200     quic::QuicRstStreamErrorCode stream_error_;
201     bool fin_sent_;
202     bool fin_received_;
203     uint64_t stream_bytes_read_;
204     uint64_t stream_bytes_written_;
205     bool is_done_reading_;
206     bool is_first_stream_;
207     size_t num_bytes_consumed_;
208     Idempotency idempotency_ = DEFAULT_IDEMPOTENCY;
209 
210     int net_error_ = ERR_UNEXPECTED;
211 
212     NetLogWithSource net_log_;
213 
214     // The time at which the first 103 Early Hints response is received.
215     base::TimeTicks first_early_hints_time_;
216 
217     base::TimeTicks headers_received_start_time_;
218 
219     base::WeakPtrFactory<Handle> weak_factory_{this};
220   };
221 
222   QuicChromiumClientStream(
223       quic::QuicStreamId id,
224       quic::QuicSpdyClientSessionBase* session,
225       quic::StreamType type,
226       const NetLogWithSource& net_log,
227       const NetworkTrafficAnnotationTag& traffic_annotation);
228   QuicChromiumClientStream(
229       quic::PendingStream* pending,
230       quic::QuicSpdyClientSessionBase* session,
231       const NetLogWithSource& net_log,
232       const NetworkTrafficAnnotationTag& traffic_annotation);
233 
234   QuicChromiumClientStream(const QuicChromiumClientStream&) = delete;
235   QuicChromiumClientStream& operator=(const QuicChromiumClientStream&) = delete;
236 
237   ~QuicChromiumClientStream() override;
238 
239   // quic::QuicSpdyStream
240   void OnInitialHeadersComplete(
241       bool fin,
242       size_t frame_len,
243       const quic::QuicHeaderList& header_list) override;
244   void OnTrailingHeadersComplete(
245       bool fin,
246       size_t frame_len,
247       const quic::QuicHeaderList& header_list) override;
248   void OnBodyAvailable() override;
249   void OnClose() override;
250   void OnCanWrite() override;
251   size_t WriteHeaders(
252       spdy::Http2HeaderBlock header_block,
253       bool fin,
254       quiche::QuicheReferenceCountedPointer<quic::QuicAckListenerInterface>
255           ack_listener) override;
256 
257   // While the server's set_priority shouldn't be called externally, the creator
258   // of client-side streams should be able to set the priority.
259   using quic::QuicSpdyStream::SetPriority;
260 
261   // Writes |data| to the peer and closes the write side if |fin| is true.
262   // Returns true if the data have been fully written. If the data was not fully
263   // written, returns false and OnCanWrite() will be invoked later.
264   bool WriteStreamData(std::string_view data, bool fin);
265   // Same as WriteStreamData except it writes data from a vector of IOBuffers,
266   // with the length of each buffer at the corresponding index in |lengths|.
267   bool WritevStreamData(const std::vector<scoped_refptr<IOBuffer>>& buffers,
268                         const std::vector<int>& lengths,
269                         bool fin);
270 
271   // Creates a new Handle for this stream. Must only be called once.
272   std::unique_ptr<QuicChromiumClientStream::Handle> CreateHandle();
273 
274   // Clears |handle_| from this stream.
275   void ClearHandle();
276 
277   // Notifies the stream handle of error, but doesn't close the stream.
278   void OnError(int error);
279 
280   // Reads at most |buf_len| bytes into |buf|. Returns the number of bytes read.
281   int Read(IOBuffer* buf, int buf_len);
282 
net_log()283   const NetLogWithSource& net_log() const { return net_log_; }
284 
285   // Prevents this stream from migrating to a cellular network. May be reset
286   // when connection migrates to a cellular network.
287   void DisableConnectionMigrationToCellularNetwork();
288 
can_migrate_to_cellular_network()289   bool can_migrate_to_cellular_network() {
290     return can_migrate_to_cellular_network_;
291   }
292 
293   // True if this stream is the first data stream created on this session.
294   bool IsFirstStream();
295 
296   int DeliverEarlyHints(spdy::Http2HeaderBlock* header_block);
297 
298   int DeliverInitialHeaders(spdy::Http2HeaderBlock* header_block);
299 
300   bool DeliverTrailingHeaders(spdy::Http2HeaderBlock* header_block,
301                               int* frame_len);
302 
303   using quic::QuicSpdyStream::HasBufferedData;
304   using quic::QuicStream::sequencer;
305 
306  private:
307   void NotifyHandleOfInitialHeadersAvailableLater();
308   void NotifyHandleOfInitialHeadersAvailable();
309   void NotifyHandleOfTrailingHeadersAvailableLater();
310   void NotifyHandleOfTrailingHeadersAvailable();
311   void NotifyHandleOfDataAvailableLater();
312   void NotifyHandleOfDataAvailable();
313 
314   NetLogWithSource net_log_;
315   raw_ptr<Handle> handle_ = nullptr;
316 
317   // True when initial headers have been sent.
318   bool initial_headers_sent_ = false;
319 
320   raw_ptr<quic::QuicSpdyClientSessionBase> session_;
321   quic::QuicTransportVersion quic_version_;
322 
323   // Set to false if this stream should not be migrated to a cellular network
324   // during connection migration.
325   bool can_migrate_to_cellular_network_ = true;
326 
327   // True if non-informational (non-1xx) initial headers have arrived.
328   bool initial_headers_arrived_ = false;
329   // True if non-informational (non-1xx) initial headers have been delivered to
330   // the handle.
331   bool headers_delivered_ = false;
332   // Stores the initial header until they are delivered to the handle.
333   spdy::Http2HeaderBlock initial_headers_;
334   // Length of the HEADERS frame containing initial headers.
335   size_t initial_headers_frame_len_ = 0;
336 
337   // Length of the HEADERS frame containing trailing headers.
338   size_t trailing_headers_frame_len_ = 0;
339 
340   struct EarlyHints {
EarlyHintsEarlyHints341     EarlyHints(spdy::Http2HeaderBlock headers, size_t frame_len)
342         : headers(std::move(headers)), frame_len(frame_len) {}
343     EarlyHints(EarlyHints&& other) = default;
344     EarlyHints& operator=(EarlyHints&& other) = default;
345     EarlyHints(const EarlyHints& other) = delete;
346     EarlyHints& operator=(const EarlyHints& other) = delete;
347 
348     spdy::Http2HeaderBlock headers;
349     size_t frame_len = 0;
350   };
351   base::circular_deque<EarlyHints> early_hints_;
352 
353   base::WeakPtrFactory<QuicChromiumClientStream> weak_factory_{this};
354 };
355 
356 }  // namespace net
357 
358 #endif  // NET_QUIC_QUIC_CHROMIUM_CLIENT_STREAM_H_
359