• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 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 #ifndef NET_WEBSOCKETS_WEBSOCKET_BASIC_STREAM_H_
6 #define NET_WEBSOCKETS_WEBSOCKET_BASIC_STREAM_H_
7 
8 #include <memory>
9 #include <string>
10 #include <vector>
11 
12 #include "base/containers/queue.h"
13 #include "base/memory/scoped_refptr.h"
14 #include "base/time/time.h"
15 #include "net/base/completion_once_callback.h"
16 #include "net/base/net_export.h"
17 #include "net/log/net_log_with_source.h"
18 #include "net/traffic_annotation/network_traffic_annotation.h"
19 #include "net/websockets/websocket_frame_parser.h"
20 #include "net/websockets/websocket_stream.h"
21 
22 namespace net {
23 
24 class ClientSocketHandle;
25 class DrainableIOBuffer;
26 class GrowableIOBuffer;
27 class IOBuffer;
28 class IOBufferWithSize;
29 struct WebSocketFrame;
30 struct WebSocketFrameChunk;
31 
32 // Implementation of WebSocketStream for non-multiplexed ws:// connections (or
33 // the physical side of a multiplexed ws:// connection).
34 //
35 // Please update the traffic annotations in the websocket_basic_stream.cc and
36 // websocket_stream.cc if the class is used for any communication with Google.
37 // In such a case, annotation should be passed from the callers to this class
38 // and a local annotation can not be used anymore.
39 class NET_EXPORT_PRIVATE WebSocketBasicStream final : public WebSocketStream {
40  public:
41   typedef WebSocketMaskingKey (*WebSocketMaskingKeyGeneratorFunction)();
42 
43   enum class BufferSize : uint8_t {
44     kSmall,
45     kLarge,
46   };
47 
48   // A class that calculates whether the associated WebSocketBasicStream
49   // should use a small buffer or large buffer, given the timing information
50   // or Read calls. This class is public for testing.
51   class NET_EXPORT_PRIVATE BufferSizeManager final {
52    public:
53     BufferSizeManager();
54     BufferSizeManager(const BufferSizeManager&) = delete;
55     BufferSizeManager& operator=(const BufferSizeManager&) = delete;
56     ~BufferSizeManager();
57 
58     // Called when the associated WebSocketBasicStream starts reading data
59     // into a buffer.
60     void OnRead(base::TimeTicks now);
61 
62     // Called when the Read operation completes. `size` must be positive.
63     void OnReadComplete(base::TimeTicks now, int size);
64 
65     // Returns the appropriate buffer size the associated WebSocketBasicStream
66     // should use.
buffer_size()67     BufferSize buffer_size() const { return buffer_size_; }
68 
69     // Set the rolling average window for tests.
set_window_for_test(size_t size)70     void set_window_for_test(size_t size) { rolling_average_window_ = size; }
71 
72    private:
73     // This keeps the best read buffer size.
74     BufferSize buffer_size_ = BufferSize::kSmall;
75 
76     // The number of results to calculate the throughput. This is a variable so
77     // that unittests can set other values.
78     size_t rolling_average_window_ = 100;
79 
80     // This keeps the timestamps to calculate the throughput.
81     base::queue<base::TimeTicks> read_start_timestamps_;
82 
83     // The sum of the last few read size.
84     int rolling_byte_total_ = 0;
85 
86     // This keeps the read size.
87     base::queue<int> recent_read_sizes_;
88   };
89 
90   // Adapter that allows WebSocketBasicStream to use
91   // either a TCP/IP or TLS socket, or an HTTP/2 stream.
92   class Adapter {
93    public:
94     virtual ~Adapter() = default;
95     virtual int Read(IOBuffer* buf,
96                      int buf_len,
97                      CompletionOnceCallback callback) = 0;
98     virtual int Write(
99         IOBuffer* buf,
100         int buf_len,
101         CompletionOnceCallback callback,
102         const NetworkTrafficAnnotationTag& traffic_annotation) = 0;
103     virtual void Disconnect() = 0;
104     virtual bool is_initialized() const = 0;
105   };
106 
107   // This class should not normally be constructed directly; see
108   // WebSocketStream::CreateAndConnectStream() and
109   // WebSocketBasicHandshakeStream::Upgrade().
110   WebSocketBasicStream(std::unique_ptr<Adapter> connection,
111                        const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
112                        const std::string& sub_protocol,
113                        const std::string& extensions,
114                        const NetLogWithSource& net_log);
115 
116   // The destructor has to make sure the connection is closed when we finish so
117   // that it does not get returned to the pool.
118   ~WebSocketBasicStream() override;
119 
120   // WebSocketStream implementation.
121   int ReadFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
122                  CompletionOnceCallback callback) override;
123 
124   int WriteFrames(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
125                   CompletionOnceCallback callback) override;
126 
127   void Close() override;
128 
129   std::string GetSubProtocol() const override;
130 
131   std::string GetExtensions() const override;
132 
133   const NetLogWithSource& GetNetLogWithSource() const override;
134 
135   ////////////////////////////////////////////////////////////////////////////
136   // Methods for testing only.
137 
138   static std::unique_ptr<WebSocketBasicStream>
139   CreateWebSocketBasicStreamForTesting(
140       std::unique_ptr<ClientSocketHandle> connection,
141       const scoped_refptr<GrowableIOBuffer>& http_read_buffer,
142       const std::string& sub_protocol,
143       const std::string& extensions,
144       const NetLogWithSource& net_log,
145       WebSocketMaskingKeyGeneratorFunction key_generator_function);
146 
147  private:
148   // Reads until socket read returns asynchronously or returns error.
149   // If returns ERR_IO_PENDING, then |read_callback_| will be called with result
150   // later.
151   int ReadEverything(std::vector<std::unique_ptr<WebSocketFrame>>* frames);
152 
153   // Called when a read completes. Parses the result, tries to read more.
154   // Might call |read_callback_|.
155   void OnReadComplete(std::vector<std::unique_ptr<WebSocketFrame>>* frames,
156                       int result);
157 
158   // Writes until |buffer| is fully drained (in which case returns OK) or a
159   // socket write returns asynchronously or returns an error.  If returns
160   // ERR_IO_PENDING, then |write_callback_| will be called with result later.
161   int WriteEverything(const scoped_refptr<DrainableIOBuffer>& buffer);
162 
163   // Called when a write completes.  Tries to write more.
164   // Might call |write_callback_|.
165   void OnWriteComplete(const scoped_refptr<DrainableIOBuffer>& buffer,
166                        int result);
167 
168   // Attempts to parse the output of a read as WebSocket frames. On success,
169   // returns OK and places the frame(s) in |frames|.
170   int HandleReadResult(int result,
171                        std::vector<std::unique_ptr<WebSocketFrame>>* frames);
172 
173   // Converts the chunks in |frame_chunks| into frames and writes them to
174   // |frames|. |frame_chunks| is destroyed in the process. Returns
175   // ERR_WS_PROTOCOL_ERROR if an invalid chunk was found. If one or more frames
176   // was added to |frames|, then returns OK, otherwise returns ERR_IO_PENDING.
177   int ConvertChunksToFrames(
178       std::vector<std::unique_ptr<WebSocketFrameChunk>>* frame_chunks,
179       std::vector<std::unique_ptr<WebSocketFrame>>* frames);
180 
181   // Converts a |chunk| to a |frame|. |*frame| should be NULL on entry to this
182   // method. If |chunk| is an incomplete control frame, or an empty middle
183   // frame, then |*frame| may still be NULL on exit. If an invalid control frame
184   // is found, returns ERR_WS_PROTOCOL_ERROR and the stream is no longer
185   // usable. Otherwise returns OK (even if frame is still NULL).
186   int ConvertChunkToFrame(std::unique_ptr<WebSocketFrameChunk> chunk,
187                           std::unique_ptr<WebSocketFrame>* frame);
188 
189   // Creates a frame based on the value of |is_final_chunk|, |data| and
190   // |current_frame_header_|. Clears |current_frame_header_| if |is_final_chunk|
191   // is true. |data| may be NULL if the frame has an empty payload. A frame in
192   // the middle of a message with no data is not useful; in this case the
193   // returned frame will be NULL. Otherwise, |current_frame_header_->opcode| is
194   // set to Continuation after use if it was Text or Binary, in accordance with
195   // WebSocket RFC6455 section 5.4.
196   std::unique_ptr<WebSocketFrame> CreateFrame(bool is_final_chunk,
197                                               base::span<const char> data);
198 
199   // Adds |data_buffer| to the end of |incomplete_control_frame_body_|, applying
200   // bounds checks.
201   void AddToIncompleteControlFrameBody(base::span<const char> data);
202 
203   // Storage for pending reads.
204   scoped_refptr<IOBufferWithSize> read_buffer_;
205 
206   // The best read buffer size for the current throughput.
207   size_t target_read_buffer_size_;
208 
209   // The connection, wrapped in a ClientSocketHandle so that we can prevent it
210   // from being returned to the pool.
211   std::unique_ptr<Adapter> connection_;
212 
213   // Frame header for the frame currently being received. Only non-NULL while we
214   // are processing the frame. If the frame arrives in multiple chunks, it can
215   // remain non-NULL until additional chunks arrive. If the header of the frame
216   // was invalid, this is set to NULL, the channel is failed, and subsequent
217   // chunks of the same frame will be ignored.
218   std::unique_ptr<WebSocketFrameHeader> current_frame_header_;
219 
220   // Although it should rarely happen in practice, a control frame can arrive
221   // broken into chunks. This variable provides storage for a partial control
222   // frame until the rest arrives. It will be empty the rest of the time.
223   std::vector<char> incomplete_control_frame_body_;
224   // Storage for payload of combined (see |incomplete_control_frame_body_|)
225   // control frame.
226   std::vector<char> complete_control_frame_body_;
227 
228   // Only used during handshake. Some data may be left in this buffer after the
229   // handshake, in which case it will be picked up during the first call to
230   // ReadFrames(). The type is GrowableIOBuffer for compatibility with
231   // net::HttpStreamParser, which is used to parse the handshake.
232   scoped_refptr<GrowableIOBuffer> http_read_buffer_;
233   // Flag to keep above buffer until next ReadFrames() after decoding.
234   bool is_http_read_buffer_decoded_ = false;
235 
236   // This keeps the current parse state (including any incomplete headers) and
237   // parses frames.
238   WebSocketFrameParser parser_;
239 
240   // The negotated sub-protocol, or empty for none.
241   const std::string sub_protocol_;
242 
243   // The extensions negotiated with the remote server.
244   const std::string extensions_;
245 
246   NetLogWithSource net_log_;
247 
248   // This is used for adaptive read buffer size.
249   BufferSizeManager buffer_size_manager_;
250 
251   // This keeps the current read buffer size.
252   BufferSize buffer_size_ = buffer_size_manager_.buffer_size();
253 
254   // This can be overridden in tests to make the output deterministic. We don't
255   // use a Callback here because a function pointer is faster and good enough
256   // for our purposes.
257   WebSocketMaskingKeyGeneratorFunction generate_websocket_masking_key_;
258 
259   // User callback saved for asynchronous writes and reads.
260   CompletionOnceCallback write_callback_;
261   CompletionOnceCallback read_callback_;
262 };
263 
264 }  // namespace net
265 
266 #endif  // NET_WEBSOCKETS_WEBSOCKET_BASIC_STREAM_H_
267