• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2015 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 // A base class for the toy client, which connects to a specified port and sends
6 // QUIC request to that endpoint.
7 
8 #ifndef QUICHE_QUIC_TOOLS_QUIC_CLIENT_BASE_H_
9 #define QUICHE_QUIC_TOOLS_QUIC_CLIENT_BASE_H_
10 
11 #include <memory>
12 #include <string>
13 
14 #include "absl/base/attributes.h"
15 #include "absl/strings/string_view.h"
16 #include "quiche/quic/core/crypto/crypto_handshake.h"
17 #include "quiche/quic/core/deterministic_connection_id_generator.h"
18 #include "quiche/quic/core/http/quic_client_push_promise_index.h"
19 #include "quiche/quic/core/http/quic_spdy_client_session.h"
20 #include "quiche/quic/core/http/quic_spdy_client_stream.h"
21 #include "quiche/quic/core/quic_config.h"
22 #include "quiche/quic/core/quic_connection_id.h"
23 #include "quiche/quic/platform/api/quic_socket_address.h"
24 
25 namespace quic {
26 
27 class ProofVerifier;
28 class QuicServerId;
29 class SessionCache;
30 
31 // A path context which owns the writer.
32 class QUIC_EXPORT_PRIVATE PathMigrationContext
33     : public QuicPathValidationContext {
34  public:
PathMigrationContext(std::unique_ptr<QuicPacketWriter> writer,const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address)35   PathMigrationContext(std::unique_ptr<QuicPacketWriter> writer,
36                        const QuicSocketAddress& self_address,
37                        const QuicSocketAddress& peer_address)
38       : QuicPathValidationContext(self_address, peer_address),
39         alternative_writer_(std::move(writer)) {}
40 
WriterToUse()41   QuicPacketWriter* WriterToUse() override { return alternative_writer_.get(); }
42 
ReleaseWriter()43   QuicPacketWriter* ReleaseWriter() { return alternative_writer_.release(); }
44 
45  private:
46   std::unique_ptr<QuicPacketWriter> alternative_writer_;
47 };
48 
49 // QuicClientBase handles establishing a connection to the passed in
50 // server id, including ensuring that it supports the passed in versions
51 // and config.
52 // Subclasses derived from this class are responsible for creating the
53 // actual QuicSession instance, as well as defining functions that
54 // create and run the underlying network transport.
55 class QuicClientBase : public QuicSession::Visitor {
56  public:
57   // An interface to various network events that the QuicClient will need to
58   // interact with.
59   class NetworkHelper {
60    public:
61     virtual ~NetworkHelper();
62 
63     // Runs one iteration of the event loop.
64     virtual void RunEventLoop() = 0;
65 
66     // Used during initialization: creates the UDP socket FD, sets socket
67     // options, and binds the socket to our address.
68     virtual bool CreateUDPSocketAndBind(QuicSocketAddress server_address,
69                                         QuicIpAddress bind_to_address,
70                                         int bind_to_port) = 0;
71 
72     // Unregister and close all open UDP sockets.
73     virtual void CleanUpAllUDPSockets() = 0;
74 
75     // If the client has at least one UDP socket, return address of the latest
76     // created one. Otherwise, return an empty socket address.
77     virtual QuicSocketAddress GetLatestClientAddress() const = 0;
78 
79     // Creates a packet writer to be used for the next connection.
80     virtual QuicPacketWriter* CreateQuicPacketWriter() = 0;
81   };
82 
83   QuicClientBase(const QuicServerId& server_id,
84                  const ParsedQuicVersionVector& supported_versions,
85                  const QuicConfig& config,
86                  QuicConnectionHelperInterface* helper,
87                  QuicAlarmFactory* alarm_factory,
88                  std::unique_ptr<NetworkHelper> network_helper,
89                  std::unique_ptr<ProofVerifier> proof_verifier,
90                  std::unique_ptr<SessionCache> session_cache);
91   QuicClientBase(const QuicClientBase&) = delete;
92   QuicClientBase& operator=(const QuicClientBase&) = delete;
93 
94   virtual ~QuicClientBase();
95 
96   // Implmenets QuicSession::Visitor
OnConnectionClosed(QuicConnectionId,QuicErrorCode,const std::string &,ConnectionCloseSource)97   void OnConnectionClosed(QuicConnectionId /*server_connection_id*/,
98                           QuicErrorCode /*error*/,
99                           const std::string& /*error_details*/,
100                           ConnectionCloseSource /*source*/) override {}
101 
OnWriteBlocked(QuicBlockedWriterInterface *)102   void OnWriteBlocked(QuicBlockedWriterInterface* /*blocked_writer*/) override {
103   }
OnRstStreamReceived(const QuicRstStreamFrame &)104   void OnRstStreamReceived(const QuicRstStreamFrame& /*frame*/) override {}
OnStopSendingReceived(const QuicStopSendingFrame &)105   void OnStopSendingReceived(const QuicStopSendingFrame& /*frame*/) override {}
TryAddNewConnectionId(const QuicConnectionId &,const QuicConnectionId &)106   bool TryAddNewConnectionId(
107       const QuicConnectionId& /*server_connection_id*/,
108       const QuicConnectionId& /*new_connection_id*/) override {
109     return false;
110   }
OnConnectionIdRetired(const QuicConnectionId &)111   void OnConnectionIdRetired(
112       const QuicConnectionId& /*server_connection_id*/) override {}
113   void OnServerPreferredAddressAvailable(
114       const QuicSocketAddress& server_preferred_address) override;
115 
116   // Initializes the client to create a connection. Should be called exactly
117   // once before calling StartConnect or Connect. Returns true if the
118   // initialization succeeds, false otherwise.
119   virtual bool Initialize();
120 
121   // "Connect" to the QUIC server, including performing synchronous crypto
122   // handshake.
123   bool Connect();
124 
125   // Start the crypto handshake.  This can be done in place of the synchronous
126   // Connect(), but callers are responsible for making sure the crypto handshake
127   // completes.
128   void StartConnect();
129 
130   // Calls session()->Initialize(). Subclasses may override this if any extra
131   // initialization needs to be done. Subclasses should expect that session()
132   // is non-null and valid.
133   virtual void InitializeSession();
134 
135   // Disconnects from the QUIC server.
136   void Disconnect();
137 
138   // Returns true if the crypto handshake has yet to establish encryption.
139   // Returns false if encryption is active (even if the server hasn't confirmed
140   // the handshake) or if the connection has been closed.
141   bool EncryptionBeingEstablished();
142 
143   // Wait for events until the stream with the given ID is closed.
144   void WaitForStreamToClose(QuicStreamId id);
145 
146   // Wait for 1-RTT keys become available.
147   // Returns true once 1-RTT keys are available, false otherwise.
148   ABSL_MUST_USE_RESULT bool WaitForOneRttKeysAvailable();
149 
150   // Wait for handshake state proceeds to HANDSHAKE_CONFIRMED.
151   // In QUIC crypto, this does the same as WaitForOneRttKeysAvailable, while in
152   // TLS, this waits for HANDSHAKE_DONE frame is received.
153   ABSL_MUST_USE_RESULT bool WaitForHandshakeConfirmed();
154 
155   // Wait up to 50ms, and handle any events which occur.
156   // Returns true if there are any outstanding requests.
157   bool WaitForEvents();
158 
159   // Performs the part of WaitForEvents() that is done after the actual event
160   // loop call.
161   bool WaitForEventsPostprocessing();
162 
163   // Migrate to a new socket (new_host) during an active connection.
164   bool MigrateSocket(const QuicIpAddress& new_host);
165 
166   // Migrate to a new socket (new_host, port) during an active connection.
167   bool MigrateSocketWithSpecifiedPort(const QuicIpAddress& new_host, int port);
168 
169   // Validate the new socket and migrate to it if the validation succeeds.
170   // Otherwise stay on the current socket. Return true if the validation has
171   // started.
172   bool ValidateAndMigrateSocket(const QuicIpAddress& new_host);
173 
174   // Open a new socket to change to a new ephemeral port.
175   bool ChangeEphemeralPort();
176 
177   QuicSession* session();
178   const QuicSession* session() const;
179 
180   bool connected() const;
181   virtual bool goaway_received() const;
182 
server_id()183   const QuicServerId& server_id() const { return server_id_; }
184 
185   // This should only be set before the initial Connect()
set_server_id(const QuicServerId & server_id)186   void set_server_id(const QuicServerId& server_id) { server_id_ = server_id; }
187 
SetUserAgentID(const std::string & user_agent_id)188   void SetUserAgentID(const std::string& user_agent_id) {
189     crypto_config_.set_user_agent_id(user_agent_id);
190   }
191 
SetTlsSignatureAlgorithms(std::string signature_algorithms)192   void SetTlsSignatureAlgorithms(std::string signature_algorithms) {
193     crypto_config_.set_tls_signature_algorithms(
194         std::move(signature_algorithms));
195   }
196 
supported_versions()197   const ParsedQuicVersionVector& supported_versions() const {
198     return supported_versions_;
199   }
200 
SetSupportedVersions(const ParsedQuicVersionVector & versions)201   void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
202     supported_versions_ = versions;
203   }
204 
config()205   QuicConfig* config() { return &config_; }
206 
crypto_config()207   QuicCryptoClientConfig* crypto_config() { return &crypto_config_; }
208 
209   // Change the initial maximum packet size of the connection.  Has to be called
210   // before Connect()/StartConnect() in order to have any effect.
set_initial_max_packet_length(QuicByteCount initial_max_packet_length)211   void set_initial_max_packet_length(QuicByteCount initial_max_packet_length) {
212     initial_max_packet_length_ = initial_max_packet_length;
213   }
214 
215   // The number of client hellos sent.
216   int GetNumSentClientHellos();
217 
218   // Returns true if early data (0-RTT data) was sent and the server accepted
219   // it.
220   virtual bool EarlyDataAccepted() = 0;
221 
222   // Returns true if the handshake was delayed one round trip by the server
223   // because the server wanted proof the client controls its source address
224   // before progressing further. In Google QUIC, this would be due to an
225   // inchoate REJ in the QUIC Crypto handshake; in IETF QUIC this would be due
226   // to a Retry packet.
227   // TODO(nharper): Consider a better name for this method.
228   virtual bool ReceivedInchoateReject() = 0;
229 
230   // Gather the stats for the last session and update the stats for the overall
231   // connection.
232   void UpdateStats();
233 
234   // The number of server config updates received.
235   int GetNumReceivedServerConfigUpdates();
236 
237   // Returns any errors that occurred at the connection-level.
238   QuicErrorCode connection_error() const;
set_connection_error(QuicErrorCode connection_error)239   void set_connection_error(QuicErrorCode connection_error) {
240     connection_error_ = connection_error;
241   }
242 
connected_or_attempting_connect()243   bool connected_or_attempting_connect() const {
244     return connected_or_attempting_connect_;
245   }
set_connected_or_attempting_connect(bool connected_or_attempting_connect)246   void set_connected_or_attempting_connect(
247       bool connected_or_attempting_connect) {
248     connected_or_attempting_connect_ = connected_or_attempting_connect;
249   }
250 
writer()251   QuicPacketWriter* writer() { return writer_.get(); }
set_writer(QuicPacketWriter * writer)252   void set_writer(QuicPacketWriter* writer) {
253     if (writer_.get() != writer) {
254       writer_.reset(writer);
255     }
256   }
257 
reset_writer()258   void reset_writer() { writer_.reset(); }
259 
260   ProofVerifier* proof_verifier() const;
261 
set_bind_to_address(QuicIpAddress address)262   void set_bind_to_address(QuicIpAddress address) {
263     bind_to_address_ = address;
264   }
265 
bind_to_address()266   QuicIpAddress bind_to_address() const { return bind_to_address_; }
267 
set_local_port(int local_port)268   void set_local_port(int local_port) { local_port_ = local_port; }
269 
local_port()270   int local_port() const { return local_port_; }
271 
server_address()272   const QuicSocketAddress& server_address() const { return server_address_; }
273 
set_server_address(const QuicSocketAddress & server_address)274   void set_server_address(const QuicSocketAddress& server_address) {
275     server_address_ = server_address;
276   }
277 
helper()278   QuicConnectionHelperInterface* helper() { return helper_.get(); }
279 
280   NetworkHelper* network_helper();
281   const NetworkHelper* network_helper() const;
282 
initialized()283   bool initialized() const { return initialized_; }
284 
SetPreSharedKey(absl::string_view key)285   void SetPreSharedKey(absl::string_view key) {
286     crypto_config_.set_pre_shared_key(key);
287   }
288 
set_connection_debug_visitor(QuicConnectionDebugVisitor * connection_debug_visitor)289   void set_connection_debug_visitor(
290       QuicConnectionDebugVisitor* connection_debug_visitor) {
291     connection_debug_visitor_ = connection_debug_visitor;
292   }
293 
294   // Sets the interface name to bind. If empty, will not attempt to bind the
295   // socket to that interface. Defaults to empty string.
set_interface_name(std::string interface_name)296   void set_interface_name(std::string interface_name) {
297     interface_name_ = interface_name;
298   }
299 
interface_name()300   std::string interface_name() const { return interface_name_; }
301 
set_server_connection_id_override(const QuicConnectionId & connection_id)302   void set_server_connection_id_override(
303       const QuicConnectionId& connection_id) {
304     server_connection_id_override_ = connection_id;
305   }
306 
set_server_connection_id_length(uint8_t server_connection_id_length)307   void set_server_connection_id_length(uint8_t server_connection_id_length) {
308     server_connection_id_length_ = server_connection_id_length;
309   }
310 
set_client_connection_id_length(uint8_t client_connection_id_length)311   void set_client_connection_id_length(uint8_t client_connection_id_length) {
312     client_connection_id_length_ = client_connection_id_length;
313   }
314 
315   bool HasPendingPathValidation();
316 
317   void ValidateNewNetwork(const QuicIpAddress& host);
318 
AddValidatedPath(std::unique_ptr<QuicPathValidationContext> context)319   void AddValidatedPath(std::unique_ptr<QuicPathValidationContext> context) {
320     validated_paths_.push_back(std::move(context));
321   }
322 
323   const std::vector<std::unique_ptr<QuicPathValidationContext>>&
validated_paths()324   validated_paths() const {
325     return validated_paths_;
326   }
327 
328  protected:
329   // TODO(rch): Move GetNumSentClientHellosFromSession and
330   // GetNumReceivedServerConfigUpdatesFromSession into a new/better
331   // QuicSpdyClientSession class. The current inherits dependencies from
332   // Spdy. When that happens this class and all its subclasses should
333   // work with QuicSpdyClientSession instead of QuicSession.
334   // That will obviate the need for the pure virtual functions below.
335 
336   // Extract the number of sent client hellos from the session.
337   virtual int GetNumSentClientHellosFromSession() = 0;
338 
339   // The number of server config updates received.
340   virtual int GetNumReceivedServerConfigUpdatesFromSession() = 0;
341 
342   // If this client supports buffering data, resend it.
343   virtual void ResendSavedData() = 0;
344 
345   // If this client supports buffering data, clear it.
346   virtual void ClearDataToResend() = 0;
347 
348   // Takes ownership of |connection|. If you override this function,
349   // you probably want to call ResetSession() in your destructor.
350   // TODO(rch): Change the connection parameter to take in a
351   // std::unique_ptr<QuicConnection> instead.
352   virtual std::unique_ptr<QuicSession> CreateQuicClientSession(
353       const ParsedQuicVersionVector& supported_versions,
354       QuicConnection* connection) = 0;
355 
356   // Generates the next ConnectionId for |server_id_|.  By default, if the
357   // cached server config contains a server-designated ID, that ID will be
358   // returned.  Otherwise, the next random ID will be returned.
359   QuicConnectionId GetNextConnectionId();
360 
361   // Generates a new, random connection ID (as opposed to a server-designated
362   // connection ID).
363   virtual QuicConnectionId GenerateNewConnectionId();
364 
365   // Returns the client connection ID to use.
366   virtual QuicConnectionId GetClientConnectionId();
367 
alarm_factory()368   QuicAlarmFactory* alarm_factory() { return alarm_factory_.get(); }
369 
370   // Subclasses may need to explicitly clear the session on destruction
371   // if they create it with objects that will be destroyed before this is.
372   // You probably want to call this if you override CreateQuicSpdyClientSession.
ResetSession()373   void ResetSession() { session_.reset(); }
374 
375   // Returns true if the corresponding of this client has active requests.
376   virtual bool HasActiveRequests() = 0;
377 
378   // Allows derived classes to access this when creating connections.
379   ConnectionIdGeneratorInterface& connection_id_generator();
380 
381  private:
382   // Returns true and set |version| if client can reconnect with a different
383   // version.
384   bool CanReconnectWithDifferentVersion(ParsedQuicVersion* version) const;
385 
386   std::unique_ptr<QuicPacketWriter> CreateWriterForNewNetwork(
387       const QuicIpAddress& new_host, int port);
388 
389   // |server_id_| is a tuple (hostname, port, is_https) of the server.
390   QuicServerId server_id_;
391 
392   // Tracks if the client is initialized to connect.
393   bool initialized_;
394 
395   // Address of the server.
396   QuicSocketAddress server_address_;
397 
398   // If initialized, the address to bind to.
399   QuicIpAddress bind_to_address_;
400 
401   // Local port to bind to. Initialize to 0.
402   int local_port_;
403 
404   // config_ and crypto_config_ contain configuration and cached state about
405   // servers.
406   QuicConfig config_;
407   QuicCryptoClientConfig crypto_config_;
408 
409   // Helper to be used by created connections. Must outlive |session_|.
410   std::unique_ptr<QuicConnectionHelperInterface> helper_;
411 
412   // Alarm factory to be used by created connections. Must outlive |session_|.
413   std::unique_ptr<QuicAlarmFactory> alarm_factory_;
414 
415   // Writer used to actually send packets to the wire. Must outlive |session_|.
416   std::unique_ptr<QuicPacketWriter> writer_;
417 
418   // Session which manages streams.
419   std::unique_ptr<QuicSession> session_;
420 
421   // This vector contains QUIC versions which we currently support.
422   // This should be ordered such that the highest supported version is the first
423   // element, with subsequent elements in descending order (versions can be
424   // skipped as necessary). We will always pick supported_versions_[0] as the
425   // initial version to use.
426   ParsedQuicVersionVector supported_versions_;
427 
428   // The initial value of maximum packet size of the connection.  If set to
429   // zero, the default is used.
430   QuicByteCount initial_max_packet_length_;
431 
432   // The number of hellos sent during the current/latest connection.
433   int num_sent_client_hellos_;
434 
435   // Used to store any errors that occurred with the overall connection (as
436   // opposed to that associated with the last session object).
437   QuicErrorCode connection_error_;
438 
439   // True when the client is attempting to connect.  Set to false between a call
440   // to Disconnect() and the subsequent call to StartConnect().  When
441   // connected_or_attempting_connect_ is false, the session object corresponds
442   // to the previous client-level connection.
443   bool connected_or_attempting_connect_;
444 
445   // The network helper used to create sockets and manage the event loop.
446   // Not owned by this class.
447   std::unique_ptr<NetworkHelper> network_helper_;
448 
449   // The debug visitor set on the connection right after it is constructed.
450   // Not owned, must be valid for the lifetime of the QuicClientBase instance.
451   QuicConnectionDebugVisitor* connection_debug_visitor_;
452 
453   // If set,
454   // - GetNextConnectionId will use this as the next server connection id.
455   // - GenerateNewConnectionId will not be called.
456   absl::optional<QuicConnectionId> server_connection_id_override_;
457 
458   // GenerateNewConnectionId creates a random connection ID of this length.
459   // Defaults to 8.
460   uint8_t server_connection_id_length_;
461 
462   // GetClientConnectionId creates a random connection ID of this length.
463   // Defaults to 0.
464   uint8_t client_connection_id_length_;
465 
466   // Stores validated paths.
467   std::vector<std::unique_ptr<QuicPathValidationContext>> validated_paths_;
468 
469   // Stores the interface name to bind. If empty, will not attempt to bind the
470   // socket to that interface. Defaults to empty string.
471   std::string interface_name_;
472 
473   DeterministicConnectionIdGenerator connection_id_generator_{
474       kQuicDefaultConnectionIdLength};
475 };
476 
477 }  // namespace quic
478 
479 #endif  // QUICHE_QUIC_TOOLS_QUIC_CLIENT_BASE_H_
480