1
#pragma once
2

            
3
#include <memory>
4

            
5
#include "envoy/access_log/access_log.h"
6
#include "envoy/buffer/buffer.h"
7
#include "envoy/config/extension_config_provider.h"
8
#include "envoy/config/typed_metadata.h"
9
#include "envoy/network/listen_socket.h"
10
#include "envoy/network/listener_filter_buffer.h"
11
#include "envoy/network/transport_socket.h"
12
#include "envoy/stream_info/stream_info.h"
13
#include "envoy/upstream/host_description.h"
14

            
15
#include "source/common/protobuf/protobuf.h"
16

            
17
namespace quiche {
18
class QuicheSocketAddress;
19
} // namespace quiche
20

            
21
namespace quic {
22
class QuicReceivedPacket;
23
} // namespace quic
24

            
25
namespace Envoy {
26

            
27
namespace Event {
28
class Dispatcher;
29
}
30

            
31
namespace Network {
32

            
33
class Connection;
34
class ConnectionSocket;
35
class Socket;
36
class UdpListener;
37
struct UdpRecvData;
38

            
39
/**
40
 * Status codes returned by filters that can cause future filters to not get iterated to.
41
 */
42
enum class FilterStatus {
43
  // Continue to further filters.
44
  Continue,
45
  // Stop executing further filters.
46
  StopIteration
47
};
48

            
49
/**
50
 * Callbacks used by individual filter instances to communicate with the filter manager.
51
 */
52
class NetworkFilterCallbacks {
53
public:
54
114387
  virtual ~NetworkFilterCallbacks() = default;
55

            
56
  /**
57
   * @return the connection that owns this filter.
58
   */
59
  virtual Connection& connection() PURE;
60

            
61
  /**
62
   * @return Socket the socket the filter is operating on.
63
   */
64
  virtual const ConnectionSocket& socket() PURE;
65
};
66

            
67
/**
68
 * Callbacks used by individual write filter instances to communicate with the filter manager.
69
 */
70
class WriteFilterCallbacks : public virtual NetworkFilterCallbacks {
71
public:
72
410
  ~WriteFilterCallbacks() override = default;
73

            
74
  /**
75
   * Pass data directly to subsequent filters in the filter chain. This method is used in
76
   * advanced cases in which a filter needs full control over how subsequent filters view data.
77
   * Using this method allows a filter to buffer data (or not) and then periodically inject data
78
   * to subsequent filters, indicating end_stream at an appropriate time.
79
   * This can be used to implement rate limiting, periodic data emission, etc.
80
   *
81
   * When using this callback, filters should generally move passed in buffer and return
82
   * FilterStatus::StopIteration from their onWrite() call, since use of this method
83
   * indicates that a filter does not wish to participate in a standard write flow
84
   * and will perform any necessary buffering and continuation on its own.
85
   *
86
   * @param data supplies the write data to be propagated directly to further filters in the filter
87
   *             chain.
88
   * @param end_stream supplies the end_stream status to be propagated directly to further filters
89
   *                   in the filter chain.
90
   */
91
  virtual void injectWriteDataToFilterChain(Buffer::Instance& data, bool end_stream) PURE;
92

            
93
  /**
94
   * Control the filter close status for write filters.
95
   *
96
   * When `disabled` is `true`, the connection closure process is paused or delayed by marking the
97
   * closure as pending. When `disabled` is `false`, the connection closure process is resumed if it
98
   * was previously delayed.
99
   *
100
   * This method affects the filter's "close status" within the context of the connection closure
101
   * process managed by the filter manager:
102
   *    - `disableClose(true)` marks the filter as unable to close by delaying the closure process.
103
   *    - Calling `disableClose(true)` again has no additional effect, as the closure is already
104
   *      marked as pending.
105
   *    - `disableClose(false)` mark the filter is ready to be closed. If no further pending
106
   * closures exist and there is a latched close action, it will close the connection with the
107
   * latched close action.
108
   *
109
   * Note that this method only takes effect when the connection closure is being managed through
110
   * the filter manager.
111
   *
112
   * @param disabled A boolean flag:
113
   *   - `true`: Delays the connection closure process if there is any,
114
   *             marking the filter as unable to close.
115
   *   - `false`: Resumes the connection closure process if there is any,
116
   *              marking the filter as close ready.
117
   */
118
  virtual void disableClose(bool disabled) PURE;
119
};
120

            
121
/**
122
 * A write path binary connection filter.
123
 */
124
class WriteFilter {
125
public:
126
2655
  virtual ~WriteFilter() = default;
127

            
128
  /**
129
   * Called when data is to be written on the connection.
130
   * @param data supplies the buffer to be written which may be modified.
131
   * @param end_stream supplies whether this is the last byte to write on the connection.
132
   * @return status used by the filter manager to manage further filter iteration.
133
   */
134
  virtual FilterStatus onWrite(Buffer::Instance& data, bool end_stream) PURE;
135

            
136
  /**
137
   * Initializes the write filter callbacks used to interact with the filter manager. It will be
138
   * called by the filter manager a single time when the filter is first registered. Thus, any
139
   * construction that requires the backing connection should take place in the context of this
140
   * function.
141
   *
142
   * IMPORTANT: No outbound networking or complex processing should be done in this function.
143
   *            That should be done in the context of ReadFilter::onNewConnection() if needed.
144
   *
145
   * @param callbacks supplies the callbacks.
146
   */
147
  virtual void initializeWriteFilterCallbacks(WriteFilterCallbacks&) {}
148
};
149

            
150
using WriteFilterSharedPtr = std::shared_ptr<WriteFilter>;
151

            
152
/**
153
 * Callbacks used by individual read filter instances to communicate with the filter manager.
154
 */
155
class ReadFilterCallbacks : public virtual NetworkFilterCallbacks {
156
public:
157
113976
  ~ReadFilterCallbacks() override = default;
158

            
159
  /**
160
   * If a read filter stopped filter iteration, continueReading() can be called to continue the
161
   * filter chain. The next filter will be called with all currently available data in the read
162
   * buffer (it will also have onNewConnection() called on it if it was not previously called).
163
   */
164
  virtual void continueReading() PURE;
165

            
166
  /**
167
   * Pass data directly to subsequent filters in the filter chain. This method is used in
168
   * advanced cases in which a filter needs full control over how subsequent filters view data,
169
   * and does not want to make use of connection-level buffering. Using this method allows
170
   * a filter to buffer data (or not) and then periodically inject data to subsequent filters,
171
   * indicating end_stream at an appropriate time. This can be used to implement rate limiting,
172
   * periodic data emission, etc.
173
   *
174
   * When using this callback, filters should generally move passed in buffer and return
175
   * FilterStatus::StopIteration from their onData() call, since use of this method
176
   * indicates that a filter does not wish to participate in standard connection-level
177
   * buffering and continuation and will perform any necessary buffering and continuation on its
178
   * own.
179
   *
180
   * This callback is different from continueReading() in that the specified data and end_stream
181
   * status will be propagated verbatim to further filters in the filter chain
182
   * (while continueReading() propagates connection-level read buffer and end_stream status).
183
   *
184
   * @param data supplies the read data to be propagated directly to further filters in the filter
185
   *             chain.
186
   * @param end_stream supplies the end_stream status to be propagated directly to further filters
187
   *                   in the filter chain.
188
   */
189
  virtual void injectReadDataToFilterChain(Buffer::Instance& data, bool end_stream) PURE;
190

            
191
  /**
192
   * Return the currently selected upstream host, if any. This can be used for communication
193
   * between multiple network level filters, for example the TCP proxy filter communicating its
194
   * selection to another filter for logging.
195
   */
196
  virtual Upstream::HostDescriptionConstSharedPtr upstreamHost() PURE;
197

            
198
  /**
199
   * Set the currently selected upstream host for the connection.
200
   */
201
  virtual void upstreamHost(Upstream::HostDescriptionConstSharedPtr host) PURE;
202

            
203
  /**
204
   * Signal to the filter manager to enable secure transport mode in upstream connection.
205
   * This is done when upstream connection's transport socket is of startTLS type. At the moment
206
   * it is the only transport socket type which can be programmatically converted from non-secure
207
   * mode to secure mode.
208
   */
209
  virtual bool startUpstreamSecureTransport() PURE;
210

            
211
  /**
212
   * Control the filter close status for read filters.
213
   *
214
   * When `disabled` is `true`, the connection closure process is paused or delayed by marking the
215
   * closure as pending. When `disabled` is `false`, the connection closure process is resumed if it
216
   * was previously delayed.
217
   *
218
   * This method affects the filter's "close status" within the context of the connection closure
219
   * process managed by the filter manager:
220
   *    - `disableClose(true)` marks the filter as unable to close by delaying the closure process.
221
   *    - Calling `disableClose(true)` again has no additional effect, as the closure is already
222
   *      marked as pending.
223
   *    - `disableClose(false)` mark the filter is ready to be closed. If no further pending
224
   * closures exist and there is a latched close action, it will close the connection with the
225
   * latched close action.
226
   *
227
   * Note that this method only takes effect when the connection closure is being managed through
228
   * the filter manager.
229
   *
230
   * @param disabled A boolean flag:
231
   *   - `true`: Delays the connection closure process if there is any,
232
   *             marking the filter as unable to close.
233
   *   - `false`: Resumes the connection closure process if there is any,
234
   *              marking the filter as close ready.
235
   */
236
  virtual void disableClose(bool disable) PURE;
237
};
238

            
239
/**
240
 * A read path binary connection filter.
241
 */
242
class ReadFilter {
243
public:
244
116681
  virtual ~ReadFilter() = default;
245

            
246
  /**
247
   * Called when data is read on the connection.
248
   * @param data supplies the read data which may be modified.
249
   * @param end_stream supplies whether this is the last byte on the connection. This will only
250
   *        be set if the connection has half-close semantics enabled.
251
   * @return status used by the filter manager to manage further filter iteration.
252
   */
253
  virtual FilterStatus onData(Buffer::Instance& data, bool end_stream) PURE;
254

            
255
  /**
256
   * Called when a connection is first established. Filters should do one time long term processing
257
   * that needs to be done when a connection is established. Filter chain iteration can be stopped
258
   * if needed.
259
   * @return status used by the filter manager to manage further filter iteration.
260
   */
261
  virtual FilterStatus onNewConnection() PURE;
262

            
263
  /**
264
   * Initializes the read filter callbacks used to interact with the filter manager. It will be
265
   * called by the filter manager a single time when the filter is first registered. Thus, any
266
   * construction that requires the backing connection should take place in the context of this
267
   * function.
268
   *
269
   * IMPORTANT: No outbound networking or complex processing should be done in this function.
270
   *            That should be done in the context of onNewConnection() if needed.
271
   *
272
   * @param callbacks supplies the callbacks.
273
   */
274
  virtual void initializeReadFilterCallbacks(ReadFilterCallbacks& callbacks) PURE;
275

            
276
  /**
277
   * Method is called by the filter manager to convert upstream's connection transport socket
278
   * from non-secure mode to secure mode. Only terminal filters are aware of upstream connection and
279
   * non-terminal filters should not implement startUpstreamSecureTransport.
280
   */
281
2
  virtual bool startUpstreamSecureTransport() { return false; }
282
};
283

            
284
using ReadFilterSharedPtr = std::shared_ptr<ReadFilter>;
285

            
286
/**
287
 * A combination read and write filter. This allows a single filter instance to cover
288
 * both the read and write paths.
289
 */
290
class Filter : public WriteFilter, public ReadFilter {};
291
using FilterSharedPtr = std::shared_ptr<Filter>;
292

            
293
/**
294
 * Interface for adding individual network filters to a manager.
295
 */
296
class FilterManager {
297
public:
298
122606
  virtual ~FilterManager() = default;
299

            
300
  /**
301
   * Add a write filter to the connection. Filters are invoked in LIFO order (the last added
302
   * filter is called first).
303
   */
304
  virtual void addWriteFilter(WriteFilterSharedPtr filter) PURE;
305

            
306
  /**
307
   * Add a combination filter to the connection. Equivalent to calling both addWriteFilter()
308
   * and addReadFilter() with the same filter instance.
309
   */
310
  virtual void addFilter(FilterSharedPtr filter) PURE;
311

            
312
  /**
313
   * Add a read filter to the connection. Filters are invoked in FIFO order (the filter added
314
   * first is called first).
315
   */
316
  virtual void addReadFilter(ReadFilterSharedPtr filter) PURE;
317

            
318
  /**
319
   * Remove a read filter from the connection.
320
   */
321
  virtual void removeReadFilter(ReadFilterSharedPtr filter) PURE;
322

            
323
  /**
324
   * Initialize all of the installed read filters. This effectively calls onNewConnection() on
325
   * each of them.
326
   * @return true if read filters were initialized successfully, otherwise false.
327
   */
328
  virtual bool initializeReadFilters() PURE;
329

            
330
  /**
331
   * Add a network access log handler to the connection. The added log handlers will be called on
332
   * during connections' destruction.
333
   * @param handler supplies the access log handler to add.
334
   */
335
  virtual void addAccessLogHandler(AccessLog::InstanceSharedPtr handler) PURE;
336
};
337

            
338
/**
339
 * This function is used to wrap the creation of a network filter chain for new connections as
340
 * they come in. Filter factories create the lambda at configuration initialization time, and then
341
 * they are used at runtime.
342
 * @param filter_manager supplies the filter manager for the connection to install filters
343
 * to. Typically the function will install a single filter, but it's technically possibly to
344
 * install more than one if desired.
345
 */
346
using FilterFactoryCb = std::function<void(FilterManager& filter_manager)>;
347

            
348
/**
349
 * Callbacks used by individual listener filter instances to communicate with the listener filter
350
 * manager.
351
 */
352
class ListenerFilterCallbacks {
353
public:
354
57613
  virtual ~ListenerFilterCallbacks() = default;
355

            
356
  /**
357
   * @return ConnectionSocket the socket the filter is operating on.
358
   */
359
  virtual ConnectionSocket& socket() PURE;
360

            
361
  /**
362
   * @param name the namespace used in the metadata in reverse DNS format, for example:
363
   * envoy.test.my_filter.
364
   * @param value the struct to set on the namespace. A merge will be performed with new values for
365
   * the same key overriding existing.
366
   */
367
  virtual void setDynamicMetadata(const std::string& name, const Protobuf::Struct& value) PURE;
368

            
369
  /**
370
   * @param name the namespace used in the metadata in reverse DNS format, for example:
371
   * envoy.test.my_filter.
372
   * @param value of type protobuf any to set on the namespace. A merge will be performed with new
373
   * values for the same key overriding existing.
374
   */
375
  virtual void setDynamicTypedMetadata(const std::string& name, const Protobuf::Any& value) PURE;
376

            
377
  /**
378
   * @return const envoy::config::core::v3::Metadata& the dynamic metadata associated with this
379
   * connection.
380
   */
381
  virtual envoy::config::core::v3::Metadata& dynamicMetadata() PURE;
382
  virtual const envoy::config::core::v3::Metadata& dynamicMetadata() const PURE;
383

            
384
  /**
385
   * @return Object on which filters can share data on a per-request basis.
386
   */
387
  virtual StreamInfo::FilterState& filterState() PURE;
388

            
389
  /**
390
   * @return the Dispatcher for issuing events.
391
   */
392
  virtual Event::Dispatcher& dispatcher() PURE;
393

            
394
  /**
395
   * If a filter returned `FilterStatus::ContinueIteration`, `continueFilterChain(true)`
396
   * should be called to continue the filter chain iteration. Or `continueFilterChain(false)`
397
   * should be called if the filter returned `FilterStatus::StopIteration` and closed
398
   * the socket.
399
   * @param success boolean telling whether the filter execution was successful or not.
400
   */
401
  virtual void continueFilterChain(bool success) PURE;
402

            
403
  /**
404
   * Overwrite the default use original dst setting for current connection. This allows the
405
   * listener filter to control whether the connection should be forwarded to other listeners
406
   * based on the original destination address or not.
407
   * @param use_original_dst whether to use original destination address or not.
408
   */
409
  virtual void useOriginalDst(bool use_original_dst) PURE;
410

            
411
  /**
412
   * Return the connection level stream info interface.
413
   */
414
  virtual StreamInfo::StreamInfo& streamInfo() PURE;
415
};
416

            
417
/**
418
 *  Interface for a listener filter matching with incoming traffic.
419
 */
420
class ListenerFilterMatcher {
421
public:
422
129
  virtual ~ListenerFilterMatcher() = default;
423
  virtual bool matches(Network::ListenerFilterCallbacks& cb) const PURE;
424
};
425
using ListenerFilterMatcherPtr = std::unique_ptr<ListenerFilterMatcher>;
426
using ListenerFilterMatcherSharedPtr = std::shared_ptr<ListenerFilterMatcher>;
427

            
428
/**
429
 * TCP Listener Filter
430
 */
431
class ListenerFilter {
432
public:
433
1347
  virtual ~ListenerFilter() = default;
434

            
435
  /**
436
   * Called when a new connection is accepted, but before a Connection is created.
437
   * Filter chain iteration can be stopped if need more data from the connection
438
   * by returning `FilterStatus::StopIteration`, or continue the filter chain iteration
439
   * by returning `FilterStatus::ContinueIteration`. Reject the connection by closing
440
   * the socket and returning `FilterStatus::StopIteration`.
441
   * @param cb the callbacks the filter instance can use to communicate with the filter chain.
442
   * @return status used by the filter manager to manage further filter iteration.
443
   */
444
  virtual FilterStatus onAccept(ListenerFilterCallbacks& cb) PURE;
445

            
446
  /**
447
   * Called when data is read from the connection. If the filter doesn't get
448
   * enough data, filter chain iteration can be stopped if needed by returning
449
   * `FilterStatus::StopIteration`. Or continue the filter chain iteration by returning
450
   * `FilterStatus::ContinueIteration` if the filter get enough data. Reject the connection
451
   * by closing the socket and returning `FilterStatus::StopIteration`.
452
   * @param buffer the buffer of data.
453
   * @return status used by the filter manager to manage further filter iteration.
454
   */
455
  virtual FilterStatus onData(Network::ListenerFilterBuffer& buffer) PURE;
456

            
457
  /**
458
   * Called when the connection is closed. Only the current filter that has stopped filter
459
   * chain iteration will get the callback.
460
   */
461
9
  virtual void onClose() {};
462

            
463
  /**
464
   * Return the size of data the filter want to inspect from the connection.
465
   * The size can be increased after filter need to inspect more data.
466
   * @return maximum number of bytes of the data consumed by the filter. 0 means filter does not
467
   * need any data.
468
   */
469
  virtual size_t maxReadBytes() const PURE;
470
};
471

            
472
using ListenerFilterPtr = std::unique_ptr<ListenerFilter>;
473

            
474
/**
475
 * Interface for filter callbacks and adding listener filters to a manager.
476
 */
477
class ListenerFilterManager {
478
public:
479
54197
  virtual ~ListenerFilterManager() = default;
480

            
481
  /**
482
   * Add a filter to the listener. Filters are invoked in FIFO order (the filter added
483
   * first is called first).
484
   * @param listener_filter_matcher supplies the matcher to decide when filter is enabled.
485
   * @param filter supplies the filter being added.
486
   */
487
  virtual void addAcceptFilter(const ListenerFilterMatcherSharedPtr& listener_filter_matcher,
488
                               ListenerFilterPtr&& filter) PURE;
489
};
490

            
491
/**
492
 * This function is used to wrap the creation of a listener filter chain for new sockets as they are
493
 * created. Filter factories create the lambda at configuration initialization time, and then they
494
 * are used at runtime.
495
 * @param filter_manager supplies the filter manager for the listener to install filters to.
496
 * Typically the function will install a single filter, but it's technically possibly to install
497
 * more than one if desired.
498
 */
499
using ListenerFilterFactoryCb = std::function<void(ListenerFilterManager& filter_manager)>;
500

            
501
/**
502
 * QUIC Listener Filter
503
 */
504
class QuicListenerFilter {
505
public:
506
34
  virtual ~QuicListenerFilter() = default;
507

            
508
  /**
509
   * Called when a new connection is accepted, but before a Connection is created.
510
   * Filter chain iteration can be terminated if the cb shouldn't be accessed any more
511
   * by returning `FilterStatus::StopIteration`, or continue the filter chain iteration
512
   * by returning `FilterStatus::ContinueIteration`. Reject the connection by closing
513
   * the socket and returning `FilterStatus::StopIteration`. If `FilterStatus::StopIteration` is
514
   * returned, following filters' onAccept() will be skipped, but the connection creation is not
515
   * going to be paused. If the connection socket is closed upon connection creation, the connection
516
   * will be closed immediately.
517
   * @param cb the callbacks the filter instance can use to communicate with the filter chain.
518
   * @param server_preferred_addresses the server's preferred addresses to be advertised.
519
   * @return status used by the filter manager to manage further filter iteration.
520
   */
521
  virtual FilterStatus onAccept(ListenerFilterCallbacks& cb) PURE;
522

            
523
  /**
524
   * Called before connection creation.
525
   * @return false if the given preferred address is incomplatible with this filter and the listener
526
   * shouldn't advertise the given preferred address. I.e. onAccept() would have behaved differently
527
   * if the connection socket's destination address were the preferred address.
528
   */
529
  virtual bool isCompatibleWithServerPreferredAddress(
530
      const quiche::QuicheSocketAddress& server_preferred_address) const PURE;
531

            
532
  /**
533
   * Called after the peer has migrated to a different address. Check if the connection
534
   * migration is compatible with this listener filter. If not, close the connection and return
535
   * `FilterStatus::StopIteration`. An alternative approach is to disable active migration on the
536
   * given connection during connection creation. But peer address change is inevitable given NAT
537
   * rebinding is more frequent than TCP, and such passive address change is indistinguishable from
538
   * active migration. So there is no way to completely disable connection migration. disable client
539
   * connection migration.
540
   * @param new_address the address the peer has migrated to.
541
   * @param connection the connection just migrated.
542
   * @return status used by the filter manager to manage further filter iteration.
543
   */
544
  virtual FilterStatus onPeerAddressChanged(const quiche::QuicheSocketAddress& new_address,
545
                                            Connection& connection) PURE;
546

            
547
  /**
548
   * Called when the QUIC server session processes its first packet.
549
   * @param packet the received packet.
550
   * @return status used by the filter manager to manage further filter iteration.
551
   */
552
  virtual FilterStatus onFirstPacketReceived(const quic::QuicReceivedPacket&) PURE;
553
};
554

            
555
using QuicListenerFilterPtr = std::unique_ptr<QuicListenerFilter>;
556

            
557
/**
558
 * Interface for filter callbacks and adding listener filters to a manager.
559
 */
560
class QuicListenerFilterManager {
561
public:
562
2975
  virtual ~QuicListenerFilterManager() = default;
563

            
564
  /**
565
   * Add a filter to the listener. Filters are invoked in FIFO order (the filter added
566
   * first is called first).
567
   * @param listener_filter_matcher supplies the matcher to decide when filter is enabled.
568
   * @param filter supplies the filter being added.
569
   */
570
  virtual void addFilter(const ListenerFilterMatcherSharedPtr& listener_filter_matcher,
571
                         QuicListenerFilterPtr&& filter) PURE;
572

            
573
  virtual bool shouldAdvertiseServerPreferredAddress(
574
      const quiche::QuicheSocketAddress& server_preferred_address) const PURE;
575

            
576
  virtual void onPeerAddressChanged(const quiche::QuicheSocketAddress& new_address,
577
                                    Connection& connection) PURE;
578
  virtual void onFirstPacketReceived(const quic::QuicReceivedPacket&) PURE;
579
};
580

            
581
/**
582
 * This function is used to wrap the creation of a QUIC listener filter chain for new connections.
583
 * Filter factories create the lambda at configuration initialization time, and then they are used
584
 * at runtime.
585
 * @param filter_manager supplies the filter manager for the listener to install filters to.
586
 * Typically the function will install a single filter, but it's technically possibly to install
587
 * more than one if desired.
588
 */
589
using QuicListenerFilterFactoryCb = std::function<void(QuicListenerFilterManager& filter_manager)>;
590

            
591
template <class FactoryCb>
592
using FilterConfigProvider = Envoy::Config::ExtensionConfigProvider<FactoryCb>;
593

            
594
template <class FactoryCb>
595
using FilterConfigProviderPtr = std::unique_ptr<FilterConfigProvider<FactoryCb>>;
596

            
597
using NetworkFilterFactoriesList = std::vector<FilterConfigProviderPtr<FilterFactoryCb>>;
598

            
599
/**
600
 * Interface representing a single filter chain info.
601
 */
602
class FilterChainInfo {
603
public:
604
11729
  virtual ~FilterChainInfo() = default;
605

            
606
  /**
607
   * @return the name of this filter chain.
608
   */
609
  virtual absl::string_view name() const PURE;
610

            
611
  /**
612
   * @return the metadata of this filter chain.
613
   */
614
  virtual const envoy::config::core::v3::Metadata& metadata() const PURE;
615

            
616
  /**
617
   * @return the typed metadata provided in the config for this filter chain.
618
   */
619
  virtual const Envoy::Config::TypedMetadata& typedMetadata() const PURE;
620
};
621

            
622
using FilterChainInfoSharedPtr = std::shared_ptr<const FilterChainInfo>;
623

            
624
/**
625
 * Interface representing a single filter chain.
626
 */
627
class FilterChain {
628
public:
629
39891
  virtual ~FilterChain() = default;
630

            
631
  /**
632
   * @return const TransportSocketFactory& a transport socket factory to be used by the new
633
   * connection.
634
   */
635
  virtual const DownstreamTransportSocketFactory& transportSocketFactory() const PURE;
636

            
637
  /**
638
   * @return std::chrono::milliseconds the amount of time to wait for the transport socket to report
639
   * that a connection has been established. If the timeout is reached, the connection is closed. 0
640
   * specifies a disabled timeout.
641
   */
642
  virtual std::chrono::milliseconds transportSocketConnectTimeout() const PURE;
643

            
644
  /**
645
   * @return const Filter::NetworkFilterFactoriesList& a list of filter factory providers to be
646
   * used by the new connection.
647
   */
648
  virtual const NetworkFilterFactoriesList& networkFilterFactories() const PURE;
649

            
650
  /**
651
   * @return the name of this filter chain.
652
   */
653
  virtual absl::string_view name() const PURE;
654

            
655
  /**
656
   * @return true if this filter chain configuration was discovered by FCDS.
657
   */
658
  virtual bool addedViaApi() const PURE;
659

            
660
  /**
661
   * @return the filter chain info for this filter chain.
662
   */
663
  virtual const FilterChainInfoSharedPtr& filterChainInfo() const PURE;
664
};
665

            
666
using FilterChainSharedPtr = std::shared_ptr<FilterChain>;
667

            
668
/**
669
 * A filter chain that can be drained.
670
 */
671
class DrainableFilterChain : public FilterChain {
672
public:
673
  virtual void startDraining() PURE;
674
};
675

            
676
using DrainableFilterChainSharedPtr = std::shared_ptr<DrainableFilterChain>;
677

            
678
/**
679
 * Interface for searching through configured filter chains.
680
 */
681
class FilterChainManager {
682
public:
683
40018
  virtual ~FilterChainManager() = default;
684

            
685
  /**
686
   * Find filter chain that's matching metadata from the new connection.
687
   * @param socket supplies connection metadata that's going to be used for the filter chain lookup.
688
   * @param info supplies the dynamic metadata and the filter state populated by the listener
689
   * filters.
690
   * @return const FilterChain* filter chain to be used by the new connection,
691
   *         nullptr if no matching filter chain was found.
692
   */
693
  virtual const FilterChain* findFilterChain(const ConnectionSocket& socket,
694
                                             const StreamInfo::StreamInfo& info) const PURE;
695
};
696

            
697
/**
698
 * Callbacks used by individual UDP listener read filter instances to communicate with the filter
699
 * manager.
700
 */
701
class UdpReadFilterCallbacks {
702
public:
703
453
  virtual ~UdpReadFilterCallbacks() = default;
704

            
705
  /**
706
   * @return the udp listener that owns this read filter.
707
   */
708
  virtual UdpListener& udpListener() PURE;
709
};
710

            
711
/**
712
 * UDP Listener Read Filter
713
 */
714
class UdpListenerReadFilter {
715
public:
716
441
  virtual ~UdpListenerReadFilter() = default;
717

            
718
  /**
719
   * Called when a new data packet is received on a UDP listener.
720
   * @param data supplies the read data which may be modified.
721
   * @return status used by the filter manager to manage further filter iteration.
722
   */
723
  virtual FilterStatus onData(UdpRecvData& data) PURE;
724

            
725
  /**
726
   * Called when there is an error event in the receive data path.
727
   *
728
   * @param error_code supplies the received error on the listener.
729
   * @return status used by the filter manager to manage further filter iteration.
730
   */
731
  virtual FilterStatus onReceiveError(Api::IoError::IoErrorCode error_code) PURE;
732

            
733
protected:
734
  /**
735
   * @param callbacks supplies the read filter callbacks used to interact with the filter manager.
736
   */
737
441
  UdpListenerReadFilter(UdpReadFilterCallbacks& callbacks) : read_callbacks_(&callbacks) {}
738

            
739
  UdpReadFilterCallbacks* read_callbacks_{};
740
};
741

            
742
using UdpListenerReadFilterPtr = std::unique_ptr<UdpListenerReadFilter>;
743

            
744
/**
745
 * Interface for adding UDP listener filters to a manager.
746
 */
747
class UdpListenerFilterManager {
748
public:
749
294
  virtual ~UdpListenerFilterManager() = default;
750

            
751
  /**
752
   * Add a read filter to the udp listener. Filters are invoked in FIFO order (the
753
   * filter added first is called first).
754
   * @param filter supplies the filter being added.
755
   */
756
  virtual void addReadFilter(UdpListenerReadFilterPtr&& filter) PURE;
757
};
758

            
759
using UdpListenerFilterFactoryCb = std::function<void(
760
    UdpListenerFilterManager& udp_listener_filter_manager, UdpReadFilterCallbacks& callbacks)>;
761

            
762
/**
763
 * Common interface for UdpSessionReadFilterCallbacks and UdpSessionWriteFilterCallbacks.
764
 */
765
class UdpSessionFilterCallbacks {
766
public:
767
307
  virtual ~UdpSessionFilterCallbacks() = default;
768

            
769
  /**
770
   * @return uint64_t the ID of the originating UDP session.
771
   */
772
  virtual uint64_t sessionId() const PURE;
773

            
774
  /**
775
   * @return StreamInfo for logging purposes.
776
   */
777
  virtual StreamInfo::StreamInfo& streamInfo() PURE;
778

            
779
  /**
780
   * Allows a filter to inject a datagram to successive filters in the session filter chain.
781
   * The injected datagram will be iterated as a regular received datagram, and may also be
782
   * stopped by further filters. This can be used, for example, to continue processing previously
783
   * buffered datagrams by a filter after an asynchronous operation ended.
784
   */
785
  virtual void injectDatagramToFilterChain(Network::UdpRecvData& data) PURE;
786
};
787

            
788
class UdpSessionReadFilterCallbacks : public UdpSessionFilterCallbacks {
789
public:
790
179
  ~UdpSessionReadFilterCallbacks() override = default;
791

            
792
  /**
793
   * If a read filter stopped filter iteration, continueFilterChain() can be called to continue the
794
   * filter chain. It will have onNewSession() called if it was not previously called.
795
   * @return false if the session is removed and no longer valid, otherwise returns true.
796
   */
797
  virtual bool continueFilterChain() PURE;
798
};
799

            
800
class UdpSessionWriteFilterCallbacks : public UdpSessionFilterCallbacks {};
801

            
802
class UdpSessionFilterBase {
803
public:
804
187
  virtual ~UdpSessionFilterBase() = default;
805

            
806
  /**
807
   * This routine is called before the access log handlers' final log() is called. Filters can use
808
   * this callback to enrich the data passed in to the log handlers.
809
   */
810
268
  void onSessionComplete() {
811
268
    if (!on_session_complete_already_called_) {
812
158
      onSessionCompleteInternal();
813
158
      on_session_complete_already_called_ = true;
814
158
    }
815
268
  }
816

            
817
protected:
818
  /**
819
   * This routine is called by onSessionComplete to enrich the data passed in to the log handlers.
820
   */
821
90
  virtual void onSessionCompleteInternal() { ASSERT(!on_session_complete_already_called_); }
822

            
823
private:
824
  bool on_session_complete_already_called_{false};
825
};
826

            
827
/**
828
 * Return codes for read filter invocations.
829
 */
830
enum class UdpSessionReadFilterStatus {
831
  // Continue to further session filters.
832
  Continue,
833
  // Stop executing further session filters.
834
  StopIteration,
835
};
836

            
837
/**
838
 * Session read filter interface.
839
 */
840
class UdpSessionReadFilter : public virtual UdpSessionFilterBase {
841
public:
842
179
  ~UdpSessionReadFilter() override = default;
843

            
844
  /**
845
   * Called when a new UDP session is first established. Filters should do one time long term
846
   * processing that needs to be done when a session is established. Filter chain iteration
847
   * can be stopped if needed.
848
   * @return status used by the filter manager to manage further filter iteration.
849
   */
850
  virtual UdpSessionReadFilterStatus onNewSession() PURE;
851

            
852
  /**
853
   * Called when UDP datagram is read and matches the session that manages the filter.
854
   * @param data supplies the read data which may be modified.
855
   * @return status used by the filter manager to manage further filter iteration.
856
   */
857
  virtual UdpSessionReadFilterStatus onData(Network::UdpRecvData& data) PURE;
858

            
859
  /**
860
   * Initializes the read filter callbacks used to interact with the filter manager. It will be
861
   * called by the filter manager a single time when the filter is first registered.
862
   *
863
   * IMPORTANT: No outbound networking or complex processing should be done in this function.
864
   *            That should be done in the context of onNewSession() if needed.
865
   *
866
   * @param callbacks supplies the callbacks.
867
   */
868
  virtual void initializeReadFilterCallbacks(UdpSessionReadFilterCallbacks& callbacks) PURE;
869
};
870

            
871
using UdpSessionReadFilterSharedPtr = std::shared_ptr<UdpSessionReadFilter>;
872

            
873
/**
874
 * Return codes for write filter invocations.
875
 */
876
enum class UdpSessionWriteFilterStatus {
877
  // Continue to further session filters.
878
  Continue,
879
  // Stop executing further session filters.
880
  StopIteration,
881
};
882

            
883
/**
884
 * Session write filter interface.
885
 */
886
class UdpSessionWriteFilter : public virtual UdpSessionFilterBase {
887
public:
888
128
  ~UdpSessionWriteFilter() override = default;
889

            
890
  /**
891
   * Called when data is to be written on the UDP session.
892
   * @param data supplies the buffer to be written which may be modified.
893
   * @return status used by the filter manager to manage further filter iteration.
894
   */
895
  virtual UdpSessionWriteFilterStatus onWrite(Network::UdpRecvData& data) PURE;
896

            
897
  /**
898
   * Initializes the write filter callbacks used to interact with the filter manager. It will be
899
   * called by the filter manager a single time when the filter is first registered.
900
   *
901
   * IMPORTANT: No outbound networking or complex processing should be done in this function.
902
   *            That should be done in the context of ReadFilter::onNewSession() if needed.
903
   *
904
   * @param callbacks supplies the callbacks.
905
   */
906
  virtual void initializeWriteFilterCallbacks(UdpSessionWriteFilterCallbacks& callbacks) PURE;
907
};
908

            
909
using UdpSessionWriteFilterSharedPtr = std::shared_ptr<UdpSessionWriteFilter>;
910

            
911
/**
912
 * A combination read and write filter. This allows a single filter instance to cover
913
 * both the read and write paths.
914
 */
915
class UdpSessionFilter : public virtual UdpSessionReadFilter,
916
                         public virtual UdpSessionWriteFilter {};
917
using UdpSessionFilterSharedPtr = std::shared_ptr<UdpSessionFilter>;
918

            
919
/**
920
 * These callbacks are provided by the UDP session manager to the factory so that the factory
921
 * can * build the filter chain in an application specific way.
922
 */
923
class UdpSessionFilterChainFactoryCallbacks {
924
public:
925
175
  virtual ~UdpSessionFilterChainFactoryCallbacks() = default;
926

            
927
  /**
928
   * Add a read filter that is used when reading UDP session data.
929
   * @param filter supplies the filter to add.
930
   */
931
  virtual void addReadFilter(UdpSessionReadFilterSharedPtr filter) PURE;
932

            
933
  /**
934
   * Add a write filter that is used when writing UDP session data.
935
   * @param filter supplies the filter to add.
936
   */
937
  virtual void addWriteFilter(UdpSessionWriteFilterSharedPtr filter) PURE;
938

            
939
  /**
940
   * Add a bidirectional filter that is used when reading and writing UDP session data.
941
   * @param filter supplies the filter to add.
942
   */
943
  virtual void addFilter(UdpSessionFilterSharedPtr filter) PURE;
944
};
945

            
946
/**
947
 * This function is used to wrap the creation of a UDP session filter chain for new sessions as they
948
 * come in. Filter factories create the function at configuration initialization time, and then
949
 * they are used at runtime.
950
 * @param callbacks supplies the callbacks for the stream to install filters to. Typically the
951
 * function will install a single filter, but it's technically possibly to install more than one
952
 * if desired.
953
 */
954
using UdpSessionFilterFactoryCb =
955
    std::function<void(UdpSessionFilterChainFactoryCallbacks& callbacks)>;
956

            
957
/**
958
 * A UdpSessionFilterChainFactory is used by a UDP session manager to create a UDP session filter
959
 * chain when a new session is created.
960
 */
961
class UdpSessionFilterChainFactory {
962
public:
963
166
  virtual ~UdpSessionFilterChainFactory() = default;
964

            
965
  /**
966
   * Called when a new UDP session is created.
967
   * @param callbacks supplies the "sink" that is used for actually creating the filter chain. @see
968
   *                  UdpSessionFilterChainFactoryCallbacks.
969
   * @return true if filter chain was created successfully. Otherwise false.
970
   */
971
  virtual bool createFilterChain(UdpSessionFilterChainFactoryCallbacks& callbacks) const PURE;
972
};
973

            
974
/**
975
 * Creates a chain of network filters for a new connection.
976
 */
977
class FilterChainFactory {
978
public:
979
40489
  virtual ~FilterChainFactory() = default;
980

            
981
  /**
982
   * Called to create the network filter chain.
983
   * @param connection supplies the connection to create the chain on.
984
   * @param filter_factories supplies a list of filter factories to create the chain from.
985
   * @return true if filter chain was created successfully. Otherwise
986
   *   false, e.g. filter chain is empty.
987
   */
988
  virtual bool createNetworkFilterChain(Connection& connection,
989
                                        const NetworkFilterFactoriesList& filter_factories) PURE;
990

            
991
  /**
992
   * Called to create the listener filter chain.
993
   * @param listener supplies the listener to create the chain on.
994
   * @return true if filter chain was created successfully. Otherwise false.
995
   */
996
  virtual bool createListenerFilterChain(ListenerFilterManager& listener) PURE;
997

            
998
  /**
999
   * Called to create a Udp Listener Filter Chain object
   *
   * @param udp_listener supplies the listener to create the chain on.
   * @param callbacks supplies the callbacks needed to create a filter.
   */
  virtual void createUdpListenerFilterChain(UdpListenerFilterManager& udp_listener,
                                            UdpReadFilterCallbacks& callbacks) PURE;
  /**
   * Called to create the QUIC listener filter chain.
   * @param manager supplies the filter manager to create the chain on.
   * @return true if filter chain was created successfully. Otherwise false.
   */
  virtual bool createQuicListenerFilterChain(QuicListenerFilterManager& manager) PURE;
};
/**
 * Network filter matching context data for unified matchers.
 */
class MatchingData {
public:
14559
  static absl::string_view name() { return "network"; }
7
  virtual ~MatchingData() = default;
  virtual const ConnectionSocket& socket() const PURE;
  virtual const StreamInfo::FilterState& filterState() const PURE;
  virtual const envoy::config::core::v3::Metadata& dynamicMetadata() const PURE;
90
  const ConnectionInfoProvider& connectionInfoProvider() const {
90
    return socket().connectionInfoProvider();
90
  }
45
  const Address::Instance& localAddress() const { return *connectionInfoProvider().localAddress(); }
15
  const Address::Instance& remoteAddress() const {
15
    return *connectionInfoProvider().remoteAddress();
15
  }
3
  Ssl::ConnectionInfoConstSharedPtr ssl() const { return connectionInfoProvider().sslConnection(); }
};
/**
 * UDP listener filter matching context data for unified matchers.
 */
class UdpMatchingData {
public:
6589
  static absl::string_view name() { return "network"; }
  virtual ~UdpMatchingData() = default;
  virtual const Address::Instance& localAddress() const PURE;
  virtual const Address::Instance& remoteAddress() const PURE;
};
} // namespace Network
} // namespace Envoy