1
#pragma once
2

            
3
#include <vector>
4

            
5
#include "envoy/api/io_error.h"
6
#include "envoy/buffer/buffer.h"
7
#include "envoy/common/optref.h"
8
#include "envoy/common/pure.h"
9
#include "envoy/network/io_handle.h"
10
#include "envoy/network/listen_socket.h"
11
#include "envoy/network/post_io_action.h"
12
#include "envoy/network/proxy_protocol.h"
13
#include "envoy/ssl/connection.h"
14
#include "envoy/ssl/context.h"
15
#include "envoy/stream_info/filter_state.h"
16

            
17
#include "absl/types/optional.h"
18

            
19
#ifdef ENVOY_ENABLE_QUIC
20
namespace quic {
21
class QuicCryptoClientConfig;
22
}
23
#endif
24

            
25
namespace Envoy {
26

            
27
namespace Upstream {
28
class HostDescription;
29
}
30
namespace Ssl {
31
class ClientContextConfig;
32
}
33

            
34
namespace Network {
35

            
36
class Connection;
37
enum class ConnectionEvent;
38

            
39
/**
40
 * Result of each I/O event.
41
 */
42
struct IoResult {
43
  IoResult(PostIoAction action, uint64_t bytes_processed, bool end_stream_read)
44
34131
      : action_(action), bytes_processed_(bytes_processed), end_stream_read_(end_stream_read),
45
34131
        err_code_(absl::nullopt) {}
46

            
47
  IoResult(PostIoAction action, uint64_t bytes_processed, bool end_stream_read,
48
           absl::optional<Api::IoError::IoErrorCode> err_code)
49
1820453
      : action_(action), bytes_processed_(bytes_processed), end_stream_read_(end_stream_read),
50
1820453
        err_code_(err_code) {}
51

            
52
  PostIoAction action_;
53

            
54
  /**
55
   * Number of bytes processed by the I/O event.
56
   */
57
  uint64_t bytes_processed_;
58

            
59
  /**
60
   * True if an end-of-stream was read from a connection. This
61
   * can only be true for read operations.
62
   */
63
  bool end_stream_read_;
64

            
65
  /**
66
   * The underlying I/O error code.
67
   */
68
  absl::optional<Api::IoError::IoErrorCode> err_code_;
69
};
70

            
71
/**
72
 * Callbacks used by transport socket instances to communicate with connection.
73
 */
74
class TransportSocketCallbacks {
75
public:
76
111425
  virtual ~TransportSocketCallbacks() = default;
77

            
78
  /**
79
   * @return reference to the IoHandle associated with the connection.
80
   */
81
  virtual IoHandle& ioHandle() PURE;
82

            
83
  /**
84
   * @return const reference to the IoHandle associated with the connection.
85
   */
86
  virtual const IoHandle& ioHandle() const PURE;
87

            
88
  /**
89
   * @return Network::Connection& the connection interface.
90
   */
91
  virtual Network::Connection& connection() PURE;
92

            
93
  /**
94
   * @return bool whether the read buffer should be drained. This is used to enforce yielding for
95
   *         configured read limits.
96
   */
97
  virtual bool shouldDrainReadBuffer() PURE;
98

            
99
  /**
100
   * Mark the transport socket as readable in order to force a read in a future iteration of the
101
   * event loop. This is used when yielding following shouldDrainReadBuffer().
102
   */
103
  virtual void setTransportSocketIsReadable() PURE;
104

            
105
  /**
106
   * Raise a connection event to the connection. This can be used by a secure socket (e.g. TLS)
107
   * to raise a connected event when handshake is done.
108
   * @param event supplies the connection event
109
   */
110
  virtual void raiseEvent(ConnectionEvent event) PURE;
111

            
112
  /**
113
   * If the callbacks' write buffer is not empty, try to drain the buffer.
114
   * As of 2/20, used by Google.
115
   */
116
  virtual void flushWriteBuffer() PURE;
117
};
118

            
119
/**
120
 * A transport socket that does actual read / write. It can also do some transformations on
121
 * the data (e.g. TLS).
122
 */
123
class TransportSocket {
124
public:
125
109095
  virtual ~TransportSocket() = default;
126

            
127
  /**
128
   * Called by connection once to initialize the transport socket callbacks that the transport
129
   * socket should use.
130
   * @param callbacks supplies the callbacks instance.
131
   */
132
  virtual void setTransportSocketCallbacks(TransportSocketCallbacks& callbacks) PURE;
133

            
134
  /**
135
   * @return std::string the protocol to use as selected by network level negotiation. (E.g., ALPN).
136
   *         If network level negotiation is not supported by the connection or no protocol
137
   *         has been negotiated the empty string is returned.
138
   */
139
  virtual std::string protocol() const PURE;
140

            
141
  /**
142
   * @return std::string the last failure reason occurred on the transport socket. If no failure
143
   *         has been occurred the empty string is returned.
144
   */
145
  virtual absl::string_view failureReason() const PURE;
146

            
147
  /**
148
   * @return bool whether the socket can be flushed and closed.
149
   */
150
  virtual bool canFlushClose() PURE;
151

            
152
  /**
153
   * Connect the underlying transport.
154
   * @param socket provides the socket to connect.
155
   * @return int the result from connect.
156
   */
157
53634
  virtual Api::SysCallIntResult connect(Network::ConnectionSocket& socket) {
158
53634
    return socket.connect(socket.connectionInfoProvider().remoteAddress());
159
53634
  }
160

            
161
  /**
162
   * Closes the transport socket.
163
   * @param event supplies the connection event that is closing the socket.
164
   */
165
  virtual void closeSocket(Network::ConnectionEvent event) PURE;
166

            
167
  /**
168
   * @param buffer supplies the buffer to read to.
169
   * @return IoResult the result of the read action.
170
   */
171
  virtual IoResult doRead(Buffer::Instance& buffer) PURE;
172

            
173
  /**
174
   * @param buffer supplies the buffer to write from
175
   * @param end_stream supplies whether this is the end of the stream. If true and all
176
   *        data in buffer is written, the connection will be half-closed.
177
   * @return IoResult the result of the write action.
178
   */
179
  virtual IoResult doWrite(Buffer::Instance& buffer, bool end_stream) PURE;
180

            
181
  /**
182
   * Called when underlying transport is established.
183
   */
184
  virtual void onConnected() PURE;
185

            
186
  /**
187
   * @return the const SSL connection data if this is an SSL connection, or nullptr if it is not.
188
   */
189
  virtual Ssl::ConnectionInfoConstSharedPtr ssl() const PURE;
190

            
191
  /**
192
   * Instructs a transport socket to start using secure transport.
193
   * It is up to the caller of this method to manage the coordination between the client
194
   * and server with regard to when to start secure transport. This is typically done via
195
   * some signal message. See STARTTLS for an example of such negotiation.
196
   * Note: Not all transport sockets support such operation.
197
   * @return boolean indicating if the transport socket was able to start secure transport.
198
   */
199
  virtual bool startSecureTransport() PURE;
200

            
201
  /**
202
   * Try to configure the connection's initial congestion window.
203
   * The operation is advisory - the connection may not support it, even if it's supported, it may
204
   * not do anything after the first few network round trips with the peer.
205
   * @param bandwidth_bits_per_sec The estimated bandwidth between the two endpoints of the
206
   * connection.
207
   * @param rtt The estimated round trip time between the two endpoints of the connection.
208
   */
209
  virtual void configureInitialCongestionWindow(uint64_t bandwidth_bits_per_sec,
210
                                                std::chrono::microseconds rtt) PURE;
211
};
212

            
213
using TransportSocketPtr = std::unique_ptr<TransportSocket>;
214

            
215
/**
216
 * Options for creating transport sockets.
217
 */
218
class TransportSocketOptions {
219
public:
220
59168
  virtual ~TransportSocketOptions() = default;
221

            
222
  /**
223
   * @return the const optional server name to set in the transport socket, for example SNI for
224
   *         SSL, regardless of the upstream cluster configuration. Filters that influence
225
   *         upstream connection selection, such as tcp_proxy, should take this option into account
226
   *         and should pass it through to the connection pool to ensure the correct endpoints are
227
   *         selected and the upstream connection is set up accordingly.
228
   */
229
  virtual const absl::optional<std::string>& serverNameOverride() const PURE;
230

            
231
  /**
232
   * @return the optional overridden SAN names to verify, if the transport socket supports SAN
233
   *         verification.
234
   */
235
  virtual const std::vector<std::string>& verifySubjectAltNameListOverride() const PURE;
236

            
237
  /**
238
   * The application protocols to use when negotiating an upstream connection. When an application
239
   * protocol override is provided, it will *always* be used.
240
   * @return the optional overridden application protocols.
241
   */
242
  virtual const std::vector<std::string>& applicationProtocolListOverride() const PURE;
243

            
244
  /**
245
   * The application protocol(s) to use when negotiating an upstream connection and no other
246
   * application protocol has been configured. Both
247
   * TransportSocketOptions::applicationProtocolListOverride and application protocols configured
248
   * in the CommonTlsContext on the Cluster will take precedence.
249
   *
250
   * Note that this option is intended for intermediate code (e.g. the HTTP connection pools) to
251
   * specify a default ALPN when no specific values are specified elsewhere. As such, providing a
252
   * value here might not make sense prior to load balancing.
253
   * @return the optional fallback(s) for application protocols, for when they are not specified in
254
   *         the TLS configuration.
255
   */
256
  virtual const std::vector<std::string>& applicationProtocolFallback() const PURE;
257

            
258
  /**
259
   * @return optional PROXY protocol address information.
260
   */
261
  virtual absl::optional<Network::ProxyProtocolData> proxyProtocolOptions() const PURE;
262

            
263
  // Information for use by the http_11_proxy transport socket.
264
  struct Http11ProxyInfo {
265
    Http11ProxyInfo(std::string hostname, Network::Address::InstanceConstSharedPtr address)
266
34
        : hostname(hostname), proxy_address(address) {}
267
    // The hostname of the original request, to be used in CONNECT request if
268
    // the underlying transport is TLS.
269
    std::string hostname;
270
    // The address of the proxy, where connections should be routed to.
271
    Network::Address::InstanceConstSharedPtr proxy_address;
272
  };
273

            
274
  /**
275
   * @return any proxy information if sending to an intermediate proxy over HTTP/1.1.
276
   */
277
  virtual OptRef<const Http11ProxyInfo> http11ProxyInfo() const PURE;
278

            
279
  /**
280
   * @return filter state objects from the downstream request or connection
281
   * that are marked as shared with the upstream connection.
282
   */
283
  virtual const StreamInfo::FilterState::Objects& downstreamSharedFilterStateObjects() const PURE;
284
};
285

            
286
using TransportSocketOptionsConstSharedPtr = std::shared_ptr<const TransportSocketOptions>;
287

            
288
/**
289
 * A factory for creating transport sockets.
290
 **/
291
class TransportSocketFactoryBase {
292
public:
293
443324
  virtual ~TransportSocketFactoryBase() = default;
294

            
295
  /**
296
   * @return bool whether the transport socket implements secure transport.
297
   */
298
  virtual bool implementsSecureTransport() const PURE;
299
};
300

            
301
/**
302
 * A factory for creating upstream transport sockets. It will be associated to clusters.
303
 */
304
class UpstreamTransportSocketFactory : public virtual TransportSocketFactoryBase {
305
public:
306
439830
  ~UpstreamTransportSocketFactory() override = default;
307

            
308
  /**
309
   * @param options for creating the transport socket
310
   * @param host description for the destination upstream host
311
   * @return Network::TransportSocketPtr a transport socket to be passed to client connection.
312
   */
313
  virtual TransportSocketPtr
314
  createTransportSocket(TransportSocketOptionsConstSharedPtr options,
315
                        std::shared_ptr<const Upstream::HostDescription> host) const PURE;
316

            
317
  /**
318
   * @return the default Http11ProxyInfo if configured, or nullopt.
319
   */
320
30599
  virtual OptRef<const TransportSocketOptions::Http11ProxyInfo> defaultHttp11ProxyInfo() const {
321
30599
    return {};
322
30599
  }
323

            
324
  /**
325
   * Returns true if the transport socket created by this factory supports some form of ALPN
326
   * negotiation.
327
   */
328
16354
  virtual bool supportsAlpn() const { return false; }
329

            
330
  /**
331
   * Returns the default SNI for transport sockets created by this factory.
332
   * This will return an empty string view if the transport sockets created are
333
   * not client-side TLS sockets.
334
   */
335
  virtual absl::string_view defaultServerNameIndication() const PURE;
336

            
337
  /**
338
   * @param key supplies a vector of bytes to which the option should append hash key data that will
339
   *        be used to separate connections based on the option. Any data already in the key vector
340
   *        must not be modified.
341
   * @param options supplies the transport socket options.
342
   */
343
  virtual void hashKey(std::vector<uint8_t>& key,
344
                       TransportSocketOptionsConstSharedPtr options) const PURE;
345

            
346
  /*
347
   * @return the pointer to the SSL context, or nullptr for non-TLS factories.
348
   */
349
43858
  virtual Envoy::Ssl::ClientContextSharedPtr sslCtx() { return nullptr; }
350

            
351
  /*
352
   * @return the ClientContextConfig, or absl::nullopt for non-TLS factories.
353
   */
354
  virtual OptRef<const Ssl::ClientContextConfig> clientContextConfig() const { return {}; }
355

            
356
#ifdef ENVOY_ENABLE_QUIC
357
  /*
358
   * @return the QuicCryptoClientConfig or nullptr for non-QUIC factories.
359
   */
360
  virtual std::shared_ptr<quic::QuicCryptoClientConfig> getCryptoConfig() { return nullptr; }
361
#endif
362
};
363

            
364
/**
365
 * A factory for creating downstream transport sockets. It will be associated to listeners.
366
 */
367
class DownstreamTransportSocketFactory : public virtual TransportSocketFactoryBase {
368
public:
369
284781
  ~DownstreamTransportSocketFactory() override = default;
370

            
371
  /**
372
   * @return Network::TransportSocketPtr a transport socket to be passed to server connection.
373
   */
374
  virtual TransportSocketPtr createDownstreamTransportSocket() const PURE;
375
};
376

            
377
using UpstreamTransportSocketFactoryPtr = std::unique_ptr<UpstreamTransportSocketFactory>;
378
using DownstreamTransportSocketFactoryPtr = std::unique_ptr<DownstreamTransportSocketFactory>;
379

            
380
} // namespace Network
381
} // namespace Envoy