From 06008a9337ca9444b8d208558b66fe2964ae9c05 Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Tue, 15 Dec 2020 22:16:59 +0000 Subject: [PATCH 1/8] stream info: cleanup address handling Consolidate all downstream address handling setting into a single function. Also remove duplicate setting in the connection handler. This should make this logic less error prone than it was previously. Fixes https://github.com/envoyproxy/envoy/issues/14133 Signed-off-by: Matt Klein --- include/envoy/network/connection.h | 24 +++---------------- include/envoy/network/listen_socket.h | 20 +++++++++------- include/envoy/network/socket.h | 20 ++++++++++------ include/envoy/stream_info/BUILD | 1 + include/envoy/stream_info/stream_info.h | 21 ++++++---------- source/common/http/conn_manager_impl.cc | 8 ++----- source/common/stream_info/stream_info_impl.h | 17 ++++++------- source/common/upstream/health_checker_impl.cc | 3 +-- source/common/upstream/health_checker_impl.h | 15 +++++++++++- .../network/dubbo_proxy/active_message.cc | 4 +--- .../network/thrift_proxy/conn_manager.h | 7 +----- source/server/connection_handler_impl.cc | 3 +-- source/server/connection_handler_impl.h | 3 --- test/common/grpc/BUILD | 1 + test/common/grpc/async_client_impl_test.cc | 6 +++-- .../grpc/google_async_client_impl_test.cc | 7 ++++-- test/common/stream_info/test_util.h | 16 +++++-------- test/common/tcp_proxy/tcp_proxy_test.cc | 11 +++------ .../grpc/http_grpc_access_log_impl_test.cc | 3 ++- test/mocks/stream_info/mocks.cc | 17 ++++++------- test/mocks/stream_info/mocks.h | 5 ++-- 21 files changed, 93 insertions(+), 119 deletions(-) diff --git a/include/envoy/network/connection.h b/include/envoy/network/connection.h index d3a1c649cda9..74f6277409da 100644 --- a/include/envoy/network/connection.h +++ b/include/envoy/network/connection.h @@ -73,7 +73,9 @@ enum class ConnectionCloseType { /** * An abstract raw connection. Free the connection or call close() to disconnect. */ -class Connection : public Event::DeferredDeletable, public FilterManager { +class Connection : public Event::DeferredDeletable, + public FilterManager, + public ConnectedSocketAddressProvider { public: enum class State { Open, Closing, Closed }; @@ -187,18 +189,6 @@ class Connection : public Event::DeferredDeletable, public FilterManager { */ virtual bool readEnabled() const PURE; - /** - * @return The address of the remote client. Note that this method will never return nullptr. - */ - virtual const Network::Address::InstanceConstSharedPtr& remoteAddress() const PURE; - - /** - * @return The address of the remote directly connected peer. Note that this method - * will never return nullptr. This address is not affected or modified by PROXY protocol - * or any other listener filter. - */ - virtual const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const PURE; - /** * Credentials of the peer of a socket as decided by SO_PEERCRED. */ @@ -223,14 +213,6 @@ class Connection : public Event::DeferredDeletable, public FilterManager { */ virtual absl::optional unixSocketPeerCredentials() const PURE; - /** - * @return the local address of the connection. For client connections, this is the origin - * address. For server connections, this is the local destination address. For server connections - * it can be different from the proxy address if the downstream connection has been redirected or - * the proxy is operating in transparent mode. Note that this method will never return nullptr. - */ - virtual const Network::Address::InstanceConstSharedPtr& localAddress() const PURE; - /** * Set the stats to update for various connection state changes. Note that for performance reasons * these stats are eventually consistent and may not always accurately represent the connection diff --git a/include/envoy/network/listen_socket.h b/include/envoy/network/listen_socket.h index e6f9cef2f20d..5099fe67bd79 100644 --- a/include/envoy/network/listen_socket.h +++ b/include/envoy/network/listen_socket.h @@ -19,16 +19,10 @@ namespace Envoy { namespace Network { /** - * A socket passed to a connection. For server connections this represents the accepted socket, and - * for client connections this represents the socket being connected to a remote address. - * - * TODO(jrajahalme): Hide internals (e.g., fd) from listener filters by providing callbacks filters - * may need (set/getsockopt(), peek(), recv(), etc.) + * Interface for providing a connected socket's remote addresses. */ -class ConnectionSocket : public virtual Socket { +class ConnectedSocketAddressProvider : public virtual SocketAddressProvider { public: - ~ConnectionSocket() override = default; - /** * @return the remote address of the socket. */ @@ -39,7 +33,17 @@ class ConnectionSocket : public virtual Socket { * connected peer, and cannot be modified by listener filters. */ virtual const Address::InstanceConstSharedPtr& directRemoteAddress() const PURE; +}; +/** + * A socket passed to a connection. For server connections this represents the accepted socket, and + * for client connections this represents the socket being connected to a remote address. + * + * TODO(jrajahalme): Hide internals (e.g., fd) from listener filters by providing callbacks filters + * may need (set/getsockopt(), peek(), recv(), etc.) + */ +class ConnectionSocket : public virtual Socket, public ConnectedSocketAddressProvider { +public: /** * Restores the local address of the socket. On accepted sockets the local address defaults to the * one at which the connection was received at, which is the same as the listener's address, if diff --git a/include/envoy/network/socket.h b/include/envoy/network/socket.h index 51a2f7304aec..bcb18107d769 100644 --- a/include/envoy/network/socket.h +++ b/include/envoy/network/socket.h @@ -43,21 +43,27 @@ struct SocketOptionName { Network::SocketOptionName(level, option, #level "/" #option) /** - * Base class for Sockets + * Interface for providing a socket's local address. */ -class Socket { +class SocketAddressProvider { public: - virtual ~Socket() = default; + virtual ~SocketAddressProvider() = default; /** - * Type of sockets supported. See man 2 socket for more details + * @return the local address of the socket. */ - enum class Type { Stream, Datagram }; + virtual const Address::InstanceConstSharedPtr& localAddress() const PURE; +}; +/** + * Base class for Sockets + */ +class Socket : public virtual SocketAddressProvider { +public: /** - * @return the local address of the socket. + * Type of sockets supported. See man 2 socket for more details */ - virtual const Address::InstanceConstSharedPtr& localAddress() const PURE; + enum class Type { Stream, Datagram }; /** * Set the local address of the socket. On accepted sockets the local address defaults to the diff --git a/include/envoy/stream_info/BUILD b/include/envoy/stream_info/BUILD index 40d9710e2184..ed5ab3e66014 100644 --- a/include/envoy/stream_info/BUILD +++ b/include/envoy/stream_info/BUILD @@ -18,6 +18,7 @@ envoy_cc_library( "//include/envoy/http:header_map_interface", "//include/envoy/http:protocol_interface", "//include/envoy/http:request_id_extension_interface", + "//include/envoy/network:listen_socket_interface", "//include/envoy/ssl:connection_interface", "//include/envoy/upstream:host_description_interface", "//source/common/common:assert_lib", diff --git a/include/envoy/stream_info/stream_info.h b/include/envoy/stream_info/stream_info.h index dc4a67973976..e017e8ee49b9 100644 --- a/include/envoy/stream_info/stream_info.h +++ b/include/envoy/stream_info/stream_info.h @@ -10,6 +10,7 @@ #include "envoy/http/header_map.h" #include "envoy/http/protocol.h" #include "envoy/http/request_id_extension.h" +#include "envoy/network/listen_socket.h" #include "envoy/ssl/connection.h" #include "envoy/stream_info/filter_state.h" #include "envoy/upstream/host_description.h" @@ -445,25 +446,11 @@ class StreamInfo { */ virtual void healthCheck(bool is_health_check) PURE; - /** - * @param downstream_local_address sets the local address of the downstream connection. Note that - * it can be different than the local address of the upstream connection. - */ - virtual void setDownstreamLocalAddress( - const Network::Address::InstanceConstSharedPtr& downstream_local_address) PURE; - /** * @return the downstream local address. Note that this will never be nullptr. */ virtual const Network::Address::InstanceConstSharedPtr& downstreamLocalAddress() const PURE; - /** - * @param downstream_direct_remote_address sets the direct physical address of downstream - * connection. - */ - virtual void setDownstreamDirectRemoteAddress( - const Network::Address::InstanceConstSharedPtr& downstream_direct_remote_address) PURE; - /** * @return the downstream directly connected address. This will never be nullptr. This is * equivalent to the address of the physical connection. @@ -484,6 +471,12 @@ class StreamInfo { */ virtual const Network::Address::InstanceConstSharedPtr& downstreamRemoteAddress() const PURE; + /** + * Set the stream's downstream addresses as a set. + */ + virtual void + setDownstreamAddresses(const Network::ConnectedSocketAddressProvider& address_provider) PURE; + /** * @param connection_info sets the downstream ssl connection. */ diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index fe435c3977e8..0c7d1af2d330 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -618,16 +618,12 @@ ConnectionManagerImpl::ActiveStream::ActiveStream(ConnectionManagerImpl& connect } else { connection_manager_.stats_.named_.downstream_rq_http1_total_.inc(); } - filter_manager_.streamInfo().setDownstreamLocalAddress( - connection_manager_.read_callbacks_->connection().localAddress()); - filter_manager_.streamInfo().setDownstreamDirectRemoteAddress( - connection_manager_.read_callbacks_->connection().directRemoteAddress()); // Initially, the downstream remote address is the source address of the // downstream connection. That can change later in the request's lifecycle, // based on XFF processing, but setting the downstream remote address here // prevents surprises for logging code in edge cases. - filter_manager_.streamInfo().setDownstreamRemoteAddress( - connection_manager_.read_callbacks_->connection().remoteAddress()); + filter_manager_.streamInfo().setDownstreamAddresses( + connection_manager_.read_callbacks_->connection()); filter_manager_.streamInfo().setDownstreamSslConnection( connection_manager_.read_callbacks_->connection().ssl()); diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index 1c0614d93cbf..bbed64eef74e 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -184,20 +184,10 @@ struct StreamInfoImpl : public StreamInfo { void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } - void setDownstreamLocalAddress( - const Network::Address::InstanceConstSharedPtr& downstream_local_address) override { - downstream_local_address_ = downstream_local_address; - } - const Network::Address::InstanceConstSharedPtr& downstreamLocalAddress() const override { return downstream_local_address_; } - void setDownstreamDirectRemoteAddress( - const Network::Address::InstanceConstSharedPtr& downstream_direct_remote_address) override { - downstream_direct_remote_address_ = downstream_direct_remote_address; - } - const Network::Address::InstanceConstSharedPtr& downstreamDirectRemoteAddress() const override { return downstream_direct_remote_address_; } @@ -211,6 +201,13 @@ struct StreamInfoImpl : public StreamInfo { return downstream_remote_address_; } + void + setDownstreamAddresses(const Network::ConnectedSocketAddressProvider& address_provider) override { + downstream_local_address_ = address_provider.localAddress(); + downstream_direct_remote_address_ = address_provider.directRemoteAddress(); + downstream_remote_address_ = address_provider.remoteAddress(); + } + void setDownstreamSslConnection(const Ssl::ConnectionInfoConstSharedPtr& connection_info) override { downstream_ssl_info_ = connection_info; diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index 47b3c551f006..a1ff5dd32c88 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -270,8 +270,7 @@ void HttpHealthCheckerImpl::HttpActiveHealthCheckSession::onInterval() { Router::FilterUtility::setUpstreamScheme( *request_headers, host_->transportSocketFactory().implementsSecureTransport()); StreamInfo::StreamInfoImpl stream_info(protocol_, parent_.dispatcher_.timeSource()); - stream_info.setDownstreamLocalAddress(local_address_); - stream_info.setDownstreamRemoteAddress(local_address_); + stream_info.setDownstreamAddresses(*this); stream_info.onUpstreamHostSelected(host_); parent_.request_headers_parser_->evaluateHeaders(*request_headers, stream_info); auto status = request_encoder->encodeHeaders(*request_headers, true); diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index 97976d14287a..1b940d339a10 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -6,6 +6,7 @@ #include "envoy/config/core/v3/health_check.pb.h" #include "envoy/data/core/v3/health_check_event.pb.h" #include "envoy/grpc/status.h" +#include "envoy/network/listen_socket.h" #include "envoy/type/v3/http.pb.h" #include "envoy/type/v3/range.pb.h" @@ -71,7 +72,8 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { private: struct HttpActiveHealthCheckSession : public ActiveHealthCheckSession, public Http::ResponseDecoder, - public Http::StreamCallbacks { + public Http::StreamCallbacks, + public Network::ConnectedSocketAddressProvider { HttpActiveHealthCheckSession(HttpHealthCheckerImpl& parent, const HostSharedPtr& host); ~HttpActiveHealthCheckSession() override; @@ -104,6 +106,17 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { void onAboveWriteBufferHighWatermark() override {} void onBelowWriteBufferLowWatermark() override {} + // Network::ConnectedSocketAddressProvider + const Network::Address::InstanceConstSharedPtr& localAddress() const override { + return local_address_; + } + const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const override { + return local_address_; + } + const Network::Address::InstanceConstSharedPtr& remoteAddress() const override { + return local_address_; + } + void onEvent(Network::ConnectionEvent event); class ConnectionCallbackImpl : public Network::ConnectionCallbacks { diff --git a/source/extensions/filters/network/dubbo_proxy/active_message.cc b/source/extensions/filters/network/dubbo_proxy/active_message.cc index d4af36ae17b1..3723578981ea 100644 --- a/source/extensions/filters/network/dubbo_proxy/active_message.cc +++ b/source/extensions/filters/network/dubbo_proxy/active_message.cc @@ -189,9 +189,7 @@ ActiveMessage::ActiveMessage(ConnectionManager& parent) stream_info_(parent.timeSystem()), pending_stream_decoded_(false), local_response_sent_(false) { parent_.stats().request_active_.inc(); - stream_info_.setDownstreamLocalAddress(parent_.connection().localAddress()); - stream_info_.setDownstreamRemoteAddress(parent_.connection().remoteAddress()); - stream_info_.setDownstreamDirectRemoteAddress(parent_.connection().directRemoteAddress()); + stream_info_.setDownstreamAddresses(parent_.connection()); } ActiveMessage::~ActiveMessage() { diff --git a/source/extensions/filters/network/thrift_proxy/conn_manager.h b/source/extensions/filters/network/thrift_proxy/conn_manager.h index 3fc0cf7b2f04..dcb0661f1b74 100644 --- a/source/extensions/filters/network/thrift_proxy/conn_manager.h +++ b/source/extensions/filters/network/thrift_proxy/conn_manager.h @@ -164,12 +164,7 @@ class ConnectionManager : public Network::ReadFilter, stream_info_(parent_.time_source_), local_response_sent_{false}, pending_transport_end_{ false} { parent_.stats_.request_active_.inc(); - - stream_info_.setDownstreamLocalAddress(parent_.read_callbacks_->connection().localAddress()); - stream_info_.setDownstreamRemoteAddress( - parent_.read_callbacks_->connection().remoteAddress()); - stream_info_.setDownstreamDirectRemoteAddress( - parent_.read_callbacks_->connection().directRemoteAddress()); + stream_info_.setDownstreamAddresses(parent_.read_callbacks_->connection()); } ~ActiveRpc() override { request_timer_->complete(); diff --git a/source/server/connection_handler_impl.cc b/source/server/connection_handler_impl.cc index 91b92f763ffc..393fb7f313a4 100644 --- a/source/server/connection_handler_impl.cc +++ b/source/server/connection_handler_impl.cc @@ -462,8 +462,7 @@ void ConnectionHandlerImpl::ActiveTcpListener::newConnection( Network::ConnectionSocketPtr&& socket, std::unique_ptr stream_info) { // Refresh addresses in case they are modified by listener filters, such as proxy protocol or // original_dst. - stream_info->setDownstreamLocalAddress(socket->localAddress()); - stream_info->setDownstreamRemoteAddress(socket->remoteAddress()); + stream_info->setDownstreamAddresses(*socket); // Find matching filter chain. const auto filter_chain = config_->filterChainManager().findFilterChain(*socket); diff --git a/source/server/connection_handler_impl.h b/source/server/connection_handler_impl.h index 66d317e8f10e..5c7fe20362c6 100644 --- a/source/server/connection_handler_impl.h +++ b/source/server/connection_handler_impl.h @@ -252,9 +252,6 @@ class ConnectionHandlerImpl : public Network::ConnectionHandler, listener_.parent_.dispatcher_.timeSource(), StreamInfo::FilterState::LifeSpan::Connection)) { listener_.stats_.downstream_pre_cx_active_.inc(); - stream_info_->setDownstreamLocalAddress(socket_->localAddress()); - stream_info_->setDownstreamRemoteAddress(socket_->remoteAddress()); - stream_info_->setDownstreamDirectRemoteAddress(socket_->directRemoteAddress()); } ~ActiveTcpSocket() override { accept_filters_.clear(); diff --git a/test/common/grpc/BUILD b/test/common/grpc/BUILD index 86752e0f318c..83ec4bc4380c 100644 --- a/test/common/grpc/BUILD +++ b/test/common/grpc/BUILD @@ -108,6 +108,7 @@ envoy_cc_test( "//source/common/stats:stats_lib", "//source/common/tracing:http_tracer_lib", "//test/mocks/grpc:grpc_mocks", + "//test/mocks/network:network_mocks", "//test/mocks/tracing:tracing_mocks", "//test/proto:helloworld_proto_cc_proto", "//test/test_common:test_time_lib", diff --git a/test/common/grpc/async_client_impl_test.cc b/test/common/grpc/async_client_impl_test.cc index 2305c706e5e5..df0775115369 100644 --- a/test/common/grpc/async_client_impl_test.cc +++ b/test/common/grpc/async_client_impl_test.cc @@ -128,9 +128,11 @@ TEST_F(EnvoyAsyncClientImplTest, MetadataIsInitialized) { .WillOnce(Invoke([&http_callbacks](Http::HeaderMap&, bool) { http_callbacks->onReset(); })); // Prepare the parent context of this call. + NiceMock socket; + socket.local_address_ = + std::make_shared(expected_downstream_local_address); StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem()}; - stream_info.setDownstreamLocalAddress( - std::make_shared(expected_downstream_local_address)); + stream_info.setDownstreamAddresses(socket); Http::AsyncClient::ParentContext parent_context{&stream_info}; Http::AsyncClient::StreamOptions stream_options; diff --git a/test/common/grpc/google_async_client_impl_test.cc b/test/common/grpc/google_async_client_impl_test.cc index 31e732d98d85..f41f26acc89d 100644 --- a/test/common/grpc/google_async_client_impl_test.cc +++ b/test/common/grpc/google_async_client_impl_test.cc @@ -9,6 +9,7 @@ #include "common/stream_info/stream_info_impl.h" #include "test/mocks/grpc/mocks.h" +#include "test/mocks/network/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/proto/helloworld.pb.h" #include "test/test_common/test_time.h" @@ -121,9 +122,11 @@ TEST_F(EnvoyGoogleAsyncClientImplTest, MetadataIsInitialized) { EXPECT_CALL(grpc_callbacks, onRemoteClose(Status::WellKnownGrpcStatus::Unavailable, "")); // Prepare the parent context of this call. + NiceMock socket; + socket.local_address_ = + std::make_shared(expected_downstream_local_address); StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem()}; - stream_info.setDownstreamLocalAddress( - std::make_shared(expected_downstream_local_address)); + stream_info.setDownstreamAddresses(socket); Http::AsyncClient::ParentContext parent_context{&stream_info}; Http::AsyncClient::StreamOptions stream_options; diff --git a/test/common/stream_info/test_util.h b/test/common/stream_info/test_util.h index 560b485e18c0..7b1853dd14e3 100644 --- a/test/common/stream_info/test_util.h +++ b/test/common/stream_info/test_util.h @@ -73,18 +73,9 @@ class TestStreamInfo : public StreamInfo::StreamInfo { } bool healthCheck() const override { return health_check_request_; } void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } - - void setDownstreamLocalAddress( - const Network::Address::InstanceConstSharedPtr& downstream_local_address) override { - downstream_local_address_ = downstream_local_address; - } const Network::Address::InstanceConstSharedPtr& downstreamLocalAddress() const override { return downstream_local_address_; } - void setDownstreamDirectRemoteAddress( - const Network::Address::InstanceConstSharedPtr& downstream_direct_remote_address) override { - downstream_direct_remote_address_ = downstream_direct_remote_address; - } const Network::Address::InstanceConstSharedPtr& downstreamDirectRemoteAddress() const override { return downstream_direct_remote_address_; } @@ -95,7 +86,12 @@ class TestStreamInfo : public StreamInfo::StreamInfo { const Network::Address::InstanceConstSharedPtr& downstreamRemoteAddress() const override { return downstream_remote_address_; } - + void + setDownstreamAddresses(const Network::ConnectedSocketAddressProvider& address_provider) override { + downstream_local_address_ = address_provider.localAddress(); + downstream_direct_remote_address_ = address_provider.directRemoteAddress(); + downstream_remote_address_ = address_provider.remoteAddress(); + } void setDownstreamSslConnection(const Ssl::ConnectionInfoConstSharedPtr& connection_info) override { downstream_connection_info_ = connection_info; diff --git a/test/common/tcp_proxy/tcp_proxy_test.cc b/test/common/tcp_proxy/tcp_proxy_test.cc index 540506dd97df..ac3bc5ae8f37 100644 --- a/test/common/tcp_proxy/tcp_proxy_test.cc +++ b/test/common/tcp_proxy/tcp_proxy_test.cc @@ -935,10 +935,8 @@ class TcpProxyTest : public testing::Test { filter_->initializeReadFilterCallbacks(filter_callbacks_); filter_callbacks_.connection_.streamInfo().setDownstreamSslConnection( filter_callbacks_.connection_.ssl()); - filter_callbacks_.connection_.streamInfo().setDownstreamLocalAddress( - filter_callbacks_.connection_.localAddress()); - filter_callbacks_.connection_.streamInfo().setDownstreamRemoteAddress( - filter_callbacks_.connection_.remoteAddress()); + filter_callbacks_.connection_.streamInfo().setDownstreamAddresses( + filter_callbacks_.connection_); EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection()); EXPECT_EQ(absl::optional(), filter_->computeHashKey()); @@ -1092,10 +1090,7 @@ TEST_F(TcpProxyTest, BadFactory) { filter_->initializeReadFilterCallbacks(filter_callbacks_); filter_callbacks_.connection_.streamInfo().setDownstreamSslConnection( filter_callbacks_.connection_.ssl()); - filter_callbacks_.connection_.streamInfo().setDownstreamLocalAddress( - filter_callbacks_.connection_.localAddress()); - filter_callbacks_.connection_.streamInfo().setDownstreamRemoteAddress( - filter_callbacks_.connection_.remoteAddress()); + filter_callbacks_.connection_.streamInfo().setDownstreamAddresses(filter_callbacks_.connection_); EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection()); } diff --git a/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc b/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc index 3c3301ba5f56..f465af9991c8 100644 --- a/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc +++ b/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc @@ -146,7 +146,8 @@ TEST_F(HttpGrpcAccessLogTest, Marshalling) { stream_info.start_time_ = SystemTime(1h); stream_info.start_time_monotonic_ = MonotonicTime(1h); stream_info.last_downstream_tx_byte_sent_ = 2ms; - stream_info.setDownstreamLocalAddress(std::make_shared("/foo")); + stream_info.downstream_local_address_ = + std::make_shared("/foo"); (*stream_info.metadata_.mutable_filter_metadata())["foo"] = ProtobufWkt::Struct(); stream_info.filter_state_->setData("string_accessor", std::make_unique("test_value"), diff --git a/test/mocks/stream_info/mocks.cc b/test/mocks/stream_info/mocks.cc index 8373bdeb3603..c51f5790b4ab 100644 --- a/test/mocks/stream_info/mocks.cc +++ b/test/mocks/stream_info/mocks.cc @@ -58,17 +58,7 @@ MockStreamInfo::MockStreamInfo() upstream_local_address_ = upstream_local_address; })); ON_CALL(*this, upstreamLocalAddress()).WillByDefault(ReturnRef(upstream_local_address_)); - ON_CALL(*this, setDownstreamLocalAddress(_)) - .WillByDefault( - Invoke([this](const Network::Address::InstanceConstSharedPtr& downstream_local_address) { - downstream_local_address_ = downstream_local_address; - })); ON_CALL(*this, downstreamLocalAddress()).WillByDefault(ReturnRef(downstream_local_address_)); - ON_CALL(*this, setDownstreamDirectRemoteAddress(_)) - .WillByDefault(Invoke( - [this](const Network::Address::InstanceConstSharedPtr& downstream_direct_remote_address) { - downstream_direct_remote_address_ = downstream_direct_remote_address; - })); ON_CALL(*this, downstreamDirectRemoteAddress()) .WillByDefault(ReturnRef(downstream_direct_remote_address_)); ON_CALL(*this, setDownstreamRemoteAddress(_)) @@ -76,6 +66,13 @@ MockStreamInfo::MockStreamInfo() Invoke([this](const Network::Address::InstanceConstSharedPtr& downstream_remote_address) { downstream_remote_address_ = downstream_remote_address; })); + ON_CALL(*this, setDownstreamAddresses(_)) + .WillByDefault( + Invoke([this](const Network::ConnectedSocketAddressProvider& address_provider) { + downstream_local_address_ = address_provider.localAddress(); + downstream_direct_remote_address_ = address_provider.directRemoteAddress(); + downstream_remote_address_ = address_provider.remoteAddress(); + })); ON_CALL(*this, downstreamRemoteAddress()).WillByDefault(ReturnRef(downstream_remote_address_)); ON_CALL(*this, setDownstreamSslConnection(_)) .WillByDefault(Invoke( diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index b02b849c2310..380178853687 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -2,6 +2,7 @@ #include "envoy/config/core/v3/base.pb.h" #include "envoy/http/request_id_extension.h" +#include "envoy/network/listen_socket.h" #include "envoy/stream_info/stream_info.h" #include "common/stream_info/filter_state_impl.h" @@ -63,15 +64,13 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, upstreamLocalAddress, (), (const)); MOCK_METHOD(bool, healthCheck, (), (const)); MOCK_METHOD(void, healthCheck, (bool is_health_check)); - MOCK_METHOD(void, setDownstreamLocalAddress, (const Network::Address::InstanceConstSharedPtr&)); MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, downstreamLocalAddress, (), (const)); - MOCK_METHOD(void, setDownstreamDirectRemoteAddress, - (const Network::Address::InstanceConstSharedPtr&)); MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, downstreamDirectRemoteAddress, (), (const)); MOCK_METHOD(void, setDownstreamRemoteAddress, (const Network::Address::InstanceConstSharedPtr&)); MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, downstreamRemoteAddress, (), (const)); + MOCK_METHOD(void, setDownstreamAddresses, (const Network::ConnectedSocketAddressProvider&)); MOCK_METHOD(void, setDownstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); MOCK_METHOD(Ssl::ConnectionInfoConstSharedPtr, downstreamSslConnection, (), (const)); MOCK_METHOD(void, setUpstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); From 1d66ada2fab41688f5ac948e2cade6ef04f59420 Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Fri, 18 Dec 2020 00:32:24 +0000 Subject: [PATCH 2/8] comments Signed-off-by: Matt Klein --- include/envoy/network/connection.h | 7 +- include/envoy/network/listen_socket.h | 42 +---------- include/envoy/network/socket.h | 73 ++++++++++++++++--- include/envoy/stream_info/BUILD | 2 +- include/envoy/stream_info/stream_info.h | 10 +-- source/common/http/http1/codec_impl.cc | 2 +- source/common/http/http2/codec_impl.h | 2 +- source/common/network/connection_impl.h | 10 +-- source/common/network/listen_socket_impl.h | 29 ++------ source/common/network/socket_impl.cc | 23 +++--- source/common/network/socket_impl.h | 41 +++++++++-- source/common/network/tcp_listener_impl.cc | 2 +- source/common/network/utility.cc | 4 +- source/common/stream_info/stream_info_impl.h | 27 +++---- .../proxy_protocol/proxy_protocol_header.cc | 4 +- test/test_common/network_utility.cc | 12 +-- 16 files changed, 152 insertions(+), 138 deletions(-) diff --git a/include/envoy/network/connection.h b/include/envoy/network/connection.h index 74f6277409da..62b4012f3cba 100644 --- a/include/envoy/network/connection.h +++ b/include/envoy/network/connection.h @@ -73,9 +73,7 @@ enum class ConnectionCloseType { /** * An abstract raw connection. Free the connection or call close() to disconnect. */ -class Connection : public Event::DeferredDeletable, - public FilterManager, - public ConnectedSocketAddressProvider { +class Connection : public Event::DeferredDeletable, public FilterManager { public: enum class State { Open, Closing, Closed }; @@ -189,6 +187,9 @@ class Connection : public Event::DeferredDeletable, */ virtual bool readEnabled() const PURE; + // fixfix + virtual SocketAddressProviderConstSharedPtr addressProvider() const PURE; + /** * Credentials of the peer of a socket as decided by SO_PEERCRED. */ diff --git a/include/envoy/network/listen_socket.h b/include/envoy/network/listen_socket.h index 5099fe67bd79..a4d7f4be6bfe 100644 --- a/include/envoy/network/listen_socket.h +++ b/include/envoy/network/listen_socket.h @@ -18,23 +18,6 @@ namespace Envoy { namespace Network { -/** - * Interface for providing a connected socket's remote addresses. - */ -class ConnectedSocketAddressProvider : public virtual SocketAddressProvider { -public: - /** - * @return the remote address of the socket. - */ - virtual const Address::InstanceConstSharedPtr& remoteAddress() const PURE; - - /** - * @return the direct remote address of the socket. This is the address of the directly - * connected peer, and cannot be modified by listener filters. - */ - virtual const Address::InstanceConstSharedPtr& directRemoteAddress() const PURE; -}; - /** * A socket passed to a connection. For server connections this represents the accepted socket, and * for client connections this represents the socket being connected to a remote address. @@ -42,31 +25,8 @@ class ConnectedSocketAddressProvider : public virtual SocketAddressProvider { * TODO(jrajahalme): Hide internals (e.g., fd) from listener filters by providing callbacks filters * may need (set/getsockopt(), peek(), recv(), etc.) */ -class ConnectionSocket : public virtual Socket, public ConnectedSocketAddressProvider { +class ConnectionSocket : public virtual Socket { public: - /** - * Restores the local address of the socket. On accepted sockets the local address defaults to the - * one at which the connection was received at, which is the same as the listener's address, if - * the listener is bound to a specific address. Call this to restore the address to a value - * different from the one the socket was initially accepted at. This should only be called when - * restoring the original destination address of a connection redirected by iptables REDIRECT. The - * caller is responsible for making sure the new address is actually different. - * - * @param local_address the new local address. - */ - virtual void restoreLocalAddress(const Address::InstanceConstSharedPtr& local_address) PURE; - - /** - * Set the remote address of the socket. - */ - virtual void setRemoteAddress(const Address::InstanceConstSharedPtr& remote_address) PURE; - - /** - * @return true if the local address has been restored to a value that is different from the - * address the socket was initially accepted at. - */ - virtual bool localAddressRestored() const PURE; - /** * Set detected transport protocol (e.g. RAW_BUFFER, TLS). */ diff --git a/include/envoy/network/socket.h b/include/envoy/network/socket.h index bcb18107d769..31de390c5605 100644 --- a/include/envoy/network/socket.h +++ b/include/envoy/network/socket.h @@ -53,26 +53,79 @@ class SocketAddressProvider { * @return the local address of the socket. */ virtual const Address::InstanceConstSharedPtr& localAddress() const PURE; + + /** + * Set the local address of the socket. On accepted sockets the local address defaults to the + * one at which the connection was received at, which is the same as the listener's address, if + * the listener is bound to a specific address. + * + * @param local_address the new local address. + */ + virtual void setLocalAddress(const Address::InstanceConstSharedPtr& local_address) PURE; + + /** + * Restores the local address of the socket. On accepted sockets the local address defaults to the + * one at which the connection was received at, which is the same as the listener's address, if + * the listener is bound to a specific address. Call this to restore the address to a value + * different from the one the socket was initially accepted at. This should only be called when + * restoring the original destination address of a connection redirected by iptables REDIRECT. The + * caller is responsible for making sure the new address is actually different. + * + * @param local_address the new local address. + */ + virtual void restoreLocalAddress(const Address::InstanceConstSharedPtr& local_address) PURE; + + /** + * @return true if the local address has been restored to a value that is different from the + * address the socket was initially accepted at. + */ + virtual bool localAddressRestored() const PURE; + + /** + * @return the remote address of the socket. + */ + virtual const Address::InstanceConstSharedPtr& remoteAddress() const PURE; + + /** + * @return the direct remote address of the socket. This is the address of the directly + * connected peer, and cannot be modified by listener filters. + */ + virtual const Address::InstanceConstSharedPtr& directRemoteAddress() const PURE; + + /** + * Set the remote address of the socket. + */ + virtual void setRemoteAddress(const Address::InstanceConstSharedPtr& remote_address) PURE; + + /** + * @return the type (IP or pipe) of addresses used by the socket (subset of socket domain) + */ + virtual Address::Type addressType() const PURE; + + /** + * @return the IP version used by the socket if address type is IP, absl::nullopt otherwise + */ + virtual absl::optional ipVersion() const PURE; }; +using SocketAddressProviderSharedPtr = std::shared_ptr; +using SocketAddressProviderConstSharedPtr = std::shared_ptr; + /** * Base class for Sockets */ -class Socket : public virtual SocketAddressProvider { +class Socket { public: + virtual ~Socket() = default; + /** * Type of sockets supported. See man 2 socket for more details */ enum class Type { Stream, Datagram }; - /** - * Set the local address of the socket. On accepted sockets the local address defaults to the - * one at which the connection was received at, which is the same as the listener's address, if - * the listener is bound to a specific address. - * - * @param local_address the new local address. - */ - virtual void setLocalAddress(const Address::InstanceConstSharedPtr& local_address) PURE; + // fixfix + virtual SocketAddressProvider& addressProvider() PURE; + virtual SocketAddressProviderConstSharedPtr addressProvider() const PURE; /** * @return IoHandle for the underlying connection @@ -95,7 +148,7 @@ class Socket : public virtual SocketAddressProvider { */ virtual Socket::Type socketType() const PURE; - /** +/** * @return the type (IP or pipe) of addresses used by the socket (subset of socket domain) */ virtual Address::Type addressType() const PURE; diff --git a/include/envoy/stream_info/BUILD b/include/envoy/stream_info/BUILD index ed5ab3e66014..ff6df798b1d6 100644 --- a/include/envoy/stream_info/BUILD +++ b/include/envoy/stream_info/BUILD @@ -18,7 +18,7 @@ envoy_cc_library( "//include/envoy/http:header_map_interface", "//include/envoy/http:protocol_interface", "//include/envoy/http:request_id_extension_interface", - "//include/envoy/network:listen_socket_interface", + "//include/envoy/network:socket_interface", "//include/envoy/ssl:connection_interface", "//include/envoy/upstream:host_description_interface", "//source/common/common:assert_lib", diff --git a/include/envoy/stream_info/stream_info.h b/include/envoy/stream_info/stream_info.h index 7e40d08b2425..027554b11b54 100644 --- a/include/envoy/stream_info/stream_info.h +++ b/include/envoy/stream_info/stream_info.h @@ -10,7 +10,7 @@ #include "envoy/http/header_map.h" #include "envoy/http/protocol.h" #include "envoy/http/request_id_extension.h" -#include "envoy/network/listen_socket.h" +#include "envoy/network/socket.h" #include "envoy/ssl/connection.h" #include "envoy/stream_info/filter_state.h" #include "envoy/upstream/host_description.h" @@ -463,12 +463,6 @@ class StreamInfo { virtual const Network::Address::InstanceConstSharedPtr& downstreamDirectRemoteAddress() const PURE; - /** - * @param downstream_remote_address sets the remote address of downstream connection. - */ - virtual void setDownstreamRemoteAddress( - const Network::Address::InstanceConstSharedPtr& downstream_remote_address) PURE; - /** * @return the downstream remote address. Note that this will never be nullptr. This may be * equivalent to downstreamDirectRemoteAddress, unless the remote address is inferred from a @@ -480,7 +474,7 @@ class StreamInfo { * Set the stream's downstream addresses as a set. */ virtual void - setDownstreamAddresses(const Network::ConnectedSocketAddressProvider& address_provider) PURE; + setDownstreamAddresses(const Network::SocketAddressProviderConstSharedPtr& address_provider) PURE; /** * @param connection_info sets the downstream ssl connection. diff --git a/source/common/http/http1/codec_impl.cc b/source/common/http/http1/codec_impl.cc index 0e8a38eb0fce..5d8817838b8d 100644 --- a/source/common/http/http1/codec_impl.cc +++ b/source/common/http/http1/codec_impl.cc @@ -332,7 +332,7 @@ void StreamEncoderImpl::readDisable(bool disable) { uint32_t StreamEncoderImpl::bufferLimit() { return connection_.bufferLimit(); } const Network::Address::InstanceConstSharedPtr& StreamEncoderImpl::connectionLocalAddress() { - return connection_.connection().localAddress(); + return connection_.connection().addressProvider()->localAddress(); } static const char RESPONSE_PREFIX[] = "HTTP/1.1 "; diff --git a/source/common/http/http2/codec_impl.h b/source/common/http/http2/codec_impl.h index 7fed071a8063..2c481fd2d6e2 100644 --- a/source/common/http/http2/codec_impl.h +++ b/source/common/http/http2/codec_impl.h @@ -219,7 +219,7 @@ class ConnectionImpl : public virtual Connection, protected Logger::LoggablelocalAddress(); } absl::string_view responseDetails() override { return details_; } void setFlushTimeout(std::chrono::milliseconds timeout) override { diff --git a/source/common/network/connection_impl.h b/source/common/network/connection_impl.h index c7b630c4dec7..a3cd69798817 100644 --- a/source/common/network/connection_impl.h +++ b/source/common/network/connection_impl.h @@ -68,14 +68,8 @@ class ConnectionImpl : public ConnectionImplBase, public TransportSocketCallback void readDisable(bool disable) override; void detectEarlyCloseWhenReadDisabled(bool value) override { detect_early_close_ = value; } bool readEnabled() const override; - const Address::InstanceConstSharedPtr& remoteAddress() const override { - return socket_->remoteAddress(); - } - const Address::InstanceConstSharedPtr& directRemoteAddress() const override { - return socket_->directRemoteAddress(); - } - const Address::InstanceConstSharedPtr& localAddress() const override { - return socket_->localAddress(); + SocketAddressProviderConstSharedPtr addressProvider() const override { + return socket_->addressProvider(); } absl::optional unixSocketPeerCredentials() const override; Ssl::ConnectionInfoConstSharedPtr ssl() const override { return transport_socket_->ssl(); } diff --git a/source/common/network/listen_socket_impl.h b/source/common/network/listen_socket_impl.h index 4f2b92f40f1e..aa9f376354c4 100644 --- a/source/common/network/listen_socket_impl.h +++ b/source/common/network/listen_socket_impl.h @@ -19,11 +19,12 @@ namespace Network { class ListenSocketImpl : public SocketImpl { protected: ListenSocketImpl(IoHandlePtr&& io_handle, const Address::InstanceConstSharedPtr& local_address) - : SocketImpl(std::move(io_handle), local_address) {} + : SocketImpl(std::move(io_handle), local_address, nullptr) {} SocketPtr duplicate() override { // Using `new` to access a non-public constructor. - return absl::WrapUnique(new ListenSocketImpl(io_handle_->duplicate(), local_address_)); + return absl::WrapUnique( + new ListenSocketImpl(io_handle_->duplicate(), address_provider_->localAddress())); } void setupSocket(const Network::Socket::OptionsSharedPtr& options, bool bind_to_port); @@ -86,33 +87,18 @@ class ConnectionSocketImpl : public SocketImpl, public ConnectionSocket { ConnectionSocketImpl(IoHandlePtr&& io_handle, const Address::InstanceConstSharedPtr& local_address, const Address::InstanceConstSharedPtr& remote_address) - : SocketImpl(std::move(io_handle), local_address), remote_address_(remote_address), - direct_remote_address_(remote_address) {} + : SocketImpl(std::move(io_handle), local_address, remote_address) {} ConnectionSocketImpl(Socket::Type type, const Address::InstanceConstSharedPtr& local_address, const Address::InstanceConstSharedPtr& remote_address) - : SocketImpl(type, local_address), remote_address_(remote_address), - direct_remote_address_(remote_address) { - setLocalAddress(local_address); + : SocketImpl(type, local_address, remote_address) { + address_provider_->setLocalAddress(local_address); } // Network::Socket Socket::Type socketType() const override { return Socket::Type::Stream; } // Network::ConnectionSocket - const Address::InstanceConstSharedPtr& remoteAddress() const override { return remote_address_; } - const Address::InstanceConstSharedPtr& directRemoteAddress() const override { - return direct_remote_address_; - } - void restoreLocalAddress(const Address::InstanceConstSharedPtr& local_address) override { - setLocalAddress(local_address); - local_address_restored_ = true; - } - void setRemoteAddress(const Address::InstanceConstSharedPtr& remote_address) override { - remote_address_ = remote_address; - } - bool localAddressRestored() const override { return local_address_restored_; } - void setDetectedTransportProtocol(absl::string_view protocol) override { transport_protocol_ = std::string(protocol); } @@ -138,9 +124,6 @@ class ConnectionSocketImpl : public SocketImpl, public ConnectionSocket { } protected: - Address::InstanceConstSharedPtr remote_address_; - const Address::InstanceConstSharedPtr direct_remote_address_; - bool local_address_restored_{false}; std::string transport_protocol_; std::vector application_protocols_; std::string server_name_; diff --git a/source/common/network/socket_impl.cc b/source/common/network/socket_impl.cc index 05191ef4dd9a..56ef32bfb518 100644 --- a/source/common/network/socket_impl.cc +++ b/source/common/network/socket_impl.cc @@ -9,16 +9,19 @@ namespace Envoy { namespace Network { -SocketImpl::SocketImpl(Socket::Type sock_type, const Address::InstanceConstSharedPtr addr) - : io_handle_(ioHandleForAddr(sock_type, addr)), sock_type_(sock_type), - addr_type_(addr->type()) {} +SocketImpl::SocketImpl(Socket::Type sock_type, + const Address::InstanceConstSharedPtr& address_for_io_handle) + : io_handle_(ioHandleForAddr(sock_type, address_for_io_handle)), sock_type_(sock_type), + addr_type_(address_for_io_handle->type()), + address_provider_(std::make_shared(nullptr)) {} SocketImpl::SocketImpl(IoHandlePtr&& io_handle, const Address::InstanceConstSharedPtr& local_address) - : io_handle_(std::move(io_handle)), local_address_(local_address) { + : io_handle_(std::move(io_handle)), + address_provider_(std::make_shared(local_address)) { - if (local_address_ != nullptr) { - addr_type_ = local_address_->type(); + if (address_provider_->localAddress() != nullptr) { + addr_type_ = address_provider_->localAddress()->type(); return; } @@ -64,7 +67,7 @@ Api::SysCallIntResult SocketImpl::bind(Network::Address::InstanceConstSharedPtr bind_result = io_handle_->bind(address); if (bind_result.rc_ == 0 && address->ip()->port() == 0) { - local_address_ = io_handle_->localAddress(); + address_provider_->setLocalAddress(io_handle_->localAddress()); } return bind_result; } @@ -74,7 +77,7 @@ Api::SysCallIntResult SocketImpl::listen(int backlog) { return io_handle_->liste Api::SysCallIntResult SocketImpl::connect(const Network::Address::InstanceConstSharedPtr address) { auto result = io_handle_->connect(address); if (address->type() == Address::Type::Ip) { - local_address_ = io_handle_->localAddress(); + address_provider_->setLocalAddress(io_handle_->localAddress()); } return result; } @@ -96,8 +99,8 @@ Api::SysCallIntResult SocketImpl::setBlockingForTest(bool blocking) { absl::optional SocketImpl::ipVersion() const { if (addr_type_ == Address::Type::Ip) { // Always hit after socket is initialized, i.e., accepted or connected - if (local_address_ != nullptr) { - return local_address_->ip()->version(); + if (address_provider_->localAddress() != nullptr) { + return address_provider_->localAddress()->ip()->version(); } else { auto domain = io_handle_->domain(); if (!domain.has_value()) { diff --git a/source/common/network/socket_impl.h b/source/common/network/socket_impl.h index 065965a0cdda..23e942eeba23 100644 --- a/source/common/network/socket_impl.h +++ b/source/common/network/socket_impl.h @@ -7,16 +7,46 @@ namespace Envoy { namespace Network { -class SocketImpl : public virtual Socket { +class SocketAddressProviderImpl : public SocketAddressProvider { public: - SocketImpl(Socket::Type socket_type, const Address::InstanceConstSharedPtr addr); + SocketAddressProviderImpl(const Address::InstanceConstSharedPtr& local_address, + const Address::InstanceConstSharedPtr& remote_address) + : local_address_(local_address), remote_address_(remote_address), + direct_remote_address_(remote_address) {} - // Network::Socket + // fixfix const Address::InstanceConstSharedPtr& localAddress() const override { return local_address_; } void setLocalAddress(const Address::InstanceConstSharedPtr& local_address) override { local_address_ = local_address; } + void restoreLocalAddress(const Address::InstanceConstSharedPtr& local_address) override { + setLocalAddress(local_address); + local_address_restored_ = true; + } + bool localAddressRestored() const override { return local_address_restored_; } + const Address::InstanceConstSharedPtr& remoteAddress() const override { return remote_address_; } + void setRemoteAddress(const Address::InstanceConstSharedPtr& remote_address) override { + remote_address_ = remote_address; + } + const Address::InstanceConstSharedPtr& directRemoteAddress() const override { + return direct_remote_address_; + } +private: + Address::InstanceConstSharedPtr local_address_; + bool local_address_restored_{false}; + Address::InstanceConstSharedPtr remote_address_; + const Address::InstanceConstSharedPtr direct_remote_address_; +}; + +class SocketImpl : public virtual Socket { +public: + SocketImpl(Socket::Type socket_type, const Address::InstanceConstSharedPtr& address_for_io_handle, + const Address::InstanceConstSharedPtr& remote_address); + + // Network::Socket + SocketAddressProvider& addressProvider() override { return *address_provider_; } + SocketAddressProviderConstSharedPtr addressProvider() const override { return address_provider_; } SocketPtr duplicate() override { // Implementing the functionality here for all sockets is tricky because it leads // into object slicing issues. @@ -60,13 +90,14 @@ class SocketImpl : public virtual Socket { absl::optional ipVersion() const override; protected: - SocketImpl(IoHandlePtr&& io_handle, const Address::InstanceConstSharedPtr& local_address); + SocketImpl(IoHandlePtr&& io_handle, const Address::InstanceConstSharedPtr& local_address, + const Address::InstanceConstSharedPtr& remote_address); const IoHandlePtr io_handle_; - Address::InstanceConstSharedPtr local_address_; OptionsSharedPtr options_; Socket::Type sock_type_; Address::Type addr_type_; + const SocketAddressProviderSharedPtr address_provider_; }; } // namespace Network diff --git a/source/common/network/tcp_listener_impl.cc b/source/common/network/tcp_listener_impl.cc index 2cacbe309f7c..1d9b37b1a324 100644 --- a/source/common/network/tcp_listener_impl.cc +++ b/source/common/network/tcp_listener_impl.cc @@ -106,7 +106,7 @@ void TcpListenerImpl::setupServerSocket(Event::DispatcherImpl& dispatcher, Socke if (!Network::Socket::applyOptions(socket.options(), socket, envoy::config::core::v3::SocketOption::STATE_LISTENING)) { throw CreateListenerException(fmt::format("cannot set post-listen socket option on socket: {}", - socket.localAddress()->asString())); + socket.addressProvider().localAddress()->asString())); } } diff --git a/source/common/network/utility.cc b/source/common/network/utility.cc index 05a73a0ebf66..b18f08592393 100644 --- a/source/common/network/utility.cc +++ b/source/common/network/utility.cc @@ -277,11 +277,11 @@ bool Utility::isSameIpOrLoopback(const ConnectionSocket& socket) { // - Pipes // - Sockets to a loopback address // - Sockets where the local and remote address (ignoring port) are the same - const auto& remote_address = socket.remoteAddress(); + const auto& remote_address = socket.addressProvider()->remoteAddress(); if (remote_address->type() == Address::Type::Pipe || isLoopbackAddress(*remote_address)) { return true; } - const auto local_ip = socket.localAddress()->ip(); + const auto local_ip = socket.addressProvider()->localAddress()->ip(); const auto remote_ip = remote_address->ip(); if (remote_ip != nullptr && local_ip != nullptr && remote_ip->addressAsString() == local_ip->addressAsString()) { diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index a82dc4bbe1ce..516b494db7b1 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -7,6 +7,7 @@ #include "envoy/config/core/v3/base.pb.h" #include "envoy/http/header_map.h" #include "envoy/http/request_id_extension.h" +#include "envoy/network/socket.h" #include "envoy/stream_info/stream_info.h" #include "common/common/assert.h" @@ -187,27 +188,23 @@ struct StreamInfoImpl : public StreamInfo { void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } const Network::Address::InstanceConstSharedPtr& downstreamLocalAddress() const override { - return downstream_local_address_; + // fixfix null check. + return downstream_address_provider_->localAddress(); } const Network::Address::InstanceConstSharedPtr& downstreamDirectRemoteAddress() const override { - return downstream_direct_remote_address_; - } - - void setDownstreamRemoteAddress( - const Network::Address::InstanceConstSharedPtr& downstream_remote_address) override { - downstream_remote_address_ = downstream_remote_address; + // fixfix null check. + return downstream_address_provider_->directRemoteAddress(); } const Network::Address::InstanceConstSharedPtr& downstreamRemoteAddress() const override { - return downstream_remote_address_; + // fixfix null check. + return downstream_address_provider_->remoteAddress(); } - void - setDownstreamAddresses(const Network::ConnectedSocketAddressProvider& address_provider) override { - downstream_local_address_ = address_provider.localAddress(); - downstream_direct_remote_address_ = address_provider.directRemoteAddress(); - downstream_remote_address_ = address_provider.remoteAddress(); + void setDownstreamAddresses( + const Network::SocketAddressProviderConstSharedPtr& address_provider) override { + downstream_address_provider_ = address_provider; } void @@ -326,9 +323,7 @@ struct StreamInfoImpl : public StreamInfo { uint64_t bytes_received_{}; uint64_t bytes_sent_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; - Network::Address::InstanceConstSharedPtr downstream_local_address_; - Network::Address::InstanceConstSharedPtr downstream_direct_remote_address_; - Network::Address::InstanceConstSharedPtr downstream_remote_address_; + Network::SocketAddressProviderConstSharedPtr downstream_address_provider_; Ssl::ConnectionInfoConstSharedPtr downstream_ssl_info_; Ssl::ConnectionInfoConstSharedPtr upstream_ssl_info_; std::string requested_server_name_; diff --git a/source/extensions/common/proxy_protocol/proxy_protocol_header.cc b/source/extensions/common/proxy_protocol/proxy_protocol_header.cc index 0342f3d1aff3..139ebd500405 100644 --- a/source/extensions/common/proxy_protocol/proxy_protocol_header.cc +++ b/source/extensions/common/proxy_protocol/proxy_protocol_header.cc @@ -109,8 +109,8 @@ void generateV2Header(const Network::Address::Ip& source_address, void generateProxyProtoHeader(const envoy::config::core::v3::ProxyProtocolConfig& config, const Network::Connection& connection, Buffer::Instance& out) { - const Network::Address::Ip& dest_address = *connection.localAddress()->ip(); - const Network::Address::Ip& source_address = *connection.remoteAddress()->ip(); + const Network::Address::Ip& dest_address = *connection.addressProvider()->localAddress()->ip(); + const Network::Address::Ip& source_address = *connection.addressProvider()->remoteAddress()->ip(); if (config.version() == envoy::config::core::v3::ProxyProtocolConfig::V1) { generateV1Header(source_address, dest_address, out); } else if (config.version() == envoy::config::core::v3::ProxyProtocolConfig::V2) { diff --git a/test/test_common/network_utility.cc b/test/test_common/network_utility.cc index b0be174d9f04..17a9ebdc69bc 100644 --- a/test/test_common/network_utility.cc +++ b/test/test_common/network_utility.cc @@ -28,7 +28,7 @@ Address::InstanceConstSharedPtr findOrCheckFreePort(Address::InstanceConstShared << (addr_port == nullptr ? "nullptr" : addr_port->asString()); return nullptr; } - SocketImpl sock(type, addr_port); + SocketImpl sock(type, addr_port, nullptr); // Not setting REUSEADDR, therefore if the address has been recently used we won't reuse it here. // However, because we're going to use the address while checking if it is available, we'll need // to set REUSEADDR on listener sockets created by tests using an address validated by this means. @@ -57,7 +57,7 @@ Address::InstanceConstSharedPtr findOrCheckFreePort(Address::InstanceConstShared << ")"; return nullptr; } - return sock.localAddress(); + return sock.addressProvider().localAddress(); } Address::InstanceConstSharedPtr findOrCheckFreePort(const std::string& addr_port, @@ -164,7 +164,7 @@ std::string ipVersionToDnsFamily(Network::Address::IpVersion version) { std::pair bindFreeLoopbackPort(Address::IpVersion version, Socket::Type type, bool reuse_port) { Address::InstanceConstSharedPtr addr = getCanonicalLoopbackAddress(version); - SocketPtr sock = std::make_unique(type, addr); + SocketPtr sock = std::make_unique(type, addr, nullptr); if (reuse_port) { sock->addOptions(SocketOptionFactory::buildReusePortOptions()); Socket::applyOptions(sock->options(), *sock, @@ -179,7 +179,7 @@ bindFreeLoopbackPort(Address::IpVersion version, Socket::Type type, bool reuse_p throw EnvoyException(msg); } - return std::make_pair(sock->localAddress(), std::move(sock)); + return std::make_pair(sock->addressProvider().localAddress(), std::move(sock)); } TransportSocketPtr createRawBufferSocket() { return std::make_unique(); } @@ -235,8 +235,8 @@ void UdpSyncPeer::write(const std::string& buffer, const Network::Address::Insta void UdpSyncPeer::recv(Network::UdpRecvData& datagram) { if (received_datagrams_.empty()) { - const auto rc = Network::Test::readFromSocket(socket_->ioHandle(), *socket_->localAddress(), - received_datagrams_); + const auto rc = Network::Test::readFromSocket( + socket_->ioHandle(), *socket_->addressProvider().localAddress(), received_datagrams_); ASSERT_TRUE(rc.ok()); } datagram = std::move(received_datagrams_.front()); From 58f8d927fa02797f1da18d1126e358ab80973a7c Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Fri, 18 Dec 2020 19:59:35 +0000 Subject: [PATCH 3/8] more Signed-off-by: Matt Klein --- include/envoy/network/connection.h | 7 +--- include/envoy/network/socket.h | 13 +------ include/envoy/stream_info/stream_info.h | 24 +----------- .../formatter/substitution_formatter.cc | 14 +++---- source/common/http/async_client_impl.cc | 4 +- source/common/http/http1/codec_impl.cc | 2 +- source/common/http/http2/codec_impl.h | 2 +- source/common/network/base_listener_impl.cc | 4 +- source/common/network/connection_impl.cc | 11 +++--- source/common/network/connection_impl.h | 3 +- source/common/network/listen_socket_impl.cc | 11 +++--- source/common/network/socket_impl.cc | 11 ++++-- source/common/network/socket_impl.h | 5 ++- source/common/network/udp_listener_impl.cc | 10 +++-- source/common/network/utility.cc | 4 +- source/common/router/header_formatter.cc | 10 ++--- source/common/router/router.h | 6 ++- source/common/router/upstream_request.cc | 2 +- source/common/stream_info/stream_info_impl.h | 37 +++++++------------ source/common/tracing/http_tracer_impl.cc | 2 +- source/common/upstream/health_checker_impl.cc | 8 ++-- source/common/upstream/health_checker_impl.h | 18 ++------- .../common/upstream/original_dst_cluster.cc | 4 +- .../proxy_protocol/proxy_protocol_header.cc | 4 +- source/server/connection_handler_impl.cc | 3 -- test/common/network/connection_impl_test.cc | 5 ++- test/mocks/network/connection.cc | 21 ++++++----- test/mocks/network/connection.h | 7 +--- test/mocks/network/mocks.cc | 21 ++++++----- test/mocks/network/mocks.h | 21 +++++------ test/mocks/network/socket.h | 7 ++-- test/mocks/stream_info/mocks.cc | 25 +++---------- test/mocks/stream_info/mocks.h | 13 ++----- test/test_common/network_utility.h | 4 +- 34 files changed, 140 insertions(+), 203 deletions(-) diff --git a/include/envoy/network/connection.h b/include/envoy/network/connection.h index 62b4012f3cba..d082c679ec5c 100644 --- a/include/envoy/network/connection.h +++ b/include/envoy/network/connection.h @@ -188,7 +188,7 @@ class Connection : public Event::DeferredDeletable, public FilterManager { virtual bool readEnabled() const PURE; // fixfix - virtual SocketAddressProviderConstSharedPtr addressProvider() const PURE; + virtual const SocketAddressProvider& addressProvider() const PURE; /** * Credentials of the peer of a socket as decided by SO_PEERCRED. @@ -270,11 +270,6 @@ class Connection : public Event::DeferredDeletable, public FilterManager { */ virtual uint32_t bufferLimit() const PURE; - /** - * @return boolean telling if the connection's local address has been restored to an original - * destination address, rather than the address the connection was accepted at. - */ - virtual bool localAddressRestored() const PURE; /** * @return boolean telling if the connection is currently above the high watermark. diff --git a/include/envoy/network/socket.h b/include/envoy/network/socket.h index 31de390c5605..e0beff5445df 100644 --- a/include/envoy/network/socket.h +++ b/include/envoy/network/socket.h @@ -96,16 +96,6 @@ class SocketAddressProvider { * Set the remote address of the socket. */ virtual void setRemoteAddress(const Address::InstanceConstSharedPtr& remote_address) PURE; - - /** - * @return the type (IP or pipe) of addresses used by the socket (subset of socket domain) - */ - virtual Address::Type addressType() const PURE; - - /** - * @return the IP version used by the socket if address type is IP, absl::nullopt otherwise - */ - virtual absl::optional ipVersion() const PURE; }; using SocketAddressProviderSharedPtr = std::shared_ptr; @@ -125,7 +115,8 @@ class Socket { // fixfix virtual SocketAddressProvider& addressProvider() PURE; - virtual SocketAddressProviderConstSharedPtr addressProvider() const PURE; + virtual const SocketAddressProvider& addressProvider() const PURE; + virtual SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const PURE; /** * @return IoHandle for the underlying connection diff --git a/include/envoy/stream_info/stream_info.h b/include/envoy/stream_info/stream_info.h index 027554b11b54..a7fa8eaa06f2 100644 --- a/include/envoy/stream_info/stream_info.h +++ b/include/envoy/stream_info/stream_info.h @@ -452,29 +452,9 @@ class StreamInfo { virtual void healthCheck(bool is_health_check) PURE; /** - * @return the downstream local address. Note that this will never be nullptr. + * fixfix */ - virtual const Network::Address::InstanceConstSharedPtr& downstreamLocalAddress() const PURE; - - /** - * @return the downstream directly connected address. This will never be nullptr. This is - * equivalent to the address of the physical connection. - */ - virtual const Network::Address::InstanceConstSharedPtr& - downstreamDirectRemoteAddress() const PURE; - - /** - * @return the downstream remote address. Note that this will never be nullptr. This may be - * equivalent to downstreamDirectRemoteAddress, unless the remote address is inferred from a - * proxy proto, x-forwarded-for, etc. - */ - virtual const Network::Address::InstanceConstSharedPtr& downstreamRemoteAddress() const PURE; - - /** - * Set the stream's downstream addresses as a set. - */ - virtual void - setDownstreamAddresses(const Network::SocketAddressProviderConstSharedPtr& address_provider) PURE; + virtual const Network::SocketAddressProvider& downstreamAddressProvider() const PURE; /** * @param connection_info sets the downstream ssl connection. diff --git a/source/common/formatter/substitution_formatter.cc b/source/common/formatter/substitution_formatter.cc index fc6a92fa9995..9e1810b5873e 100644 --- a/source/common/formatter/substitution_formatter.cc +++ b/source/common/formatter/substitution_formatter.cc @@ -658,37 +658,37 @@ StreamInfoFormatter::StreamInfoFormatter(const std::string& field_name) { } else if (field_name == "DOWNSTREAM_LOCAL_ADDRESS") { field_extractor_ = StreamInfoAddressFieldExtractor::withPort([](const StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamLocalAddress(); + return stream_info.downstreamAddressProvider().localAddress(); }); } else if (field_name == "DOWNSTREAM_LOCAL_ADDRESS_WITHOUT_PORT") { field_extractor_ = StreamInfoAddressFieldExtractor::withoutPort( [](const Envoy::StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamLocalAddress(); + return stream_info.downstreamAddressProvider().localAddress(); }); } else if (field_name == "DOWNSTREAM_LOCAL_PORT") { field_extractor_ = StreamInfoAddressFieldExtractor::justPort( [](const Envoy::StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamLocalAddress(); + return stream_info.downstreamAddressProvider().localAddress(); }); } else if (field_name == "DOWNSTREAM_REMOTE_ADDRESS") { field_extractor_ = StreamInfoAddressFieldExtractor::withPort([](const StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamRemoteAddress(); + return stream_info.downstreamAddressProvider().remoteAddress(); }); } else if (field_name == "DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT") { field_extractor_ = StreamInfoAddressFieldExtractor::withoutPort([](const StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamRemoteAddress(); + return stream_info.downstreamAddressProvider().remoteAddress(); }); } else if (field_name == "DOWNSTREAM_DIRECT_REMOTE_ADDRESS") { field_extractor_ = StreamInfoAddressFieldExtractor::withPort([](const StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamDirectRemoteAddress(); + return stream_info.downstreamAddressProvider().directRemoteAddress(); }); } else if (field_name == "DOWNSTREAM_DIRECT_REMOTE_ADDRESS_WITHOUT_PORT") { field_extractor_ = StreamInfoAddressFieldExtractor::withoutPort([](const StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamDirectRemoteAddress(); + return stream_info.downstreamAddressProvider().directRemoteAddress(); }); } else if (field_name == "CONNECTION_ID") { field_extractor_ = std::make_unique( diff --git a/source/common/http/async_client_impl.cc b/source/common/http/async_client_impl.cc index 25e1e3704cd3..f2a35c3246d7 100644 --- a/source/common/http/async_client_impl.cc +++ b/source/common/http/async_client_impl.cc @@ -6,6 +6,7 @@ #include #include +#include "common/network/socket_impl.h" #include "envoy/config/core/v3/base.pb.h" #include "common/grpc/common.h" @@ -81,7 +82,8 @@ AsyncClient::Stream* AsyncClientImpl::start(AsyncClient::StreamCallbacks& callba AsyncStreamImpl::AsyncStreamImpl(AsyncClientImpl& parent, AsyncClient::StreamCallbacks& callbacks, const AsyncClient::StreamOptions& options) : parent_(parent), stream_callbacks_(callbacks), stream_id_(parent.config_.random_.random()), - router_(parent.config_), stream_info_(Protocol::Http11, parent.dispatcher().timeSource()), + router_(parent.config_), + stream_info_(Protocol::Http11, parent.dispatcher().timeSource(), nullptr), tracing_config_(Tracing::EgressConfig::get()), route_(std::make_shared(parent_.cluster_->name(), options.timeout, options.hash_policy)), diff --git a/source/common/http/http1/codec_impl.cc b/source/common/http/http1/codec_impl.cc index 5d8817838b8d..f0ce0cfb5f88 100644 --- a/source/common/http/http1/codec_impl.cc +++ b/source/common/http/http1/codec_impl.cc @@ -332,7 +332,7 @@ void StreamEncoderImpl::readDisable(bool disable) { uint32_t StreamEncoderImpl::bufferLimit() { return connection_.bufferLimit(); } const Network::Address::InstanceConstSharedPtr& StreamEncoderImpl::connectionLocalAddress() { - return connection_.connection().addressProvider()->localAddress(); + return connection_.connection().addressProvider().localAddress(); } static const char RESPONSE_PREFIX[] = "HTTP/1.1 "; diff --git a/source/common/http/http2/codec_impl.h b/source/common/http/http2/codec_impl.h index 2c481fd2d6e2..023c32c77e13 100644 --- a/source/common/http/http2/codec_impl.h +++ b/source/common/http/http2/codec_impl.h @@ -219,7 +219,7 @@ class ConnectionImpl : public virtual Connection, protected Logger::LoggablelocalAddress(); + return parent_.connection_.addressProvider().localAddress(); } absl::string_view responseDetails() override { return details_; } void setFlushTimeout(std::chrono::milliseconds timeout) override { diff --git a/source/common/network/base_listener_impl.cc b/source/common/network/base_listener_impl.cc index e1adf6b930ec..bd524c792154 100644 --- a/source/common/network/base_listener_impl.cc +++ b/source/common/network/base_listener_impl.cc @@ -17,12 +17,12 @@ namespace Network { BaseListenerImpl::BaseListenerImpl(Event::DispatcherImpl& dispatcher, SocketSharedPtr socket) : local_address_(nullptr), dispatcher_(dispatcher), socket_(std::move(socket)) { - const auto ip = socket_->localAddress()->ip(); + const auto ip = socket_->addressProvider().localAddress()->ip(); // Only use the listen socket's local address for new connections if it is not the all hosts // address (e.g., 0.0.0.0 for IPv4). if (!(ip && ip->isAnyAddress())) { - local_address_ = socket_->localAddress(); + local_address_ = socket_->addressProvider().localAddress(); } } diff --git a/source/common/network/connection_impl.cc b/source/common/network/connection_impl.cc index 53c79cefdd63..f812bffb4ac2 100644 --- a/source/common/network/connection_impl.cc +++ b/source/common/network/connection_impl.cc @@ -794,7 +794,7 @@ ClientConnectionImpl::ClientConnectionImpl( const Network::ConnectionSocket::OptionsSharedPtr& options) : ConnectionImpl(dispatcher, std::make_unique(remote_address, options), std::move(transport_socket), stream_info_, false), - stream_info_(dispatcher.timeSource()) { + stream_info_(dispatcher.timeSource(), socket_->addressProviderSharedPtr()) { // There are no meaningful socket options or source address semantics for // non-IP sockets, so skip. if (remote_address->ip() != nullptr) { @@ -810,8 +810,8 @@ ClientConnectionImpl::ClientConnectionImpl( const Network::Address::InstanceConstSharedPtr* source = &source_address; - if (socket_->localAddress()) { - source = &socket_->localAddress(); + if (socket_->addressProvider().localAddress()) { + source = &socket_->addressProvider().localAddress(); } if (*source != nullptr) { @@ -833,8 +833,9 @@ ClientConnectionImpl::ClientConnectionImpl( } void ClientConnectionImpl::connect() { - ENVOY_CONN_LOG(debug, "connecting to {}", *this, socket_->remoteAddress()->asString()); - const Api::SysCallIntResult result = socket_->connect(socket_->remoteAddress()); + ENVOY_CONN_LOG(debug, "connecting to {}", *this, + socket_->addressProvider().remoteAddress()->asString()); + const Api::SysCallIntResult result = socket_->connect(socket_->addressProvider().remoteAddress()); if (result.rc_ == 0) { // write will become ready. ASSERT(connecting_); diff --git a/source/common/network/connection_impl.h b/source/common/network/connection_impl.h index a3cd69798817..2a76afb9644f 100644 --- a/source/common/network/connection_impl.h +++ b/source/common/network/connection_impl.h @@ -68,7 +68,7 @@ class ConnectionImpl : public ConnectionImplBase, public TransportSocketCallback void readDisable(bool disable) override; void detectEarlyCloseWhenReadDisabled(bool value) override { detect_early_close_ = value; } bool readEnabled() const override; - SocketAddressProviderConstSharedPtr addressProvider() const override { + const SocketAddressProvider& addressProvider() const override { return socket_->addressProvider(); } absl::optional unixSocketPeerCredentials() const override; @@ -78,7 +78,6 @@ class ConnectionImpl : public ConnectionImplBase, public TransportSocketCallback void write(Buffer::Instance& data, bool end_stream) override; void setBufferLimits(uint32_t limit) override; uint32_t bufferLimit() const override { return read_buffer_limit_; } - bool localAddressRestored() const override { return socket_->localAddressRestored(); } bool aboveHighWatermark() const override { return write_buffer_above_high_watermark_; } const ConnectionSocket::OptionsSharedPtr& socketOptions() const override { return socket_->options(); diff --git a/source/common/network/listen_socket_impl.cc b/source/common/network/listen_socket_impl.cc index cba7fce24bc4..674cf456bce0 100644 --- a/source/common/network/listen_socket_impl.cc +++ b/source/common/network/listen_socket_impl.cc @@ -19,12 +19,13 @@ namespace Envoy { namespace Network { Api::SysCallIntResult ListenSocketImpl::bind(Network::Address::InstanceConstSharedPtr address) { - local_address_ = address; + address_provider_->setLocalAddress(address); - const Api::SysCallIntResult result = SocketImpl::bind(local_address_); + const Api::SysCallIntResult result = SocketImpl::bind(address_provider_->localAddress()); if (SOCKET_FAILURE(result.rc_)) { close(); - throw SocketBindException(fmt::format("cannot bind '{}': {}", local_address_->asString(), + throw SocketBindException(fmt::format("cannot bind '{}': {}", + address_provider_->localAddress()->asString(), errorDetails(result.errno_)), result.errno_); } @@ -43,7 +44,7 @@ void ListenSocketImpl::setupSocket(const Network::Socket::OptionsSharedPtr& opti setListenSocketOptions(options); if (bind_to_port) { - bind(local_address_); + bind(address_provider_->localAddress()); } } @@ -64,7 +65,7 @@ void NetworkListenSocket>::setPrebind UdsListenSocket::UdsListenSocket(const Address::InstanceConstSharedPtr& address) : ListenSocketImpl(ioHandleForAddr(Socket::Type::Stream, address), address) { RELEASE_ASSERT(io_handle_->isOpen(), ""); - bind(local_address_); + bind(address_provider_->localAddress()); } UdsListenSocket::UdsListenSocket(IoHandlePtr&& io_handle, diff --git a/source/common/network/socket_impl.cc b/source/common/network/socket_impl.cc index 56ef32bfb518..46ecd4e04cf4 100644 --- a/source/common/network/socket_impl.cc +++ b/source/common/network/socket_impl.cc @@ -10,15 +10,18 @@ namespace Envoy { namespace Network { SocketImpl::SocketImpl(Socket::Type sock_type, - const Address::InstanceConstSharedPtr& address_for_io_handle) + const Address::InstanceConstSharedPtr& address_for_io_handle, + const Address::InstanceConstSharedPtr& remote_address) : io_handle_(ioHandleForAddr(sock_type, address_for_io_handle)), sock_type_(sock_type), addr_type_(address_for_io_handle->type()), - address_provider_(std::make_shared(nullptr)) {} + address_provider_(std::make_shared(nullptr, remote_address)) {} SocketImpl::SocketImpl(IoHandlePtr&& io_handle, - const Address::InstanceConstSharedPtr& local_address) + const Address::InstanceConstSharedPtr& local_address, + const Address::InstanceConstSharedPtr& remote_address) : io_handle_(std::move(io_handle)), - address_provider_(std::make_shared(local_address)) { + address_provider_( + std::make_shared(local_address, remote_address)) { if (address_provider_->localAddress() != nullptr) { addr_type_ = address_provider_->localAddress()->type(); diff --git a/source/common/network/socket_impl.h b/source/common/network/socket_impl.h index 23e942eeba23..da996ae66da0 100644 --- a/source/common/network/socket_impl.h +++ b/source/common/network/socket_impl.h @@ -46,7 +46,10 @@ class SocketImpl : public virtual Socket { // Network::Socket SocketAddressProvider& addressProvider() override { return *address_provider_; } - SocketAddressProviderConstSharedPtr addressProvider() const override { return address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return address_provider_; + } SocketPtr duplicate() override { // Implementing the functionality here for all sockets is tricky because it leads // into object slicing issues. diff --git a/source/common/network/udp_listener_impl.cc b/source/common/network/udp_listener_impl.cc index 694647e54c55..aa160de9745e 100644 --- a/source/common/network/udp_listener_impl.cc +++ b/source/common/network/udp_listener_impl.cc @@ -37,8 +37,9 @@ UdpListenerImpl::UdpListenerImpl(Event::DispatcherImpl& dispatcher, SocketShared if (!Network::Socket::applyOptions(socket_->options(), *socket_, envoy::config::core::v3::SocketOption::STATE_BOUND)) { - throw CreateListenerException(fmt::format("cannot set post-bound socket option on socket: {}", - socket_->localAddress()->asString())); + throw CreateListenerException( + fmt::format("cannot set post-bound socket option on socket: {}", + socket_->addressProvider().localAddress()->asString())); } } @@ -69,7 +70,8 @@ void UdpListenerImpl::handleReadCallback() { ENVOY_UDP_LOG(trace, "handleReadCallback"); cb_.onReadReady(); const Api::IoErrorPtr result = Utility::readPacketsFromSocket( - socket_->ioHandle(), *socket_->localAddress(), *this, time_source_, packets_dropped_); + socket_->ioHandle(), *socket_->addressProvider().localAddress(), *this, time_source_, + packets_dropped_); // TODO(mattklein123): Handle no error when we limit the number of packets read. if (result->getErrorCode() != Api::IoError::IoErrorCode::Again) { // TODO(mattklein123): When rate limited logging is implemented log this at error level @@ -99,7 +101,7 @@ void UdpListenerImpl::handleWriteCallback() { Event::Dispatcher& UdpListenerImpl::dispatcher() { return dispatcher_; } const Address::InstanceConstSharedPtr& UdpListenerImpl::localAddress() const { - return socket_->localAddress(); + return socket_->addressProvider().localAddress(); } Api::IoCallUint64Result UdpListenerImpl::send(const UdpSendData& send_data) { diff --git a/source/common/network/utility.cc b/source/common/network/utility.cc index b18f08592393..61685068e650 100644 --- a/source/common/network/utility.cc +++ b/source/common/network/utility.cc @@ -277,11 +277,11 @@ bool Utility::isSameIpOrLoopback(const ConnectionSocket& socket) { // - Pipes // - Sockets to a loopback address // - Sockets where the local and remote address (ignoring port) are the same - const auto& remote_address = socket.addressProvider()->remoteAddress(); + const auto& remote_address = socket.addressProvider().remoteAddress(); if (remote_address->type() == Address::Type::Pipe || isLoopbackAddress(*remote_address)) { return true; } - const auto local_ip = socket.addressProvider()->localAddress()->ip(); + const auto local_ip = socket.addressProvider().localAddress()->ip(); const auto remote_ip = remote_address->ip(); if (remote_ip != nullptr && local_ip != nullptr && remote_ip->addressAsString() == local_ip->addressAsString()) { diff --git a/source/common/router/header_formatter.cc b/source/common/router/header_formatter.cc index a15e07ec374a..f79c83b0de35 100644 --- a/source/common/router/header_formatter.cc +++ b/source/common/router/header_formatter.cc @@ -236,26 +236,26 @@ StreamInfoHeaderFormatter::StreamInfoHeaderFormatter(absl::string_view field_nam }; } else if (field_name == "DOWNSTREAM_REMOTE_ADDRESS") { field_extractor_ = [](const StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamRemoteAddress()->asString(); + return stream_info.downstreamAddressProvider().remoteAddress()->asString(); }; } else if (field_name == "DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT") { field_extractor_ = [](const Envoy::StreamInfo::StreamInfo& stream_info) { return StreamInfo::Utility::formatDownstreamAddressNoPort( - *stream_info.downstreamRemoteAddress()); + *stream_info.downstreamAddressProvider().remoteAddress()); }; } else if (field_name == "DOWNSTREAM_LOCAL_ADDRESS") { field_extractor_ = [](const StreamInfo::StreamInfo& stream_info) { - return stream_info.downstreamLocalAddress()->asString(); + return stream_info.downstreamAddressProvider().localAddress()->asString(); }; } else if (field_name == "DOWNSTREAM_LOCAL_ADDRESS_WITHOUT_PORT") { field_extractor_ = [](const Envoy::StreamInfo::StreamInfo& stream_info) { return StreamInfo::Utility::formatDownstreamAddressNoPort( - *stream_info.downstreamLocalAddress()); + *stream_info.downstreamAddressProvider().localAddress()); }; } else if (field_name == "DOWNSTREAM_LOCAL_PORT") { field_extractor_ = [](const Envoy::StreamInfo::StreamInfo& stream_info) { return StreamInfo::Utility::formatDownstreamAddressJustPort( - *stream_info.downstreamLocalAddress()); + *stream_info.downstreamAddressProvider().localAddress()); }; } else if (field_name == "DOWNSTREAM_PEER_URI_SAN") { field_extractor_ = diff --git a/source/common/router/router.h b/source/common/router/router.h index 24cfff0dcb7a..5bc2144a8438 100644 --- a/source/common/router/router.h +++ b/source/common/router/router.h @@ -306,7 +306,8 @@ class Filter : Logger::Loggable, auto hash_policy = route_entry_->hashPolicy(); if (hash_policy) { return hash_policy->generateHash( - callbacks_->streamInfo().downstreamRemoteAddress().get(), *downstream_headers_, + callbacks_->streamInfo().downstreamAddressProvider().remoteAddress().get(), + *downstream_headers_, [this](const std::string& key, const std::string& path, std::chrono::seconds max_age) { return addDownstreamSetCookie(key, path, max_age); }, @@ -401,7 +402,8 @@ class Filter : Logger::Loggable, std::string value; const Network::Connection* conn = downstreamConnection(); // Need to check for null conn if this is ever used by Http::AsyncClient in the future. - value = conn->remoteAddress()->asString() + conn->localAddress()->asString(); + value = conn->addressProvider().remoteAddress()->asString() + + conn->addressProvider().localAddress()->asString(); const std::string cookie_value = Hex::uint64ToHex(HashUtil::xxHash64(value)); downstream_set_cookies_.emplace_back( diff --git a/source/common/router/upstream_request.cc b/source/common/router/upstream_request.cc index e63d30ff59c7..cbd96a2cc623 100644 --- a/source/common/router/upstream_request.cc +++ b/source/common/router/upstream_request.cc @@ -44,7 +44,7 @@ namespace Router { UpstreamRequest::UpstreamRequest(RouterFilterInterface& parent, std::unique_ptr&& conn_pool) : parent_(parent), conn_pool_(std::move(conn_pool)), grpc_rq_success_deferred_(false), - stream_info_(parent_.callbacks()->dispatcher().timeSource()), + stream_info_(parent_.callbacks()->dispatcher().timeSource(), nullptr), start_time_(parent_.callbacks()->dispatcher().timeSource().monotonicTime()), calling_encode_headers_(false), upstream_canary_(false), decode_complete_(false), encode_complete_(false), encode_trailers_(false), retried_(false), awaiting_headers_(true), diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index 516b494db7b1..c0170aeeb015 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -34,17 +34,21 @@ const ReplacementMap& emptySpaceReplacement() { struct StreamInfoImpl : public StreamInfo { StreamInfoImpl(TimeSource& time_source, + const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider, FilterState::LifeSpan life_span = FilterState::LifeSpan::FilterChain) - : StreamInfoImpl(absl::nullopt, time_source, std::make_shared(life_span)) {} + : StreamInfoImpl(absl::nullopt, time_source, downstream_address_provider, + std::make_shared(life_span)) {} - StreamInfoImpl(Http::Protocol protocol, TimeSource& time_source) - : StreamInfoImpl(protocol, time_source, + StreamInfoImpl(Http::Protocol protocol, TimeSource& time_source, + const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider) + : StreamInfoImpl(protocol, time_source, downstream_address_provider, std::make_shared(FilterState::LifeSpan::FilterChain)) {} StreamInfoImpl(Http::Protocol protocol, TimeSource& time_source, + const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider, FilterStateSharedPtr parent_filter_state, FilterState::LifeSpan life_span) : StreamInfoImpl( - protocol, time_source, + protocol, time_source, downstream_address_provider, std::make_shared( FilterStateImpl::LazyCreateAncestor(std::move(parent_filter_state), life_span), FilterState::LifeSpan::FilterChain)) {} @@ -187,24 +191,8 @@ struct StreamInfoImpl : public StreamInfo { void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } - const Network::Address::InstanceConstSharedPtr& downstreamLocalAddress() const override { - // fixfix null check. - return downstream_address_provider_->localAddress(); - } - - const Network::Address::InstanceConstSharedPtr& downstreamDirectRemoteAddress() const override { - // fixfix null check. - return downstream_address_provider_->directRemoteAddress(); - } - - const Network::Address::InstanceConstSharedPtr& downstreamRemoteAddress() const override { - // fixfix null check. - return downstream_address_provider_->remoteAddress(); - } - - void setDownstreamAddresses( - const Network::SocketAddressProviderConstSharedPtr& address_provider) override { - downstream_address_provider_ = address_provider; + const Network::SocketAddressProvider& downstreamAddressProvider() const override { + return *downstream_address_provider_; } void @@ -313,17 +301,20 @@ struct StreamInfoImpl : public StreamInfo { std::string route_name_; private: + // fixfix null check StreamInfoImpl(absl::optional protocol, TimeSource& time_source, + const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider, FilterStateSharedPtr filter_state) : time_source_(time_source), start_time_(time_source.systemTime()), start_time_monotonic_(time_source.monotonicTime()), protocol_(protocol), filter_state_(std::move(filter_state)), + downstream_address_provider_(downstream_address_provider), request_id_extension_(Http::RequestIDExtensionFactory::noopInstance()) {} uint64_t bytes_received_{}; uint64_t bytes_sent_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; - Network::SocketAddressProviderConstSharedPtr downstream_address_provider_; + const Network::SocketAddressProviderConstSharedPtr downstream_address_provider_; Ssl::ConnectionInfoConstSharedPtr downstream_ssl_info_; Ssl::ConnectionInfoConstSharedPtr upstream_ssl_info_; std::string requested_server_name_; diff --git a/source/common/tracing/http_tracer_impl.cc b/source/common/tracing/http_tracer_impl.cc index 8f46c812af64..4b8e5e595fc9 100644 --- a/source/common/tracing/http_tracer_impl.cc +++ b/source/common/tracing/http_tracer_impl.cc @@ -173,7 +173,7 @@ void HttpTracerUtility::finalizeDownstreamSpan(Span& span, Tracing::Tags::get().HttpProtocol, Formatter::SubstitutionFormatUtils::protocolToStringOrDefault(stream_info.protocol())); - const auto& remote_address = stream_info.downstreamDirectRemoteAddress(); + const auto& remote_address = stream_info.downstreamAddressProvider().directRemoteAddress(); if (remote_address->type() == Network::Address::Type::Ip) { const auto remote_ip = remote_address->ip(); diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index a1ff5dd32c88..7f346812db6f 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -18,6 +18,7 @@ #include "common/http/header_map_impl.h" #include "common/http/header_utility.h" #include "common/network/address_impl.h" +#include "common/network/socket_impl.h" #include "common/router/router.h" #include "common/runtime/runtime_features.h" #include "common/runtime/runtime_impl.h" @@ -214,7 +215,8 @@ HttpHealthCheckerImpl::HttpActiveHealthCheckSession::HttpActiveHealthCheckSessio : ActiveHealthCheckSession(parent, host), parent_(parent), hostname_(getHostname(host, parent_.host_value_, parent_.cluster_.info())), protocol_(codecClientTypeToProtocol(parent_.codec_client_type_)), - local_address_(std::make_shared("127.0.0.1")) {} + local_address_provider_(std::make_shared( + std::make_shared("127.0.0.1"), nullptr)) {} HttpHealthCheckerImpl::HttpActiveHealthCheckSession::~HttpActiveHealthCheckSession() { ASSERT(client_ == nullptr); @@ -269,8 +271,8 @@ void HttpHealthCheckerImpl::HttpActiveHealthCheckSession::onInterval() { {Http::Headers::get().UserAgent, Http::Headers::get().UserAgentValues.EnvoyHealthChecker}}); Router::FilterUtility::setUpstreamScheme( *request_headers, host_->transportSocketFactory().implementsSecureTransport()); - StreamInfo::StreamInfoImpl stream_info(protocol_, parent_.dispatcher_.timeSource()); - stream_info.setDownstreamAddresses(*this); + StreamInfo::StreamInfoImpl stream_info(protocol_, parent_.dispatcher_.timeSource(), + local_address_provider_); stream_info.onUpstreamHostSelected(host_); parent_.request_headers_parser_->evaluateHeaders(*request_headers, stream_info); auto status = request_encoder->encodeHeaders(*request_headers, true); diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index 1b940d339a10..6adee7a4d789 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -6,7 +6,7 @@ #include "envoy/config/core/v3/health_check.pb.h" #include "envoy/data/core/v3/health_check_event.pb.h" #include "envoy/grpc/status.h" -#include "envoy/network/listen_socket.h" +#include "envoy/network/socket.h" #include "envoy/type/v3/http.pb.h" #include "envoy/type/v3/range.pb.h" @@ -72,8 +72,7 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { private: struct HttpActiveHealthCheckSession : public ActiveHealthCheckSession, public Http::ResponseDecoder, - public Http::StreamCallbacks, - public Network::ConnectedSocketAddressProvider { + public Http::StreamCallbacks { HttpActiveHealthCheckSession(HttpHealthCheckerImpl& parent, const HostSharedPtr& host); ~HttpActiveHealthCheckSession() override; @@ -106,17 +105,6 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { void onAboveWriteBufferHighWatermark() override {} void onBelowWriteBufferLowWatermark() override {} - // Network::ConnectedSocketAddressProvider - const Network::Address::InstanceConstSharedPtr& localAddress() const override { - return local_address_; - } - const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const override { - return local_address_; - } - const Network::Address::InstanceConstSharedPtr& remoteAddress() const override { - return local_address_; - } - void onEvent(Network::ConnectionEvent event); class ConnectionCallbackImpl : public Network::ConnectionCallbacks { @@ -137,7 +125,7 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { Http::ResponseHeaderMapPtr response_headers_; const std::string& hostname_; const Http::Protocol protocol_; - Network::Address::InstanceConstSharedPtr local_address_; + Network::SocketAddressProviderConstSharedPtr local_address_provider_; bool expect_reset_{}; }; diff --git a/source/common/upstream/original_dst_cluster.cc b/source/common/upstream/original_dst_cluster.cc index 51c49c1340a2..f869a22d039c 100644 --- a/source/common/upstream/original_dst_cluster.cc +++ b/source/common/upstream/original_dst_cluster.cc @@ -31,8 +31,8 @@ HostConstSharedPtr OriginalDstCluster::LoadBalancer::chooseHost(LoadBalancerCont const Network::Connection* connection = context->downstreamConnection(); // The local address of the downstream connection is the original destination address, // if localAddressRestored() returns 'true'. - if (connection && connection->localAddressRestored()) { - dst_host = connection->localAddress(); + if (connection && connection->addressProvider().localAddressRestored()) { + dst_host = connection->addressProvider().localAddress(); } } diff --git a/source/extensions/common/proxy_protocol/proxy_protocol_header.cc b/source/extensions/common/proxy_protocol/proxy_protocol_header.cc index 139ebd500405..454bcfd420d0 100644 --- a/source/extensions/common/proxy_protocol/proxy_protocol_header.cc +++ b/source/extensions/common/proxy_protocol/proxy_protocol_header.cc @@ -109,8 +109,8 @@ void generateV2Header(const Network::Address::Ip& source_address, void generateProxyProtoHeader(const envoy::config::core::v3::ProxyProtocolConfig& config, const Network::Connection& connection, Buffer::Instance& out) { - const Network::Address::Ip& dest_address = *connection.addressProvider()->localAddress()->ip(); - const Network::Address::Ip& source_address = *connection.addressProvider()->remoteAddress()->ip(); + const Network::Address::Ip& dest_address = *connection.addressProvider().localAddress()->ip(); + const Network::Address::Ip& source_address = *connection.addressProvider().remoteAddress()->ip(); if (config.version() == envoy::config::core::v3::ProxyProtocolConfig::V1) { generateV1Header(source_address, dest_address, out); } else if (config.version() == envoy::config::core::v3::ProxyProtocolConfig::V2) { diff --git a/source/server/connection_handler_impl.cc b/source/server/connection_handler_impl.cc index 393fb7f313a4..ef27d2457f29 100644 --- a/source/server/connection_handler_impl.cc +++ b/source/server/connection_handler_impl.cc @@ -460,9 +460,6 @@ void ConnectionHandlerImpl::ActiveTcpListener::resumeListening() { void ConnectionHandlerImpl::ActiveTcpListener::newConnection( Network::ConnectionSocketPtr&& socket, std::unique_ptr stream_info) { - // Refresh addresses in case they are modified by listener filters, such as proxy protocol or - // original_dst. - stream_info->setDownstreamAddresses(*socket); // Find matching filter chain. const auto filter_chain = config_->filterChainManager().findFilterChain(*socket); diff --git a/test/common/network/connection_impl_test.cc b/test/common/network/connection_impl_test.cc index 279e2f78d9ab..9aff2cac0007 100644 --- a/test/common/network/connection_impl_test.cc +++ b/test/common/network/connection_impl_test.cc @@ -108,7 +108,7 @@ TEST_P(ConnectionImplDeathTest, BadFd) { Api::ApiPtr api = Api::createApiForTest(); Event::DispatcherPtr dispatcher(api->allocateDispatcher("test_thread")); IoHandlePtr io_handle = std::make_unique(); - StreamInfo::StreamInfoImpl stream_info(dispatcher->timeSource()); + StreamInfo::StreamInfoImpl stream_info(dispatcher->timeSource(), nullptr); EXPECT_DEATH( ConnectionImpl(*dispatcher, std::make_unique(std::move(io_handle), nullptr, nullptr), @@ -124,7 +124,8 @@ class TestClientConnectionImpl : public Network::ClientConnectionImpl { class ConnectionImplTest : public testing::TestWithParam { protected: - ConnectionImplTest() : api_(Api::createApiForTest(time_system_)), stream_info_(time_system_) {} + ConnectionImplTest() + : api_(Api::createApiForTest(time_system_)), stream_info_(time_system_, nullptr) {} void setUpBasicConnection() { if (dispatcher_ == nullptr) { diff --git a/test/mocks/network/connection.cc b/test/mocks/network/connection.cc index 7bbefb5ae5fa..a0fe1bca4612 100644 --- a/test/mocks/network/connection.cc +++ b/test/mocks/network/connection.cc @@ -76,9 +76,6 @@ template static void initializeMockConnection(T& connection) { ON_CALL(connection, close(_)).WillByDefault(Invoke([&connection](ConnectionCloseType) -> void { connection.raiseEvent(Network::ConnectionEvent::LocalClose); })); - ON_CALL(connection, remoteAddress()).WillByDefault(ReturnRef(connection.remote_address_)); - ON_CALL(connection, directRemoteAddress()).WillByDefault(ReturnRef(connection.remote_address_)); - ON_CALL(connection, localAddress()).WillByDefault(ReturnRef(connection.local_address_)); ON_CALL(connection, id()).WillByDefault(Return(connection.next_id_)); ON_CALL(connection, state()).WillByDefault(ReturnPointee(&connection.state_)); @@ -92,29 +89,35 @@ template static void initializeMockConnection(T& connection) { } MockConnection::MockConnection() { - remote_address_ = Utility::resolveUrl("tcp://10.0.0.3:50000"); + stream_info_.downstream_address_provider_->setRemoteAddress( + Utility::resolveUrl("tcp://10.0.0.3:50000")); initializeMockConnection(*this); } MockConnection::~MockConnection() = default; MockServerConnection::MockServerConnection() { - remote_address_ = Utility::resolveUrl("tcp://10.0.0.1:443"); - local_address_ = Utility::resolveUrl("tcp://10.0.0.2:40000"); + stream_info_.downstream_address_provider_->setRemoteAddress( + Utility::resolveUrl("tcp://10.0.0.1:443")); + stream_info_.downstream_address_provider_->setLocalAddress( + Utility::resolveUrl("tcp://10.0.0.2:40000")); initializeMockConnection(*this); } MockServerConnection::~MockServerConnection() = default; MockClientConnection::MockClientConnection() { - remote_address_ = Utility::resolveUrl("tcp://10.0.0.1:443"); - local_address_ = Utility::resolveUrl("tcp://10.0.0.2:40000"); + stream_info_.downstream_address_provider_->setRemoteAddress( + Utility::resolveUrl("tcp://10.0.0.1:443")); + stream_info_.downstream_address_provider_->setLocalAddress( + Utility::resolveUrl("tcp://10.0.0.2:40000")); initializeMockConnection(*this); } MockClientConnection::~MockClientConnection() = default; MockFilterManagerConnection::MockFilterManagerConnection() { - remote_address_ = Utility::resolveUrl("tcp://10.0.0.3:50000"); + stream_info_.downstream_address_provider_->setRemoteAddress( + Utility::resolveUrl("tcp://10.0.0.3:50000")); initializeMockConnection(*this); // The real implementation will move the buffer data into the socket. diff --git a/test/mocks/network/connection.h b/test/mocks/network/connection.h index 45cac5fcd780..2fcc5eb8b701 100644 --- a/test/mocks/network/connection.h +++ b/test/mocks/network/connection.h @@ -38,8 +38,6 @@ class MockConnectionBase { std::list callbacks_; std::list bytes_sent_callbacks_; uint64_t id_{next_id_++}; - Address::InstanceConstSharedPtr remote_address_; - Address::InstanceConstSharedPtr local_address_; bool read_enabled_{true}; testing::NiceMock stream_info_; Connection::State state_{Connection::State::Open}; @@ -66,11 +64,9 @@ class MockConnectionBase { MOCK_METHOD(void, readDisable, (bool disable)); \ MOCK_METHOD(void, detectEarlyCloseWhenReadDisabled, (bool)); \ MOCK_METHOD(bool, readEnabled, (), (const)); \ - MOCK_METHOD(const Address::InstanceConstSharedPtr&, remoteAddress, (), (const)); \ - MOCK_METHOD(const Address::InstanceConstSharedPtr&, directRemoteAddress, (), (const)); \ + MOCK_METHOD(const SocketAddressProvider&, addressProvider, (), (const)); \ MOCK_METHOD(absl::optional, \ unixSocketPeerCredentials, (), (const)); \ - MOCK_METHOD(const Address::InstanceConstSharedPtr&, localAddress, (), (const)); \ MOCK_METHOD(void, setConnectionStats, (const ConnectionStats& stats)); \ MOCK_METHOD(Ssl::ConnectionInfoConstSharedPtr, ssl, (), (const)); \ MOCK_METHOD(absl::string_view, requestedServerName, (), (const)); \ @@ -79,7 +75,6 @@ class MockConnectionBase { MOCK_METHOD(void, write, (Buffer::Instance & data, bool end_stream)); \ MOCK_METHOD(void, setBufferLimits, (uint32_t limit)); \ MOCK_METHOD(uint32_t, bufferLimit, (), (const)); \ - MOCK_METHOD(bool, localAddressRestored, (), (const)); \ MOCK_METHOD(bool, aboveHighWatermark, (), (const)); \ MOCK_METHOD(const Network::ConnectionSocket::OptionsSharedPtr&, socketOptions, (), (const)); \ MOCK_METHOD(StreamInfo::StreamInfo&, streamInfo, ()); \ diff --git a/test/mocks/network/mocks.cc b/test/mocks/network/mocks.cc index db6e933ec19c..2dc630226a9c 100644 --- a/test/mocks/network/mocks.cc +++ b/test/mocks/network/mocks.cc @@ -30,7 +30,8 @@ MockListenerConfig::MockListenerConfig() udp_listener_worker_router_(std::make_unique(1)) { ON_CALL(*this, filterChainFactory()).WillByDefault(ReturnRef(filter_chain_factory_)); ON_CALL(*this, listenSocketFactory()).WillByDefault(ReturnRef(socket_factory_)); - ON_CALL(socket_factory_, localAddress()).WillByDefault(ReturnRef(socket_->localAddress())); + ON_CALL(socket_factory_, localAddress()) + .WillByDefault(ReturnRef(socket_->addressProvider().localAddress())); ON_CALL(socket_factory_, getListenSocket()).WillByDefault(Return(socket_)); ON_CALL(socket_factory_, sharedSocket()) .WillByDefault(Return(std::reference_wrapper(*socket_))); @@ -131,8 +132,8 @@ MockFilterChainFactory::~MockFilterChainFactory() = default; MockListenSocket::MockListenSocket() : io_handle_(std::make_unique()), - local_address_(new Address::Ipv4Instance(80)) { - ON_CALL(*this, localAddress()).WillByDefault(ReturnRef(local_address_)); + address_provider_(std::make_shared( + std::make_shared(80), nullptr)) { ON_CALL(*this, options()).WillByDefault(ReturnRef(options_)); ON_CALL(*this, ioHandle()).WillByDefault(ReturnRef(*io_handle_)); ON_CALL(testing::Const(*this), ioHandle()).WillByDefault(ReturnRef(*io_handle_)); @@ -140,7 +141,8 @@ MockListenSocket::MockListenSocket() ON_CALL(testing::Const(*this), isOpen()).WillByDefault(Invoke([this]() { return socket_is_open_; })); - ON_CALL(*this, ipVersion()).WillByDefault(Return(local_address_->ip()->version())); + ON_CALL(*this, ipVersion()) + .WillByDefault(Return(address_provider_->localAddress()->ip()->version())); } MockSocketOption::MockSocketOption() { @@ -151,14 +153,13 @@ MockSocketOption::~MockSocketOption() = default; MockConnectionSocket::MockConnectionSocket() : io_handle_(std::make_unique()), - local_address_(new Address::Ipv4Instance(80)), - remote_address_(new Address::Ipv4Instance(80)) { - ON_CALL(*this, localAddress()).WillByDefault(ReturnRef(local_address_)); - ON_CALL(*this, remoteAddress()).WillByDefault(ReturnRef(remote_address_)); - ON_CALL(*this, directRemoteAddress()).WillByDefault(ReturnRef(remote_address_)); + address_provider_(std::make_shared( + std::make_shared(80), + std::make_shared(80))) { ON_CALL(*this, ioHandle()).WillByDefault(ReturnRef(*io_handle_)); ON_CALL(testing::Const(*this), ioHandle()).WillByDefault(ReturnRef(*io_handle_)); - ON_CALL(*this, ipVersion()).WillByDefault(Return(local_address_->ip()->version())); + ON_CALL(*this, ipVersion()) + .WillByDefault(Return(address_provider_->localAddress()->ip()->version())); } MockConnectionSocket::~MockConnectionSocket() = default; diff --git a/test/mocks/network/mocks.h b/test/mocks/network/mocks.h index 27f9782cdfaa..7dadc4dfdb0c 100644 --- a/test/mocks/network/mocks.h +++ b/test/mocks/network/mocks.h @@ -11,6 +11,7 @@ #include "envoy/network/drain_decision.h" #include "envoy/network/filter.h" #include "envoy/network/resolver.h" +#include "envoy/network/socket.h" #include "envoy/network/transport_socket.h" #include "envoy/stats/scope.h" @@ -222,8 +223,9 @@ class MockListenSocket : public Socket { void addOption(const Socket::OptionConstSharedPtr& option) override { addOption_(option); } void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } - MOCK_METHOD(const Address::InstanceConstSharedPtr&, localAddress, (), (const)); - MOCK_METHOD(void, setLocalAddress, (const Address::InstanceConstSharedPtr&)); + SocketAddressProvider& addressProvider() override; + const SocketAddressProvider& addressProvider() const override; + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override; MOCK_METHOD(IoHandle&, ioHandle, ()); MOCK_METHOD(SocketPtr, duplicate, ()); MOCK_METHOD(const IoHandle&, ioHandle, (), (const)); @@ -246,7 +248,7 @@ class MockListenSocket : public Socket { MOCK_METHOD(Api::SysCallIntResult, setBlockingForTest, (bool)); IoHandlePtr io_handle_; - Address::InstanceConstSharedPtr local_address_; + Network::SocketAddressProviderSharedPtr address_provider_; OptionsSharedPtr options_; bool socket_is_open_ = true; }; @@ -271,13 +273,9 @@ class MockConnectionSocket : public ConnectionSocket { void addOption(const Socket::OptionConstSharedPtr& option) override { addOption_(option); } void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } - MOCK_METHOD(const Address::InstanceConstSharedPtr&, localAddress, (), (const)); - MOCK_METHOD(void, setLocalAddress, (const Address::InstanceConstSharedPtr&)); - MOCK_METHOD(void, restoreLocalAddress, (const Address::InstanceConstSharedPtr&)); - MOCK_METHOD(bool, localAddressRestored, (), (const)); - MOCK_METHOD(void, setRemoteAddress, (const Address::InstanceConstSharedPtr&)); - MOCK_METHOD(const Address::InstanceConstSharedPtr&, remoteAddress, (), (const)); - MOCK_METHOD(const Address::InstanceConstSharedPtr&, directRemoteAddress, (), (const)); + SocketAddressProvider& addressProvider() override; + const SocketAddressProvider& addressProvider() const override; + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override; MOCK_METHOD(void, setDetectedTransportProtocol, (absl::string_view)); MOCK_METHOD(absl::string_view, detectedTransportProtocol, (), (const)); MOCK_METHOD(void, setRequestedApplicationProtocols, (const std::vector&)); @@ -307,8 +305,7 @@ class MockConnectionSocket : public ConnectionSocket { MOCK_METHOD(absl::optional, lastRoundTripTime, ()); IoHandlePtr io_handle_; - Address::InstanceConstSharedPtr local_address_; - Address::InstanceConstSharedPtr remote_address_; + Network::SocketAddressProviderSharedPtr address_provider_; bool is_closed_; }; diff --git a/test/mocks/network/socket.h b/test/mocks/network/socket.h index c03db0ad489a..d6ca57d3bb8d 100644 --- a/test/mocks/network/socket.h +++ b/test/mocks/network/socket.h @@ -14,14 +14,15 @@ class MockSocket : public Socket { MockSocket(); ~MockSocket() override; + SocketAddressProvider& addressProvider() override; + const SocketAddressProvider& addressProvider() const override; + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override; IoHandle& ioHandle() override; const IoHandle& ioHandle() const override; Api::SysCallIntResult setSocketOption(int level, int optname, const void* optval, socklen_t len) override; - MOCK_METHOD(const Address::InstanceConstSharedPtr&, localAddress, (), (const, override)); - MOCK_METHOD(void, setLocalAddress, (const Address::InstanceConstSharedPtr&), (override)); - MOCK_METHOD(Network::SocketPtr, duplicate, (), ()); + MOCK_METHOD(Network::SocketPtr, duplicate, (), (override)); MOCK_METHOD(Socket::Type, socketType, (), (const, override)); MOCK_METHOD(Address::Type, addressType, (), (const, override)); MOCK_METHOD(absl::optional, ipVersion, (), (const, override)); diff --git a/test/mocks/stream_info/mocks.cc b/test/mocks/stream_info/mocks.cc index 6c1615c12e39..d686f538735a 100644 --- a/test/mocks/stream_info/mocks.cc +++ b/test/mocks/stream_info/mocks.cc @@ -1,6 +1,7 @@ #include "test/mocks/stream_info/mocks.h" #include "common/network/address_impl.h" +#include "common/network/socket_impl.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -18,9 +19,9 @@ namespace StreamInfo { MockStreamInfo::MockStreamInfo() : start_time_(ts_.systemTime()), filter_state_(std::make_shared(FilterState::LifeSpan::FilterChain)), - downstream_local_address_(new Network::Address::Ipv4Instance("127.0.0.2")), - downstream_direct_remote_address_(new Network::Address::Ipv4Instance("127.0.0.1")), - downstream_remote_address_(new Network::Address::Ipv4Instance("127.0.0.1")) { + downstream_address_provider_(std::make_shared( + std::make_shared("127.0.0.2"), + std::make_shared("127.0.0.1"))) { ON_CALL(*this, setResponseFlag(_)).WillByDefault(Invoke([this](ResponseFlag response_flag) { response_flags_ |= response_flag; })); @@ -61,22 +62,8 @@ MockStreamInfo::MockStreamInfo() upstream_local_address_ = upstream_local_address; })); ON_CALL(*this, upstreamLocalAddress()).WillByDefault(ReturnRef(upstream_local_address_)); - ON_CALL(*this, downstreamLocalAddress()).WillByDefault(ReturnRef(downstream_local_address_)); - ON_CALL(*this, downstreamDirectRemoteAddress()) - .WillByDefault(ReturnRef(downstream_direct_remote_address_)); - ON_CALL(*this, setDownstreamRemoteAddress(_)) - .WillByDefault( - Invoke([this](const Network::Address::InstanceConstSharedPtr& downstream_remote_address) { - downstream_remote_address_ = downstream_remote_address; - })); - ON_CALL(*this, setDownstreamAddresses(_)) - .WillByDefault( - Invoke([this](const Network::ConnectedSocketAddressProvider& address_provider) { - downstream_local_address_ = address_provider.localAddress(); - downstream_direct_remote_address_ = address_provider.directRemoteAddress(); - downstream_remote_address_ = address_provider.remoteAddress(); - })); - ON_CALL(*this, downstreamRemoteAddress()).WillByDefault(ReturnRef(downstream_remote_address_)); + ON_CALL(*this, downstreamAddressProvider()) + .WillByDefault(ReturnPointee(downstream_address_provider_)); ON_CALL(*this, setDownstreamSslConnection(_)) .WillByDefault(Invoke( [this](const auto& connection_info) { downstream_connection_info_ = connection_info; })); diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index 9e4b8fb67300..5a75e0583c62 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -3,6 +3,7 @@ #include "envoy/config/core/v3/base.pb.h" #include "envoy/http/request_id_extension.h" #include "envoy/network/listen_socket.h" +#include "envoy/network/socket.h" #include "envoy/stream_info/stream_info.h" #include "common/stream_info/filter_state_impl.h" @@ -65,13 +66,7 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, upstreamLocalAddress, (), (const)); MOCK_METHOD(bool, healthCheck, (), (const)); MOCK_METHOD(void, healthCheck, (bool is_health_check)); - MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, downstreamLocalAddress, (), (const)); - MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, downstreamDirectRemoteAddress, (), - (const)); - MOCK_METHOD(void, setDownstreamRemoteAddress, (const Network::Address::InstanceConstSharedPtr&)); - MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, downstreamRemoteAddress, (), - (const)); - MOCK_METHOD(void, setDownstreamAddresses, (const Network::ConnectedSocketAddressProvider&)); + MOCK_METHOD(const Network::SocketAddressProvider&, downstreamAddressProvider, (), (const)); MOCK_METHOD(void, setDownstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); MOCK_METHOD(Ssl::ConnectionInfoConstSharedPtr, downstreamSslConnection, (), (const)); MOCK_METHOD(void, setUpstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); @@ -125,9 +120,7 @@ class MockStreamInfo : public StreamInfo { uint64_t bytes_received_{}; uint64_t bytes_sent_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; - Network::Address::InstanceConstSharedPtr downstream_local_address_; - Network::Address::InstanceConstSharedPtr downstream_direct_remote_address_; - Network::Address::InstanceConstSharedPtr downstream_remote_address_; + Network::SocketAddressProviderSharedPtr downstream_address_provider_; Ssl::ConnectionInfoConstSharedPtr downstream_connection_info_; Ssl::ConnectionInfoConstSharedPtr upstream_connection_info_; std::string requested_server_name_; diff --git a/test/test_common/network_utility.h b/test/test_common/network_utility.h index 02f745a7e665..48291748904e 100644 --- a/test/test_common/network_utility.h +++ b/test/test_common/network_utility.h @@ -193,7 +193,9 @@ class UdpSyncPeer { void recv(Network::UdpRecvData& datagram); // Return the local peer's socket address. - const Network::Address::InstanceConstSharedPtr& localAddress() { return socket_->localAddress(); } + const Network::Address::InstanceConstSharedPtr& localAddress() { + return socket_->addressProvider().localAddress(); + } private: const Network::SocketPtr socket_; From d38f9635cff32332e92e774d5cc86199ff9a8118 Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Fri, 18 Dec 2020 23:26:37 +0000 Subject: [PATCH 4/8] more Signed-off-by: Matt Klein --- include/envoy/network/connection.h | 3 +- include/envoy/network/socket.h | 4 +- source/common/http/async_client_impl.cc | 1 - source/common/http/conn_manager_impl.cc | 16 ++-- source/common/http/conn_manager_utility.cc | 8 +- source/common/http/filter_manager.h | 3 +- source/common/network/connection_impl.h | 3 + source/common/network/filter_matcher.h | 2 +- source/common/network/socket_impl.cc | 6 +- source/common/network/socket_impl.h | 2 +- source/common/stream_info/stream_info_impl.h | 13 ++- source/common/tcp_proxy/tcp_proxy.cc | 17 ++-- source/common/tcp_proxy/tcp_proxy.h | 5 +- source/common/tcp_proxy/upstream.cc | 2 +- .../quic_listeners/quiche/envoy_quic_utils.cc | 2 +- .../upstreams/http/tcp/upstream_request.cc | 2 +- source/server/api_listener_impl.h | 10 -- source/server/filter_chain_manager_impl.cc | 6 +- source/server/listener_impl.cc | 2 +- test/common/http/codec_client_test.cc | 5 +- .../http/conn_manager_impl_fuzz_test.cc | 8 +- test/common/http/conn_manager_impl_test.cc | 32 ++++--- .../http/conn_manager_impl_test_base.cc | 8 +- test/common/http/conn_manager_utility_test.cc | 83 +++++++++++------ test/common/network/address_impl_test.cc | 10 +- test/common/network/connection_impl_test.cc | 29 +++--- test/common/network/dns_impl_test.cc | 14 ++- test/common/network/filter_matcher_test.cc | 5 +- .../common/network/listen_socket_impl_test.cc | 20 ++-- test/common/network/listener_impl_test.cc | 70 +++++++------- .../network/socket_option_factory_test.cc | 8 +- test/common/network/socket_option_test.h | 2 +- .../udp_listener_impl_batch_writer_test.cc | 11 ++- test/common/network/udp_listener_impl_test.cc | 7 +- .../network/udp_listener_impl_test_base.h | 14 +-- test/common/network/utility_test.cc | 72 ++++++++------ test/common/stream_info/test_util.h | 26 +----- test/common/tcp_proxy/tcp_proxy_test.cc | 93 ++++++++++++------- test/fuzz/utility.h | 6 +- test/mocks/network/connection.cc | 4 +- test/mocks/network/connection.h | 44 +-------- test/mocks/network/mocks.h | 16 ++-- test/mocks/network/socket.h | 9 +- test/mocks/stream_info/mocks.h | 1 - 44 files changed, 376 insertions(+), 328 deletions(-) diff --git a/include/envoy/network/connection.h b/include/envoy/network/connection.h index d082c679ec5c..db6820c439a8 100644 --- a/include/envoy/network/connection.h +++ b/include/envoy/network/connection.h @@ -11,6 +11,7 @@ #include "envoy/network/address.h" #include "envoy/network/filter.h" #include "envoy/network/listen_socket.h" +#include "envoy/network/socket.h" #include "envoy/ssl/connection.h" #include "envoy/stream_info/stream_info.h" @@ -189,6 +190,7 @@ class Connection : public Event::DeferredDeletable, public FilterManager { // fixfix virtual const SocketAddressProvider& addressProvider() const PURE; + virtual SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const PURE; /** * Credentials of the peer of a socket as decided by SO_PEERCRED. @@ -270,7 +272,6 @@ class Connection : public Event::DeferredDeletable, public FilterManager { */ virtual uint32_t bufferLimit() const PURE; - /** * @return boolean telling if the connection is currently above the high watermark. */ diff --git a/include/envoy/network/socket.h b/include/envoy/network/socket.h index e0beff5445df..24ab937fd228 100644 --- a/include/envoy/network/socket.h +++ b/include/envoy/network/socket.h @@ -63,7 +63,7 @@ class SocketAddressProvider { */ virtual void setLocalAddress(const Address::InstanceConstSharedPtr& local_address) PURE; - /** + /** * Restores the local address of the socket. On accepted sockets the local address defaults to the * one at which the connection was received at, which is the same as the listener's address, if * the listener is bound to a specific address. Call this to restore the address to a value @@ -139,7 +139,7 @@ class Socket { */ virtual Socket::Type socketType() const PURE; -/** + /** * @return the type (IP or pipe) of addresses used by the socket (subset of socket domain) */ virtual Address::Type addressType() const PURE; diff --git a/source/common/http/async_client_impl.cc b/source/common/http/async_client_impl.cc index f2a35c3246d7..361fdfb173ac 100644 --- a/source/common/http/async_client_impl.cc +++ b/source/common/http/async_client_impl.cc @@ -6,7 +6,6 @@ #include #include -#include "common/network/socket_impl.h" #include "envoy/config/core/v3/base.pb.h" #include "common/grpc/common.h" diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index 0c7d1af2d330..631a842d633c 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -618,12 +618,6 @@ ConnectionManagerImpl::ActiveStream::ActiveStream(ConnectionManagerImpl& connect } else { connection_manager_.stats_.named_.downstream_rq_http1_total_.inc(); } - // Initially, the downstream remote address is the source address of the - // downstream connection. That can change later in the request's lifecycle, - // based on XFF processing, but setting the downstream remote address here - // prevents surprises for logging code in edge cases. - filter_manager_.streamInfo().setDownstreamAddresses( - connection_manager_.read_callbacks_->connection()); filter_manager_.streamInfo().setDownstreamSslConnection( connection_manager_.read_callbacks_->connection().ssl()); @@ -822,7 +816,7 @@ const Network::Connection* ConnectionManagerImpl::ActiveStream::connection() { } uint32_t ConnectionManagerImpl::ActiveStream::localPort() { - auto ip = connection()->localAddress()->ip(); + auto ip = connection()->addressProvider().localAddress()->ip(); if (ip == nullptr) { return 0; } @@ -1010,12 +1004,14 @@ void ConnectionManagerImpl::ActiveStream::decodeHeaders(RequestHeaderMapPtr&& he if (!state_.is_internally_created_) { // Only sanitize headers on first pass. // Modify the downstream remote address depending on configuration and headers. - filter_manager_.streamInfo().setDownstreamRemoteAddress( + ASSERT(false); // fixfix + /*filter_manager_.streamInfo().setDownstreamRemoteAddress( ConnectionManagerUtility::mutateRequestHeaders( *request_headers_, connection_manager_.read_callbacks_->connection(), - connection_manager_.config_, *snapped_route_config_, connection_manager_.local_info_)); + connection_manager_.config_, *snapped_route_config_, + connection_manager_.local_info_));*/ } - ASSERT(filter_manager_.streamInfo().downstreamRemoteAddress() != nullptr); + ASSERT(filter_manager_.streamInfo().downstreamAddressProvider().remoteAddress() != nullptr); ASSERT(!cached_route_); refreshCachedRoute(); diff --git a/source/common/http/conn_manager_utility.cc b/source/common/http/conn_manager_utility.cc index 6042af59adcc..8ed108a4fc6e 100644 --- a/source/common/http/conn_manager_utility.cc +++ b/source/common/http/conn_manager_utility.cc @@ -110,13 +110,13 @@ Network::Address::InstanceConstSharedPtr ConnectionManagerUtility::mutateRequest // are but they didn't populate XFF properly, the trusted client address is the // source address of the immediate downstream's connection to us. if (final_remote_address == nullptr) { - final_remote_address = connection.remoteAddress(); + final_remote_address = connection.addressProvider().remoteAddress(); } if (!config.skipXffAppend()) { - if (Network::Utility::isLoopbackAddress(*connection.remoteAddress())) { + if (Network::Utility::isLoopbackAddress(*connection.addressProvider().remoteAddress())) { Utility::appendXff(request_headers, config.localAddress()); } else { - Utility::appendXff(request_headers, *connection.remoteAddress()); + Utility::appendXff(request_headers, *connection.addressProvider().remoteAddress()); } } // If the prior hop is not a trusted proxy, overwrite any x-forwarded-proto value it set as @@ -157,7 +157,7 @@ Network::Address::InstanceConstSharedPtr ConnectionManagerUtility::mutateRequest // After determining internal request status, if there is no final remote address, due to no XFF, // busted XFF, etc., use the direct connection remote address for logging. if (final_remote_address == nullptr) { - final_remote_address = connection.remoteAddress(); + final_remote_address = connection.addressProvider().remoteAddress(); } // Edge request is the request from external clients to front Envoy. diff --git a/source/common/http/filter_manager.h b/source/common/http/filter_manager.h index 21109a82d774..8800de157607 100644 --- a/source/common/http/filter_manager.h +++ b/source/common/http/filter_manager.h @@ -619,7 +619,8 @@ class FilterManager : public ScopeTrackedObject, connection_(connection), stream_id_(stream_id), proxy_100_continue_(proxy_100_continue), buffer_limit_(buffer_limit), filter_chain_factory_(filter_chain_factory), local_reply_(local_reply), - stream_info_(protocol, time_source, parent_filter_state, filter_state_life_span) {} + stream_info_(protocol, time_source, connection.addressProviderSharedPtr(), + parent_filter_state, filter_state_life_span) {} ~FilterManager() override { ASSERT(state_.destroyed_); ASSERT(state_.filter_call_state_ == 0); diff --git a/source/common/network/connection_impl.h b/source/common/network/connection_impl.h index 2a76afb9644f..15e3b6e032d4 100644 --- a/source/common/network/connection_impl.h +++ b/source/common/network/connection_impl.h @@ -71,6 +71,9 @@ class ConnectionImpl : public ConnectionImplBase, public TransportSocketCallback const SocketAddressProvider& addressProvider() const override { return socket_->addressProvider(); } + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return socket_->addressProviderSharedPtr(); + } absl::optional unixSocketPeerCredentials() const override; Ssl::ConnectionInfoConstSharedPtr ssl() const override { return transport_socket_->ssl(); } State state() const override; diff --git a/source/common/network/filter_matcher.h b/source/common/network/filter_matcher.h index ab2dd5f8068a..be2114bdabe4 100644 --- a/source/common/network/filter_matcher.h +++ b/source/common/network/filter_matcher.h @@ -45,7 +45,7 @@ class ListenerFilterDstPortMatcher final : public ListenerFilterMatcher { explicit ListenerFilterDstPortMatcher(const ::envoy::type::v3::Int32Range& range) : start_(range.start()), end_(range.end()) {} bool matches(ListenerFilterCallbacks& cb) const override { - const auto& address = cb.socket().localAddress(); + const auto& address = cb.socket().addressProvider().localAddress(); // Match on destination port (only for IP addresses). if (address->type() == Address::Type::Ip) { const auto port = address->ip()->port(); diff --git a/source/common/network/socket_impl.cc b/source/common/network/socket_impl.cc index 46ecd4e04cf4..8c44690f2789 100644 --- a/source/common/network/socket_impl.cc +++ b/source/common/network/socket_impl.cc @@ -12,9 +12,9 @@ namespace Network { SocketImpl::SocketImpl(Socket::Type sock_type, const Address::InstanceConstSharedPtr& address_for_io_handle, const Address::InstanceConstSharedPtr& remote_address) - : io_handle_(ioHandleForAddr(sock_type, address_for_io_handle)), sock_type_(sock_type), - addr_type_(address_for_io_handle->type()), - address_provider_(std::make_shared(nullptr, remote_address)) {} + : io_handle_(ioHandleForAddr(sock_type, address_for_io_handle)), + address_provider_(std::make_shared(nullptr, remote_address)), + sock_type_(sock_type), addr_type_(address_for_io_handle->type()) {} SocketImpl::SocketImpl(IoHandlePtr&& io_handle, const Address::InstanceConstSharedPtr& local_address, diff --git a/source/common/network/socket_impl.h b/source/common/network/socket_impl.h index da996ae66da0..8bc4a2a799d5 100644 --- a/source/common/network/socket_impl.h +++ b/source/common/network/socket_impl.h @@ -97,10 +97,10 @@ class SocketImpl : public virtual Socket { const Address::InstanceConstSharedPtr& remote_address); const IoHandlePtr io_handle_; + const SocketAddressProviderSharedPtr address_provider_; OptionsSharedPtr options_; Socket::Type sock_type_; Address::Type addr_type_; - const SocketAddressProviderSharedPtr address_provider_; }; } // namespace Network diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index c0170aeeb015..4fbf37fe54b1 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -3,6 +3,8 @@ #include #include +#include "common/common/macros.h" +#include "common/network/socket_impl.h" #include "envoy/common/time.h" #include "envoy/config/core/v3/base.pb.h" #include "envoy/http/header_map.h" @@ -301,14 +303,21 @@ struct StreamInfoImpl : public StreamInfo { std::string route_name_; private: - // fixfix null check + static Network::SocketAddressProviderConstSharedPtr emptyDownstreamAddressProvider() { + MUTABLE_CONSTRUCT_ON_FIRST_USE( + Network::SocketAddressProviderConstSharedPtr, + std::make_shared(nullptr, nullptr)); + } + StreamInfoImpl(absl::optional protocol, TimeSource& time_source, const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider, FilterStateSharedPtr filter_state) : time_source_(time_source), start_time_(time_source.systemTime()), start_time_monotonic_(time_source.monotonicTime()), protocol_(protocol), filter_state_(std::move(filter_state)), - downstream_address_provider_(downstream_address_provider), + downstream_address_provider_(downstream_address_provider != nullptr + ? downstream_address_provider + : emptyDownstreamAddressProvider()), request_id_extension_(Http::RequestIDExtensionFactory::noopInstance()) {} uint64_t bytes_received_{}; diff --git a/source/common/tcp_proxy/tcp_proxy.cc b/source/common/tcp_proxy/tcp_proxy.cc index fe64127a0aa1..31efb90c282b 100644 --- a/source/common/tcp_proxy/tcp_proxy.cc +++ b/source/common/tcp_proxy/tcp_proxy.cc @@ -56,20 +56,24 @@ Config::RouteImpl::RouteImpl( bool Config::RouteImpl::matches(Network::Connection& connection) const { if (!source_port_ranges_.empty() && - !Network::Utility::portInRangeList(*connection.remoteAddress(), source_port_ranges_)) { + !Network::Utility::portInRangeList(*connection.addressProvider().remoteAddress(), + source_port_ranges_)) { return false; } - if (!source_ips_.empty() && !source_ips_.contains(*connection.remoteAddress())) { + if (!source_ips_.empty() && + !source_ips_.contains(*connection.addressProvider().remoteAddress())) { return false; } if (!destination_port_ranges_.empty() && - !Network::Utility::portInRangeList(*connection.localAddress(), destination_port_ranges_)) { + !Network::Utility::portInRangeList(*connection.addressProvider().localAddress(), + destination_port_ranges_)) { return false; } - if (!destination_ips_.empty() && !destination_ips_.contains(*connection.localAddress())) { + if (!destination_ips_.empty() && + !destination_ips_.contains(*connection.addressProvider().localAddress())) { return false; } @@ -425,8 +429,9 @@ Network::FilterStatus Filter::initializeUpstreamConnection() { Network::ProxyProtocolFilterState::key())) { read_callbacks_->connection().streamInfo().filterState()->setData( Network::ProxyProtocolFilterState::key(), - std::make_unique(Network::ProxyProtocolData{ - downstreamConnection()->remoteAddress(), downstreamConnection()->localAddress()}), + std::make_unique( + Network::ProxyProtocolData{downstreamConnection()->addressProvider().remoteAddress(), + downstreamConnection()->addressProvider().localAddress()}), StreamInfo::FilterState::StateType::ReadOnly, StreamInfo::FilterState::LifeSpan::Connection); } diff --git a/source/common/tcp_proxy/tcp_proxy.h b/source/common/tcp_proxy/tcp_proxy.h index a5e43e6e8ca5..3ffa00e71a61 100644 --- a/source/common/tcp_proxy/tcp_proxy.h +++ b/source/common/tcp_proxy/tcp_proxy.h @@ -266,8 +266,9 @@ class Filter : public Network::ReadFilter, absl::optional computeHashKey() override { auto hash_policy = config_->hashPolicy(); if (hash_policy) { - return hash_policy->generateHash(downstreamConnection()->remoteAddress().get(), - downstreamConnection()->localAddress().get()); + return hash_policy->generateHash( + downstreamConnection()->addressProvider().remoteAddress().get(), + downstreamConnection()->addressProvider().localAddress().get()); } return {}; diff --git a/source/common/tcp_proxy/upstream.cc b/source/common/tcp_proxy/upstream.cc index 5b286f64dbc7..6b0f9446ad15 100644 --- a/source/common/tcp_proxy/upstream.cc +++ b/source/common/tcp_proxy/upstream.cc @@ -175,7 +175,7 @@ void TcpConnPool::onPoolReady(Tcp::ConnectionPool::ConnectionDataPtr&& conn_data auto upstream = std::make_unique(std::move(conn_data), upstream_callbacks_); callbacks_->onGenericPoolReady(&connection.streamInfo(), std::move(upstream), host, - latched_data->connection().localAddress(), + latched_data->connection().addressProvider().localAddress(), latched_data->connection().streamInfo().downstreamSslConnection()); } diff --git a/source/extensions/quic_listeners/quiche/envoy_quic_utils.cc b/source/extensions/quic_listeners/quiche/envoy_quic_utils.cc index bd0a8a657ccd..611a7a28d6f3 100644 --- a/source/extensions/quic_listeners/quiche/envoy_quic_utils.cc +++ b/source/extensions/quic_listeners/quiche/envoy_quic_utils.cc @@ -132,7 +132,7 @@ createConnectionSocket(Network::Address::InstanceConstSharedPtr& peer_addr, } connection_socket->bind(local_addr); ASSERT(local_addr->ip()); - local_addr = connection_socket->localAddress(); + local_addr = connection_socket->addressProvider().localAddress(); if (!Network::Socket::applyOptions(connection_socket->options(), *connection_socket, envoy::config::core::v3::SocketOption::STATE_BOUND)) { ENVOY_LOG_MISC(error, "Fail to apply post-bind options"); diff --git a/source/extensions/upstreams/http/tcp/upstream_request.cc b/source/extensions/upstreams/http/tcp/upstream_request.cc index 8d0d4b25a4b5..0ecc732e507a 100644 --- a/source/extensions/upstreams/http/tcp/upstream_request.cc +++ b/source/extensions/upstreams/http/tcp/upstream_request.cc @@ -29,7 +29,7 @@ void TcpConnPool::onPoolReady(Envoy::Tcp::ConnectionPool::ConnectionDataPtr&& co Network::Connection& latched_conn = conn_data->connection(); auto upstream = std::make_unique(&callbacks_->upstreamToDownstream(), std::move(conn_data)); - callbacks_->onPoolReady(std::move(upstream), host, latched_conn.localAddress(), + callbacks_->onPoolReady(std::move(upstream), host, latched_conn.addressProvider().localAddress(), latched_conn.streamInfo(), {}); } diff --git a/source/server/api_listener_impl.h b/source/server/api_listener_impl.h index bbda83bb6559..3452864a79d5 100644 --- a/source/server/api_listener_impl.h +++ b/source/server/api_listener_impl.h @@ -111,19 +111,10 @@ class ApiListenerImplBase : public ApiListener, void readDisable(bool) override {} void detectEarlyCloseWhenReadDisabled(bool) override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } bool readEnabled() const override { return true; } - const Network::Address::InstanceConstSharedPtr& remoteAddress() const override { - return parent_.parent_.address(); - } - const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const override { - return parent_.parent_.address(); - } absl::optional unixSocketPeerCredentials() const override { return absl::nullopt; } - const Network::Address::InstanceConstSharedPtr& localAddress() const override { - return parent_.parent_.address(); - } void setConnectionStats(const Network::Connection::ConnectionStats&) override {} Ssl::ConnectionInfoConstSharedPtr ssl() const override { return nullptr; } absl::string_view requestedServerName() const override { return EMPTY_STRING; } @@ -132,7 +123,6 @@ class ApiListenerImplBase : public ApiListener, void write(Buffer::Instance&, bool) override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } void setBufferLimits(uint32_t) override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } uint32_t bufferLimit() const override { return 65000; } - bool localAddressRestored() const override { return false; } bool aboveHighWatermark() const override { return false; } const Network::ConnectionSocket::OptionsSharedPtr& socketOptions() const override { return options_; diff --git a/source/server/filter_chain_manager_impl.cc b/source/server/filter_chain_manager_impl.cc index 3caf91fc01c6..6ec4a9f0832f 100644 --- a/source/server/filter_chain_manager_impl.cc +++ b/source/server/filter_chain_manager_impl.cc @@ -419,7 +419,7 @@ std::pair> makeCidrListEntry(const s const Network::FilterChain* FilterChainManagerImpl::findFilterChain(const Network::ConnectionSocket& socket) const { - const auto& address = socket.localAddress(); + const auto& address = socket.addressProvider().localAddress(); const Network::FilterChain* best_match_filter_chain = nullptr; // Match on destination port (only for IP addresses). @@ -449,7 +449,7 @@ FilterChainManagerImpl::findFilterChain(const Network::ConnectionSocket& socket) const Network::FilterChain* FilterChainManagerImpl::findFilterChainForDestinationIP( const DestinationIPsTrie& destination_ips_trie, const Network::ConnectionSocket& socket) const { - auto address = socket.localAddress(); + auto address = socket.addressProvider().localAddress(); if (address->type() != Network::Address::Type::Ip) { address = fakeAddress(); } @@ -570,7 +570,7 @@ const Network::FilterChain* FilterChainManagerImpl::findFilterChainForSourceType const Network::FilterChain* FilterChainManagerImpl::findFilterChainForSourceIpAndPort( const SourceIPsTrie& source_ips_trie, const Network::ConnectionSocket& socket) const { - auto address = socket.remoteAddress(); + auto address = socket.addressProvider().remoteAddress(); if (address->type() != Network::Address::Type::Ip) { address = fakeAddress(); } diff --git a/source/server/listener_impl.cc b/source/server/listener_impl.cc index 879386ce1c04..2745a53f8913 100644 --- a/source/server/listener_impl.cc +++ b/source/server/listener_impl.cc @@ -109,7 +109,7 @@ ListenSocketFactoryImpl::ListenSocketFactoryImpl(ListenerComponentFactory& facto } if (socket_ && local_address_->ip() && local_address_->ip()->port() == 0) { - local_address_ = socket_->localAddress(); + local_address_ = socket_->addressProvider().localAddress(); } ENVOY_LOG(debug, "Set listener {} socket factory local address to {}", listener_name_, local_address_->asString()); diff --git a/test/common/http/codec_client_test.cc b/test/common/http/codec_client_test.cc index ae92e74fe6f0..9c6cd18a7168 100644 --- a/test/common/http/codec_client_test.cc +++ b/test/common/http/codec_client_test.cc @@ -296,12 +296,13 @@ TEST_F(CodecClientTest, SSLConnectionInfo) { class CodecNetworkTest : public Event::TestUsingSimulatedTime, public testing::TestWithParam { public: - CodecNetworkTest() : api_(Api::createApiForTest()), stream_info_(api_->timeSource()) { + CodecNetworkTest() : api_(Api::createApiForTest()), stream_info_(api_->timeSource(), nullptr) { dispatcher_ = api_->allocateDispatcher("test_thread"); auto socket = std::make_shared( Network::Test::getCanonicalLoopbackAddress(GetParam()), nullptr, true); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), source_address_, Network::Test::createRawBufferSocket(), nullptr); + socket->addressProvider().localAddress(), source_address_, + Network::Test::createRawBufferSocket(), nullptr); upstream_listener_ = dispatcher_->createListener(std::move(socket), listener_callbacks_, true, ENVOY_TCP_BACKLOG_SIZE); client_connection_ = client_connection.get(); diff --git a/test/common/http/conn_manager_impl_fuzz_test.cc b/test/common/http/conn_manager_impl_fuzz_test.cc index fdf1bbe7ef2a..1f188c544faa 100644 --- a/test/common/http/conn_manager_impl_fuzz_test.cc +++ b/test/common/http/conn_manager_impl_fuzz_test.cc @@ -570,10 +570,10 @@ DEFINE_PROTO_FUZZER(const test::common::http::ConnManagerImplTestCase& input) { ON_CALL(Const(filter_callbacks.connection_), ssl()).WillByDefault(Return(ssl_connection)); ON_CALL(filter_callbacks.connection_, close(_)) .WillByDefault(InvokeWithoutArgs([&connection_alive] { connection_alive = false; })); - filter_callbacks.connection_.local_address_ = - std::make_shared("127.0.0.1"); - filter_callbacks.connection_.remote_address_ = - std::make_shared("0.0.0.0"); + filter_callbacks.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("127.0.0.1")); + filter_callbacks.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0")); ConnectionManagerImpl conn_manager(config, drain_close, random, http_context, runtime, local_info, cluster_manager, overload_manager, config.time_system_); diff --git a/test/common/http/conn_manager_impl_test.cc b/test/common/http/conn_manager_impl_test.cc index 811a4140be6c..c2e3486dd503 100644 --- a/test/common/http/conn_manager_impl_test.cc +++ b/test/common/http/conn_manager_impl_test.cc @@ -1561,14 +1561,16 @@ TEST_F(HttpConnectionManagerImplTest, TestAccessLog) { const StreamInfo::StreamInfo& stream_info) { EXPECT_TRUE(stream_info.responseCode()); EXPECT_EQ(stream_info.responseCode().value(), uint32_t(200)); - EXPECT_NE(nullptr, stream_info.downstreamLocalAddress()); - EXPECT_NE(nullptr, stream_info.downstreamRemoteAddress()); - EXPECT_NE(nullptr, stream_info.downstreamDirectRemoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().localAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().remoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().directRemoteAddress()); EXPECT_NE(nullptr, stream_info.routeEntry()); - EXPECT_EQ(stream_info.downstreamRemoteAddress()->ip()->addressAsString(), xff_address); - EXPECT_EQ(stream_info.downstreamDirectRemoteAddress()->ip()->addressAsString(), - local_address); + EXPECT_EQ(stream_info.downstreamAddressProvider().remoteAddress()->ip()->addressAsString(), + xff_address); + EXPECT_EQ( + stream_info.downstreamAddressProvider().directRemoteAddress()->ip()->addressAsString(), + local_address); })); EXPECT_CALL(*codec_, dispatch(_)) @@ -1700,9 +1702,9 @@ TEST_F(HttpConnectionManagerImplTest, TestAccessLogWithTrailers) { const StreamInfo::StreamInfo& stream_info) { EXPECT_TRUE(stream_info.responseCode()); EXPECT_EQ(stream_info.responseCode().value(), uint32_t(200)); - EXPECT_NE(nullptr, stream_info.downstreamLocalAddress()); - EXPECT_NE(nullptr, stream_info.downstreamRemoteAddress()); - EXPECT_NE(nullptr, stream_info.downstreamDirectRemoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().localAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().remoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().directRemoteAddress()); EXPECT_NE(nullptr, stream_info.routeEntry()); })); @@ -1750,9 +1752,9 @@ TEST_F(HttpConnectionManagerImplTest, TestAccessLogWithInvalidRequest) { EXPECT_TRUE(stream_info.responseCode()); EXPECT_EQ(stream_info.responseCode().value(), uint32_t(400)); EXPECT_EQ("missing_host_header", stream_info.responseCodeDetails().value()); - EXPECT_NE(nullptr, stream_info.downstreamLocalAddress()); - EXPECT_NE(nullptr, stream_info.downstreamRemoteAddress()); - EXPECT_NE(nullptr, stream_info.downstreamDirectRemoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().localAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().remoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().directRemoteAddress()); EXPECT_EQ(nullptr, stream_info.routeEntry()); })); @@ -1847,9 +1849,9 @@ TEST_F(HttpConnectionManagerImplTest, TestAccessLogSsl) { const StreamInfo::StreamInfo& stream_info) { EXPECT_TRUE(stream_info.responseCode()); EXPECT_EQ(stream_info.responseCode().value(), uint32_t(200)); - EXPECT_NE(nullptr, stream_info.downstreamLocalAddress()); - EXPECT_NE(nullptr, stream_info.downstreamRemoteAddress()); - EXPECT_NE(nullptr, stream_info.downstreamDirectRemoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().localAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().remoteAddress()); + EXPECT_NE(nullptr, stream_info.downstreamAddressProvider().directRemoteAddress()); EXPECT_NE(nullptr, stream_info.downstreamSslConnection()); EXPECT_NE(nullptr, stream_info.routeEntry()); })); diff --git a/test/common/http/conn_manager_impl_test_base.cc b/test/common/http/conn_manager_impl_test_base.cc index f32f39b70258..91e674ef82c8 100644 --- a/test/common/http/conn_manager_impl_test_base.cc +++ b/test/common/http/conn_manager_impl_test_base.cc @@ -57,10 +57,10 @@ void HttpConnectionManagerImplTest::setup(bool ssl, const std::string& server_na .WillByDefault([&](auto, auto callback) { return filter_callbacks_.connection_.dispatcher_.createTimer(callback).release(); }); - filter_callbacks_.connection_.local_address_ = - std::make_shared("127.0.0.1", 443); - filter_callbacks_.connection_.remote_address_ = - std::make_shared("0.0.0.0"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("127.0.0.1", 443)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0")); conn_manager_ = std::make_unique( *this, drain_close_, random_, http_context_, runtime_, local_info_, cluster_manager_, overload_manager_, test_time_.timeSystem()); diff --git a/test/common/http/conn_manager_utility_test.cc b/test/common/http/conn_manager_utility_test.cc index 24ae4608e4cb..cc3dabe3ebf4 100644 --- a/test/common/http/conn_manager_utility_test.cc +++ b/test/common/http/conn_manager_utility_test.cc @@ -197,13 +197,16 @@ TEST_F(ConnectionManagerUtilityTest, DetermineNextProtocol) { // Verify external request and XFF is set when we are using remote address and the address is // external. TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWhenNotLocalHostRemoteAddress) { - connection_.remote_address_ = std::make_shared("12.12.12.12"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("12.12.12.12")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers; EXPECT_EQ((MutateRequestRet{"12.12.12.12:0", false}), callMutateRequestHeaders(headers, Protocol::Http2)); - EXPECT_EQ(connection_.remote_address_->ip()->addressAsString(), + EXPECT_EQ(connection_.stream_info_.downstream_address_provider_->remoteAddress() + ->ip() + ->addressAsString(), headers.get_(Headers::get().ForwardedFor)); } @@ -211,7 +214,8 @@ TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWhenNotLocalHostRemoteAddre // address and where the address is external. TEST_F(ConnectionManagerUtilityTest, SkipXffAppendUseRemoteAddress) { EXPECT_CALL(config_, skipXffAppend()).WillOnce(Return(true)); - connection_.remote_address_ = std::make_shared("12.12.12.12"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("12.12.12.12")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers; @@ -224,7 +228,8 @@ TEST_F(ConnectionManagerUtilityTest, SkipXffAppendUseRemoteAddress) { // address and where the address is external. TEST_F(ConnectionManagerUtilityTest, SkipXffAppendPassThruUseRemoteAddress) { EXPECT_CALL(config_, skipXffAppend()).WillOnce(Return(true)); - connection_.remote_address_ = std::make_shared("12.12.12.12"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("12.12.12.12")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-forwarded-for", "198.51.100.1"}}; @@ -239,7 +244,8 @@ TEST_F(ConnectionManagerUtilityTest, PreserveForwardedProtoWhenInternal) { ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(config_, xffNumTrustedHops()).WillByDefault(Return(1)); EXPECT_CALL(config_, skipXffAppend()).WillOnce(Return(true)); - connection_.remote_address_ = std::make_shared("12.12.12.12"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("12.12.12.12")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-forwarded-proto", "https"}}; @@ -250,7 +256,8 @@ TEST_F(ConnectionManagerUtilityTest, PreserveForwardedProtoWhenInternal) { TEST_F(ConnectionManagerUtilityTest, OverwriteForwardedProtoWhenExternal) { ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(config_, xffNumTrustedHops()).WillByDefault(Return(0)); - connection_.remote_address_ = std::make_shared("127.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("127.0.0.1")); TestRequestHeaderMapImpl headers{{"x-forwarded-proto", "https"}}; Network::Address::Ipv4Instance local_address("10.3.2.1"); ON_CALL(config_, localAddress()).WillByDefault(ReturnRef(local_address)); @@ -270,7 +277,8 @@ TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWhenUserConfiguredRemoteAdd ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(config_, localAddress()).WillByDefault(ReturnRef(local_address)); - connection_.remote_address_ = std::make_shared("12.12.12.12"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("12.12.12.12")); TestRequestHeaderMapImpl headers; EXPECT_EQ((MutateRequestRet{"12.12.12.12:0", true}), @@ -280,7 +288,8 @@ TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWhenUserConfiguredRemoteAdd // Verify internal request and XFF is set when we are using remote address the address is internal. TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWhenLocalHostRemoteAddress) { - connection_.remote_address_ = std::make_shared("127.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("127.0.0.1")); Network::Address::Ipv4Instance local_address("10.3.2.1"); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(config_, localAddress()).WillByDefault(ReturnRef(local_address)); @@ -293,7 +302,8 @@ TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWhenLocalHostRemoteAddress) // Verify that we trust Nth address from XFF when using remote address with xff_num_trusted_hops. TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWithXFFTrustedHops) { - connection_.remote_address_ = std::make_shared("203.0.113.128"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("203.0.113.128")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(config_, xffNumTrustedHops()).WillByDefault(Return(1)); TestRequestHeaderMapImpl headers{{"x-forwarded-for", "198.51.100.1"}}; @@ -304,7 +314,8 @@ TEST_F(ConnectionManagerUtilityTest, UseRemoteAddressWithXFFTrustedHops) { // Verify that xff_num_trusted_hops works when not using remote address. TEST_F(ConnectionManagerUtilityTest, UseXFFTrustedHopsWithoutRemoteAddress) { - connection_.remote_address_ = std::make_shared("127.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("127.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(false)); ON_CALL(config_, xffNumTrustedHops()).WillByDefault(Return(1)); TestRequestHeaderMapImpl headers{{"x-forwarded-for", "198.51.100.2, 198.51.100.1"}}; @@ -315,7 +326,8 @@ TEST_F(ConnectionManagerUtilityTest, UseXFFTrustedHopsWithoutRemoteAddress) { // Verify that we don't set the via header on requests/responses when empty. TEST_F(ConnectionManagerUtilityTest, ViaEmpty) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl request_headers; @@ -332,7 +344,8 @@ TEST_F(ConnectionManagerUtilityTest, ViaEmpty) { // Verify that we append a non-empty via header on requests/responses. TEST_F(ConnectionManagerUtilityTest, ViaAppend) { via_ = "foo"; - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl request_headers; @@ -351,7 +364,8 @@ TEST_F(ConnectionManagerUtilityTest, ViaAppend) { // Verify that we don't set user agent when it is already set. TEST_F(ConnectionManagerUtilityTest, UserAgentDontSet) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"user-agent", "foo"}}; @@ -364,7 +378,8 @@ TEST_F(ConnectionManagerUtilityTest, UserAgentDontSet) { // Verify that we do set user agent when it is empty. TEST_F(ConnectionManagerUtilityTest, UserAgentSetWhenIncomingEmpty) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(local_info_, nodeName()).WillByDefault(ReturnRef(canary_node_)); user_agent_ = "bar"; @@ -422,7 +437,8 @@ TEST_F(ConnectionManagerUtilityTest, InternalServiceForceTrace) { // Test generating request-id in various edge request scenarios. TEST_F(ConnectionManagerUtilityTest, EdgeRequestRegenerateRequestIdAndWipeDownstream) { - connection_.remote_address_ = std::make_shared("34.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("34.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(runtime_.snapshot_, featureEnabled("tracing.global_enabled", An(), _)) @@ -482,7 +498,6 @@ TEST_F(ConnectionManagerUtilityTest, EdgeRequestRegenerateRequestIdAndWipeDownst // does not overwrite x-request-id. This happens in the internal ingress case. TEST_F(ConnectionManagerUtilityTest, ExternalRequestPreserveRequestIdAndDownstream) { ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(false)); - EXPECT_CALL(connection_, remoteAddress()).Times(0); TestRequestHeaderMapImpl headers{{"x-envoy-downstream-service-cluster", "foo"}, {"x-request-id", "id"}, {"x-forwarded-for", "34.0.0.1"}}; @@ -499,7 +514,8 @@ TEST_F(ConnectionManagerUtilityTest, ExternalRequestPreserveRequestIdAndDownstre // Verify that we don't overwrite user agent, but do set x-envoy-downstream-service-cluster // correctly. TEST_F(ConnectionManagerUtilityTest, UserAgentSetIncomingUserAgent) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); user_agent_ = "bar"; @@ -516,7 +532,8 @@ TEST_F(ConnectionManagerUtilityTest, UserAgentSetIncomingUserAgent) { // Verify that we set both user agent and x-envoy-downstream-service-cluster. TEST_F(ConnectionManagerUtilityTest, UserAgentSetNoIncomingUserAgent) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); user_agent_ = "bar"; TestRequestHeaderMapImpl headers; @@ -553,7 +570,8 @@ TEST_F(ConnectionManagerUtilityTest, RequestIdGeneratedWhenItsNotPresent) { // Make sure we do not overwrite x-request-id if the request is internal. TEST_F(ConnectionManagerUtilityTest, DoNotOverrideRequestIdIfPresentWhenInternalRequest) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-request-id", "original_request_id"}}; EXPECT_CALL(random_, uuid()).Times(0); @@ -565,7 +583,8 @@ TEST_F(ConnectionManagerUtilityTest, DoNotOverrideRequestIdIfPresentWhenInternal // Make sure that we do overwrite x-request-id for "edge" external requests. TEST_F(ConnectionManagerUtilityTest, OverrideRequestIdForExternalRequests) { - connection_.remote_address_ = std::make_shared("134.2.2.11"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("134.2.2.11")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-request-id", "original"}}; EXPECT_CALL(random_, uuid()).WillOnce(Return("override")); @@ -578,7 +597,8 @@ TEST_F(ConnectionManagerUtilityTest, OverrideRequestIdForExternalRequests) { // A request that uses remote address and is from an external address should be treated as an // external request with all internal only headers cleaned. TEST_F(ConnectionManagerUtilityTest, ExternalAddressExternalRequestUseRemote) { - connection_.remote_address_ = std::make_shared("50.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("50.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); route_config_.internal_only_headers_.push_back(LowerCaseString("custom_header")); TestRequestHeaderMapImpl headers{{"x-envoy-decorator-operation", "foo"}, @@ -618,7 +638,8 @@ TEST_F(ConnectionManagerUtilityTest, ExternalAddressExternalRequestUseRemote) { // A request that is from an external address, but does not use remote address, should pull the // address from XFF. TEST_F(ConnectionManagerUtilityTest, ExternalAddressExternalRequestDontUseRemote) { - connection_.remote_address_ = std::make_shared("60.0.0.2"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("60.0.0.2")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(false)); TestRequestHeaderMapImpl headers{{"x-envoy-external-address", "60.0.0.1"}, {"x-forwarded-for", "60.0.0.1"}}; @@ -631,7 +652,8 @@ TEST_F(ConnectionManagerUtilityTest, ExternalAddressExternalRequestDontUseRemote // Verify that if XFF is invalid we fall back to remote address, even if it is a pipe. TEST_F(ConnectionManagerUtilityTest, PipeAddressInvalidXFFtDontUseRemote) { - connection_.remote_address_ = std::make_shared("/blah"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("/blah")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(false)); TestRequestHeaderMapImpl headers{{"x-forwarded-for", "blah"}}; @@ -643,7 +665,8 @@ TEST_F(ConnectionManagerUtilityTest, PipeAddressInvalidXFFtDontUseRemote) { // includes only internal addresses. Note that this is legacy behavior. See the comments // in mutateRequestHeaders() for more info. TEST_F(ConnectionManagerUtilityTest, AppendInternalAddressXffNotInternalRequest) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-forwarded-for", "10.0.0.2"}}; @@ -655,7 +678,8 @@ TEST_F(ConnectionManagerUtilityTest, AppendInternalAddressXffNotInternalRequest) // A request that is from an internal address and uses remote address should be an internal request. // It should also preserve x-envoy-external-address. TEST_F(ConnectionManagerUtilityTest, ExternalAddressInternalRequestUseRemote) { - connection_.remote_address_ = std::make_shared("10.0.0.1"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("10.0.0.1")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-envoy-external-address", "60.0.0.1"}, {"x-envoy-expected-rq-timeout-ms", "10"}}; @@ -1438,7 +1462,8 @@ TEST_F(ConnectionManagerUtilityTest, RemovePort) { // test preserve_external_request_id true does not reset the passed requestId if passed TEST_F(ConnectionManagerUtilityTest, PreserveExternalRequestId) { - connection_.remote_address_ = std::make_shared("134.2.2.11"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("134.2.2.11")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(config_, preserveExternalRequestId()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-request-id", "my-request-id"}, @@ -1453,7 +1478,8 @@ TEST_F(ConnectionManagerUtilityTest, PreserveExternalRequestId) { // test preserve_external_request_id true but generates new request id when not passed TEST_F(ConnectionManagerUtilityTest, PreseverExternalRequestIdNoReqId) { - connection_.remote_address_ = std::make_shared("134.2.2.11"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("134.2.2.11")); ON_CALL(config_, useRemoteAddress()).WillByDefault(Return(true)); ON_CALL(config_, preserveExternalRequestId()).WillByDefault(Return(true)); TestRequestHeaderMapImpl headers{{"x-forwarded-for", "198.51.100.1"}}; @@ -1489,7 +1515,8 @@ TEST_F(ConnectionManagerUtilityTest, PreserveExternalRequestIdNoEdgeRequestGener // test preserve_external_request_id false edge request generates new request id TEST_F(ConnectionManagerUtilityTest, NoPreserveExternalRequestIdEdgeRequestGenerateRequestId) { ON_CALL(config_, preserveExternalRequestId()).WillByDefault(Return(false)); - connection_.remote_address_ = std::make_shared("134.2.2.11"); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("134.2.2.11")); // with request id { diff --git a/test/common/network/address_impl_test.cc b/test/common/network/address_impl_test.cc index d1a01ca6734b..5284464bb165 100644 --- a/test/common/network/address_impl_test.cc +++ b/test/common/network/address_impl_test.cc @@ -49,7 +49,7 @@ void testSocketBindAndConnect(Network::Address::IpVersion ip_version, bool v6onl ASSERT_NE(addr_port->ip(), nullptr); // Create a socket on which we'll listen for connections from clients. - SocketImpl sock(Socket::Type::Stream, addr_port); + SocketImpl sock(Socket::Type::Stream, addr_port, nullptr); EXPECT_TRUE(sock.ioHandle().isOpen()) << addr_port->asString(); // Check that IPv6 sockets accept IPv6 connections only. @@ -71,7 +71,7 @@ void testSocketBindAndConnect(Network::Address::IpVersion ip_version, bool v6onl auto client_connect = [](Address::InstanceConstSharedPtr addr_port) { // Create a client socket and connect to the server. - SocketImpl client_sock(Socket::Type::Stream, addr_port); + SocketImpl client_sock(Socket::Type::Stream, addr_port, nullptr); EXPECT_TRUE(client_sock.ioHandle().isOpen()) << addr_port->asString(); @@ -344,7 +344,7 @@ TEST(PipeInstanceTest, BasicPermission) { const mode_t mode = 0777; PipeInstance pipe(path, mode); InstanceConstSharedPtr address = std::make_shared(pipe); - SocketImpl sock(Socket::Type::Stream, address); + SocketImpl sock(Socket::Type::Stream, address, nullptr); EXPECT_TRUE(sock.ioHandle().isOpen()) << pipe.asString(); @@ -371,7 +371,7 @@ TEST(PipeInstanceTest, PermissionFail) { const mode_t mode = 0777; PipeInstance pipe(path, mode); InstanceConstSharedPtr address = std::make_shared(pipe); - SocketImpl sock(Socket::Type::Stream, address); + SocketImpl sock(Socket::Type::Stream, address, nullptr); EXPECT_TRUE(sock.ioHandle().isOpen()) << pipe.asString(); @@ -443,7 +443,7 @@ TEST(PipeInstanceTest, UnlinksExistingFile) { const auto bind_uds_socket = [](const std::string& path) { PipeInstance pipe(path); InstanceConstSharedPtr address = std::make_shared(pipe); - SocketImpl sock(Socket::Type::Stream, address); + SocketImpl sock(Socket::Type::Stream, address, nullptr); EXPECT_TRUE(sock.ioHandle().isOpen()) << pipe.asString(); diff --git a/test/common/network/connection_impl_test.cc b/test/common/network/connection_impl_test.cc index 9aff2cac0007..ed323277d899 100644 --- a/test/common/network/connection_impl_test.cc +++ b/test/common/network/connection_impl_test.cc @@ -136,13 +136,13 @@ class ConnectionImplTest : public testing::TestWithParam { listener_ = dispatcher_->createListener(socket_, listener_callbacks_, true, ENVOY_TCP_BACKLOG_SIZE); client_connection_ = std::make_unique( - *dispatcher_, socket_->localAddress(), source_address_, + *dispatcher_, socket_->addressProvider().localAddress(), source_address_, Network::Test::createRawBufferSocket(), socket_options_); client_connection_->addConnectionCallbacks(client_callbacks_); EXPECT_EQ(nullptr, client_connection_->ssl()); const Network::ClientConnection& const_connection = *client_connection_; EXPECT_EQ(nullptr, const_connection.ssl()); - EXPECT_FALSE(client_connection_->localAddressRestored()); + EXPECT_FALSE(client_connection_->addressProvider().localAddressRestored()); } void connect() { @@ -376,7 +376,7 @@ TEST_P(ConnectionImplTest, ImmediateConnectError) { Address::InstanceConstSharedPtr broadcast_address; socket_ = std::make_shared( Network::Test::getCanonicalLoopbackAddress(GetParam()), nullptr, true); - if (socket_->localAddress()->ip()->version() == Address::IpVersion::v4) { + if (socket_->addressProvider().localAddress()->ip()->version() == Address::IpVersion::v4) { broadcast_address = std::make_shared("224.0.0.1", 0); } else { broadcast_address = std::make_shared("ff02::1", 0); @@ -483,8 +483,8 @@ TEST_P(ConnectionImplTest, SocketOptions) { server_connection_->addReadFilter(read_filter_); upstream_connection_ = dispatcher_->createClientConnection( - socket_->localAddress(), source_address_, Network::Test::createRawBufferSocket(), - server_connection_->socketOptions()); + socket_->addressProvider().localAddress(), source_address_, + Network::Test::createRawBufferSocket(), server_connection_->socketOptions()); })); EXPECT_CALL(server_callbacks_, onEvent(ConnectionEvent::RemoteClose)) @@ -532,8 +532,8 @@ TEST_P(ConnectionImplTest, SocketOptionsFailureTest) { server_connection_->addReadFilter(read_filter_); upstream_connection_ = dispatcher_->createClientConnection( - socket_->localAddress(), source_address_, Network::Test::createRawBufferSocket(), - server_connection_->socketOptions()); + socket_->addressProvider().localAddress(), source_address_, + Network::Test::createRawBufferSocket(), server_connection_->socketOptions()); upstream_connection_->addConnectionCallbacks(upstream_callbacks_); })); @@ -1268,7 +1268,8 @@ TEST_P(ConnectionImplTest, BindTest) { } setUpBasicConnection(); connect(); - EXPECT_EQ(address_string, server_connection_->remoteAddress()->ip()->addressAsString()); + EXPECT_EQ(address_string, + server_connection_->addressProvider().remoteAddress()->ip()->addressAsString()); disconnect(true); } @@ -1287,7 +1288,7 @@ TEST_P(ConnectionImplTest, BindFromSocketTest) { auto option = std::make_shared>(); EXPECT_CALL(*option, setOption(_, Eq(envoy::config::core::v3::SocketOption::STATE_PREBIND))) .WillOnce(Invoke([&](Socket& socket, envoy::config::core::v3::SocketOption::SocketState) { - socket.setLocalAddress(new_source_address); + socket.addressProvider().setLocalAddress(new_source_address); return true; })); @@ -1295,7 +1296,8 @@ TEST_P(ConnectionImplTest, BindFromSocketTest) { socket_options_->emplace_back(std::move(option)); setUpBasicConnection(); connect(); - EXPECT_EQ(address_string, server_connection_->remoteAddress()->ip()->addressAsString()); + EXPECT_EQ(address_string, + server_connection_->addressProvider().remoteAddress()->ip()->addressAsString()); disconnect(true); } @@ -1317,7 +1319,8 @@ TEST_P(ConnectionImplTest, BindFailureTest) { dispatcher_->createListener(socket_, listener_callbacks_, true, ENVOY_TCP_BACKLOG_SIZE); client_connection_ = dispatcher_->createClientConnection( - socket_->localAddress(), source_address_, Network::Test::createRawBufferSocket(), nullptr); + socket_->addressProvider().localAddress(), source_address_, + Network::Test::createRawBufferSocket(), nullptr); MockConnectionStats connection_stats; client_connection_->setConnectionStats(connection_stats.toBufferStats()); @@ -1879,7 +1882,7 @@ class FakeReadFilter : public Network::ReadFilter { class MockTransportConnectionImplTest : public testing::Test { public: - MockTransportConnectionImplTest() : stream_info_(dispatcher_.timeSource()) { + MockTransportConnectionImplTest() : stream_info_(dispatcher_.timeSource(), nullptr) { EXPECT_CALL(dispatcher_.buffer_factory_, create_(_, _, _)) .WillRepeatedly(Invoke([](std::function below_low, std::function above_high, std::function above_overflow) -> Buffer::Instance* { @@ -2684,7 +2687,7 @@ class ReadBufferLimitTest : public ConnectionImplTest { dispatcher_->createListener(socket_, listener_callbacks_, true, ENVOY_TCP_BACKLOG_SIZE); client_connection_ = dispatcher_->createClientConnection( - socket_->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket_->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection_->addConnectionCallbacks(client_callbacks_); client_connection_->connect(); diff --git a/test/common/network/dns_impl_test.cc b/test/common/network/dns_impl_test.cc index e6282f2e6405..6fc0703641e6 100644 --- a/test/common/network/dns_impl_test.cc +++ b/test/common/network/dns_impl_test.cc @@ -271,7 +271,7 @@ class TestDnsServerQuery { class TestDnsServer : public TcpListenerCallbacks { public: TestDnsServer(Event::Dispatcher& dispatcher) - : dispatcher_(dispatcher), record_ttl_(0), stream_info_(dispatcher.timeSource()) {} + : dispatcher_(dispatcher), record_ttl_(0), stream_info_(dispatcher.timeSource(), nullptr) {} void onAccept(ConnectionSocketPtr&& socket) override { Network::ConnectionPtr new_connection = dispatcher_.createServerConnection( @@ -441,7 +441,8 @@ class DnsImplTest : public testing::TestWithParam { listener_ = dispatcher_->createListener(socket_, *server_, true, ENVOY_TCP_BACKLOG_SIZE); if (setResolverInConstructor()) { - resolver_ = dispatcher_->createDnsResolver({socket_->localAddress()}, useTcpForDnsLookups()); + resolver_ = dispatcher_->createDnsResolver({socket_->addressProvider().localAddress()}, + useTcpForDnsLookups()); } else { resolver_ = dispatcher_->createDnsResolver({}, useTcpForDnsLookups()); } @@ -451,7 +452,8 @@ class DnsImplTest : public testing::TestWithParam { if (tcpOnly()) { peer_->resetChannelTcpOnly(zeroTimeout()); } - ares_set_servers_ports_csv(peer_->channel(), socket_->localAddress()->asString().c_str()); + ares_set_servers_ports_csv(peer_->channel(), + socket_->addressProvider().localAddress()->asString().c_str()); } void TearDown() override { @@ -585,7 +587,8 @@ TEST_P(DnsImplTest, DestructCallback) { // This simulates destruction thanks to another query setting the dirty_channel_ bit, thus causing // a subsequent result to call ares_destroy. peer_->resetChannelTcpOnly(zeroTimeout()); - ares_set_servers_ports_csv(peer_->channel(), socket_->localAddress()->asString().c_str()); + ares_set_servers_ports_csv(peer_->channel(), + socket_->addressProvider().localAddress()->asString().c_str()); dispatcher_->run(Event::Dispatcher::RunType::Block); } @@ -712,7 +715,8 @@ TEST_P(DnsImplTest, DestroyChannelOnRefused) { if (tcpOnly()) { peer_->resetChannelTcpOnly(zeroTimeout()); } - ares_set_servers_ports_csv(peer_->channel(), socket_->localAddress()->asString().c_str()); + ares_set_servers_ports_csv(peer_->channel(), + socket_->addressProvider().localAddress()->asString().c_str()); EXPECT_NE(nullptr, resolveWithExpectations("some.good.domain", DnsLookupFamily::Auto, DnsResolver::ResolutionStatus::Success, diff --git a/test/common/network/filter_matcher_test.cc b/test/common/network/filter_matcher_test.cc index cd00d5cc7174..0039642c0cba 100644 --- a/test/common/network/filter_matcher_test.cc +++ b/test/common/network/filter_matcher_test.cc @@ -14,17 +14,16 @@ namespace { struct CallbackHandle { std::unique_ptr callback_; std::unique_ptr socket_; - Address::InstanceConstSharedPtr address_; }; } // namespace class ListenerFilterMatcherTest : public testing::Test { public: std::unique_ptr createCallbackOnPort(int port) { auto handle = std::make_unique(); - handle->address_ = std::make_shared("127.0.0.1", port); handle->socket_ = std::make_unique(); handle->callback_ = std::make_unique(); - EXPECT_CALL(*(handle->socket_), localAddress()).WillRepeatedly(ReturnRef(handle->address_)); + handle->socket_->address_provider_->setLocalAddress( + std::make_shared("127.0.0.1", port)); EXPECT_CALL(*(handle->callback_), socket()).WillRepeatedly(ReturnRef(*(handle->socket_))); return handle; } diff --git a/test/common/network/listen_socket_impl_test.cc b/test/common/network/listen_socket_impl_test.cc index f252b2c6d063..b8155b927dea 100644 --- a/test/common/network/listen_socket_impl_test.cc +++ b/test/common/network/listen_socket_impl_test.cc @@ -87,8 +87,9 @@ class ListenSocketImplTest : public testing::TestWithParam { EXPECT_EQ(0, socket1->listen(0).rc_); } - EXPECT_EQ(addr->ip()->port(), socket1->localAddress()->ip()->port()); - EXPECT_EQ(addr->ip()->addressAsString(), socket1->localAddress()->ip()->addressAsString()); + EXPECT_EQ(addr->ip()->port(), socket1->addressProvider().localAddress()->ip()->port()); + EXPECT_EQ(addr->ip()->addressAsString(), + socket1->addressProvider().localAddress()->ip()->addressAsString()); EXPECT_EQ(Type, socket1->socketType()); auto option2 = std::make_unique(); @@ -108,7 +109,7 @@ class ListenSocketImplTest : public testing::TestWithParam { EXPECT_TRUE(SOCKET_VALID(socket_result.rc_)); Network::IoHandlePtr io_handle = std::make_unique(socket_result.rc_); auto socket3 = createListenSocketPtr(std::move(io_handle), addr, nullptr); - EXPECT_EQ(socket3->localAddress()->asString(), addr->asString()); + EXPECT_EQ(socket3->addressProvider().localAddress()->asString(), addr->asString()); // Test successful. return; @@ -118,10 +119,11 @@ class ListenSocketImplTest : public testing::TestWithParam { void testBindPortZero() { auto loopback = Network::Test::getCanonicalLoopbackAddress(version_); auto socket = createListenSocketPtr(loopback, nullptr, true); - EXPECT_EQ(Address::Type::Ip, socket->localAddress()->type()); - EXPECT_EQ(version_, socket->localAddress()->ip()->version()); - EXPECT_EQ(loopback->ip()->addressAsString(), socket->localAddress()->ip()->addressAsString()); - EXPECT_GT(socket->localAddress()->ip()->port(), 0U); + EXPECT_EQ(Address::Type::Ip, socket->addressProvider().localAddress()->type()); + EXPECT_EQ(version_, socket->addressProvider().localAddress()->ip()->version()); + EXPECT_EQ(loopback->ip()->addressAsString(), + socket->addressProvider().localAddress()->ip()->addressAsString()); + EXPECT_GT(socket->addressProvider().localAddress()->ip()->port(), 0U); EXPECT_EQ(Type, socket->socketType()); } }; @@ -160,9 +162,9 @@ TEST_P(ListenSocketImplTestTcp, SetLocalAddress) { TestListenSocket socket(Utility::getIpv4AnyAddress()); - socket.setLocalAddress(address); + socket.addressProvider().setLocalAddress(address); - EXPECT_EQ(socket.localAddress(), address); + EXPECT_EQ(socket.addressProvider().localAddress(), address); } TEST_P(ListenSocketImplTestUdp, BindSpecificPort) { testBindSpecificPort(); } diff --git a/test/common/network/listener_impl_test.cc b/test/common/network/listener_impl_test.cc index 9bbfe6643c42..38dc232a4b7f 100644 --- a/test/common/network/listener_impl_test.cc +++ b/test/common/network/listener_impl_test.cc @@ -40,11 +40,11 @@ static void errorCallbackTest(Address::IpVersion version) { dispatcher->createListener(socket, listener_callbacks, true, ENVOY_TCP_BACKLOG_SIZE); Network::ClientConnectionPtr client_connection = dispatcher->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->connect(); - StreamInfo::StreamInfoImpl stream_info(dispatcher->timeSource()); + StreamInfo::StreamInfoImpl stream_info(dispatcher->timeSource(), nullptr); EXPECT_CALL(listener_callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& accepted_socket) -> void { Network::ConnectionPtr conn = dispatcher->createServerConnection( @@ -113,7 +113,7 @@ TEST_P(TcpListenerImplTest, SetListeningSocketOptionsError) { TestTcpListenerImpl(dispatcherImpl(), random_generator, socket, listener_callbacks, true), CreateListenerException, fmt::format("cannot set post-listen socket option on socket: {}", - socket->localAddress()->asString())); + socket->addressProvider().localAddress()->asString())); } TEST_P(TcpListenerImplTest, UseActualDst) { @@ -131,19 +131,20 @@ TEST_P(TcpListenerImplTest, UseActualDst) { listener_callbacks2, false); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->connect(); EXPECT_CALL(listener, getLocalAddress(_)).Times(0); - StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource()); + StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource(), nullptr); EXPECT_CALL(listener_callbacks2, onAccept_(_)).Times(0); EXPECT_CALL(listener_callbacks1, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& accepted_socket) -> void { Network::ConnectionPtr conn = dispatcher_->createServerConnection( std::move(accepted_socket), Network::Test::createRawBufferSocket(), stream_info); - EXPECT_EQ(*conn->localAddress(), *socket->localAddress()); + EXPECT_EQ(*conn->addressProvider().localAddress(), + *socket->addressProvider().localAddress()); client_connection->close(ConnectionCloseType::NoFlush); conn->close(ConnectionCloseType::NoFlush); dispatcher_->exit(); @@ -167,7 +168,7 @@ TEST_P(TcpListenerImplTest, GlobalConnectionLimitEnforcement) { std::vector client_connections; std::vector server_connections; - StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource()); + StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource(), nullptr); EXPECT_CALL(listener_callbacks, onAccept_(_)) .WillRepeatedly(Invoke([&](Network::ConnectionSocketPtr& accepted_socket) -> void { server_connections.emplace_back(dispatcher_->createServerConnection( @@ -178,7 +179,7 @@ TEST_P(TcpListenerImplTest, GlobalConnectionLimitEnforcement) { auto initiate_connections = [&](const int count) { for (int i = 0; i < count; ++i) { client_connections.emplace_back(dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr)); client_connections.back()->connect(); } @@ -231,19 +232,20 @@ TEST_P(TcpListenerImplTest, WildcardListenerUseActualDst) { Network::TestTcpListenerImpl listener(dispatcherImpl(), random_generator, socket, listener_callbacks, true); - auto local_dst_address = Network::Utility::getAddressWithPort( - *Network::Test::getCanonicalLoopbackAddress(version_), socket->localAddress()->ip()->port()); + auto local_dst_address = + Network::Utility::getAddressWithPort(*Network::Test::getCanonicalLoopbackAddress(version_), + socket->addressProvider().localAddress()->ip()->port()); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( local_dst_address, Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->connect(); - StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource()); + StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource(), nullptr); EXPECT_CALL(listener_callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void { Network::ConnectionPtr conn = dispatcher_->createServerConnection( std::move(socket), Network::Test::createRawBufferSocket(), stream_info); - EXPECT_EQ(*conn->localAddress(), *local_dst_address); + EXPECT_EQ(*conn->addressProvider().localAddress(), *local_dst_address); client_connection->close(ConnectionCloseType::NoFlush); conn->close(ConnectionCloseType::NoFlush); dispatcher_->exit(); @@ -269,29 +271,33 @@ TEST_P(TcpListenerImplTest, WildcardListenerIpv4Compat) { Network::MockConnectionHandler connection_handler; Random::MockRandomGenerator random_generator; - ASSERT_TRUE(socket->localAddress()->ip()->isAnyAddress()); + ASSERT_TRUE(socket->addressProvider().localAddress()->ip()->isAnyAddress()); // Do not redirect since use_original_dst is false. Network::TestTcpListenerImpl listener(dispatcherImpl(), random_generator, socket, listener_callbacks, true); - auto listener_address = Network::Utility::getAddressWithPort( - *Network::Test::getCanonicalLoopbackAddress(version_), socket->localAddress()->ip()->port()); - auto local_dst_address = Network::Utility::getAddressWithPort( - *Network::Utility::getCanonicalIpv4LoopbackAddress(), socket->localAddress()->ip()->port()); + auto listener_address = + Network::Utility::getAddressWithPort(*Network::Test::getCanonicalLoopbackAddress(version_), + socket->addressProvider().localAddress()->ip()->port()); + auto local_dst_address = + Network::Utility::getAddressWithPort(*Network::Utility::getCanonicalIpv4LoopbackAddress(), + socket->addressProvider().localAddress()->ip()->port()); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( local_dst_address, Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->connect(); - StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource()); + StreamInfo::StreamInfoImpl stream_info(dispatcher_->timeSource(), nullptr); EXPECT_CALL(listener_callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void { Network::ConnectionPtr conn = dispatcher_->createServerConnection( std::move(socket), Network::Test::createRawBufferSocket(), stream_info); - EXPECT_EQ(conn->localAddress()->ip()->version(), conn->remoteAddress()->ip()->version()); - EXPECT_EQ(conn->localAddress()->asString(), local_dst_address->asString()); - EXPECT_EQ(*conn->localAddress(), *local_dst_address); + EXPECT_EQ(conn->addressProvider().localAddress()->ip()->version(), + conn->addressProvider().remoteAddress()->ip()->version()); + EXPECT_EQ(conn->addressProvider().localAddress()->asString(), + local_dst_address->asString()); + EXPECT_EQ(*conn->addressProvider().localAddress(), *local_dst_address); client_connection->close(ConnectionCloseType::NoFlush); conn->close(ConnectionCloseType::NoFlush); dispatcher_->exit(); @@ -314,9 +320,9 @@ TEST_P(TcpListenerImplTest, DisableAndEnableListener) { // When listener is disabled, the timer should fire before any connection is accepted. listener.disable(); - ClientConnectionPtr client_connection = - dispatcher_->createClientConnection(socket->localAddress(), Address::InstanceConstSharedPtr(), - Network::Test::createRawBufferSocket(), nullptr); + ClientConnectionPtr client_connection = dispatcher_->createClientConnection( + socket->addressProvider().localAddress(), Address::InstanceConstSharedPtr(), + Network::Test::createRawBufferSocket(), nullptr); client_connection->addConnectionCallbacks(connection_callbacks); client_connection->connect(); @@ -362,9 +368,9 @@ TEST_P(TcpListenerImplTest, SetListenerRejectFractionZero) { } EXPECT_CALL(listener_callbacks, onAccept_(_)).WillOnce([&] { dispatcher_->exit(); }); - ClientConnectionPtr client_connection = - dispatcher_->createClientConnection(socket->localAddress(), Address::InstanceConstSharedPtr(), - Network::Test::createRawBufferSocket(), nullptr); + ClientConnectionPtr client_connection = dispatcher_->createClientConnection( + socket->addressProvider().localAddress(), Address::InstanceConstSharedPtr(), + Network::Test::createRawBufferSocket(), nullptr); client_connection->addConnectionCallbacks(connection_callbacks); client_connection->connect(); dispatcher_->run(Event::Dispatcher::RunType::Block); @@ -401,7 +407,7 @@ TEST_P(TcpListenerImplTest, SetListenerRejectFractionIntermediate) { { ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->addConnectionCallbacks(connection_callbacks); client_connection->connect(); @@ -424,7 +430,7 @@ TEST_P(TcpListenerImplTest, SetListenerRejectFractionIntermediate) { { ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->addConnectionCallbacks(connection_callbacks); client_connection->connect(); @@ -461,9 +467,9 @@ TEST_P(TcpListenerImplTest, SetListenerRejectFractionAll) { }); } - ClientConnectionPtr client_connection = - dispatcher_->createClientConnection(socket->localAddress(), Address::InstanceConstSharedPtr(), - Network::Test::createRawBufferSocket(), nullptr); + ClientConnectionPtr client_connection = dispatcher_->createClientConnection( + socket->addressProvider().localAddress(), Address::InstanceConstSharedPtr(), + Network::Test::createRawBufferSocket(), nullptr); client_connection->addConnectionCallbacks(connection_callbacks); client_connection->connect(); dispatcher_->run(Event::Dispatcher::RunType::Block); diff --git a/test/common/network/socket_option_factory_test.cc b/test/common/network/socket_option_factory_test.cc index b25894f27cb5..30ee22cd15c1 100644 --- a/test/common/network/socket_option_factory_test.cc +++ b/test/common/network/socket_option_factory_test.cc @@ -33,12 +33,14 @@ class SocketOptionFactoryTest : public testing::Test { testing::NiceMock socket_mock_; Api::MockOsSysCalls os_sys_calls_mock_; - void SetUp() override { socket_mock_.local_address_.reset(); } + void SetUp() override { socket_mock_.address_provider_->setLocalAddress(nullptr); } void makeSocketV4() { - socket_mock_.local_address_ = std::make_unique("1.2.3.4", 5678); + socket_mock_.address_provider_->setLocalAddress( + std::make_unique("1.2.3.4", 5678)); } void makeSocketV6() { - socket_mock_.local_address_ = std::make_unique("::1:2:3:4", 5678); + socket_mock_.address_provider_->setLocalAddress( + std::make_unique("::1:2:3:4", 5678)); } }; diff --git a/test/common/network/socket_option_test.h b/test/common/network/socket_option_test.h index ed6c4568061d..e780c3e2ec2a 100644 --- a/test/common/network/socket_option_test.h +++ b/test/common/network/socket_option_test.h @@ -25,7 +25,7 @@ namespace { class SocketOptionTest : public testing::Test { public: SocketOptionTest() { - socket_.local_address_.reset(); + socket_.address_provider_->setLocalAddress(nullptr); EXPECT_CALL(os_sys_calls_, socket(_, _, _)) .Times(AnyNumber()) diff --git a/test/common/network/udp_listener_impl_batch_writer_test.cc b/test/common/network/udp_listener_impl_batch_writer_test.cc index 959fd52515f1..40e4c0a87671 100644 --- a/test/common/network/udp_listener_impl_batch_writer_test.cc +++ b/test/common/network/udp_listener_impl_batch_writer_test.cc @@ -196,8 +196,8 @@ TEST_P(UdpListenerImplBatchWriterTest, WriteBlocked) { // First have initial payload added to the udp_packet_writer's internal buffer. Buffer::InstancePtr initial_buffer(new Buffer::OwnedImpl()); initial_buffer->add(initial_payload); - UdpSendData initial_send_data{send_to_addr_->ip(), *server_socket_->localAddress(), - *initial_buffer}; + UdpSendData initial_send_data{ + send_to_addr_->ip(), *server_socket_->addressProvider().localAddress(), *initial_buffer}; auto send_result = listener_->send(initial_send_data); internal_buffer.append(initial_payload); EXPECT_TRUE(send_result.ok()); @@ -220,8 +220,8 @@ TEST_P(UdpListenerImplBatchWriterTest, WriteBlocked) { // Now send the following payload Buffer::InstancePtr following_buffer(new Buffer::OwnedImpl()); following_buffer->add(following_payload); - UdpSendData following_send_data{send_to_addr_->ip(), *server_socket_->localAddress(), - *following_buffer}; + UdpSendData following_send_data{ + send_to_addr_->ip(), *server_socket_->addressProvider().localAddress(), *following_buffer}; send_result = listener_->send(following_send_data); if (following_payload.length() < initial_payload.length()) { @@ -238,7 +238,8 @@ TEST_P(UdpListenerImplBatchWriterTest, WriteBlocked) { return -1; })); following_buffer->add(following_payload); - UdpSendData final_send_data{send_to_addr_->ip(), *server_socket_->localAddress(), + UdpSendData final_send_data{send_to_addr_->ip(), + *server_socket_->addressProvider().localAddress(), *following_buffer}; send_result = listener_->send(final_send_data); } diff --git a/test/common/network/udp_listener_impl_test.cc b/test/common/network/udp_listener_impl_test.cc index b6e4bd670510..caddb62bc4ce 100644 --- a/test/common/network/udp_listener_impl_test.cc +++ b/test/common/network/udp_listener_impl_test.cc @@ -258,7 +258,7 @@ TEST_P(UdpListenerImplTest, UdpEcho) { * Tests UDP listener's `enable` and `disable` APIs. */ TEST_P(UdpListenerImplTest, UdpListenerEnableDisable) { - auto const* server_ip = server_socket_->localAddress()->ip(); + auto const* server_ip = server_socket_->addressProvider().localAddress()->ip(); ASSERT_NE(server_ip, nullptr); // We first disable the listener and then send two packets. @@ -304,7 +304,7 @@ TEST_P(UdpListenerImplTest, UdpListenerEnableDisable) { * Tests UDP listener's error callback. */ TEST_P(UdpListenerImplTest, UdpListenerRecvMsgError) { - auto const* server_ip = server_socket_->localAddress()->ip(); + auto const* server_ip = server_socket_->addressProvider().localAddress()->ip(); ASSERT_NE(server_ip, nullptr); // When the `receive` system call returns an error, we expect the `onReceiveError` @@ -377,7 +377,8 @@ TEST_P(UdpListenerImplTest, SendDataError) { Buffer::InstancePtr buffer(new Buffer::OwnedImpl()); buffer->add(payload); // send data to itself - UdpSendData send_data{send_to_addr_->ip(), *server_socket_->localAddress(), *buffer}; + UdpSendData send_data{send_to_addr_->ip(), *server_socket_->addressProvider().localAddress(), + *buffer}; // Inject mocked OsSysCalls implementation to mock a write failure. Api::MockOsSysCalls os_sys_calls; diff --git a/test/common/network/udp_listener_impl_test_base.h b/test/common/network/udp_listener_impl_test_base.h index f3b57a1dd136..b3dc07dc30b4 100644 --- a/test/common/network/udp_listener_impl_test_base.h +++ b/test/common/network/udp_listener_impl_test_base.h @@ -38,11 +38,13 @@ class UdpListenerImplTestBase : public ListenerImplTestBase { protected: Address::Instance* getServerLoopbackAddress() { if (version_ == Address::IpVersion::v4) { - return new Address::Ipv4Instance(Network::Test::getLoopbackAddressString(version_), - server_socket_->localAddress()->ip()->port()); + return new Address::Ipv4Instance( + Network::Test::getLoopbackAddressString(version_), + server_socket_->addressProvider().localAddress()->ip()->port()); } - return new Address::Ipv6Instance(Network::Test::getLoopbackAddressString(version_), - server_socket_->localAddress()->ip()->port()); + return new Address::Ipv6Instance( + Network::Test::getLoopbackAddressString(version_), + server_socket_->addressProvider().localAddress()->ip()->port()); } SocketSharedPtr createServerSocket(bool bind) { @@ -64,7 +66,7 @@ class UdpListenerImplTestBase : public ListenerImplTestBase { if (version_ == Address::IpVersion::v4) { // Linux kernel regards any 127.x.x.x as local address. But Mac OS doesn't. send_from_addr = std::make_shared( - "127.0.0.1", server_socket_->localAddress()->ip()->port()); + "127.0.0.1", server_socket_->addressProvider().localAddress()->ip()->port()); } else { // Only use non-local v6 address if IP_FREEBIND is supported. Otherwise use // ::1 to avoid EINVAL error. Unfortunately this can't verify that sendmsg with @@ -76,7 +78,7 @@ class UdpListenerImplTestBase : public ListenerImplTestBase { #else "::1", #endif - server_socket_->localAddress()->ip()->port()); + server_socket_->addressProvider().localAddress()->ip()->port()); } return send_from_addr; } diff --git a/test/common/network/utility_test.cc b/test/common/network/utility_test.cc index 9588f02bb364..b2005e530ea1 100644 --- a/test/common/network/utility_test.cc +++ b/test/common/network/utility_test.cc @@ -183,60 +183,76 @@ TEST(NetworkUtility, GetOriginalDst) { } TEST(NetworkUtility, LocalConnection) { - Network::Address::InstanceConstSharedPtr local_addr; - Network::Address::InstanceConstSharedPtr remote_addr; - testing::NiceMock socket; - EXPECT_CALL(socket, localAddress()).WillRepeatedly(testing::ReturnRef(local_addr)); - EXPECT_CALL(socket, remoteAddress()).WillRepeatedly(testing::ReturnRef(remote_addr)); - - local_addr = std::make_shared("127.0.0.1"); - remote_addr = std::make_shared("/pipe/path"); + socket.address_provider_->setLocalAddress( + std::make_shared("127.0.0.1")); + socket.address_provider_->setRemoteAddress( + std::make_shared("/pipe/path")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("/pipe/path"); - remote_addr = std::make_shared("/pipe/path"); + socket.address_provider_->setLocalAddress( + std::make_shared("/pipe/path")); + socket.address_provider_->setRemoteAddress( + std::make_shared("/pipe/path")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("127.0.0.1"); - remote_addr = std::make_shared("127.0.0.1"); + socket.address_provider_->setLocalAddress( + std::make_shared("127.0.0.1")); + socket.address_provider_->setRemoteAddress( + std::make_shared("127.0.0.1")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("127.0.0.2"); + socket.address_provider_->setLocalAddress( + std::make_shared("127.0.0.2")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("4.4.4.4"); - remote_addr = std::make_shared("8.8.8.8"); + socket.address_provider_->setLocalAddress( + std::make_shared("4.4.4.4")); + socket.address_provider_->setRemoteAddress( + std::make_shared("8.8.8.8")); EXPECT_FALSE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("4.4.4.4"); - remote_addr = std::make_shared("4.4.4.4"); + socket.address_provider_->setLocalAddress( + std::make_shared("4.4.4.4")); + socket.address_provider_->setRemoteAddress( + std::make_shared("4.4.4.4")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("4.4.4.4", 1234); - remote_addr = std::make_shared("4.4.4.4", 4321); + socket.address_provider_->setLocalAddress( + std::make_shared("4.4.4.4", 1234)); + socket.address_provider_->setRemoteAddress( + std::make_shared("4.4.4.4", 4321)); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("::1"); - remote_addr = std::make_shared("::1"); + socket.address_provider_->setLocalAddress( + std::make_shared("::1")); + socket.address_provider_->setRemoteAddress( + std::make_shared("::1")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - local_addr = std::make_shared("::2"); - remote_addr = std::make_shared("::1"); + socket.address_provider_->setLocalAddress( + std::make_shared("::2")); + socket.address_provider_->setRemoteAddress( + std::make_shared("::1")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - remote_addr = std::make_shared("::3"); + socket.address_provider_->setRemoteAddress( + std::make_shared("::3")); EXPECT_FALSE(Utility::isSameIpOrLoopback(socket)); - remote_addr = std::make_shared("::2"); + socket.address_provider_->setRemoteAddress( + std::make_shared("::2")); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - remote_addr = std::make_shared("::2", 4321); - local_addr = std::make_shared("::2", 1234); + socket.address_provider_->setRemoteAddress( + std::make_shared("::2", 4321)); + socket.address_provider_->setLocalAddress( + std::make_shared("::2", 1234)); EXPECT_TRUE(Utility::isSameIpOrLoopback(socket)); - remote_addr = std::make_shared("fd00::"); + socket.address_provider_->setRemoteAddress( + std::make_shared("fd00::")); EXPECT_FALSE(Utility::isSameIpOrLoopback(socket)); } diff --git a/test/common/stream_info/test_util.h b/test/common/stream_info/test_util.h index e42913a2d72e..88c73b8dd90d 100644 --- a/test/common/stream_info/test_util.h +++ b/test/common/stream_info/test_util.h @@ -6,6 +6,7 @@ #include "common/common/assert.h" #include "common/common/random_generator.h" #include "common/http/request_id_extension_impl.h" +#include "common/network/socket_impl.h" #include "common/stream_info/filter_state_impl.h" #include "test/test_common/simulated_time_system.h" @@ -74,24 +75,8 @@ class TestStreamInfo : public StreamInfo::StreamInfo { } bool healthCheck() const override { return health_check_request_; } void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } - const Network::Address::InstanceConstSharedPtr& downstreamLocalAddress() const override { - return downstream_local_address_; - } - const Network::Address::InstanceConstSharedPtr& downstreamDirectRemoteAddress() const override { - return downstream_direct_remote_address_; - } - void setDownstreamRemoteAddress( - const Network::Address::InstanceConstSharedPtr& downstream_remote_address) override { - downstream_remote_address_ = downstream_remote_address; - } - const Network::Address::InstanceConstSharedPtr& downstreamRemoteAddress() const override { - return downstream_remote_address_; - } - void - setDownstreamAddresses(const Network::ConnectedSocketAddressProvider& address_provider) override { - downstream_local_address_ = address_provider.localAddress(); - downstream_direct_remote_address_ = address_provider.directRemoteAddress(); - downstream_remote_address_ = address_provider.remoteAddress(); + const Network::SocketAddressProvider& downstreamAddressProvider() const override { + return *downstream_address_provider_; } void setDownstreamSslConnection(const Ssl::ConnectionInfoConstSharedPtr& connection_info) override { @@ -256,9 +241,8 @@ class TestStreamInfo : public StreamInfo::StreamInfo { bool health_check_request_{}; std::string route_name_; Network::Address::InstanceConstSharedPtr upstream_local_address_; - Network::Address::InstanceConstSharedPtr downstream_local_address_; - Network::Address::InstanceConstSharedPtr downstream_direct_remote_address_; - Network::Address::InstanceConstSharedPtr downstream_remote_address_; + Network::SocketAddressProviderSharedPtr downstream_address_provider_{ + std::make_shared(nullptr, nullptr)}; Ssl::ConnectionInfoConstSharedPtr downstream_connection_info_; Ssl::ConnectionInfoConstSharedPtr upstream_connection_info_; const Router::RouteEntry* route_entry_{}; diff --git a/test/common/tcp_proxy/tcp_proxy_test.cc b/test/common/tcp_proxy/tcp_proxy_test.cc index ac3bc5ae8f37..88e992faca2d 100644 --- a/test/common/tcp_proxy/tcp_proxy_test.cc +++ b/test/common/tcp_proxy/tcp_proxy_test.cc @@ -208,7 +208,8 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // hit route with destination_ip (10.10.10.10/32) NiceMock connection; - connection.local_address_ = std::make_shared("10.10.10.10"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.10.10.10")); EXPECT_EQ(std::string("with_destination_ip_list"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -216,15 +217,18 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall-through NiceMock connection; - connection.local_address_ = std::make_shared("10.10.10.11"); - connection.remote_address_ = std::make_shared("0.0.0.0"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.10.10.11")); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0")); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } { // hit route with destination_ip (10.10.11.0/24) NiceMock connection; - connection.local_address_ = std::make_shared("10.10.11.11"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.10.11.11")); EXPECT_EQ(std::string("with_destination_ip_list"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -232,15 +236,18 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall-through NiceMock connection; - connection.local_address_ = std::make_shared("10.10.12.12"); - connection.remote_address_ = std::make_shared("0.0.0.0"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.10.12.12")); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0")); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } { // hit route with destination_ip (10.11.0.0/16) NiceMock connection; - connection.local_address_ = std::make_shared("10.11.11.11"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.11.11.11")); EXPECT_EQ(std::string("with_destination_ip_list"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -248,15 +255,18 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall-through NiceMock connection; - connection.local_address_ = std::make_shared("10.12.12.12"); - connection.remote_address_ = std::make_shared("0.0.0.0"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.12.12.12")); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0")); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } { // hit route with destination_ip (11.0.0.0/8) NiceMock connection; - connection.local_address_ = std::make_shared("11.11.11.11"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("11.11.11.11")); EXPECT_EQ(std::string("with_destination_ip_list"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -264,15 +274,18 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall-through NiceMock connection; - connection.local_address_ = std::make_shared("12.12.12.12"); - connection.remote_address_ = std::make_shared("0.0.0.0"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("12.12.12.12")); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0")); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } { // hit route with destination_ip (128.0.0.0/8) NiceMock connection; - connection.local_address_ = std::make_shared("128.255.255.255"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("128.255.255.255")); EXPECT_EQ(std::string("with_destination_ip_list"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -280,7 +293,8 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // hit route with destination port range NiceMock connection; - connection.local_address_ = std::make_shared("1.2.3.4", 12345); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 12345)); EXPECT_EQ(std::string("with_destination_ports"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -288,16 +302,20 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall through NiceMock connection; - connection.local_address_ = std::make_shared("1.2.3.4", 23456); - connection.remote_address_ = std::make_shared("0.0.0.0"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 23456)); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0")); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } { // hit route with source port range NiceMock connection; - connection.local_address_ = std::make_shared("1.2.3.4", 23456); - connection.remote_address_ = std::make_shared("0.0.0.0", 23459); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 23456)); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0", 23459)); EXPECT_EQ(std::string("with_source_ports"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -305,17 +323,20 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall through NiceMock connection; - connection.local_address_ = std::make_shared("1.2.3.4", 23456); - connection.remote_address_ = std::make_shared("0.0.0.0", 23458); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 23456)); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("0.0.0.0", 23458)); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } { // hit the route with all criteria present NiceMock connection; - connection.local_address_ = std::make_shared("10.0.0.0", 10000); - connection.remote_address_ = - std::make_shared("20.0.0.0", 20000); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.0.0.0", 10000)); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("20.0.0.0", 20000)); EXPECT_EQ(std::string("with_everything"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -323,16 +344,18 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall through NiceMock connection; - connection.local_address_ = std::make_shared("10.0.0.0", 10000); - connection.remote_address_ = - std::make_shared("30.0.0.0", 20000); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("10.0.0.0", 10000)); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("30.0.0.0", 20000)); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } { // hit route with destination_ip (::1/128) NiceMock connection; - connection.local_address_ = std::make_shared("::1"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("::1")); EXPECT_EQ(std::string("with_v6_destination"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -340,8 +363,8 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // hit route with destination_ip ("2001:abcd/64") NiceMock connection; - connection.local_address_ = - std::make_shared("2001:abcd:0:0:1::"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("2001:abcd:0:0:1::")); EXPECT_EQ(std::string("with_v6_destination"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -349,9 +372,9 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // hit route with destination_ip ("2002::/32") and source_ip ("2003::/64") NiceMock connection; - connection.local_address_ = - std::make_shared("2002:0:0:0:0:0::1"); - connection.remote_address_ = + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("2002:0:0:0:0:0::1")); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( std::make_shared("2003:0:0:0:0::5"); EXPECT_EQ(std::string("with_v6_source_and_destination"), config_obj.getRouteFromEntries(connection)->clusterName()); @@ -360,8 +383,10 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { { // fall through NiceMock connection; - connection.local_address_ = std::make_shared("2004::"); - connection.remote_address_ = std::make_shared("::"); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("2004::")); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("::")); EXPECT_EQ(std::string("catch_all"), config_obj.getRouteFromEntries(connection)->clusterName()); } } diff --git a/test/fuzz/utility.h b/test/fuzz/utility.h index 332e6ae01fce..4962fe2d782a 100644 --- a/test/fuzz/utility.h +++ b/test/fuzz/utility.h @@ -4,6 +4,7 @@ #include "common/common/empty_string.h" #include "common/network/resolver_impl.h" +#include "common/network/socket_impl.h" #include "common/network/utility.h" #include "test/common/stream_info/test_util.h" @@ -165,9 +166,8 @@ inline std::unique_ptr fromStreamInfo(const test::fuzz::StreamIn ? Envoy::Network::Address::resolveProtoAddress(stream_info.upstream_local_address()) : Network::Utility::resolveUrl("tcp://10.0.0.1:10000"); test_stream_info->upstream_local_address_ = upstream_local_address; - test_stream_info->downstream_local_address_ = address; - test_stream_info->downstream_direct_remote_address_ = address; - test_stream_info->downstream_remote_address_ = address; + test_stream_info->downstream_address_provider_ = + std::make_shared(address, address); auto connection_info = std::make_shared>(); ON_CALL(*connection_info, subjectPeerCertificate()) .WillByDefault(testing::ReturnRef(TestSubjectPeer)); diff --git a/test/mocks/network/connection.cc b/test/mocks/network/connection.cc index a0fe1bca4612..ad6327d58d88 100644 --- a/test/mocks/network/connection.cc +++ b/test/mocks/network/connection.cc @@ -54,6 +54,8 @@ void MockConnectionBase::runLowWatermarkCallbacks() { } template static void initializeMockConnection(T& connection) { + ON_CALL(connection, addressProvider()) + .WillByDefault(ReturnPointee(connection.stream_info_.downstream_address_provider_)); ON_CALL(connection, dispatcher()).WillByDefault(ReturnRef(connection.dispatcher_)); ON_CALL(connection, readEnabled()).WillByDefault(ReturnPointee(&connection.read_enabled_)); ON_CALL(connection, addConnectionCallbacks(_)) @@ -109,7 +111,7 @@ MockClientConnection::MockClientConnection() { stream_info_.downstream_address_provider_->setRemoteAddress( Utility::resolveUrl("tcp://10.0.0.1:443")); stream_info_.downstream_address_provider_->setLocalAddress( - Utility::resolveUrl("tcp://10.0.0.2:40000")); + Utility::resolveUrl("tcp://10.0.0.2:40000")); initializeMockConnection(*this); } diff --git a/test/mocks/network/connection.h b/test/mocks/network/connection.h index 2fcc5eb8b701..8e1b1e1012ce 100644 --- a/test/mocks/network/connection.h +++ b/test/mocks/network/connection.h @@ -65,6 +65,7 @@ class MockConnectionBase { MOCK_METHOD(void, detectEarlyCloseWhenReadDisabled, (bool)); \ MOCK_METHOD(bool, readEnabled, (), (const)); \ MOCK_METHOD(const SocketAddressProvider&, addressProvider, (), (const)); \ + MOCK_METHOD(SocketAddressProviderConstSharedPtr, addressProviderSharedPtr, (), (const)); \ MOCK_METHOD(absl::optional, \ unixSocketPeerCredentials, (), (const)); \ MOCK_METHOD(void, setConnectionStats, (const ConnectionStats& stats)); \ @@ -126,48 +127,7 @@ class MockFilterManagerConnection : public FilterManagerConnection, public MockC MockFilterManagerConnection(); ~MockFilterManagerConnection() override; - // Network::Connection - MOCK_METHOD(void, addConnectionCallbacks, (ConnectionCallbacks & cb)); - MOCK_METHOD(void, removeConnectionCallbacks, (ConnectionCallbacks & cb)); - MOCK_METHOD(void, addBytesSentCallback, (BytesSentCb cb)); - MOCK_METHOD(void, addWriteFilter, (WriteFilterSharedPtr filter)); - MOCK_METHOD(void, addFilter, (FilterSharedPtr filter)); - MOCK_METHOD(void, addReadFilter, (ReadFilterSharedPtr filter)); - MOCK_METHOD(void, removeReadFilter, (ReadFilterSharedPtr filter)); - MOCK_METHOD(void, enableHalfClose, (bool enabled)); - MOCK_METHOD(bool, isHalfCloseEnabled, ()); - MOCK_METHOD(void, close, (ConnectionCloseType type)); - MOCK_METHOD(Event::Dispatcher&, dispatcher, ()); - MOCK_METHOD(uint64_t, id, (), (const)); - MOCK_METHOD(void, hashKey, (std::vector&), (const)); - MOCK_METHOD(bool, initializeReadFilters, ()); - MOCK_METHOD(std::string, nextProtocol, (), (const)); - MOCK_METHOD(void, noDelay, (bool enable)); - MOCK_METHOD(void, readDisable, (bool disable)); - MOCK_METHOD(void, detectEarlyCloseWhenReadDisabled, (bool)); - MOCK_METHOD(bool, readEnabled, (), (const)); - MOCK_METHOD(const Address::InstanceConstSharedPtr&, remoteAddress, (), (const)); - MOCK_METHOD(const Address::InstanceConstSharedPtr&, directRemoteAddress, (), (const)); - MOCK_METHOD(absl::optional, - unixSocketPeerCredentials, (), (const)); - MOCK_METHOD(const Address::InstanceConstSharedPtr&, localAddress, (), (const)); - MOCK_METHOD(void, setConnectionStats, (const ConnectionStats& stats)); - MOCK_METHOD(Ssl::ConnectionInfoConstSharedPtr, ssl, (), (const)); - MOCK_METHOD(absl::string_view, requestedServerName, (), (const)); - MOCK_METHOD(State, state, (), (const)); - MOCK_METHOD(bool, connecting, (), (const)); - MOCK_METHOD(void, write, (Buffer::Instance & data, bool end_stream)); - MOCK_METHOD(void, setBufferLimits, (uint32_t limit)); - MOCK_METHOD(uint32_t, bufferLimit, (), (const)); - MOCK_METHOD(bool, localAddressRestored, (), (const)); - MOCK_METHOD(bool, aboveHighWatermark, (), (const)); - MOCK_METHOD(const Network::ConnectionSocket::OptionsSharedPtr&, socketOptions, (), (const)); - MOCK_METHOD(StreamInfo::StreamInfo&, streamInfo, ()); - MOCK_METHOD(const StreamInfo::StreamInfo&, streamInfo, (), (const)); - MOCK_METHOD(void, setDelayedCloseTimeout, (std::chrono::milliseconds)); - MOCK_METHOD(absl::string_view, transportFailureReason, (), (const)); - MOCK_METHOD(bool, startSecureTransport, ()); - MOCK_METHOD(absl::optional, lastRoundTripTime, (), (const)); + DEFINE_MOCK_CONNECTION_MOCK_METHODS; // Network::FilterManagerConnection MOCK_METHOD(StreamBuffer, getReadBuffer, ()); diff --git a/test/mocks/network/mocks.h b/test/mocks/network/mocks.h index 7dadc4dfdb0c..82a3d0890cbf 100644 --- a/test/mocks/network/mocks.h +++ b/test/mocks/network/mocks.h @@ -223,9 +223,11 @@ class MockListenSocket : public Socket { void addOption(const Socket::OptionConstSharedPtr& option) override { addOption_(option); } void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } - SocketAddressProvider& addressProvider() override; - const SocketAddressProvider& addressProvider() const override; - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override; + SocketAddressProvider& addressProvider() override { return *address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return address_provider_; + } MOCK_METHOD(IoHandle&, ioHandle, ()); MOCK_METHOD(SocketPtr, duplicate, ()); MOCK_METHOD(const IoHandle&, ioHandle, (), (const)); @@ -273,9 +275,11 @@ class MockConnectionSocket : public ConnectionSocket { void addOption(const Socket::OptionConstSharedPtr& option) override { addOption_(option); } void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } - SocketAddressProvider& addressProvider() override; - const SocketAddressProvider& addressProvider() const override; - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override; + SocketAddressProvider& addressProvider() override { return *address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return address_provider_; + } MOCK_METHOD(void, setDetectedTransportProtocol, (absl::string_view)); MOCK_METHOD(absl::string_view, detectedTransportProtocol, (), (const)); MOCK_METHOD(void, setRequestedApplicationProtocols, (const std::vector&)); diff --git a/test/mocks/network/socket.h b/test/mocks/network/socket.h index d6ca57d3bb8d..f7db519ff5d4 100644 --- a/test/mocks/network/socket.h +++ b/test/mocks/network/socket.h @@ -14,9 +14,11 @@ class MockSocket : public Socket { MockSocket(); ~MockSocket() override; - SocketAddressProvider& addressProvider() override; - const SocketAddressProvider& addressProvider() const override; - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override; + SocketAddressProvider& addressProvider() override { return *address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return address_provider_; + } IoHandle& ioHandle() override; const IoHandle& ioHandle() const override; Api::SysCallIntResult setSocketOption(int level, int optname, const void* optval, @@ -39,6 +41,7 @@ class MockSocket : public Socket { MOCK_METHOD(void, addOptions, (const Socket::OptionsSharedPtr&), (override)); const std::unique_ptr io_handle_; + Network::SocketAddressProviderSharedPtr address_provider_; }; } // namespace Network diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index 5a75e0583c62..c3f319f674de 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -2,7 +2,6 @@ #include "envoy/config/core/v3/base.pb.h" #include "envoy/http/request_id_extension.h" -#include "envoy/network/listen_socket.h" #include "envoy/network/socket.h" #include "envoy/stream_info/stream_info.h" From 51586fafe040e8b2300b92a9c12caca0c5b6693e Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Sun, 3 Jan 2021 22:02:40 +0000 Subject: [PATCH 5/8] more Signed-off-by: Matt Klein --- include/envoy/network/socket.h | 43 +++++++------- include/envoy/stream_info/stream_info.h | 2 +- source/common/http/conn_manager_impl.cc | 9 +-- source/common/http/filter_manager.h | 46 ++++++++++++++- source/common/stream_info/stream_info_impl.h | 6 +- source/common/upstream/health_checker_impl.cc | 2 +- .../grpc/grpc_access_log_utils.cc | 12 ++-- .../extensions/filters/common/expr/context.cc | 16 +++-- .../common/ext_authz/check_request_utils.cc | 6 +- .../original_src_socket_option.cc | 2 +- .../filters/common/rbac/matchers.cc | 11 ++-- .../http/ip_tagging/ip_tagging_filter.cc | 2 +- .../extensions/filters/http/lua/wrappers.cc | 6 +- .../filters/http/original_src/original_src.cc | 3 +- .../filters/http/ratelimit/ratelimit.cc | 7 ++- .../filters/http/rbac/rbac_filter.cc | 9 ++- .../listener/original_dst/original_dst.cc | 2 +- .../listener/original_src/original_src.cc | 2 +- .../listener/proxy_protocol/proxy_protocol.cc | 7 ++- .../client_ssl_auth/client_ssl_auth.cc | 3 +- .../network/dubbo_proxy/active_message.cc | 5 +- .../filters/network/rbac/rbac_filter.cc | 39 ++++++------ .../network/thrift_proxy/conn_manager.h | 6 +- .../filters/ratelimit/ratelimit.cc | 6 +- .../filters/udp/udp_proxy/udp_proxy_filter.h | 3 +- .../quiche/envoy_quic_client_connection.cc | 14 ++--- .../quiche/envoy_quic_server_connection.cc | 5 +- .../quic_listeners/quiche/envoy_quic_stream.h | 2 +- .../quic_filter_manager_connection_impl.cc | 25 +------- .../quic_filter_manager_connection_impl.h | 13 ++-- .../extensions/stat_sinks/hystrix/hystrix.cc | 10 +++- .../transport_sockets/alts/tsi_socket.cc | 4 +- .../proxy_protocol/proxy_protocol.cc | 4 +- .../transport_sockets/tap/tap_config_impl.cc | 6 +- source/server/admin/admin.cc | 2 +- source/server/admin/admin.h | 2 +- source/server/api_listener_impl.h | 13 +++- source/server/connection_handler_impl.cc | 6 +- source/server/connection_handler_impl.h | 7 ++- test/common/tcp_proxy/tcp_proxy_test.cc | 59 ++++++++++--------- .../upstream/original_dst_cluster_test.cc | 59 +++++++++---------- .../http/ip_tagging/ip_tagging_filter_test.cc | 29 ++++----- .../filters/network/rbac/filter_test.cc | 2 +- .../quiche/active_quic_listener_test.cc | 5 +- .../quiche/envoy_quic_dispatcher_test.cc | 17 +++--- .../quiche/envoy_quic_proof_source_test.cc | 4 +- test/integration/base_integration_test.cc | 2 +- test/integration/fake_upstream.cc | 2 +- test/integration/fake_upstream.h | 6 +- test/integration/server.cc | 2 +- test/mocks/stream_info/mocks.h | 2 +- test/server/admin/admin_test.cc | 2 +- test/server/connection_handler_test.cc | 19 ++---- test/server/filter_chain_benchmark_test.cc | 50 ++++++++-------- test/server/filter_chain_manager_impl_test.cc | 4 +- test/server/listener_manager_impl_test.cc | 12 ++-- test/server/listener_manager_impl_test.h | 4 +- test/server/server_test.cc | 2 +- 58 files changed, 346 insertions(+), 304 deletions(-) diff --git a/include/envoy/network/socket.h b/include/envoy/network/socket.h index 24ab937fd228..e67588e0f453 100644 --- a/include/envoy/network/socket.h +++ b/include/envoy/network/socket.h @@ -43,17 +43,37 @@ struct SocketOptionName { Network::SocketOptionName(level, option, #level "/" #option) /** - * Interface for providing a socket's local address. + * Interfaces for providing a socket's various addresses. */ -class SocketAddressProvider { +class SocketAddressProviderGetters { public: - virtual ~SocketAddressProvider() = default; + virtual ~SocketAddressProviderGetters() = default; /** * @return the local address of the socket. */ virtual const Address::InstanceConstSharedPtr& localAddress() const PURE; + /** + * @return true if the local address has been restored to a value that is different from the + * address the socket was initially accepted at. + */ + virtual bool localAddressRestored() const PURE; + + /** + * @return the remote address of the socket. + */ + virtual const Address::InstanceConstSharedPtr& remoteAddress() const PURE; + + /** + * @return the direct remote address of the socket. This is the address of the directly + * connected peer, and cannot be modified by listener filters. + */ + virtual const Address::InstanceConstSharedPtr& directRemoteAddress() const PURE; +}; + +class SocketAddressProvider : public SocketAddressProviderGetters { +public: /** * Set the local address of the socket. On accepted sockets the local address defaults to the * one at which the connection was received at, which is the same as the listener's address, if @@ -75,23 +95,6 @@ class SocketAddressProvider { */ virtual void restoreLocalAddress(const Address::InstanceConstSharedPtr& local_address) PURE; - /** - * @return true if the local address has been restored to a value that is different from the - * address the socket was initially accepted at. - */ - virtual bool localAddressRestored() const PURE; - - /** - * @return the remote address of the socket. - */ - virtual const Address::InstanceConstSharedPtr& remoteAddress() const PURE; - - /** - * @return the direct remote address of the socket. This is the address of the directly - * connected peer, and cannot be modified by listener filters. - */ - virtual const Address::InstanceConstSharedPtr& directRemoteAddress() const PURE; - /** * Set the remote address of the socket. */ diff --git a/include/envoy/stream_info/stream_info.h b/include/envoy/stream_info/stream_info.h index a7fa8eaa06f2..373d3427f36b 100644 --- a/include/envoy/stream_info/stream_info.h +++ b/include/envoy/stream_info/stream_info.h @@ -454,7 +454,7 @@ class StreamInfo { /** * fixfix */ - virtual const Network::SocketAddressProvider& downstreamAddressProvider() const PURE; + virtual const Network::SocketAddressProviderGetters& downstreamAddressProvider() const PURE; /** * @param connection_info sets the downstream ssl connection. diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index 631a842d633c..d6f501985486 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -1004,12 +1004,9 @@ void ConnectionManagerImpl::ActiveStream::decodeHeaders(RequestHeaderMapPtr&& he if (!state_.is_internally_created_) { // Only sanitize headers on first pass. // Modify the downstream remote address depending on configuration and headers. - ASSERT(false); // fixfix - /*filter_manager_.streamInfo().setDownstreamRemoteAddress( - ConnectionManagerUtility::mutateRequestHeaders( - *request_headers_, connection_manager_.read_callbacks_->connection(), - connection_manager_.config_, *snapped_route_config_, - connection_manager_.local_info_));*/ + filter_manager_.setDownstreamRemoteAddress(ConnectionManagerUtility::mutateRequestHeaders( + *request_headers_, connection_manager_.read_callbacks_->connection(), + connection_manager_.config_, *snapped_route_config_, connection_manager_.local_info_)); } ASSERT(filter_manager_.streamInfo().downstreamAddressProvider().remoteAddress() != nullptr); diff --git a/source/common/http/filter_manager.h b/source/common/http/filter_manager.h index a0e5c08b9b7a..3ac3dfd7ddf9 100644 --- a/source/common/http/filter_manager.h +++ b/source/common/http/filter_manager.h @@ -7,6 +7,7 @@ #include "envoy/http/filter.h" #include "envoy/http/header_map.h" #include "envoy/matcher/matcher.h" +#include "envoy/network/socket.h" #include "common/buffer/watermark_buffer.h" #include "common/common/dump_state_utils.h" @@ -594,6 +595,45 @@ class FilterManagerCallbacks { virtual const ScopeTrackedObject& scope() PURE; }; +/** + * fixfix + */ +class OverridableRemoteSocketAddressProviderStreamInfo : public StreamInfo::StreamInfoImpl, + Network::SocketAddressProviderGetters { +public: + using StreamInfoImpl::StreamInfoImpl; + + void setDownstreamRemoteAddress( + const Network::Address::InstanceConstSharedPtr& downstream_remote_address) { + ASSERT(overriden_downstream_remote_address_ == nullptr); + overriden_downstream_remote_address_ = downstream_remote_address; + } + + // StreamInfo::StreamInfo + const Network::SocketAddressProviderGetters& downstreamAddressProvider() const override { + return *this; + } + + // Network::SocketAddressProviderGetters + const Network::Address::InstanceConstSharedPtr& localAddress() const override { + return StreamInfoImpl::downstreamAddressProvider().localAddress(); + } + bool localAddressRestored() const override { + return StreamInfoImpl::downstreamAddressProvider().localAddressRestored(); + } + const Network::Address::InstanceConstSharedPtr& remoteAddress() const override { + return overriden_downstream_remote_address_ != nullptr + ? overriden_downstream_remote_address_ + : StreamInfoImpl::downstreamAddressProvider().remoteAddress(); + } + const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const override { + return StreamInfoImpl::downstreamAddressProvider().directRemoteAddress(); + } + +private: + Network::Address::InstanceConstSharedPtr overriden_downstream_remote_address_; +}; + /** * FilterManager manages decoding a request through a series of decoding filter and the encoding * of the resulting response. @@ -850,6 +890,10 @@ class FilterManager : public ScopeTrackedObject, // TODO(snowp): This should probably return a StreamInfo instead of the impl. StreamInfo::StreamInfoImpl& streamInfo() { return stream_info_; } const StreamInfo::StreamInfoImpl& streamInfo() const { return stream_info_; } + void setDownstreamRemoteAddress( + const Network::Address::InstanceConstSharedPtr& downstream_remote_address) { + stream_info_.setDownstreamRemoteAddress(downstream_remote_address); + } // Set up the Encoder/Decoder filter chain. bool createFilterChain(); @@ -942,7 +986,7 @@ class FilterManager : public ScopeTrackedObject, FilterChainFactory& filter_chain_factory_; const LocalReply::LocalReply& local_reply_; - StreamInfo::StreamInfoImpl stream_info_; + OverridableRemoteSocketAddressProviderStreamInfo stream_info_; // TODO(snowp): Once FM has been moved to its own file we'll make these private classes of FM, // at which point they no longer need to be friends. friend ActiveStreamFilterBase; diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index 4fbf37fe54b1..fe576890e458 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -3,8 +3,6 @@ #include #include -#include "common/common/macros.h" -#include "common/network/socket_impl.h" #include "envoy/common/time.h" #include "envoy/config/core/v3/base.pb.h" #include "envoy/http/header_map.h" @@ -14,7 +12,9 @@ #include "common/common/assert.h" #include "common/common/dump_state_utils.h" +#include "common/common/macros.h" #include "common/http/request_id_extension_impl.h" +#include "common/network/socket_impl.h" #include "common/stream_info/filter_state_impl.h" #include "absl/strings/str_replace.h" @@ -193,7 +193,7 @@ struct StreamInfoImpl : public StreamInfo { void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } - const Network::SocketAddressProvider& downstreamAddressProvider() const override { + const Network::SocketAddressProviderGetters& downstreamAddressProvider() const override { return *downstream_address_provider_; } diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index 7f346812db6f..8efb562a7ac8 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -216,7 +216,7 @@ HttpHealthCheckerImpl::HttpActiveHealthCheckSession::HttpActiveHealthCheckSessio hostname_(getHostname(host, parent_.host_value_, parent_.cluster_.info())), protocol_(codecClientTypeToProtocol(parent_.codec_client_type_)), local_address_provider_(std::make_shared( - std::make_shared("127.0.0.1"), nullptr)) {} + std::make_shared("127.0.0.1"), nullptr)) {} // fixfix HttpHealthCheckerImpl::HttpActiveHealthCheckSession::~HttpActiveHealthCheckSession() { ASSERT(client_ == nullptr); diff --git a/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc b/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc index 86556f02ffc5..361f38fc031e 100644 --- a/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc +++ b/source/extensions/access_loggers/grpc/grpc_access_log_utils.cc @@ -135,19 +135,19 @@ void Utility::extractCommonAccessLogProperties( const StreamInfo::StreamInfo& stream_info, const envoy::extensions::access_loggers::grpc::v3::CommonGrpcAccessLogConfig& config) { // TODO(mattklein123): Populate sample_rate field. - if (stream_info.downstreamRemoteAddress() != nullptr) { + if (stream_info.downstreamAddressProvider().remoteAddress() != nullptr) { Network::Utility::addressToProtobufAddress( - *stream_info.downstreamRemoteAddress(), + *stream_info.downstreamAddressProvider().remoteAddress(), *common_access_log.mutable_downstream_remote_address()); } - if (stream_info.downstreamDirectRemoteAddress() != nullptr) { + if (stream_info.downstreamAddressProvider().directRemoteAddress() != nullptr) { Network::Utility::addressToProtobufAddress( - *stream_info.downstreamDirectRemoteAddress(), + *stream_info.downstreamAddressProvider().directRemoteAddress(), *common_access_log.mutable_downstream_direct_remote_address()); } - if (stream_info.downstreamLocalAddress() != nullptr) { + if (stream_info.downstreamAddressProvider().localAddress() != nullptr) { Network::Utility::addressToProtobufAddress( - *stream_info.downstreamLocalAddress(), + *stream_info.downstreamAddressProvider().localAddress(), *common_access_log.mutable_downstream_local_address()); } if (stream_info.downstreamSslConnection() != nullptr) { diff --git a/source/extensions/filters/common/expr/context.cc b/source/extensions/filters/common/expr/context.cc index c76c11edb6c1..a0d6213ec4bb 100644 --- a/source/extensions/filters/common/expr/context.cc +++ b/source/extensions/filters/common/expr/context.cc @@ -247,18 +247,22 @@ absl::optional PeerWrapper::operator[](CelValue key) const { auto value = key.StringOrDie().value(); if (value == Address) { if (local_) { - return CelValue::CreateStringView(info_.downstreamLocalAddress()->asStringView()); + return CelValue::CreateStringView( + info_.downstreamAddressProvider().localAddress()->asStringView()); } else { - return CelValue::CreateStringView(info_.downstreamRemoteAddress()->asStringView()); + return CelValue::CreateStringView( + info_.downstreamAddressProvider().remoteAddress()->asStringView()); } } else if (value == Port) { if (local_) { - if (info_.downstreamLocalAddress()->ip() != nullptr) { - return CelValue::CreateInt64(info_.downstreamLocalAddress()->ip()->port()); + if (info_.downstreamAddressProvider().localAddress()->ip() != nullptr) { + return CelValue::CreateInt64( + info_.downstreamAddressProvider().localAddress()->ip()->port()); } } else { - if (info_.downstreamRemoteAddress()->ip() != nullptr) { - return CelValue::CreateInt64(info_.downstreamRemoteAddress()->ip()->port()); + if (info_.downstreamAddressProvider().remoteAddress()->ip() != nullptr) { + return CelValue::CreateInt64( + info_.downstreamAddressProvider().remoteAddress()->ip()->port()); } } } diff --git a/source/extensions/filters/common/ext_authz/check_request_utils.cc b/source/extensions/filters/common/ext_authz/check_request_utils.cc index 4bd09a1ab5c9..e77dd8e0b32b 100644 --- a/source/extensions/filters/common/ext_authz/check_request_utils.cc +++ b/source/extensions/filters/common/ext_authz/check_request_utils.cc @@ -39,9 +39,11 @@ void CheckRequestUtils::setAttrContextPeer(envoy::service::auth::v3::AttributeCo // Set the address auto addr = peer.mutable_address(); if (local) { - Envoy::Network::Utility::addressToProtobufAddress(*connection.localAddress(), *addr); + Envoy::Network::Utility::addressToProtobufAddress(*connection.addressProvider().localAddress(), + *addr); } else { - Envoy::Network::Utility::addressToProtobufAddress(*connection.remoteAddress(), *addr); + Envoy::Network::Utility::addressToProtobufAddress(*connection.addressProvider().remoteAddress(), + *addr); } // Set the principal. Preferably the URI SAN, DNS SAN or Subject in that order from the peer's diff --git a/source/extensions/filters/common/original_src/original_src_socket_option.cc b/source/extensions/filters/common/original_src/original_src_socket_option.cc index bb20d77b5bb2..4bdbdd4ea7f8 100644 --- a/source/extensions/filters/common/original_src/original_src_socket_option.cc +++ b/source/extensions/filters/common/original_src/original_src_socket_option.cc @@ -21,7 +21,7 @@ bool OriginalSrcSocketOption::setOption( Network::Socket& socket, envoy::config::core::v3::SocketOption::SocketState state) const { if (state == envoy::config::core::v3::SocketOption::STATE_PREBIND) { - socket.setLocalAddress(src_address_); + socket.addressProvider().setLocalAddress(src_address_); } return true; diff --git a/source/extensions/filters/common/rbac/matchers.cc b/source/extensions/filters/common/rbac/matchers.cc index 81b5be5885bf..eac3c3d20576 100644 --- a/source/extensions/filters/common/rbac/matchers.cc +++ b/source/extensions/filters/common/rbac/matchers.cc @@ -135,16 +135,16 @@ bool IPMatcher::matches(const Network::Connection& connection, const Envoy::Http Envoy::Network::Address::InstanceConstSharedPtr ip; switch (type_) { case ConnectionRemote: - ip = connection.remoteAddress(); + ip = connection.addressProvider().remoteAddress(); break; case DownstreamLocal: - ip = info.downstreamLocalAddress(); + ip = info.downstreamAddressProvider().localAddress(); break; case DownstreamDirectRemote: - ip = info.downstreamDirectRemoteAddress(); + ip = info.downstreamAddressProvider().directRemoteAddress(); break; case DownstreamRemote: - ip = info.downstreamRemoteAddress(); + ip = info.downstreamAddressProvider().remoteAddress(); break; default: NOT_REACHED_GCOVR_EXCL_LINE; @@ -154,7 +154,8 @@ bool IPMatcher::matches(const Network::Connection& connection, const Envoy::Http bool PortMatcher::matches(const Network::Connection&, const Envoy::Http::RequestHeaderMap&, const StreamInfo::StreamInfo& info) const { - const Envoy::Network::Address::Ip* ip = info.downstreamLocalAddress().get()->ip(); + const Envoy::Network::Address::Ip* ip = + info.downstreamAddressProvider().localAddress().get()->ip(); return ip && ip->port() == port_; } diff --git a/source/extensions/filters/http/ip_tagging/ip_tagging_filter.cc b/source/extensions/filters/http/ip_tagging/ip_tagging_filter.cc index 191d3f384639..ed68cbe77144 100644 --- a/source/extensions/filters/http/ip_tagging/ip_tagging_filter.cc +++ b/source/extensions/filters/http/ip_tagging/ip_tagging_filter.cc @@ -78,7 +78,7 @@ Http::FilterHeadersStatus IpTaggingFilter::decodeHeaders(Http::RequestHeaderMap& } std::vector tags = - config_->trie().getData(callbacks_->streamInfo().downstreamRemoteAddress()); + config_->trie().getData(callbacks_->streamInfo().downstreamAddressProvider().remoteAddress()); if (!tags.empty()) { const std::string tags_join = absl::StrJoin(tags, ","); diff --git a/source/extensions/filters/http/lua/wrappers.cc b/source/extensions/filters/http/lua/wrappers.cc index daf9d864f246..68b7af66188d 100644 --- a/source/extensions/filters/http/lua/wrappers.cc +++ b/source/extensions/filters/http/lua/wrappers.cc @@ -130,12 +130,14 @@ int StreamInfoWrapper::luaDownstreamSslConnection(lua_State* state) { } int StreamInfoWrapper::luaDownstreamLocalAddress(lua_State* state) { - lua_pushstring(state, stream_info_.downstreamLocalAddress()->asString().c_str()); + lua_pushstring(state, + stream_info_.downstreamAddressProvider().localAddress()->asString().c_str()); return 1; } int StreamInfoWrapper::luaDownstreamDirectRemoteAddress(lua_State* state) { - lua_pushstring(state, stream_info_.downstreamDirectRemoteAddress()->asString().c_str()); + lua_pushstring( + state, stream_info_.downstreamAddressProvider().directRemoteAddress()->asString().c_str()); return 1; } diff --git a/source/extensions/filters/http/original_src/original_src.cc b/source/extensions/filters/http/original_src/original_src.cc index b60495439669..ef5f5214ef13 100644 --- a/source/extensions/filters/http/original_src/original_src.cc +++ b/source/extensions/filters/http/original_src/original_src.cc @@ -14,7 +14,8 @@ OriginalSrcFilter::OriginalSrcFilter(const Config& config) : config_(config) {} void OriginalSrcFilter::onDestroy() {} Http::FilterHeadersStatus OriginalSrcFilter::decodeHeaders(Http::RequestHeaderMap&, bool) { - const auto downstream_address = callbacks_->streamInfo().downstreamRemoteAddress(); + const auto downstream_address = + callbacks_->streamInfo().downstreamAddressProvider().remoteAddress(); ASSERT(downstream_address); if (downstream_address->type() != Network::Address::Type::Ip) { diff --git a/source/extensions/filters/http/ratelimit/ratelimit.cc b/source/extensions/filters/http/ratelimit/ratelimit.cc index b72bb82c4b75..454e8de8e49a 100644 --- a/source/extensions/filters/http/ratelimit/ratelimit.cc +++ b/source/extensions/filters/http/ratelimit/ratelimit.cc @@ -233,9 +233,10 @@ void Filter::populateRateLimitDescriptors(const Router::RateLimitPolicy& rate_li fmt::format("ratelimit.{}.http_filter_enabled", disable_key), 100)) { continue; } - rate_limit.populateDescriptors(*route_entry, descriptors, config_->localInfo().clusterName(), - headers, *callbacks_->streamInfo().downstreamRemoteAddress(), - &callbacks_->streamInfo().dynamicMetadata()); + rate_limit.populateDescriptors( + *route_entry, descriptors, config_->localInfo().clusterName(), headers, + *callbacks_->streamInfo().downstreamAddressProvider().remoteAddress(), + &callbacks_->streamInfo().dynamicMetadata()); } } diff --git a/source/extensions/filters/http/rbac/rbac_filter.cc b/source/extensions/filters/http/rbac/rbac_filter.cc index f17fcec7b866..10ee1c025fcc 100644 --- a/source/extensions/filters/http/rbac/rbac_filter.cc +++ b/source/extensions/filters/http/rbac/rbac_filter.cc @@ -50,13 +50,12 @@ Http::FilterHeadersStatus RoleBasedAccessControlFilter::decodeHeaders(Http::RequestHeaderMap& headers, bool) { ENVOY_LOG( debug, - "checking request: requestedServerName: {}, sourceIP: {}, directRemoteIP: {}, remoteIP: {}," + "checking request: requestedServerName: {}, directRemoteIP: {}, remoteIP: {}," "localAddress: {}, ssl: {}, headers: {}, dynamicMetadata: {}", callbacks_->connection()->requestedServerName(), - callbacks_->connection()->remoteAddress()->asString(), - callbacks_->streamInfo().downstreamDirectRemoteAddress()->asString(), - callbacks_->streamInfo().downstreamRemoteAddress()->asString(), - callbacks_->streamInfo().downstreamLocalAddress()->asString(), + callbacks_->streamInfo().downstreamAddressProvider().directRemoteAddress()->asString(), + callbacks_->streamInfo().downstreamAddressProvider().remoteAddress()->asString(), + callbacks_->streamInfo().downstreamAddressProvider().localAddress()->asString(), callbacks_->connection()->ssl() ? "uriSanPeerCertificate: " + absl::StrJoin(callbacks_->connection()->ssl()->uriSanPeerCertificate(), ",") + diff --git a/source/extensions/filters/listener/original_dst/original_dst.cc b/source/extensions/filters/listener/original_dst/original_dst.cc index cea15d4664bb..b7b13621ac08 100644 --- a/source/extensions/filters/listener/original_dst/original_dst.cc +++ b/source/extensions/filters/listener/original_dst/original_dst.cc @@ -27,7 +27,7 @@ Network::FilterStatus OriginalDstFilter::onAccept(Network::ListenerFilterCallbac // In this case the listener handles the connection directly and does not hand it off. if (original_local_address) { // Restore the local address to the original one. - socket.restoreLocalAddress(original_local_address); + socket.addressProvider().restoreLocalAddress(original_local_address); } } diff --git a/source/extensions/filters/listener/original_src/original_src.cc b/source/extensions/filters/listener/original_src/original_src.cc index 684867d3c39c..a8793761cfb1 100644 --- a/source/extensions/filters/listener/original_src/original_src.cc +++ b/source/extensions/filters/listener/original_src/original_src.cc @@ -16,7 +16,7 @@ OriginalSrcFilter::OriginalSrcFilter(const Config& config) : config_(config) {} Network::FilterStatus OriginalSrcFilter::onAccept(Network::ListenerFilterCallbacks& cb) { auto& socket = cb.socket(); - auto address = socket.remoteAddress(); + auto address = socket.addressProvider().remoteAddress(); ASSERT(address); ENVOY_LOG(debug, diff --git a/source/extensions/filters/listener/proxy_protocol/proxy_protocol.cc b/source/extensions/filters/listener/proxy_protocol/proxy_protocol.cc index 89e882a0f0d8..3250236255b2 100644 --- a/source/extensions/filters/listener/proxy_protocol/proxy_protocol.cc +++ b/source/extensions/filters/listener/proxy_protocol/proxy_protocol.cc @@ -127,10 +127,11 @@ ReadOrParseState Filter::onReadWorker() { } // Only set the local address if it really changed, and mark it as address being restored. - if (*proxy_protocol_header_.value().local_address_ != *socket.localAddress()) { - socket.restoreLocalAddress(proxy_protocol_header_.value().local_address_); + if (*proxy_protocol_header_.value().local_address_ != + *socket.addressProvider().localAddress()) { + socket.addressProvider().restoreLocalAddress(proxy_protocol_header_.value().local_address_); } - socket.setRemoteAddress(proxy_protocol_header_.value().remote_address_); + socket.addressProvider().setRemoteAddress(proxy_protocol_header_.value().remote_address_); } // Release the file event so that we do not interfere with the connection read events. diff --git a/source/extensions/filters/network/client_ssl_auth/client_ssl_auth.cc b/source/extensions/filters/network/client_ssl_auth/client_ssl_auth.cc index 0499d8f49686..bceb77b412ae 100644 --- a/source/extensions/filters/network/client_ssl_auth/client_ssl_auth.cc +++ b/source/extensions/filters/network/client_ssl_auth/client_ssl_auth.cc @@ -112,7 +112,8 @@ void ClientSslAuthFilter::onEvent(Network::ConnectionEvent event) { } ASSERT(read_callbacks_->connection().ssl()); - if (config_->ipAllowlist().contains(*read_callbacks_->connection().remoteAddress())) { + if (config_->ipAllowlist().contains( + *read_callbacks_->connection().addressProvider().remoteAddress())) { config_->stats().auth_ip_allowlist_.inc(); read_callbacks_->continueReading(); return; diff --git a/source/extensions/filters/network/dubbo_proxy/active_message.cc b/source/extensions/filters/network/dubbo_proxy/active_message.cc index 3723578981ea..fc98e76a2862 100644 --- a/source/extensions/filters/network/dubbo_proxy/active_message.cc +++ b/source/extensions/filters/network/dubbo_proxy/active_message.cc @@ -186,10 +186,9 @@ ActiveMessage::ActiveMessage(ConnectionManager& parent) : parent_(parent), request_timer_(std::make_unique( parent_.stats().request_time_ms_, parent.timeSystem())), request_id_(-1), stream_id_(parent.randomGenerator().random()), - stream_info_(parent.timeSystem()), pending_stream_decoded_(false), - local_response_sent_(false) { + stream_info_(parent.timeSystem(), parent_.connection().addressProviderSharedPtr()), + pending_stream_decoded_(false), local_response_sent_(false) { parent_.stats().request_active_.inc(); - stream_info_.setDownstreamAddresses(parent_.connection()); } ActiveMessage::~ActiveMessage() { diff --git a/source/extensions/filters/network/rbac/rbac_filter.cc b/source/extensions/filters/network/rbac/rbac_filter.cc index 6e160cb24e7c..ec810a69e0e2 100644 --- a/source/extensions/filters/network/rbac/rbac_filter.cc +++ b/source/extensions/filters/network/rbac/rbac_filter.cc @@ -21,23 +21,28 @@ RoleBasedAccessControlFilterConfig::RoleBasedAccessControlFilterConfig( enforcement_type_(proto_config.enforcement_type()) {} Network::FilterStatus RoleBasedAccessControlFilter::onData(Buffer::Instance&, bool) { - ENVOY_LOG(debug, - "checking connection: requestedServerName: {}, sourceIP: {}, directRemoteIP: {}," - "remoteIP: {}, localAddress: {}, ssl: {}, dynamicMetadata: {}", - callbacks_->connection().requestedServerName(), - callbacks_->connection().remoteAddress()->asString(), - callbacks_->connection().streamInfo().downstreamDirectRemoteAddress()->asString(), - callbacks_->connection().streamInfo().downstreamRemoteAddress()->asString(), - callbacks_->connection().streamInfo().downstreamLocalAddress()->asString(), - callbacks_->connection().ssl() - ? "uriSanPeerCertificate: " + - absl::StrJoin(callbacks_->connection().ssl()->uriSanPeerCertificate(), ",") + - ", dnsSanPeerCertificate: " + - absl::StrJoin(callbacks_->connection().ssl()->dnsSansPeerCertificate(), ",") + - ", subjectPeerCertificate: " + - callbacks_->connection().ssl()->subjectPeerCertificate() - : "none", - callbacks_->connection().streamInfo().dynamicMetadata().DebugString()); + ENVOY_LOG( + debug, + "checking connection: requestedServerName: {}, sourceIP: {}, directRemoteIP: {}," + "remoteIP: {}, localAddress: {}, ssl: {}, dynamicMetadata: {}", + callbacks_->connection().requestedServerName(), + callbacks_->connection().addressProvider().remoteAddress()->asString(), + callbacks_->connection() + .streamInfo() + .downstreamAddressProvider() + .directRemoteAddress() + ->asString(), + callbacks_->connection().streamInfo().downstreamAddressProvider().remoteAddress()->asString(), + callbacks_->connection().streamInfo().downstreamAddressProvider().localAddress()->asString(), + callbacks_->connection().ssl() + ? "uriSanPeerCertificate: " + + absl::StrJoin(callbacks_->connection().ssl()->uriSanPeerCertificate(), ",") + + ", dnsSanPeerCertificate: " + + absl::StrJoin(callbacks_->connection().ssl()->dnsSansPeerCertificate(), ",") + + ", subjectPeerCertificate: " + + callbacks_->connection().ssl()->subjectPeerCertificate() + : "none", + callbacks_->connection().streamInfo().dynamicMetadata().DebugString()); std::string log_policy_id = "none"; // When the enforcement type is continuous always do the RBAC checks. If it is a one time check, diff --git a/source/extensions/filters/network/thrift_proxy/conn_manager.h b/source/extensions/filters/network/thrift_proxy/conn_manager.h index dcb0661f1b74..12bc08347150 100644 --- a/source/extensions/filters/network/thrift_proxy/conn_manager.h +++ b/source/extensions/filters/network/thrift_proxy/conn_manager.h @@ -161,10 +161,10 @@ class ConnectionManager : public Network::ReadFilter, : parent_(parent), request_timer_(new Stats::HistogramCompletableTimespanImpl( parent_.stats_.request_time_ms_, parent_.time_source_)), stream_id_(parent_.random_generator_.random()), - stream_info_(parent_.time_source_), local_response_sent_{false}, pending_transport_end_{ - false} { + stream_info_(parent_.time_source_, + parent_.read_callbacks_->connection().addressProviderSharedPtr()), + local_response_sent_{false}, pending_transport_end_{false} { parent_.stats_.request_active_.inc(); - stream_info_.setDownstreamAddresses(parent_.read_callbacks_->connection()); } ~ActiveRpc() override { request_timer_->complete(); diff --git a/source/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit.cc b/source/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit.cc index a9cf61aca3e3..61c592c28b75 100644 --- a/source/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit.cc +++ b/source/extensions/filters/network/thrift_proxy/filters/ratelimit/ratelimit.cc @@ -121,9 +121,9 @@ void Filter::populateRateLimitDescriptors( fmt::format("ratelimit.{}.thrift_filter_enabled", disable_key), 100)) { continue; } - rate_limit.populateDescriptors(*route_entry, descriptors, config_->localInfo().clusterName(), - metadata, - *decoder_callbacks_->streamInfo().downstreamRemoteAddress()); + rate_limit.populateDescriptors( + *route_entry, descriptors, config_->localInfo().clusterName(), metadata, + *decoder_callbacks_->streamInfo().downstreamAddressProvider().remoteAddress()); } } diff --git a/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h b/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h index f2646b04b1ff..bb689829228e 100644 --- a/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h +++ b/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h @@ -259,7 +259,8 @@ class UdpProxyFilter : public Network::UdpListenerReadFilter, virtual Network::SocketPtr createSocket(const Upstream::HostConstSharedPtr& host) { // Virtual so this can be overridden in unit tests. - return std::make_unique(Network::Socket::Type::Datagram, host->address()); + return std::make_unique(Network::Socket::Type::Datagram, nullptr, + host->address()); } // Upstream::ClusterUpdateCallbacks diff --git a/source/extensions/quic_listeners/quiche/envoy_quic_client_connection.cc b/source/extensions/quic_listeners/quiche/envoy_quic_client_connection.cc index 63783ee08e35..6759ec0d29d2 100644 --- a/source/extensions/quic_listeners/quiche/envoy_quic_client_connection.cc +++ b/source/extensions/quic_listeners/quiche/envoy_quic_client_connection.cc @@ -42,11 +42,11 @@ EnvoyQuicClientConnection::EnvoyQuicClientConnection( quic::QuicAlarmFactory& alarm_factory, quic::QuicPacketWriter* writer, bool owns_writer, const quic::ParsedQuicVersionVector& supported_versions, Event::Dispatcher& dispatcher, Network::ConnectionSocketPtr&& connection_socket) - : EnvoyQuicConnection( - server_connection_id, quic::QuicSocketAddress(), - envoyIpAddressToQuicSocketAddress(connection_socket->remoteAddress()->ip()), helper, - alarm_factory, writer, owns_writer, quic::Perspective::IS_CLIENT, supported_versions, - std::move(connection_socket)), + : EnvoyQuicConnection(server_connection_id, quic::QuicSocketAddress(), + envoyIpAddressToQuicSocketAddress( + connection_socket->addressProvider().remoteAddress()->ip()), + helper, alarm_factory, writer, owns_writer, quic::Perspective::IS_CLIENT, + supported_versions, std::move(connection_socket)), dispatcher_(dispatcher) {} void EnvoyQuicClientConnection::processPacket( @@ -117,8 +117,8 @@ void EnvoyQuicClientConnection::onFileEvent(uint32_t events) { // event processing. if (connected() && (events & Event::FileReadyType::Read)) { Api::IoErrorPtr err = Network::Utility::readPacketsFromSocket( - connectionSocket()->ioHandle(), *connectionSocket()->localAddress(), *this, - dispatcher_.timeSource(), packets_dropped_); + connectionSocket()->ioHandle(), *connectionSocket()->addressProvider().localAddress(), + *this, dispatcher_.timeSource(), packets_dropped_); // TODO(danzh): Handle no error when we limit the number of packets read. if (err->getErrorCode() != Api::IoError::IoErrorCode::Again) { ENVOY_CONN_LOG(error, "recvmsg result {}: {}", *this, static_cast(err->getErrorCode()), diff --git a/source/extensions/quic_listeners/quiche/envoy_quic_server_connection.cc b/source/extensions/quic_listeners/quiche/envoy_quic_server_connection.cc index 974c6c8ebc8c..214cd56c56d2 100644 --- a/source/extensions/quic_listeners/quiche/envoy_quic_server_connection.cc +++ b/source/extensions/quic_listeners/quiche/envoy_quic_server_connection.cc @@ -28,12 +28,13 @@ bool EnvoyQuicServerConnection::OnPacketHeader(const quic::QuicPacketHeader& hea if (!EnvoyQuicConnection::OnPacketHeader(header)) { return false; } - if (connectionSocket()->localAddress() != nullptr) { + if (connectionSocket()->addressProvider().localAddress() != nullptr) { return true; } ASSERT(self_address().IsInitialized()); // Self address should be initialized by now. - connectionSocket()->setLocalAddress(quicAddressToEnvoyAddressInstance(self_address())); + connectionSocket()->addressProvider().setLocalAddress( + quicAddressToEnvoyAddressInstance(self_address())); connectionSocket()->setDetectedTransportProtocol( Extensions::TransportSockets::TransportProtocolNames::get().Quic); return true; diff --git a/source/extensions/quic_listeners/quiche/envoy_quic_stream.h b/source/extensions/quic_listeners/quiche/envoy_quic_stream.h index 258f212917f1..287878b0f96b 100644 --- a/source/extensions/quic_listeners/quiche/envoy_quic_stream.h +++ b/source/extensions/quic_listeners/quiche/envoy_quic_stream.h @@ -79,7 +79,7 @@ class EnvoyQuicStream : public virtual Http::StreamEncoder, } uint32_t bufferLimit() override { return send_buffer_simulation_.highWatermark(); } const Network::Address::InstanceConstSharedPtr& connectionLocalAddress() override { - return connection()->localAddress(); + return connection()->addressProvider().localAddress(); } void maybeCheckWatermark(uint64_t buffered_data_old, uint64_t buffered_data_new, diff --git a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.cc b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.cc index 4954196bfa47..82249588bf61 100644 --- a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.cc +++ b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.cc @@ -11,7 +11,9 @@ QuicFilterManagerConnectionImpl::QuicFilterManagerConnectionImpl(EnvoyQuicConnec // Using this for purpose other than logging is not safe. Because QUIC connection id can be // 18 bytes, so there might be collision when it's hashed to 8 bytes. : Network::ConnectionImplBase(dispatcher, /*id=*/connection.connection_id().Hash()), - quic_connection_(&connection), filter_manager_(*this), stream_info_(dispatcher.timeSource()), + quic_connection_(&connection), filter_manager_(*this), + stream_info_(dispatcher.timeSource(), + connection.connectionSocket()->addressProviderSharedPtr()), write_buffer_watermark_simulation_( send_buffer_limit / 2, send_buffer_limit, [this]() { onSendBufferLowWatermark(); }, [this]() { onSendBufferHighWatermark(); }, ENVOY_LOGGER()) { @@ -107,27 +109,6 @@ QuicFilterManagerConnectionImpl::socketOptions() const { return quic_connection_->connectionSocket()->options(); } -const Network::Address::InstanceConstSharedPtr& -QuicFilterManagerConnectionImpl::remoteAddress() const { - ASSERT(quic_connection_->connectionSocket() != nullptr, - "remoteAddress() should only be called after OnPacketHeader"); - return quic_connection_->connectionSocket()->remoteAddress(); -} - -const Network::Address::InstanceConstSharedPtr& -QuicFilterManagerConnectionImpl::directRemoteAddress() const { - ASSERT(quic_connection_->connectionSocket() != nullptr, - "directRemoteAddress() should only be called after OnPacketHeader"); - return quic_connection_->connectionSocket()->directRemoteAddress(); -} - -const Network::Address::InstanceConstSharedPtr& -QuicFilterManagerConnectionImpl::localAddress() const { - ASSERT(quic_connection_->connectionSocket() != nullptr, - "localAddress() should only be called after OnPacketHeader"); - return quic_connection_->connectionSocket()->localAddress(); -} - Ssl::ConnectionInfoConstSharedPtr QuicFilterManagerConnectionImpl::ssl() const { // TODO(danzh): construct Ssl::ConnectionInfo from crypto stream return nullptr; diff --git a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h index 7057c3edeedf..04ecc3bd068e 100644 --- a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h +++ b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h @@ -45,9 +45,12 @@ class QuicFilterManagerConnectionImpl : public Network::ConnectionImplBase { void readDisable(bool /*disable*/) override { NOT_REACHED_GCOVR_EXCL_LINE; } void detectEarlyCloseWhenReadDisabled(bool /*value*/) override { NOT_REACHED_GCOVR_EXCL_LINE; } bool readEnabled() const override { return true; } - const Network::Address::InstanceConstSharedPtr& remoteAddress() const override; - const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const override; - const Network::Address::InstanceConstSharedPtr& localAddress() const override; + const Network::SocketAddressProvider& addressProvider() const override { + return quic_connection_->connectionSocket()->addressProvider(); + } + Network::SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return quic_connection_->connectionSocket()->addressProviderSharedPtr(); + } absl::optional unixSocketPeerCredentials() const override { // Unix domain socket is not supported. @@ -80,10 +83,6 @@ class QuicFilterManagerConnectionImpl : public Network::ConnectionImplBase { // As quic connection is not HTTP1.1, this method shouldn't be called by HCM. NOT_REACHED_GCOVR_EXCL_LINE; } - bool localAddressRestored() const override { - // SO_ORIGINAL_DST not supported by QUIC. - NOT_REACHED_GCOVR_EXCL_LINE; - } bool aboveHighWatermark() const override; const Network::ConnectionSocket::OptionsSharedPtr& socketOptions() const override; diff --git a/source/extensions/stat_sinks/hystrix/hystrix.cc b/source/extensions/stat_sinks/hystrix/hystrix.cc index 0eed2bbe2a7d..dae271c85d0e 100644 --- a/source/extensions/stat_sinks/hystrix/hystrix.cc +++ b/source/extensions/stat_sinks/hystrix/hystrix.cc @@ -319,7 +319,10 @@ Http::Code HystrixSink::handlerHystrixEventStream(absl::string_view, // Separated out just so it's easier to understand auto on_destroy_callback = [this, &stream_decoder_filter_callbacks]() { ENVOY_LOG(debug, "stopped sending data to hystrix dashboard on port {}", - stream_decoder_filter_callbacks.connection()->remoteAddress()->asString()); + stream_decoder_filter_callbacks.connection() + ->addressProvider() + .remoteAddress() + ->asString()); // Unregister the callbacks from the sink so data is no longer encoded through them. unregisterConnection(&stream_decoder_filter_callbacks); @@ -328,8 +331,9 @@ Http::Code HystrixSink::handlerHystrixEventStream(absl::string_view, // Add the callback to the admin_filter list of callbacks admin_stream.addOnDestroyCallback(std::move(on_destroy_callback)); - ENVOY_LOG(debug, "started sending data to hystrix dashboard on port {}", - stream_decoder_filter_callbacks.connection()->remoteAddress()->asString()); + ENVOY_LOG( + debug, "started sending data to hystrix dashboard on port {}", + stream_decoder_filter_callbacks.connection()->addressProvider().remoteAddress()->asString()); return Http::Code::OK; } diff --git a/source/extensions/transport_sockets/alts/tsi_socket.cc b/source/extensions/transport_sockets/alts/tsi_socket.cc index 5c3221e44105..ff9ffa622df8 100644 --- a/source/extensions/transport_sockets/alts/tsi_socket.cc +++ b/source/extensions/transport_sockets/alts/tsi_socket.cc @@ -55,8 +55,8 @@ void TsiSocket::doHandshakeNext() { if (!handshaker_) { handshaker_ = handshaker_factory_(callbacks_->connection().dispatcher(), - callbacks_->connection().localAddress(), - callbacks_->connection().remoteAddress()); + callbacks_->connection().addressProvider().localAddress(), + callbacks_->connection().addressProvider().remoteAddress()); if (!handshaker_) { ENVOY_CONN_LOG(warn, "TSI: failed to create handshaker", callbacks_->connection()); callbacks_->connection().close(Network::ConnectionCloseType::NoFlush); diff --git a/source/extensions/transport_sockets/proxy_protocol/proxy_protocol.cc b/source/extensions/transport_sockets/proxy_protocol/proxy_protocol.cc index 3d4f716421e7..ff428b1e832e 100644 --- a/source/extensions/transport_sockets/proxy_protocol/proxy_protocol.cc +++ b/source/extensions/transport_sockets/proxy_protocol/proxy_protocol.cc @@ -52,8 +52,8 @@ void UpstreamProxyProtocolSocket::generateHeader() { void UpstreamProxyProtocolSocket::generateHeaderV1() { // Default to local addresses (used if no downstream connection exists e.g. health checks) - auto src_addr = callbacks_->connection().localAddress(); - auto dst_addr = callbacks_->connection().remoteAddress(); + auto src_addr = callbacks_->connection().addressProvider().localAddress(); + auto dst_addr = callbacks_->connection().addressProvider().remoteAddress(); if (options_ && options_->proxyProtocolOptions().has_value()) { const auto options = options_->proxyProtocolOptions().value(); diff --git a/source/extensions/transport_sockets/tap/tap_config_impl.cc b/source/extensions/transport_sockets/tap/tap_config_impl.cc index 93887c30758e..4e817ebba294 100644 --- a/source/extensions/transport_sockets/tap/tap_config_impl.cc +++ b/source/extensions/transport_sockets/tap/tap_config_impl.cc @@ -29,12 +29,12 @@ PerSocketTapperImpl::PerSocketTapperImpl(SocketTapConfigSharedPtr config, } void PerSocketTapperImpl::fillConnectionInfo(envoy::data::tap::v3::Connection& connection) { - if (connection_.localAddress() != nullptr) { + if (connection_.addressProvider().localAddress() != nullptr) { // Local address might not be populated before a client connection is connected. - Network::Utility::addressToProtobufAddress(*connection_.localAddress(), + Network::Utility::addressToProtobufAddress(*connection_.addressProvider().localAddress(), *connection.mutable_local_address()); } - Network::Utility::addressToProtobufAddress(*connection_.remoteAddress(), + Network::Utility::addressToProtobufAddress(*connection_.addressProvider().remoteAddress(), *connection.mutable_remote_address()); } diff --git a/source/server/admin/admin.cc b/source/server/admin/admin.cc index 5b0d7d7a9f1d..680fd450d96f 100644 --- a/source/server/admin/admin.cc +++ b/source/server/admin/admin.cc @@ -140,7 +140,7 @@ void AdminImpl::startHttpListener(const std::string& access_log_path, ENVOY_LOG(critical, "cannot open admin address output file {} for writing.", address_out_path); } else { - address_out_file << socket_->localAddress()->asString(); + address_out_file << socket_->addressProvider().localAddress()->asString(); } } } diff --git a/source/server/admin/admin.h b/source/server/admin/admin.h index 6e78cea526c6..6ef4f34abb28 100644 --- a/source/server/admin/admin.h +++ b/source/server/admin/admin.h @@ -311,7 +311,7 @@ class AdminImpl : public Admin, Network::Socket::Type socketType() const override { return socket_->socketType(); } const Network::Address::InstanceConstSharedPtr& localAddress() const override { - return socket_->localAddress(); + return socket_->addressProvider().localAddress(); } Network::SocketSharedPtr getListenSocket() override { diff --git a/source/server/api_listener_impl.h b/source/server/api_listener_impl.h index 3452864a79d5..1f8872ef0f9a 100644 --- a/source/server/api_listener_impl.h +++ b/source/server/api_listener_impl.h @@ -6,6 +6,7 @@ #include "envoy/config/listener/v3/listener.pb.h" #include "envoy/network/connection.h" #include "envoy/network/filter.h" +#include "envoy/network/socket.h" #include "envoy/server/api_listener.h" #include "envoy/server/drain_manager.h" #include "envoy/server/filter_config.h" @@ -16,6 +17,7 @@ #include "common/common/logger.h" #include "common/http/conn_manager_impl.h" #include "common/init/manager_impl.h" +#include "common/network/socket_impl.h" #include "common/stream_info/stream_info_impl.h" #include "server/filter_chain_manager_impl.h" @@ -72,7 +74,9 @@ class ApiListenerImplBase : public ApiListener, class SyntheticConnection : public Network::Connection { public: SyntheticConnection(SyntheticReadCallbacks& parent) - : parent_(parent), stream_info_(parent_.parent_.factory_context_.timeSource()), + : parent_(parent), address_provider_(std::make_shared( + parent.parent_.address_, parent.parent_.address_)), + stream_info_(parent_.parent_.factory_context_.timeSource(), address_provider_), options_(std::make_shared>()) {} void raiseConnectionEvent(Network::ConnectionEvent event); @@ -111,6 +115,12 @@ class ApiListenerImplBase : public ApiListener, void readDisable(bool) override {} void detectEarlyCloseWhenReadDisabled(bool) override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } bool readEnabled() const override { return true; } + const Network::SocketAddressProvider& addressProvider() const override { + return *address_provider_; + } + Network::SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return address_provider_; + } absl::optional unixSocketPeerCredentials() const override { return absl::nullopt; @@ -135,6 +145,7 @@ class ApiListenerImplBase : public ApiListener, absl::optional lastRoundTripTime() const override { return {}; }; SyntheticReadCallbacks& parent_; + Network::SocketAddressProviderConstSharedPtr address_provider_; StreamInfo::StreamInfoImpl stream_info_; Network::ConnectionSocket::OptionsSharedPtr options_; std::list callbacks_; diff --git a/source/server/connection_handler_impl.cc b/source/server/connection_handler_impl.cc index ef27d2457f29..98191c58566a 100644 --- a/source/server/connection_handler_impl.cc +++ b/source/server/connection_handler_impl.cc @@ -360,9 +360,11 @@ void ConnectionHandlerImpl::ActiveTcpSocket::newConnection() { // Check if the socket may need to be redirected to another listener. ActiveTcpListenerOptRef new_listener; - if (hand_off_restored_destination_connections_ && socket_->localAddressRestored()) { + if (hand_off_restored_destination_connections_ && + socket_->addressProvider().localAddressRestored()) { // Find a listener associated with the original destination address. - new_listener = listener_.parent_.findActiveTcpListenerByAddress(*socket_->localAddress()); + new_listener = listener_.parent_.findActiveTcpListenerByAddress( + *socket_->addressProvider().localAddress()); } if (new_listener.has_value()) { // Hands off connections redirected by iptables to the listener associated with the diff --git a/source/server/connection_handler_impl.h b/source/server/connection_handler_impl.h index 5c7fe20362c6..e616294e53b8 100644 --- a/source/server/connection_handler_impl.h +++ b/source/server/connection_handler_impl.h @@ -248,9 +248,10 @@ class ConnectionHandlerImpl : public Network::ConnectionHandler, bool hand_off_restored_destination_connections) : listener_(listener), socket_(std::move(socket)), hand_off_restored_destination_connections_(hand_off_restored_destination_connections), - iter_(accept_filters_.end()), stream_info_(std::make_unique( - listener_.parent_.dispatcher_.timeSource(), - StreamInfo::FilterState::LifeSpan::Connection)) { + iter_(accept_filters_.end()), + stream_info_(std::make_unique( + listener_.parent_.dispatcher_.timeSource(), socket_->addressProviderSharedPtr(), + StreamInfo::FilterState::LifeSpan::Connection)) { listener_.stats_.downstream_pre_cx_active_.inc(); } ~ActiveTcpSocket() override { diff --git a/test/common/tcp_proxy/tcp_proxy_test.cc b/test/common/tcp_proxy/tcp_proxy_test.cc index 88e992faca2d..2202ca0ef11e 100644 --- a/test/common/tcp_proxy/tcp_proxy_test.cc +++ b/test/common/tcp_proxy/tcp_proxy_test.cc @@ -375,7 +375,7 @@ TEST(ConfigTest, DEPRECATED_FEATURE_TEST(Routes)) { connection.stream_info_.downstream_address_provider_->setLocalAddress( std::make_shared("2002:0:0:0:0:0::1")); connection.stream_info_.downstream_address_provider_->setRemoteAddress( - std::make_shared("2003:0:0:0:0::5"); + std::make_shared("2003:0:0:0:0::5")); EXPECT_EQ(std::string("with_v6_source_and_destination"), config_obj.getRouteFromEntries(connection)->clusterName()); } @@ -929,7 +929,8 @@ class TcpProxyTest : public testing::Test { .WillByDefault(ReturnPointee( factory_context_.cluster_manager_.thread_local_cluster_.cluster_.info_)); ON_CALL(*upstream_hosts_.at(i), address()).WillByDefault(Return(upstream_remote_address_)); - upstream_connections_.at(i)->local_address_ = upstream_local_address_; + upstream_connections_.at(i)->stream_info_.downstream_address_provider_->setLocalAddress( + upstream_local_address_); EXPECT_CALL(*upstream_connections_.at(i), dispatcher()) .WillRepeatedly(ReturnRef(filter_callbacks_.connection_.dispatcher_)); } @@ -960,8 +961,6 @@ class TcpProxyTest : public testing::Test { filter_->initializeReadFilterCallbacks(filter_callbacks_); filter_callbacks_.connection_.streamInfo().setDownstreamSslConnection( filter_callbacks_.connection_.ssl()); - filter_callbacks_.connection_.streamInfo().setDownstreamAddresses( - filter_callbacks_.connection_); EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection()); EXPECT_EQ(absl::optional(), filter_->computeHashKey()); @@ -1115,7 +1114,6 @@ TEST_F(TcpProxyTest, BadFactory) { filter_->initializeReadFilterCallbacks(filter_callbacks_); filter_callbacks_.connection_.streamInfo().setDownstreamSslConnection( filter_callbacks_.connection_.ssl()); - filter_callbacks_.connection_.streamInfo().setDownstreamAddresses(filter_callbacks_.connection_); EXPECT_EQ(Network::FilterStatus::StopIteration, filter_->onNewConnection()); } @@ -1744,10 +1742,10 @@ TEST_F(TcpProxyTest, AccessLogUpstreamLocalAddress) { // Test that access log fields %DOWNSTREAM_PEER_URI_SAN% is correctly logged. TEST_F(TcpProxyTest, AccessLogPeerUriSan) { - filter_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://1.1.1.2:20000"); - filter_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://1.1.1.1:40000"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://1.1.1.2:20000")); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://1.1.1.1:40000")); const std::vector uriSan{"someSan"}; auto mockConnectionInfo = std::make_shared(); @@ -1762,10 +1760,10 @@ TEST_F(TcpProxyTest, AccessLogPeerUriSan) { // Test that access log fields %DOWNSTREAM_TLS_SESSION_ID% is correctly logged. TEST_F(TcpProxyTest, AccessLogTlsSessionId) { - filter_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://1.1.1.2:20000"); - filter_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://1.1.1.1:40000"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://1.1.1.2:20000")); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://1.1.1.1:40000")); const std::string tlsSessionId{ "D62A523A65695219D46FE1FFE285A4C371425ACE421B110B5B8D11D3EB4D5F0B"}; @@ -1782,10 +1780,10 @@ TEST_F(TcpProxyTest, AccessLogTlsSessionId) { // Test that access log fields %DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT% and // %DOWNSTREAM_LOCAL_ADDRESS% are correctly logged. TEST_F(TcpProxyTest, AccessLogDownstreamAddress) { - filter_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://1.1.1.2:20000"); - filter_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://1.1.1.1:40000"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://1.1.1.2:20000")); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://1.1.1.1:40000")); setup(1, accessLogConfig("%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT% %DOWNSTREAM_LOCAL_ADDRESS%")); filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::RemoteClose); filter_.reset(); @@ -1934,14 +1932,10 @@ TEST_F(TcpProxyTest, AccessDownstreamAndUpstreamProperties) { setup(1); raiseEventUpstreamConnected(0); - EXPECT_EQ(filter_callbacks_.connection().streamInfo().downstreamLocalAddress(), - filter_callbacks_.connection().localAddress()); - EXPECT_EQ(filter_callbacks_.connection().streamInfo().downstreamRemoteAddress(), - filter_callbacks_.connection().remoteAddress()); EXPECT_EQ(filter_callbacks_.connection().streamInfo().downstreamSslConnection(), filter_callbacks_.connection().ssl()); EXPECT_EQ(filter_callbacks_.connection().streamInfo().upstreamLocalAddress(), - upstream_connections_.at(0)->localAddress()); + upstream_connections_.at(0)->streamInfo().downstreamAddressProvider().localAddress()); EXPECT_EQ(filter_callbacks_.connection().streamInfo().upstreamSslConnection(), upstream_connections_.at(0)->streamInfo().downstreamSslConnection()); } @@ -1992,7 +1986,8 @@ TEST_F(TcpProxyRoutingTest, DEPRECATED_FEATURE_TEST(NonRoutableConnection)) { initializeFilter(); // Port 10000 is outside the specified destination port range. - connection_.local_address_ = std::make_shared("1.2.3.4", 10000); + connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 10000)); // Expect filter to try to open a connection to the fallback cluster. EXPECT_CALL(factory_context_.cluster_manager_.thread_local_cluster_, tcpConnPool(_, _)) @@ -2014,7 +2009,8 @@ TEST_F(TcpProxyRoutingTest, DEPRECATED_FEATURE_TEST(RoutableConnection)) { initializeFilter(); // Port 9999 is within the specified destination port range. - connection_.local_address_ = std::make_shared("1.2.3.4", 9999); + connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 9999)); // Expect filter to try to open a connection to specified cluster. EXPECT_CALL(factory_context_.cluster_manager_.thread_local_cluster_, tcpConnPool(_, _)) @@ -2069,7 +2065,8 @@ TEST_F(TcpProxyRoutingTest, DEPRECATED_FEATURE_TEST(UpstreamServerName)) { })); // Port 9999 is within the specified destination port range. - connection_.local_address_ = std::make_shared("1.2.3.4", 9999); + connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 9999)); filter_->onNewConnection(); } @@ -2102,7 +2099,8 @@ TEST_F(TcpProxyRoutingTest, DEPRECATED_FEATURE_TEST(ApplicationProtocols)) { })); // Port 9999 is within the specified destination port range. - connection_.local_address_ = std::make_shared("1.2.3.4", 9999); + connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 9999)); filter_->onNewConnection(); } @@ -2128,7 +2126,8 @@ TEST_F(TcpProxyNonDeprecatedConfigRoutingTest, ClusterNameSet) { initializeFilter(); // Port 9999 is within the specified destination port range. - connection_.local_address_ = std::make_shared("1.2.3.4", 9999); + connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("1.2.3.4", 9999)); // Expect filter to try to open a connection to specified cluster. EXPECT_CALL(factory_context_.cluster_manager_.thread_local_cluster_, tcpConnPool(_, _)) @@ -2191,8 +2190,10 @@ TEST_F(TcpProxyHashingTest, HashWithSourceIp) { return nullptr; })); - connection_.remote_address_ = std::make_shared("1.2.3.4", 1111); - connection_.local_address_ = std::make_shared("2.3.4.5", 2222); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("1.2.3.4", 1111)); + connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("2.3.4.5", 2222)); filter_->onNewConnection(); } diff --git a/test/common/upstream/original_dst_cluster_test.cc b/test/common/upstream/original_dst_cluster_test.cc index 0306e583ed89..b194f218bc66 100644 --- a/test/common/upstream/original_dst_cluster_test.cc +++ b/test/common/upstream/original_dst_cluster_test.cc @@ -215,7 +215,6 @@ TEST_F(OriginalDstClusterTest, NoContext) { NiceMock connection; TestLoadBalancerContext lb_context(&connection); - EXPECT_CALL(connection, localAddressRestored()).WillOnce(Return(false)); // First argument is normally the reference to the ThreadLocalCluster's HostSet, but in these // tests we do not have the thread local clusters, so we pass a reference to the HostSet of the // primary cluster. The implementation handles both cases the same. @@ -229,8 +228,8 @@ TEST_F(OriginalDstClusterTest, NoContext) { { NiceMock connection; TestLoadBalancerContext lb_context(&connection); - connection.local_address_ = std::make_shared("unix://foo"); - EXPECT_CALL(connection, localAddressRestored()).WillRepeatedly(Return(true)); + connection.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("unix://foo")); OriginalDstCluster::LoadBalancer lb(cluster_); EXPECT_CALL(dispatcher_, post(_)).Times(0); @@ -264,8 +263,8 @@ TEST_F(OriginalDstClusterTest, Membership) { NiceMock connection; TestLoadBalancerContext lb_context(&connection); - connection.local_address_ = std::make_shared("10.10.11.11"); - EXPECT_CALL(connection, localAddressRestored()).WillRepeatedly(Return(true)); + connection.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("10.10.11.11")); Event::PostCb post_cb; EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); @@ -275,7 +274,7 @@ TEST_F(OriginalDstClusterTest, Membership) { auto cluster_hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); ASSERT_NE(host, nullptr); - EXPECT_EQ(*connection.local_address_, *host->address()); + EXPECT_EQ(*connection.addressProvider().localAddress(), *host->address()); EXPECT_EQ(1UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size()); EXPECT_EQ(1UL, cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); @@ -285,7 +284,7 @@ TEST_F(OriginalDstClusterTest, Membership) { cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHostsPerLocality().get().size()); EXPECT_EQ(host, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()[0]); - EXPECT_EQ(*connection.local_address_, + EXPECT_EQ(*connection.addressProvider().localAddress(), *cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()[0]->address()); // Same host is returned on the 2nd call @@ -353,13 +352,13 @@ TEST_F(OriginalDstClusterTest, Membership2) { NiceMock connection1; TestLoadBalancerContext lb_context1(&connection1); - connection1.local_address_ = std::make_shared("10.10.11.11"); - EXPECT_CALL(connection1, localAddressRestored()).WillRepeatedly(Return(true)); + connection1.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("10.10.11.11")); NiceMock connection2; TestLoadBalancerContext lb_context2(&connection2); - connection2.local_address_ = std::make_shared("10.10.11.12"); - EXPECT_CALL(connection2, localAddressRestored()).WillRepeatedly(Return(true)); + connection2.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("10.10.11.12")); OriginalDstCluster::LoadBalancer lb(cluster_); EXPECT_CALL(membership_updated_, ready()); @@ -368,14 +367,14 @@ TEST_F(OriginalDstClusterTest, Membership2) { HostConstSharedPtr host1 = lb.chooseHost(&lb_context1); post_cb(); ASSERT_NE(host1, nullptr); - EXPECT_EQ(*connection1.local_address_, *host1->address()); + EXPECT_EQ(*connection1.addressProvider().localAddress(), *host1->address()); EXPECT_CALL(membership_updated_, ready()); EXPECT_CALL(dispatcher_, post(_)).WillOnce(SaveArg<0>(&post_cb)); HostConstSharedPtr host2 = lb.chooseHost(&lb_context2); post_cb(); ASSERT_NE(host2, nullptr); - EXPECT_EQ(*connection2.local_address_, *host2->address()); + EXPECT_EQ(*connection2.addressProvider().localAddress(), *host2->address()); EXPECT_EQ(2UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size()); EXPECT_EQ(2UL, cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHosts().size()); @@ -385,11 +384,11 @@ TEST_F(OriginalDstClusterTest, Membership2) { cluster_->prioritySet().hostSetsPerPriority()[0]->healthyHostsPerLocality().get().size()); EXPECT_EQ(host1, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()[0]); - EXPECT_EQ(*connection1.local_address_, + EXPECT_EQ(*connection1.addressProvider().localAddress(), *cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()[0]->address()); EXPECT_EQ(host2, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()[1]); - EXPECT_EQ(*connection2.local_address_, + EXPECT_EQ(*connection2.addressProvider().localAddress(), *cluster_->prioritySet().hostSetsPerPriority()[0]->hosts()[1]->address()); auto cluster_hosts = cluster_->prioritySet().hostSetsPerPriority()[0]->hosts(); @@ -442,8 +441,8 @@ TEST_F(OriginalDstClusterTest, Connection) { // Connection to the host is made to the downstream connection's local address. NiceMock connection; TestLoadBalancerContext lb_context(&connection); - connection.local_address_ = std::make_shared("FD00::1"); - EXPECT_CALL(connection, localAddressRestored()).WillRepeatedly(Return(true)); + connection.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("FD00::1")); OriginalDstCluster::LoadBalancer lb(cluster_); Event::PostCb post_cb; @@ -451,9 +450,10 @@ TEST_F(OriginalDstClusterTest, Connection) { HostConstSharedPtr host = lb.chooseHost(&lb_context); post_cb(); ASSERT_NE(host, nullptr); - EXPECT_EQ(*connection.local_address_, *host->address()); + EXPECT_EQ(*connection.addressProvider().localAddress(), *host->address()); - EXPECT_CALL(dispatcher_, createClientConnection_(PointeesEq(connection.local_address_), _, _, _)) + EXPECT_CALL(dispatcher_, createClientConnection_( + PointeesEq(connection.addressProvider().localAddress()), _, _, _)) .WillOnce(Return(new NiceMock())); host->createConnection(dispatcher_, nullptr, nullptr); } @@ -491,8 +491,8 @@ TEST_F(OriginalDstClusterTest, MultipleClusters) { // Connection to the host is made to the downstream connection's local address. NiceMock connection; TestLoadBalancerContext lb_context(&connection); - connection.local_address_ = std::make_shared("FD00::1"); - EXPECT_CALL(connection, localAddressRestored()).WillRepeatedly(Return(true)); + connection.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("FD00::1")); OriginalDstCluster::LoadBalancer lb(cluster_); Event::PostCb post_cb; @@ -500,7 +500,7 @@ TEST_F(OriginalDstClusterTest, MultipleClusters) { HostConstSharedPtr host = lb.chooseHost(&lb_context); post_cb(); ASSERT_NE(host, nullptr); - EXPECT_EQ(*connection.local_address_, *host->address()); + EXPECT_EQ(*connection.addressProvider().localAddress(), *host->address()); EXPECT_EQ(1UL, cluster_->prioritySet().hostSetsPerPriority()[0]->hosts().size()); // Check that 'second' also gets updated @@ -549,8 +549,6 @@ TEST_F(OriginalDstClusterTest, UseHttpHeaderEnabled) { // and/or is done over Unix Domain Socket. This works, because properties of the downstream // connection are never checked when using HTTP header override. NiceMock connection2; - EXPECT_CALL(connection2, localAddress()).Times(0); - EXPECT_CALL(connection2, localAddressRestored()).Times(0); TestLoadBalancerContext lb_context2(&connection2, Http::Headers::get().EnvoyOriginalDstHost.get(), "127.0.0.1:5556"); @@ -607,8 +605,8 @@ TEST_F(OriginalDstClusterTest, UseHttpHeaderDisabled) { // Downstream connection with original_dst filter, HTTP header override ignored. NiceMock connection1; - connection1.local_address_ = std::make_shared("10.10.11.11"); - EXPECT_CALL(connection1, localAddressRestored()).WillOnce(Return(true)); + connection1.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("10.10.11.11")); TestLoadBalancerContext lb_context1(&connection1, Http::Headers::get().EnvoyOriginalDstHost.get(), "127.0.0.1:5555"); @@ -617,12 +615,12 @@ TEST_F(OriginalDstClusterTest, UseHttpHeaderDisabled) { HostConstSharedPtr host1 = lb.chooseHost(&lb_context1); post_cb(); ASSERT_NE(host1, nullptr); - EXPECT_EQ(*connection1.local_address_, *host1->address()); + EXPECT_EQ(*connection1.addressProvider().localAddress(), *host1->address()); // Downstream connection without original_dst filter, HTTP header override ignored. NiceMock connection2; - connection2.local_address_ = std::make_shared("10.10.11.11"); - EXPECT_CALL(connection2, localAddressRestored()).WillOnce(Return(false)); + connection2.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("10.10.11.11")); TestLoadBalancerContext lb_context2(&connection2, Http::Headers::get().EnvoyOriginalDstHost.get(), "127.0.0.1:5555"); @@ -633,7 +631,8 @@ TEST_F(OriginalDstClusterTest, UseHttpHeaderDisabled) { // Downstream connection over Unix Domain Socket, HTTP header override ignored. NiceMock connection3; - connection3.local_address_ = std::make_shared("unix://foo"); + connection3.stream_info_.downstream_address_provider_->restoreLocalAddress( + std::make_shared("unix://foo")); TestLoadBalancerContext lb_context3(&connection3, Http::Headers::get().EnvoyOriginalDstHost.get(), "127.0.0.1:5555"); diff --git a/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc b/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc index 7fd73e30f8d8..d6af41e9a4f2 100644 --- a/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc +++ b/test/extensions/filters/http/ip_tagging/ip_tagging_filter_test.cc @@ -66,8 +66,7 @@ TEST_F(IpTaggingFilterTest, InternalRequest) { Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("1.2.3.5"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_CALL(stats_, counter("prefix.ip_tagging.internal_request.hit")); EXPECT_CALL(stats_, counter("prefix.ip_tagging.total")); @@ -102,8 +101,7 @@ request_type: external Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("1.2.3.4"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); EXPECT_EQ("external_request", request_headers.get_(Http::Headers::get().EnvoyIpTags)); @@ -140,16 +138,14 @@ request_type: both Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("1.2.3.5"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); EXPECT_EQ("internal_request", request_headers.get_(Http::Headers::get().EnvoyIpTags)); request_headers = Http::TestRequestHeaderMapImpl{}; remote_address = Network::Utility::parseInternetAddress("1.2.3.4"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); EXPECT_EQ("external_request", request_headers.get_(Http::Headers::get().EnvoyIpTags)); @@ -161,8 +157,8 @@ TEST_F(IpTaggingFilterTest, NoHits) { Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("10.2.3.5"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); + EXPECT_CALL(stats_, counter("prefix.ip_tagging.no_hit")); EXPECT_CALL(stats_, counter("prefix.ip_tagging.total")); @@ -181,8 +177,7 @@ TEST_F(IpTaggingFilterTest, AppendEntry) { Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("1.2.3.5"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); EXPECT_EQ("test,internal_request", request_headers.get_(Http::Headers::get().EnvoyIpTags)); @@ -210,8 +205,7 @@ request_type: both Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("1.2.3.4"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_CALL(stats_, counter("prefix.ip_tagging.total")); EXPECT_CALL(stats_, counter("prefix.ip_tagging.internal_request.hit")); @@ -242,8 +236,7 @@ TEST_F(IpTaggingFilterTest, Ipv6Address) { Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("2001:abcd:ef01:2345::1"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); EXPECT_EQ("ipv6_request", request_headers.get_(Http::Headers::get().EnvoyIpTags)); @@ -259,7 +252,6 @@ TEST_F(IpTaggingFilterTest, RuntimeDisabled) { EXPECT_CALL(runtime_.snapshot_, featureEnabled("ip_tagging.http_filter_enabled", 100)) .WillOnce(Return(false)); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()).Times(0); EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); EXPECT_FALSE(request_headers.has(Http::Headers::get().EnvoyIpTags)); EXPECT_EQ(Http::FilterDataStatus::Continue, filter_->decodeData(data_, false)); @@ -273,8 +265,7 @@ TEST_F(IpTaggingFilterTest, ClearRouteCache) { Network::Address::InstanceConstSharedPtr remote_address = Network::Utility::parseInternetAddress("1.2.3.5"); - EXPECT_CALL(filter_callbacks_.stream_info_, downstreamRemoteAddress()) - .WillOnce(ReturnRef(remote_address)); + filter_callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress(remote_address); EXPECT_CALL(filter_callbacks_, clearRouteCache()); EXPECT_EQ(Http::FilterHeadersStatus::Continue, filter_->decodeHeaders(request_headers, false)); diff --git a/test/extensions/filters/network/rbac/filter_test.cc b/test/extensions/filters/network/rbac/filter_test.cc index fe042854baa7..5472131df717 100644 --- a/test/extensions/filters/network/rbac/filter_test.cc +++ b/test/extensions/filters/network/rbac/filter_test.cc @@ -65,7 +65,7 @@ class RoleBasedAccessControlNetworkFilterTest : public testing::Test { void setDestinationPort(uint16_t port) { address_ = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", port, false); - EXPECT_CALL(stream_info_, downstreamLocalAddress()).WillRepeatedly(ReturnRef(address_)); + stream_info_.downstream_address_provider_->setLocalAddress(address_); } void setRequestedServerName(std::string server_name) { diff --git a/test/extensions/quic_listeners/quiche/active_quic_listener_test.cc b/test/extensions/quic_listeners/quiche/active_quic_listener_test.cc index 8677ca8252b7..a5ca19bba232 100644 --- a/test/extensions/quic_listeners/quiche/active_quic_listener_test.cc +++ b/test/extensions/quic_listeners/quiche/active_quic_listener_test.cc @@ -208,8 +208,9 @@ class ActiveQuicListenerTest : public QuicMultiVersionTest { Buffer::RawSliceVector slice = payload.getRawSlices(); ASSERT_EQ(1u, slice.size()); // Send a full CHLO to finish 0-RTT handshake. - auto send_rc = Network::Utility::writeToSocket(client_sockets_.back()->ioHandle(), slice.data(), - 1, nullptr, *listen_socket_->localAddress()); + auto send_rc = + Network::Utility::writeToSocket(client_sockets_.back()->ioHandle(), slice.data(), 1, + nullptr, *listen_socket_->addressProvider().localAddress()); ASSERT_EQ(slice[0].len_, send_rc.rc_); #if defined(__APPLE__) diff --git a/test/extensions/quic_listeners/quiche/envoy_quic_dispatcher_test.cc b/test/extensions/quic_listeners/quiche/envoy_quic_dispatcher_test.cc index 67ddffd4d411..7a554033bae3 100644 --- a/test/extensions/quic_listeners/quiche/envoy_quic_dispatcher_test.cc +++ b/test/extensions/quic_listeners/quiche/envoy_quic_dispatcher_test.cc @@ -130,8 +130,8 @@ class EnvoyQuicDispatcherTest : public QuicMultiVersionTest, EnvoyQuicClock clock(*dispatcher_); Buffer::OwnedImpl payload = generateChloPacketToSend( quic_version_, quic_config_, crypto_config_, connection_id_, clock, - envoyIpAddressToQuicSocketAddress(listen_socket_->localAddress()->ip()), peer_addr, - "test.example.org"); + envoyIpAddressToQuicSocketAddress(listen_socket_->addressProvider().localAddress()->ip()), + peer_addr, "test.example.org"); Buffer::RawSliceVector slice = payload.getRawSlices(); ASSERT(slice.size() == 1); auto encrypted_packet = std::make_unique( @@ -141,8 +141,8 @@ class EnvoyQuicDispatcherTest : public QuicMultiVersionTest, quic::test::ConstructReceivedPacket(*encrypted_packet, clock.Now())); envoy_quic_dispatcher_.ProcessPacket( - envoyIpAddressToQuicSocketAddress(listen_socket_->localAddress()->ip()), peer_addr, - *received_packet); + envoyIpAddressToQuicSocketAddress(listen_socket_->addressProvider().localAddress()->ip()), + peer_addr, *received_packet); if (should_buffer) { // Incoming CHLO packet is buffered, because ProcessPacket() is called before @@ -166,10 +166,11 @@ class EnvoyQuicDispatcherTest : public QuicMultiVersionTest, EXPECT_EQ(1u, connection_handler_.numConnections()); auto envoy_connection = static_cast(session); EXPECT_EQ("test.example.org", envoy_connection->requestedServerName()); - EXPECT_EQ(peer_addr, - envoyIpAddressToQuicSocketAddress(envoy_connection->remoteAddress()->ip())); - ASSERT(envoy_connection->localAddress() != nullptr); - EXPECT_EQ(*listen_socket_->localAddress(), *envoy_connection->localAddress()); + EXPECT_EQ(peer_addr, envoyIpAddressToQuicSocketAddress( + envoy_connection->addressProvider().remoteAddress()->ip())); + ASSERT(envoy_connection->addressProvider().localAddress() != nullptr); + EXPECT_EQ(*listen_socket_->addressProvider().localAddress(), + *envoy_connection->addressProvider().localAddress()); } void processValidChloPacketAndInitializeFilters(bool should_buffer) { diff --git a/test/extensions/quic_listeners/quiche/envoy_quic_proof_source_test.cc b/test/extensions/quic_listeners/quiche/envoy_quic_proof_source_test.cc index 8a493a8e8954..84b8711a6ceb 100644 --- a/test/extensions/quic_listeners/quiche/envoy_quic_proof_source_test.cc +++ b/test/extensions/quic_listeners/quiche/envoy_quic_proof_source_test.cc @@ -141,9 +141,9 @@ class EnvoyQuicProofSourceTest : public ::testing::Test { EXPECT_CALL(filter_chain_manager_, findFilterChain(_)) .WillRepeatedly(Invoke([&](const Network::ConnectionSocket& connection_socket) { EXPECT_EQ(*quicAddressToEnvoyAddressInstance(server_address_), - *connection_socket.localAddress()); + *connection_socket.addressProvider().localAddress()); EXPECT_EQ(*quicAddressToEnvoyAddressInstance(client_address_), - *connection_socket.remoteAddress()); + *connection_socket.addressProvider().remoteAddress()); EXPECT_EQ(Extensions::TransportSockets::TransportProtocolNames::get().Quic, connection_socket.detectedTransportProtocol()); EXPECT_EQ("h2", connection_socket.requestedApplicationProtocols()[0]); diff --git a/test/integration/base_integration_test.cc b/test/integration/base_integration_test.cc index 2efc6074c545..cda0a100119d 100644 --- a/test/integration/base_integration_test.cc +++ b/test/integration/base_integration_test.cc @@ -276,7 +276,7 @@ void BaseIntegrationTest::registerTestServerPorts(const std::vector registerPort(*port_it, listen_addr->ip()->port()); } } - const auto admin_addr = test_server_->server().admin().socket().localAddress(); + const auto admin_addr = test_server_->server().admin().socket().addressProvider().localAddress(); if (admin_addr->type() == Network::Address::Type::Ip) { registerPort("admin", admin_addr->ip()->port()); } diff --git a/test/integration/fake_upstream.cc b/test/integration/fake_upstream.cc index 06234a2a7c78..0b18b9e8c9b6 100644 --- a/test/integration/fake_upstream.cc +++ b/test/integration/fake_upstream.cc @@ -85,7 +85,7 @@ void FakeStream::encodeHeaders(const Http::HeaderMap& headers, bool end_stream) Http::createHeaderMap(headers)); if (add_served_by_header_) { headers_copy->addCopy(Http::LowerCaseString("x-served-by"), - parent_.connection().localAddress()->asString()); + parent_.connection().addressProvider().localAddress()->asString()); } parent_.connection().dispatcher().post([this, headers_copy, end_stream]() -> void { diff --git a/test/integration/fake_upstream.h b/test/integration/fake_upstream.h index d796d27bcff2..d68f86677764 100644 --- a/test/integration/fake_upstream.h +++ b/test/integration/fake_upstream.h @@ -579,7 +579,9 @@ class FakeUpstream : Logger::Loggable, testing::AssertionResult waitForRawConnection(FakeRawConnectionPtr& connection, std::chrono::milliseconds timeout = TestUtility::DefaultTimeout); - Network::Address::InstanceConstSharedPtr localAddress() const { return socket_->localAddress(); } + Network::Address::InstanceConstSharedPtr localAddress() const { + return socket_->addressProvider().localAddress(); + } // Wait for one of the upstreams to receive a connection ABSL_MUST_USE_RESULT @@ -649,7 +651,7 @@ class FakeUpstream : Logger::Loggable, Network::Socket::Type socketType() const override { return socket_->socketType(); } const Network::Address::InstanceConstSharedPtr& localAddress() const override { - return socket_->localAddress(); + return socket_->addressProvider().localAddress(); } Network::SocketSharedPtr getListenSocket() override { return socket_; } diff --git a/test/integration/server.cc b/test/integration/server.cc index ac1e6b67e5c6..7eee8ec4e9bd 100644 --- a/test/integration/server.cc +++ b/test/integration/server.cc @@ -225,7 +225,7 @@ void IntegrationTestServerImpl::createAndRunEnvoyServer( // This is technically thread unsafe (assigning to a shared_ptr accessed // across threads), but because we synchronize below through serverReady(), the only // consumer on the main test thread in ~IntegrationTestServerImpl will not race. - admin_address_ = server.admin().socket().localAddress(); + admin_address_ = server.admin().socket().addressProvider().localAddress(); server_ = &server; stat_store_ = &stat_store; serverReady(); diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index c3f319f674de..7eee31ad94f9 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -65,7 +65,7 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, upstreamLocalAddress, (), (const)); MOCK_METHOD(bool, healthCheck, (), (const)); MOCK_METHOD(void, healthCheck, (bool is_health_check)); - MOCK_METHOD(const Network::SocketAddressProvider&, downstreamAddressProvider, (), (const)); + MOCK_METHOD(const Network::SocketAddressProviderGetters&, downstreamAddressProvider, (), (const)); MOCK_METHOD(void, setDownstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); MOCK_METHOD(Ssl::ConnectionInfoConstSharedPtr, downstreamSslConnection, (), (const)); MOCK_METHOD(void, setUpstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); diff --git a/test/server/admin/admin_test.cc b/test/server/admin/admin_test.cc index 3901262c7001..7c7a2e7c09d0 100644 --- a/test/server/admin/admin_test.cc +++ b/test/server/admin/admin_test.cc @@ -52,7 +52,7 @@ TEST_P(AdminInstanceTest, WriteAddressToFile) { std::ifstream address_file(address_out_path_); std::string address_from_file; std::getline(address_file, address_from_file); - EXPECT_EQ(admin_.socket().localAddress()->asString(), address_from_file); + EXPECT_EQ(admin_.socket().addressProvider().localAddress()->asString(), address_from_file); } TEST_P(AdminInstanceTest, AdminBadAddressOutPath) { diff --git a/test/server/connection_handler_test.cc b/test/server/connection_handler_test.cc index c4a2f8959a21..17fe5e69682b 100644 --- a/test/server/connection_handler_test.cc +++ b/test/server/connection_handler_test.cc @@ -617,12 +617,9 @@ TEST_F(ConnectionHandlerTest, NormalRedirect) { })); EXPECT_CALL(*test_filter, onAccept(_)) .WillOnce(Invoke([&](Network::ListenerFilterCallbacks& cb) -> Network::FilterStatus { - cb.socket().restoreLocalAddress(alt_address); + cb.socket().addressProvider().restoreLocalAddress(alt_address); return Network::FilterStatus::Continue; })); - EXPECT_CALL(*accepted_socket, restoreLocalAddress(alt_address)); - EXPECT_CALL(*accepted_socket, localAddressRestored()).WillOnce(Return(true)); - EXPECT_CALL(*accepted_socket, localAddress()).WillRepeatedly(ReturnRef(alt_address)); EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(filter_chain_.get())); auto* connection = new NiceMock(); EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection)); @@ -640,7 +637,7 @@ TEST_F(ConnectionHandlerTest, NormalRedirect) { .WillOnce( Invoke([&](const Http::RequestHeaderMap*, const Http::ResponseHeaderMap*, const Http::ResponseTrailerMap*, const StreamInfo::StreamInfo& stream_info) { - EXPECT_EQ(alt_address, stream_info.downstreamLocalAddress()); + EXPECT_EQ(alt_address, stream_info.downstreamAddressProvider().localAddress()); })); connection->close(Network::ConnectionCloseType::NoFlush); dispatcher_.clearDeferredDeleteList(); @@ -688,12 +685,9 @@ TEST_F(ConnectionHandlerTest, FallbackToWildcardListener) { new Network::Address::Ipv4Instance("127.0.0.2", 0, nullptr)); EXPECT_CALL(*test_filter, onAccept(_)) .WillOnce(Invoke([&](Network::ListenerFilterCallbacks& cb) -> Network::FilterStatus { - cb.socket().restoreLocalAddress(alt_address); + cb.socket().addressProvider().restoreLocalAddress(alt_address); return Network::FilterStatus::Continue; })); - EXPECT_CALL(*accepted_socket, restoreLocalAddress(alt_address)); - EXPECT_CALL(*accepted_socket, localAddressRestored()).WillOnce(Return(true)); - EXPECT_CALL(*accepted_socket, localAddress()).WillRepeatedly(ReturnRef(alt_address)); EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(filter_chain_.get())); auto* connection = new NiceMock(); EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection)); @@ -731,13 +725,10 @@ TEST_F(ConnectionHandlerTest, WildcardListenerWithOriginalDst) { })); EXPECT_CALL(*test_filter, onAccept(_)) .WillOnce(Invoke([&](Network::ListenerFilterCallbacks& cb) -> Network::FilterStatus { - cb.socket().restoreLocalAddress(original_dst_address); + cb.socket().addressProvider().restoreLocalAddress(original_dst_address); return Network::FilterStatus::Continue; })); EXPECT_CALL(*test_filter, destroy_()); - EXPECT_CALL(*accepted_socket, restoreLocalAddress(original_dst_address)); - EXPECT_CALL(*accepted_socket, localAddressRestored()).WillOnce(Return(true)); - EXPECT_CALL(*accepted_socket, localAddress()).WillRepeatedly(ReturnRef(original_dst_address)); EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(filter_chain_.get())); auto* connection = new NiceMock(); EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection)); @@ -772,8 +763,6 @@ TEST_F(ConnectionHandlerTest, WildcardListenerWithNoOriginalDst) { return true; })); EXPECT_CALL(*test_filter, onAccept(_)).WillOnce(Return(Network::FilterStatus::Continue)); - EXPECT_CALL(*accepted_socket, localAddressRestored()).WillOnce(Return(false)); - EXPECT_CALL(*accepted_socket, localAddress()).WillRepeatedly(ReturnRef(normal_address)); EXPECT_CALL(manager_, findFilterChain(_)).WillOnce(Return(filter_chain_.get())); auto* connection = new NiceMock(); EXPECT_CALL(dispatcher_, createServerConnection_()).WillOnce(Return(connection)); diff --git a/test/server/filter_chain_benchmark_test.cc b/test/server/filter_chain_benchmark_test.cc index 45b422e9f7f8..df9b11288506 100644 --- a/test/server/filter_chain_benchmark_test.cc +++ b/test/server/filter_chain_benchmark_test.cc @@ -6,6 +6,8 @@ #include "envoy/network/listen_socket.h" #include "envoy/protobuf/message_validator.h" +#include "common/network/socket_impl.h" + #include "server/filter_chain_manager_impl.h" #include "extensions/transport_sockets/well_known_names.h" @@ -38,7 +40,9 @@ class MockFilterChainFactoryBuilder : public FilterChainFactoryBuilder { class MockConnectionSocket : public Network::ConnectionSocket { public: - MockConnectionSocket() = default; + MockConnectionSocket() + : address_provider_(std::make_shared(nullptr, nullptr)) {} + static std::unique_ptr createMockConnectionSocket(uint16_t destination_port, const std::string& destination_address, const std::string& server_name, const std::string& transport_protocol, @@ -47,15 +51,18 @@ class MockConnectionSocket : public Network::ConnectionSocket { auto res = std::make_unique(); if (absl::StartsWith(destination_address, "/")) { - res->local_address_ = std::make_shared(destination_address); + res->address_provider_->setLocalAddress( + std::make_shared(destination_address)); } else { - res->local_address_ = - Network::Utility::parseInternetAddress(destination_address, destination_port); + res->address_provider_->setLocalAddress( + Network::Utility::parseInternetAddress(destination_address, destination_port)); } if (absl::StartsWith(source_address, "/")) { - res->remote_address_ = std::make_shared(source_address); + res->address_provider_->setRemoteAddress( + std::make_shared(source_address)); } else { - res->remote_address_ = Network::Utility::parseInternetAddress(source_address, source_port); + res->address_provider_->setRemoteAddress( + Network::Utility::parseInternetAddress(source_address, source_port)); } res->server_name_ = server_name; res->transport_protocol_ = transport_protocol; @@ -63,24 +70,18 @@ class MockConnectionSocket : public Network::ConnectionSocket { return res; } - const Network::Address::InstanceConstSharedPtr& remoteAddress() const override { - return remote_address_; - } - - const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const override { - return remote_address_; - } - - const Network::Address::InstanceConstSharedPtr& localAddress() const override { - return local_address_; - } - absl::string_view detectedTransportProtocol() const override { return transport_protocol_; } - absl::string_view requestedServerName() const override { return server_name_; } const std::vector& requestedApplicationProtocols() const override { return application_protocols_; } + Network::SocketAddressProvider& addressProvider() override { return *address_provider_; } + const Network::SocketAddressProvider& addressProvider() const override { + return *address_provider_; + } + Network::SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + return address_provider_; + } // Wont call Network::IoHandle& ioHandle() override { return *io_handle_; } @@ -90,15 +91,13 @@ class MockConnectionSocket : public Network::ConnectionSocket { void close() override {} bool isOpen() const override { return false; } Network::Socket::Type socketType() const override { return Network::Socket::Type::Stream; } - Network::Address::Type addressType() const override { return local_address_->type(); } + Network::Address::Type addressType() const override { + return address_provider_->localAddress()->type(); + } absl::optional ipVersion() const override { return Network::Address::IpVersion::v4; } Network::SocketPtr duplicate() override { return nullptr; } - void setLocalAddress(const Network::Address::InstanceConstSharedPtr&) override {} - void restoreLocalAddress(const Network::Address::InstanceConstSharedPtr&) override {} - void setRemoteAddress(const Network::Address::InstanceConstSharedPtr&) override {} - bool localAddressRestored() const override { return true; } void setDetectedTransportProtocol(absl::string_view) override {} void setRequestedApplicationProtocols(const std::vector&) override {} void addOption(const OptionConstSharedPtr&) override {} @@ -122,8 +121,7 @@ class MockConnectionSocket : public Network::ConnectionSocket { private: Network::IoHandlePtr io_handle_; OptionsSharedPtr options_; - Network::Address::InstanceConstSharedPtr local_address_; - Network::Address::InstanceConstSharedPtr remote_address_; + Network::SocketAddressProviderSharedPtr address_provider_; std::string server_name_; std::string transport_protocol_; std::vector application_protocols_; diff --git a/test/server/filter_chain_manager_impl_test.cc b/test/server/filter_chain_manager_impl_test.cc index 766a9bd51b7b..e59392c14b2f 100644 --- a/test/server/filter_chain_manager_impl_test.cc +++ b/test/server/filter_chain_manager_impl_test.cc @@ -81,7 +81,7 @@ class FilterChainManagerImplTest : public testing::Test { local_address_ = Network::Utility::parseInternetAddress(destination_address, destination_port); } - ON_CALL(*mock_socket, localAddress()).WillByDefault(ReturnRef(local_address_)); + mock_socket->address_provider_->setLocalAddress(local_address_); ON_CALL(*mock_socket, requestedServerName()) .WillByDefault(Return(absl::string_view(server_name))); @@ -95,7 +95,7 @@ class FilterChainManagerImplTest : public testing::Test { } else { remote_address_ = Network::Utility::parseInternetAddress(source_address, source_port); } - ON_CALL(*mock_socket, remoteAddress()).WillByDefault(ReturnRef(remote_address_)); + mock_socket->address_provider_->setRemoteAddress(remote_address_); return filter_chain_manager_.findFilterChain(*mock_socket); } diff --git a/test/server/listener_manager_impl_test.cc b/test/server/listener_manager_impl_test.cc index 86121c09ccee..c3b122e1b34e 100644 --- a/test/server/listener_manager_impl_test.cc +++ b/test/server/listener_manager_impl_test.cc @@ -1383,7 +1383,7 @@ name: foo Network::Address::InstanceConstSharedPtr local_address( new Network::Address::Ipv4Instance("127.0.0.1", 1234)); - ON_CALL(*listener_factory_.socket_, localAddress()).WillByDefault(ReturnRef(local_address)); + listener_factory_.socket_->address_provider_->setLocalAddress(local_address); ListenerHandle* listener_foo = expectListenerCreate(false, true); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, {true})); @@ -1443,7 +1443,7 @@ name: foo Network::Address::InstanceConstSharedPtr local_address( new Network::Address::Ipv4Instance("127.0.0.1", 1234)); - ON_CALL(*listener_factory_.socket_, localAddress()).WillByDefault(ReturnRef(local_address)); + listener_factory_.socket_->address_provider_->setLocalAddress(local_address); ListenerHandle* listener_foo = expectListenerCreate(false, true); EXPECT_CALL(listener_factory_, createListenSocket(_, _, _, {true})); @@ -3822,8 +3822,8 @@ TEST_F(ListenerManagerImplWithRealFiltersTest, OriginalDstTestFilter) { })); EXPECT_TRUE(filterChainFactory.createListenerFilterChain(manager)); - EXPECT_TRUE(socket.localAddressRestored()); - EXPECT_EQ("127.0.0.2:2345", socket.localAddress()->asString()); + EXPECT_TRUE(socket.addressProvider().localAddressRestored()); + EXPECT_EQ("127.0.0.2:2345", socket.addressProvider().localAddress()->asString()); } class OriginalDstTestFilterIPv6 @@ -3896,8 +3896,8 @@ TEST_F(ListenerManagerImplWithRealFiltersTest, OriginalDstTestFilterIPv6) { })); EXPECT_TRUE(filterChainFactory.createListenerFilterChain(manager)); - EXPECT_TRUE(socket.localAddressRestored()); - EXPECT_EQ("[1::2]:2345", socket.localAddress()->asString()); + EXPECT_TRUE(socket.addressProvider().localAddressRestored()); + EXPECT_EQ("[1::2]:2345", socket.addressProvider().localAddress()->asString()); } // Validate that when neither transparent nor freebind is not set in the diff --git a/test/server/listener_manager_impl_test.h b/test/server/listener_manager_impl_test.h index 68df5988d9b1..455349ec28c7 100644 --- a/test/server/listener_manager_impl_test.h +++ b/test/server/listener_manager_impl_test.h @@ -181,7 +181,7 @@ class ListenerManagerImplTest : public testing::Test { local_address_ = Network::Utility::parseInternetAddress(destination_address, destination_port); } - ON_CALL(*socket_, localAddress()).WillByDefault(ReturnRef(local_address_)); + socket_->address_provider_->setLocalAddress(local_address_); ON_CALL(*socket_, requestedServerName()).WillByDefault(Return(absl::string_view(server_name))); ON_CALL(*socket_, detectedTransportProtocol()) @@ -194,7 +194,7 @@ class ListenerManagerImplTest : public testing::Test { } else { remote_address_ = Network::Utility::parseInternetAddress(source_address, source_port); } - ON_CALL(*socket_, remoteAddress()).WillByDefault(ReturnRef(remote_address_)); + socket_->address_provider_->setRemoteAddress(remote_address_); return manager_->listeners().back().get().filterChainManager().findFilterChain(*socket_); } diff --git a/test/server/server_test.cc b/test/server/server_test.cc index c09fb90ef732..10cc3a019291 100644 --- a/test/server/server_test.cc +++ b/test/server/server_test.cc @@ -1143,7 +1143,7 @@ TEST_P(ServerInstanceImplTest, BootstrapNodeWithSocketOptions) { // Start Envoy instance with admin port with SO_REUSEPORT option. ASSERT_NO_THROW( initialize("test/server/test_data/server/node_bootstrap_with_admin_socket_options.yaml")); - const auto address = server_->admin().socket().localAddress(); + const auto address = server_->admin().socket().addressProvider().localAddress(); // First attempt to bind and listen socket should fail due to the lack of SO_REUSEPORT socket // options. From a0851697d4bd4bf1ca568f1b06b07dd7aefee561 Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Mon, 4 Jan 2021 22:43:20 +0000 Subject: [PATCH 6/8] more Signed-off-by: Matt Klein --- include/envoy/network/connection.h | 8 +- include/envoy/network/socket.h | 14 ++- include/envoy/stream_info/stream_info.h | 2 +- source/common/http/filter_manager.h | 13 +- source/common/network/connection_impl.h | 4 +- source/common/network/socket_impl.h | 14 ++- source/common/stream_info/stream_info_impl.h | 14 +-- source/common/upstream/health_checker_impl.cc | 4 +- source/common/upstream/health_checker_impl.h | 2 +- .../filters/http/rbac/rbac_filter.cc | 3 +- .../filters/udp/udp_proxy/udp_proxy_filter.h | 4 +- .../quic_filter_manager_connection_impl.h | 2 +- source/server/api_listener_impl.h | 4 +- .../substitution_formatter_speed_test.cc | 2 +- .../formatter/substitution_formatter_test.cc | 6 +- test/common/grpc/BUILD | 1 - test/common/grpc/async_client_impl_test.cc | 9 +- .../grpc/google_async_client_impl_test.cc | 9 +- test/common/http/conn_manager_impl_test.cc | 4 +- .../http/conn_manager_impl_test_base.cc | 2 + test/common/local_reply/local_reply_test.cc | 2 +- test/common/router/header_formatter_test.cc | 6 +- test/common/router/router_test.cc | 13 +- .../common/router/router_upstream_log_test.cc | 7 +- .../stream_info/stream_info_impl_test.cc | 22 ++-- test/common/tracing/http_tracer_impl_test.cc | 27 ++--- .../upstream/original_dst_cluster_test.cc | 4 +- .../grpc/http_grpc_access_log_impl_test.cc | 4 +- .../proxy_protocol_header_test.cc | 12 +- .../proxy_protocol_regression_test.cc | 23 ++-- .../filters/common/expr/context_test.cc | 4 +- .../ext_authz/check_request_utils_test.cc | 16 +-- .../original_src_socket_option_test.cc | 6 +- .../filters/common/rbac/engine_impl_test.cc | 14 +-- .../filters/common/rbac/matchers_test.cc | 46 +++---- .../http/common/fuzz/uber_per_filter.cc | 4 +- .../filters/http/ext_authz/ext_authz_test.cc | 42 +++---- .../filters/http/lua/lua_filter_test.cc | 2 +- .../filters/http/lua/wrappers_test.cc | 17 ++- .../http/original_src/original_src_test.cc | 17 +-- .../filters/http/rbac/rbac_filter_test.cc | 2 +- .../common/fuzz/listener_filter_fakes.cc | 27 +---- .../common/fuzz/listener_filter_fakes.h | 14 +-- .../common/fuzz/listener_filter_fuzzer.cc | 10 +- .../original_src/original_src_test.cc | 7 +- .../proxy_protocol/proxy_protocol_test.cc | 102 +++++++++------- .../client_ssl_auth/client_ssl_auth_test.cc | 16 +-- .../common/fuzz/uber_per_readfilter.cc | 18 ++- .../network/ext_authz/ext_authz_fuzz_test.cc | 4 +- .../network/ext_authz/ext_authz_test.cc | 37 +++--- .../common/statsd/udp_statsd_test.cc | 2 +- .../stats_sinks/hystrix/hystrix_test.cc | 2 +- .../proxy_protocol/proxy_protocol_test.cc | 112 +++++++++--------- .../tap/tap_config_impl_test.cc | 4 +- .../transport_sockets/tls/handshaker_test.cc | 5 +- .../tls/integration/ssl_integration_test.cc | 8 +- .../transport_sockets/tls/ssl_socket_test.cc | 75 ++++++------ .../http/tcp/upstream_request_test.cc | 16 +-- .../http2_flood_integration_test.cc | 6 +- test/integration/integration_test.cc | 11 +- .../socket_interface_integration_test.cc | 7 +- test/mocks/network/connection.cc | 2 + test/mocks/network/connection.h | 4 +- test/mocks/network/mocks.h | 12 +- test/mocks/network/socket.h | 6 +- test/mocks/stream_info/mocks.cc | 1 - test/mocks/stream_info/mocks.h | 4 +- test/server/filter_chain_benchmark_test.cc | 2 +- test/tools/router_check/router.cc | 7 +- 69 files changed, 476 insertions(+), 456 deletions(-) diff --git a/include/envoy/network/connection.h b/include/envoy/network/connection.h index db6820c439a8..092e8106f2c3 100644 --- a/include/envoy/network/connection.h +++ b/include/envoy/network/connection.h @@ -188,9 +188,11 @@ class Connection : public Event::DeferredDeletable, public FilterManager { */ virtual bool readEnabled() const PURE; - // fixfix - virtual const SocketAddressProvider& addressProvider() const PURE; - virtual SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const PURE; + /** + * @return the address provider backing this connection. + */ + virtual const SocketAddressProviderGetters& addressProvider() const PURE; + virtual SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const PURE; /** * Credentials of the peer of a socket as decided by SO_PEERCRED. diff --git a/include/envoy/network/socket.h b/include/envoy/network/socket.h index e67588e0f453..a9a2c0d6fb6a 100644 --- a/include/envoy/network/socket.h +++ b/include/envoy/network/socket.h @@ -43,7 +43,9 @@ struct SocketOptionName { Network::SocketOptionName(level, option, #level "/" #option) /** - * Interfaces for providing a socket's various addresses. + * Interfaces for providing a socket's various addresses. This is split into a getters interface + * and a getters + setters interface. This is so that only the getters portion can be overridden + * in certain cases. */ class SocketAddressProviderGetters { public: @@ -102,7 +104,7 @@ class SocketAddressProvider : public SocketAddressProviderGetters { }; using SocketAddressProviderSharedPtr = std::shared_ptr; -using SocketAddressProviderConstSharedPtr = std::shared_ptr; +using SocketAddressProviderGettersSharedPtr = std::shared_ptr; /** * Base class for Sockets @@ -116,10 +118,12 @@ class Socket { */ enum class Type { Stream, Datagram }; - // fixfix + /** + * @return the address provider backing this socket. + */ virtual SocketAddressProvider& addressProvider() PURE; - virtual const SocketAddressProvider& addressProvider() const PURE; - virtual SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const PURE; + virtual const SocketAddressProviderGetters& addressProvider() const PURE; + virtual SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const PURE; /** * @return IoHandle for the underlying connection diff --git a/include/envoy/stream_info/stream_info.h b/include/envoy/stream_info/stream_info.h index 373d3427f36b..9fb19fe0e111 100644 --- a/include/envoy/stream_info/stream_info.h +++ b/include/envoy/stream_info/stream_info.h @@ -452,7 +452,7 @@ class StreamInfo { virtual void healthCheck(bool is_health_check) PURE; /** - * fixfix + * @return the downstream address provider. */ virtual const Network::SocketAddressProviderGetters& downstreamAddressProvider() const PURE; diff --git a/source/common/http/filter_manager.h b/source/common/http/filter_manager.h index 3ac3dfd7ddf9..6cd84b590432 100644 --- a/source/common/http/filter_manager.h +++ b/source/common/http/filter_manager.h @@ -596,7 +596,8 @@ class FilterManagerCallbacks { }; /** - * fixfix + * This class allows the remote address to be overridden for HTTP stream info. This is used for + * XFF handling. This is required to avoid providing stream info with a non-const address provider. */ class OverridableRemoteSocketAddressProviderStreamInfo : public StreamInfo::StreamInfoImpl, Network::SocketAddressProviderGetters { @@ -605,8 +606,8 @@ class OverridableRemoteSocketAddressProviderStreamInfo : public StreamInfo::Stre void setDownstreamRemoteAddress( const Network::Address::InstanceConstSharedPtr& downstream_remote_address) { - ASSERT(overriden_downstream_remote_address_ == nullptr); - overriden_downstream_remote_address_ = downstream_remote_address; + ASSERT(overridden_downstream_remote_address_ == nullptr); + overridden_downstream_remote_address_ = downstream_remote_address; } // StreamInfo::StreamInfo @@ -622,8 +623,8 @@ class OverridableRemoteSocketAddressProviderStreamInfo : public StreamInfo::Stre return StreamInfoImpl::downstreamAddressProvider().localAddressRestored(); } const Network::Address::InstanceConstSharedPtr& remoteAddress() const override { - return overriden_downstream_remote_address_ != nullptr - ? overriden_downstream_remote_address_ + return overridden_downstream_remote_address_ != nullptr + ? overridden_downstream_remote_address_ : StreamInfoImpl::downstreamAddressProvider().remoteAddress(); } const Network::Address::InstanceConstSharedPtr& directRemoteAddress() const override { @@ -631,7 +632,7 @@ class OverridableRemoteSocketAddressProviderStreamInfo : public StreamInfo::Stre } private: - Network::Address::InstanceConstSharedPtr overriden_downstream_remote_address_; + Network::Address::InstanceConstSharedPtr overridden_downstream_remote_address_; }; /** diff --git a/source/common/network/connection_impl.h b/source/common/network/connection_impl.h index 15e3b6e032d4..fde5330f1fcf 100644 --- a/source/common/network/connection_impl.h +++ b/source/common/network/connection_impl.h @@ -68,10 +68,10 @@ class ConnectionImpl : public ConnectionImplBase, public TransportSocketCallback void readDisable(bool disable) override; void detectEarlyCloseWhenReadDisabled(bool value) override { detect_early_close_ = value; } bool readEnabled() const override; - const SocketAddressProvider& addressProvider() const override { + const SocketAddressProviderGetters& addressProvider() const override { return socket_->addressProvider(); } - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return socket_->addressProviderSharedPtr(); } absl::optional unixSocketPeerCredentials() const override; diff --git a/source/common/network/socket_impl.h b/source/common/network/socket_impl.h index 8bc4a2a799d5..c916f50fd6ee 100644 --- a/source/common/network/socket_impl.h +++ b/source/common/network/socket_impl.h @@ -14,7 +14,11 @@ class SocketAddressProviderImpl : public SocketAddressProvider { : local_address_(local_address), remote_address_(remote_address), direct_remote_address_(remote_address) {} - // fixfix + void setDirectRemoteAddressForTest(const Address::InstanceConstSharedPtr& direct_remote_address) { + direct_remote_address_ = direct_remote_address; + } + + // SocketAddressProvider const Address::InstanceConstSharedPtr& localAddress() const override { return local_address_; } void setLocalAddress(const Address::InstanceConstSharedPtr& local_address) override { local_address_ = local_address; @@ -36,7 +40,7 @@ class SocketAddressProviderImpl : public SocketAddressProvider { Address::InstanceConstSharedPtr local_address_; bool local_address_restored_{false}; Address::InstanceConstSharedPtr remote_address_; - const Address::InstanceConstSharedPtr direct_remote_address_; + Address::InstanceConstSharedPtr direct_remote_address_; }; class SocketImpl : public virtual Socket { @@ -46,8 +50,10 @@ class SocketImpl : public virtual Socket { // Network::Socket SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProvider& addressProvider() const override { return *address_provider_; } - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + const SocketAddressProviderGetters& addressProvider() const override { + return *address_provider_; + } + SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return address_provider_; } SocketPtr duplicate() override { diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index fe576890e458..494d184cc1c3 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -36,18 +36,18 @@ const ReplacementMap& emptySpaceReplacement() { struct StreamInfoImpl : public StreamInfo { StreamInfoImpl(TimeSource& time_source, - const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider, + const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider, FilterState::LifeSpan life_span = FilterState::LifeSpan::FilterChain) : StreamInfoImpl(absl::nullopt, time_source, downstream_address_provider, std::make_shared(life_span)) {} StreamInfoImpl(Http::Protocol protocol, TimeSource& time_source, - const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider) + const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider) : StreamInfoImpl(protocol, time_source, downstream_address_provider, std::make_shared(FilterState::LifeSpan::FilterChain)) {} StreamInfoImpl(Http::Protocol protocol, TimeSource& time_source, - const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider, + const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider, FilterStateSharedPtr parent_filter_state, FilterState::LifeSpan life_span) : StreamInfoImpl( protocol, time_source, downstream_address_provider, @@ -303,14 +303,14 @@ struct StreamInfoImpl : public StreamInfo { std::string route_name_; private: - static Network::SocketAddressProviderConstSharedPtr emptyDownstreamAddressProvider() { + static Network::SocketAddressProviderGettersSharedPtr emptyDownstreamAddressProvider() { MUTABLE_CONSTRUCT_ON_FIRST_USE( - Network::SocketAddressProviderConstSharedPtr, + Network::SocketAddressProviderGettersSharedPtr, std::make_shared(nullptr, nullptr)); } StreamInfoImpl(absl::optional protocol, TimeSource& time_source, - const Network::SocketAddressProviderConstSharedPtr& downstream_address_provider, + const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider, FilterStateSharedPtr filter_state) : time_source_(time_source), start_time_(time_source.systemTime()), start_time_monotonic_(time_source.monotonicTime()), protocol_(protocol), @@ -323,7 +323,7 @@ struct StreamInfoImpl : public StreamInfo { uint64_t bytes_received_{}; uint64_t bytes_sent_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; - const Network::SocketAddressProviderConstSharedPtr downstream_address_provider_; + const Network::SocketAddressProviderGettersSharedPtr downstream_address_provider_; Ssl::ConnectionInfoConstSharedPtr downstream_ssl_info_; Ssl::ConnectionInfoConstSharedPtr upstream_ssl_info_; std::string requested_server_name_; diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index 8efb562a7ac8..c5f2f0adb9b0 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -19,6 +19,7 @@ #include "common/http/header_utility.h" #include "common/network/address_impl.h" #include "common/network/socket_impl.h" +#include "common/network/utility.h" #include "common/router/router.h" #include "common/runtime/runtime_features.h" #include "common/runtime/runtime_impl.h" @@ -216,7 +217,8 @@ HttpHealthCheckerImpl::HttpActiveHealthCheckSession::HttpActiveHealthCheckSessio hostname_(getHostname(host, parent_.host_value_, parent_.cluster_.info())), protocol_(codecClientTypeToProtocol(parent_.codec_client_type_)), local_address_provider_(std::make_shared( - std::make_shared("127.0.0.1"), nullptr)) {} // fixfix + Network::Utility::getCanonicalIpv4LoopbackAddress(), + Network::Utility::getCanonicalIpv4LoopbackAddress())) {} HttpHealthCheckerImpl::HttpActiveHealthCheckSession::~HttpActiveHealthCheckSession() { ASSERT(client_ == nullptr); diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index 6adee7a4d789..f9a8357318f6 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -125,7 +125,7 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { Http::ResponseHeaderMapPtr response_headers_; const std::string& hostname_; const Http::Protocol protocol_; - Network::SocketAddressProviderConstSharedPtr local_address_provider_; + Network::SocketAddressProviderGettersSharedPtr local_address_provider_; bool expect_reset_{}; }; diff --git a/source/extensions/filters/http/rbac/rbac_filter.cc b/source/extensions/filters/http/rbac/rbac_filter.cc index 10ee1c025fcc..9f50eea99de2 100644 --- a/source/extensions/filters/http/rbac/rbac_filter.cc +++ b/source/extensions/filters/http/rbac/rbac_filter.cc @@ -50,9 +50,10 @@ Http::FilterHeadersStatus RoleBasedAccessControlFilter::decodeHeaders(Http::RequestHeaderMap& headers, bool) { ENVOY_LOG( debug, - "checking request: requestedServerName: {}, directRemoteIP: {}, remoteIP: {}," + "checking request: requestedServerName: {}, sourceIP: {}, directRemoteIP: {}, remoteIP: {}," "localAddress: {}, ssl: {}, headers: {}, dynamicMetadata: {}", callbacks_->connection()->requestedServerName(), + callbacks_->connection()->addressProvider().remoteAddress()->asString(), callbacks_->streamInfo().downstreamAddressProvider().directRemoteAddress()->asString(), callbacks_->streamInfo().downstreamAddressProvider().remoteAddress()->asString(), callbacks_->streamInfo().downstreamAddressProvider().localAddress()->asString(), diff --git a/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h b/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h index bb689829228e..304616699c6d 100644 --- a/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h +++ b/source/extensions/filters/udp/udp_proxy/udp_proxy_filter.h @@ -259,8 +259,8 @@ class UdpProxyFilter : public Network::UdpListenerReadFilter, virtual Network::SocketPtr createSocket(const Upstream::HostConstSharedPtr& host) { // Virtual so this can be overridden in unit tests. - return std::make_unique(Network::Socket::Type::Datagram, nullptr, - host->address()); + return std::make_unique(Network::Socket::Type::Datagram, host->address(), + nullptr); } // Upstream::ClusterUpdateCallbacks diff --git a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h index 04ecc3bd068e..202d0c28b393 100644 --- a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h +++ b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h @@ -48,7 +48,7 @@ class QuicFilterManagerConnectionImpl : public Network::ConnectionImplBase { const Network::SocketAddressProvider& addressProvider() const override { return quic_connection_->connectionSocket()->addressProvider(); } - Network::SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + Network::SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return quic_connection_->connectionSocket()->addressProviderSharedPtr(); } absl::optional diff --git a/source/server/api_listener_impl.h b/source/server/api_listener_impl.h index 1f8872ef0f9a..7e2864111a97 100644 --- a/source/server/api_listener_impl.h +++ b/source/server/api_listener_impl.h @@ -118,7 +118,7 @@ class ApiListenerImplBase : public ApiListener, const Network::SocketAddressProvider& addressProvider() const override { return *address_provider_; } - Network::SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + Network::SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return address_provider_; } absl::optional @@ -145,7 +145,7 @@ class ApiListenerImplBase : public ApiListener, absl::optional lastRoundTripTime() const override { return {}; }; SyntheticReadCallbacks& parent_; - Network::SocketAddressProviderConstSharedPtr address_provider_; + Network::SocketAddressProviderSharedPtr address_provider_; StreamInfo::StreamInfoImpl stream_info_; Network::ConnectionSocket::OptionsSharedPtr options_; std::list callbacks_; diff --git a/test/common/formatter/substitution_formatter_speed_test.cc b/test/common/formatter/substitution_formatter_speed_test.cc index 5cedca3fe04d..5da6fead0f89 100644 --- a/test/common/formatter/substitution_formatter_speed_test.cc +++ b/test/common/formatter/substitution_formatter_speed_test.cc @@ -48,7 +48,7 @@ std::unique_ptr makeStructFormatter(bool type std::unique_ptr makeStreamInfo() { auto stream_info = std::make_unique(); - stream_info->setDownstreamRemoteAddress( + stream_info->downstream_address_provider_->setRemoteAddress( std::make_shared("203.0.113.1")); return stream_info; } diff --git a/test/common/formatter/substitution_formatter_test.cc b/test/common/formatter/substitution_formatter_test.cc index e864914626fa..ce985dd079ae 100644 --- a/test/common/formatter/substitution_formatter_test.cc +++ b/test/common/formatter/substitution_formatter_test.cc @@ -428,7 +428,7 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { // Validate for IPv4 address auto address = Network::Address::InstanceConstSharedPtr{ new Network::Address::Ipv4Instance("127.1.2.3", 8443)}; - EXPECT_CALL(stream_info, downstreamLocalAddress()).WillRepeatedly(ReturnRef(address)); + stream_info.downstream_address_provider_->setLocalAddress(address); EXPECT_EQ("8443", upstream_format.format(request_headers, response_headers, response_trailers, stream_info, body)); EXPECT_THAT(upstream_format.formatValue(request_headers, response_headers, response_trailers, @@ -438,7 +438,7 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { // Validate for IPv6 address address = Network::Address::InstanceConstSharedPtr{new Network::Address::Ipv6Instance("::1", 9443)}; - EXPECT_CALL(stream_info, downstreamLocalAddress()).WillRepeatedly(ReturnRef(address)); + stream_info.downstream_address_provider_->setLocalAddress(address); EXPECT_EQ("9443", upstream_format.format(request_headers, response_headers, response_trailers, stream_info, body)); EXPECT_THAT(upstream_format.formatValue(request_headers, response_headers, response_trailers, @@ -447,7 +447,7 @@ TEST(SubstitutionFormatterTest, streamInfoFormatter) { // Validate for Pipe address = Network::Address::InstanceConstSharedPtr{new Network::Address::PipeInstance("/foo")}; - EXPECT_CALL(stream_info, downstreamLocalAddress()).WillRepeatedly(ReturnRef(address)); + stream_info.downstream_address_provider_->setLocalAddress(address); EXPECT_EQ("", upstream_format.format(request_headers, response_headers, response_trailers, stream_info, body)); EXPECT_THAT(upstream_format.formatValue(request_headers, response_headers, response_trailers, diff --git a/test/common/grpc/BUILD b/test/common/grpc/BUILD index 83ec4bc4380c..86752e0f318c 100644 --- a/test/common/grpc/BUILD +++ b/test/common/grpc/BUILD @@ -108,7 +108,6 @@ envoy_cc_test( "//source/common/stats:stats_lib", "//source/common/tracing:http_tracer_lib", "//test/mocks/grpc:grpc_mocks", - "//test/mocks/network:network_mocks", "//test/mocks/tracing:tracing_mocks", "//test/proto:helloworld_proto_cc_proto", "//test/test_common:test_time_lib", diff --git a/test/common/grpc/async_client_impl_test.cc b/test/common/grpc/async_client_impl_test.cc index df0775115369..882cc2598047 100644 --- a/test/common/grpc/async_client_impl_test.cc +++ b/test/common/grpc/async_client_impl_test.cc @@ -2,6 +2,7 @@ #include "common/grpc/async_client_impl.h" #include "common/network/address_impl.h" +#include "common/network/socket_impl.h" #include "test/mocks/http/mocks.h" #include "test/mocks/tracing/mocks.h" @@ -128,11 +129,9 @@ TEST_F(EnvoyAsyncClientImplTest, MetadataIsInitialized) { .WillOnce(Invoke([&http_callbacks](Http::HeaderMap&, bool) { http_callbacks->onReset(); })); // Prepare the parent context of this call. - NiceMock socket; - socket.local_address_ = - std::make_shared(expected_downstream_local_address); - StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem()}; - stream_info.setDownstreamAddresses(socket); + auto address_provider = std::make_shared( + std::make_shared(expected_downstream_local_address), nullptr); + StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem(), address_provider}; Http::AsyncClient::ParentContext parent_context{&stream_info}; Http::AsyncClient::StreamOptions stream_options; diff --git a/test/common/grpc/google_async_client_impl_test.cc b/test/common/grpc/google_async_client_impl_test.cc index f41f26acc89d..9a540c6badc2 100644 --- a/test/common/grpc/google_async_client_impl_test.cc +++ b/test/common/grpc/google_async_client_impl_test.cc @@ -9,7 +9,6 @@ #include "common/stream_info/stream_info_impl.h" #include "test/mocks/grpc/mocks.h" -#include "test/mocks/network/mocks.h" #include "test/mocks/tracing/mocks.h" #include "test/proto/helloworld.pb.h" #include "test/test_common/test_time.h" @@ -122,11 +121,9 @@ TEST_F(EnvoyGoogleAsyncClientImplTest, MetadataIsInitialized) { EXPECT_CALL(grpc_callbacks, onRemoteClose(Status::WellKnownGrpcStatus::Unavailable, "")); // Prepare the parent context of this call. - NiceMock socket; - socket.local_address_ = - std::make_shared(expected_downstream_local_address); - StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem()}; - stream_info.setDownstreamAddresses(socket); + auto address_provider = std::make_shared( + std::make_shared(expected_downstream_local_address), nullptr); + StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem(), address_provider}; Http::AsyncClient::ParentContext parent_context{&stream_info}; Http::AsyncClient::StreamOptions stream_options; diff --git a/test/common/http/conn_manager_impl_test.cc b/test/common/http/conn_manager_impl_test.cc index e6866621230e..cd9944e0d7cc 100644 --- a/test/common/http/conn_manager_impl_test.cc +++ b/test/common/http/conn_manager_impl_test.cc @@ -1539,7 +1539,7 @@ TEST_F(HttpConnectionManagerImplTest, } TEST_F(HttpConnectionManagerImplTest, TestAccessLog) { - static constexpr char local_address[] = "0.0.0.0"; + static constexpr char remote_address[] = "0.0.0.0"; static constexpr char xff_address[] = "1.2.3.4"; // stream_info.downstreamRemoteAddress will infer the address from request @@ -1570,7 +1570,7 @@ TEST_F(HttpConnectionManagerImplTest, TestAccessLog) { xff_address); EXPECT_EQ( stream_info.downstreamAddressProvider().directRemoteAddress()->ip()->addressAsString(), - local_address); + remote_address); })); EXPECT_CALL(*codec_, dispatch(_)) diff --git a/test/common/http/conn_manager_impl_test_base.cc b/test/common/http/conn_manager_impl_test_base.cc index 91e674ef82c8..973e67bf5949 100644 --- a/test/common/http/conn_manager_impl_test_base.cc +++ b/test/common/http/conn_manager_impl_test_base.cc @@ -61,6 +61,8 @@ void HttpConnectionManagerImplTest::setup(bool ssl, const std::string& server_na std::make_shared("127.0.0.1", 443)); filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( std::make_shared("0.0.0.0")); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_ + ->setDirectRemoteAddressForTest(std::make_shared("0.0.0.0")); conn_manager_ = std::make_unique( *this, drain_close_, random_, http_context_, runtime_, local_info_, cluster_manager_, overload_manager_, test_time_.timeSystem()); diff --git a/test/common/local_reply/local_reply_test.cc b/test/common/local_reply/local_reply_test.cc index 1ebab1e2e46a..64afad622bd1 100644 --- a/test/common/local_reply/local_reply_test.cc +++ b/test/common/local_reply/local_reply_test.cc @@ -23,7 +23,7 @@ const absl::string_view TestInitContentType = "content-type"; class LocalReplyTest : public testing::Test { public: - LocalReplyTest() : stream_info_(time_system_.timeSystem()) { resetData(TestInitCode); } + LocalReplyTest() : stream_info_(time_system_.timeSystem(), nullptr) { resetData(TestInitCode); } void resetData(Http::Code code) { code_ = code; diff --git a/test/common/router/header_formatter_test.cc b/test/common/router/header_formatter_test.cc index f045b12d4fda..a99d7fbfe558 100644 --- a/test/common/router/header_formatter_test.cc +++ b/test/common/router/header_formatter_test.cc @@ -82,18 +82,18 @@ TEST_F(StreamInfoHeaderFormatterTest, TestFormatWithDownstreamLocalPortVariable) // Validate for IPv4 address auto address = Network::Address::InstanceConstSharedPtr{ new Network::Address::Ipv4Instance("127.1.2.3", 8443)}; - EXPECT_CALL(stream_info, downstreamLocalAddress()).WillRepeatedly(ReturnRef(address)); + stream_info.downstream_address_provider_->setLocalAddress(address); testFormatting(stream_info, "DOWNSTREAM_LOCAL_PORT", "8443"); // Validate for IPv6 address address = Network::Address::InstanceConstSharedPtr{new Network::Address::Ipv6Instance("::1", 9443)}; - EXPECT_CALL(stream_info, downstreamLocalAddress()).WillRepeatedly(ReturnRef(address)); + stream_info.downstream_address_provider_->setLocalAddress(address); testFormatting(stream_info, "DOWNSTREAM_LOCAL_PORT", "9443"); // Validate for Pipe address = Network::Address::InstanceConstSharedPtr{new Network::Address::PipeInstance("/foo")}; - EXPECT_CALL(stream_info, downstreamLocalAddress()).WillRepeatedly(ReturnRef(address)); + stream_info.downstream_address_provider_->setLocalAddress(address); testFormatting(stream_info, "DOWNSTREAM_LOCAL_PORT", ""); } diff --git a/test/common/router/router_test.cc b/test/common/router/router_test.cc index 30cea338d1d0..f28662ff3100 100644 --- a/test/common/router/router_test.cc +++ b/test/common/router/router_test.cc @@ -108,9 +108,10 @@ class RouterTestBase : public testing::Test { .WillByDefault(Return(host_address_)); ON_CALL(*cm_.thread_local_cluster_.conn_pool_.host_, locality()) .WillByDefault(ReturnRef(upstream_locality_)); - router_.downstream_connection_.local_address_ = host_address_; - router_.downstream_connection_.remote_address_ = - Network::Utility::parseInternetAddressAndPort("1.2.3.4:80"); + router_.downstream_connection_.stream_info_.downstream_address_provider_->setLocalAddress( + host_address_); + router_.downstream_connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::parseInternetAddressAndPort("1.2.3.4:80")); // Make the "system time" non-zero, because 0 is considered invalid by DateUtil. test_time_.setMonotonicTime(std::chrono::milliseconds(50)); @@ -5248,7 +5249,7 @@ TEST_F(RouterTest, UpstreamTimingSingleRequest) { })); expectResponseTimerCreate(); - StreamInfo::StreamInfoImpl stream_info(test_time_.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(test_time_.timeSystem(), nullptr); ON_CALL(callbacks_, streamInfo()).WillByDefault(ReturnRef(stream_info)); EXPECT_FALSE(stream_info.firstUpstreamTxByteSent().has_value()); EXPECT_FALSE(stream_info.lastUpstreamTxByteSent().has_value()); @@ -5310,7 +5311,7 @@ TEST_F(RouterTest, UpstreamTimingRetry) { })); expectResponseTimerCreate(); - StreamInfo::StreamInfoImpl stream_info(test_time_); + StreamInfo::StreamInfoImpl stream_info(test_time_, nullptr); ON_CALL(callbacks_, streamInfo()).WillByDefault(ReturnRef(stream_info)); // Check that upstream timing is updated after the first request. @@ -5397,7 +5398,7 @@ TEST_F(RouterTest, UpstreamTimingTimeout) { return nullptr; })); - StreamInfo::StreamInfoImpl stream_info(test_time_); + StreamInfo::StreamInfoImpl stream_info(test_time_, nullptr); ON_CALL(callbacks_, streamInfo()).WillByDefault(ReturnRef(stream_info)); expectResponseTimerCreate(); diff --git a/test/common/router/router_upstream_log_test.cc b/test/common/router/router_upstream_log_test.cc index 6edf6d6b4b87..7821291c80a5 100644 --- a/test/common/router/router_upstream_log_test.cc +++ b/test/common/router/router_upstream_log_test.cc @@ -107,9 +107,10 @@ class RouterUpstreamLogTest : public testing::Test { .WillByDefault(Return(host_address_)); ON_CALL(*context_.cluster_manager_.thread_local_cluster_.conn_pool_.host_, locality()) .WillByDefault(ReturnRef(upstream_locality_)); - router_->downstream_connection_.local_address_ = host_address_; - router_->downstream_connection_.remote_address_ = - Network::Utility::parseInternetAddressAndPort("1.2.3.4:80"); + router_->downstream_connection_.stream_info_.downstream_address_provider_->setLocalAddress( + host_address_); + router_->downstream_connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::parseInternetAddressAndPort("1.2.3.4:80")); } void expectResponseTimerCreate() { diff --git a/test/common/stream_info/stream_info_impl_test.cc b/test/common/stream_info/stream_info_impl_test.cc index dcb62885e56f..4bfd52593d53 100644 --- a/test/common/stream_info/stream_info_impl_test.cc +++ b/test/common/stream_info/stream_info_impl_test.cc @@ -39,7 +39,7 @@ class StreamInfoImplTest : public testing::Test { TEST_F(StreamInfoImplTest, TimingTest) { MonotonicTime pre_start = test_time_.timeSystem().monotonicTime(); - StreamInfoImpl info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); Envoy::StreamInfo::UpstreamTiming upstream_timing; MonotonicTime post_start = test_time_.timeSystem().monotonicTime(); @@ -87,7 +87,7 @@ TEST_F(StreamInfoImplTest, TimingTest) { } TEST_F(StreamInfoImplTest, BytesTest) { - StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); const uint64_t bytes_sent = 7; const uint64_t bytes_received = 12; @@ -113,7 +113,7 @@ TEST_F(StreamInfoImplTest, ResponseFlagTest) { FaultInjected, RateLimited}; - StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); EXPECT_FALSE(stream_info.hasAnyResponseFlag()); EXPECT_FALSE(stream_info.intersectResponseFlags(0)); @@ -128,7 +128,7 @@ TEST_F(StreamInfoImplTest, ResponseFlagTest) { EXPECT_TRUE(stream_info.hasAnyResponseFlag()); EXPECT_EQ(0xFFF, stream_info.responseFlags()); - StreamInfoImpl stream_info2(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl stream_info2(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); stream_info2.setResponseFlag(FailedLocalHealthCheck); EXPECT_TRUE(stream_info2.intersectResponseFlags(FailedLocalHealthCheck)); @@ -136,7 +136,7 @@ TEST_F(StreamInfoImplTest, ResponseFlagTest) { TEST_F(StreamInfoImplTest, MiscSettersAndGetters) { { - StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); EXPECT_EQ(Http::Protocol::Http2, stream_info.protocol().value()); @@ -195,7 +195,7 @@ TEST_F(StreamInfoImplTest, MiscSettersAndGetters) { } TEST_F(StreamInfoImplTest, DynamicMetadataTest) { - StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); EXPECT_EQ(0, stream_info.dynamicMetadata().filter_metadata_size()); stream_info.setDynamicMetadata("com.test", MessageUtil::keyValueStruct("test_key", "test_value")); @@ -224,7 +224,7 @@ TEST_F(StreamInfoImplTest, DynamicMetadataTest) { } TEST_F(StreamInfoImplTest, DumpStateTest) { - StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); std::string prefix = ""; for (int i = 0; i < 7; ++i) { @@ -238,7 +238,7 @@ TEST_F(StreamInfoImplTest, DumpStateTest) { } TEST_F(StreamInfoImplTest, RequestHeadersTest) { - StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); EXPECT_FALSE(stream_info.getRequestHeaders()); Http::TestRequestHeaderMapImpl headers; @@ -247,7 +247,7 @@ TEST_F(StreamInfoImplTest, RequestHeadersTest) { } TEST_F(StreamInfoImplTest, DefaultRequestIDExtensionTest) { - StreamInfoImpl stream_info(test_time_.timeSystem()); + StreamInfoImpl stream_info(test_time_.timeSystem(), nullptr); EXPECT_TRUE(stream_info.getRequestIDExtension()); auto rid_extension = stream_info.getRequestIDExtension(); @@ -265,7 +265,7 @@ TEST_F(StreamInfoImplTest, DefaultRequestIDExtensionTest) { } TEST_F(StreamInfoImplTest, ConnectionID) { - StreamInfoImpl stream_info(test_time_.timeSystem()); + StreamInfoImpl stream_info(test_time_.timeSystem(), nullptr); EXPECT_FALSE(stream_info.connectionID().has_value()); uint64_t id = 123; stream_info.setConnectionID(id); @@ -273,7 +273,7 @@ TEST_F(StreamInfoImplTest, ConnectionID) { } TEST_F(StreamInfoImplTest, Details) { - StreamInfoImpl stream_info(test_time_.timeSystem()); + StreamInfoImpl stream_info(test_time_.timeSystem(), nullptr); EXPECT_FALSE(stream_info.responseCodeDetails().has_value()); stream_info.setResponseCodeDetails("two words"); ASSERT_TRUE(stream_info.responseCodeDetails().has_value()); diff --git a/test/common/tracing/http_tracer_impl_test.cc b/test/common/tracing/http_tracer_impl_test.cc index ce39a318e205..b5a8a0df4970 100644 --- a/test/common/tracing/http_tracer_impl_test.cc +++ b/test/common/tracing/http_tracer_impl_test.cc @@ -169,8 +169,7 @@ TEST_F(HttpConnManFinalizerImplTest, OriginalAndLongPath) { EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); EXPECT_CALL(span, setTag(_, _)).Times(testing::AnyNumber()); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().HttpUrl), Eq(path_prefix + expected_path))); @@ -203,8 +202,7 @@ TEST_F(HttpConnManFinalizerImplTest, NoGeneratedId) { EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); EXPECT_CALL(span, setTag(_, _)).Times(testing::AnyNumber()); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().HttpUrl), Eq(path_prefix + expected_path))); @@ -235,8 +233,7 @@ TEST_F(HttpConnManFinalizerImplTest, Connect) { EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); absl::optional response_code; EXPECT_CALL(stream_info, responseCode()).WillRepeatedly(ReturnPointee(&response_code)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); EXPECT_CALL(span, setTag(_, _)).Times(testing::AnyNumber()); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().HttpUrl), Eq(""))); @@ -358,8 +355,7 @@ TEST_F(HttpConnManFinalizerImplTest, SpanOptionalHeaders) { absl::optional protocol = Http::Protocol::Http10; EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); // Check that span is populated correctly. EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().GuidXRequestId), Eq("id"))); @@ -398,8 +394,7 @@ TEST_F(HttpConnManFinalizerImplTest, UnixDomainSocketPeerAddressTag) { const std::string path_{TestEnvironment::unixDomainSocketPath("foo")}; const auto remote_address = Network::Utility::resolveUrl("unix://" + path_); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); // Check that the PeerAddress is populated correctly for Unix domain sockets. EXPECT_CALL(span, setTag(_, _)).Times(AnyNumber()); @@ -548,8 +543,7 @@ TEST_F(HttpConnManFinalizerImplTest, SpanPopulatedFailureResponse) { absl::optional protocol = Http::Protocol::Http10; EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); // Check that span is populated correctly. EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().GuidXRequestId), Eq("id"))); @@ -608,8 +602,7 @@ TEST_F(HttpConnManFinalizerImplTest, GrpcOkStatus) { EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(11)); EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().Component), Eq(Tracing::Tags::get().Proxy))); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().DownstreamCluster), Eq("-"))); @@ -660,8 +653,7 @@ TEST_F(HttpConnManFinalizerImplTest, GrpcErrorTag) { EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(11)); EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); EXPECT_CALL(span, setTag(_, _)).Times(testing::AnyNumber()); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().Error), Eq(Tracing::Tags::get().True))); @@ -706,8 +698,7 @@ TEST_F(HttpConnManFinalizerImplTest, GrpcTrailersOnly) { EXPECT_CALL(stream_info, bytesReceived()).WillOnce(Return(10)); EXPECT_CALL(stream_info, bytesSent()).WillOnce(Return(11)); EXPECT_CALL(stream_info, protocol()).WillRepeatedly(ReturnPointee(&protocol)); - EXPECT_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillRepeatedly(ReturnPointee(&remote_address)); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(remote_address); EXPECT_CALL(span, setTag(_, _)).Times(testing::AnyNumber()); EXPECT_CALL(span, setTag(Eq(Tracing::Tags::get().Error), Eq(Tracing::Tags::get().True))); diff --git a/test/common/upstream/original_dst_cluster_test.cc b/test/common/upstream/original_dst_cluster_test.cc index b194f218bc66..26f15b226453 100644 --- a/test/common/upstream/original_dst_cluster_test.cc +++ b/test/common/upstream/original_dst_cluster_test.cc @@ -619,7 +619,7 @@ TEST_F(OriginalDstClusterTest, UseHttpHeaderDisabled) { // Downstream connection without original_dst filter, HTTP header override ignored. NiceMock connection2; - connection2.stream_info_.downstream_address_provider_->restoreLocalAddress( + connection2.stream_info_.downstream_address_provider_->setLocalAddress( std::make_shared("10.10.11.11")); TestLoadBalancerContext lb_context2(&connection2, Http::Headers::get().EnvoyOriginalDstHost.get(), "127.0.0.1:5555"); @@ -631,7 +631,7 @@ TEST_F(OriginalDstClusterTest, UseHttpHeaderDisabled) { // Downstream connection over Unix Domain Socket, HTTP header override ignored. NiceMock connection3; - connection3.stream_info_.downstream_address_provider_->restoreLocalAddress( + connection3.stream_info_.downstream_address_provider_->setLocalAddress( std::make_shared("unix://foo")); TestLoadBalancerContext lb_context3(&connection3, Http::Headers::get().EnvoyOriginalDstHost.get(), "127.0.0.1:5555"); diff --git a/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc b/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc index f465af9991c8..894e2d719993 100644 --- a/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc +++ b/test/extensions/access_loggers/grpc/http_grpc_access_log_impl_test.cc @@ -146,8 +146,8 @@ TEST_F(HttpGrpcAccessLogTest, Marshalling) { stream_info.start_time_ = SystemTime(1h); stream_info.start_time_monotonic_ = MonotonicTime(1h); stream_info.last_downstream_tx_byte_sent_ = 2ms; - stream_info.downstream_local_address_ = - std::make_shared("/foo"); + stream_info.downstream_address_provider_->setLocalAddress( + std::make_shared("/foo")); (*stream_info.metadata_.mutable_filter_metadata())["foo"] = ProtobufWkt::Struct(); stream_info.filter_state_->setData("string_accessor", std::make_unique("test_value"), diff --git a/test/extensions/common/proxy_protocol/proxy_protocol_header_test.cc b/test/extensions/common/proxy_protocol/proxy_protocol_header_test.cc index 61ac2f70946b..86461d510781 100644 --- a/test/extensions/common/proxy_protocol/proxy_protocol_header_test.cc +++ b/test/extensions/common/proxy_protocol/proxy_protocol_header_test.cc @@ -32,8 +32,10 @@ TEST(ProxyProtocolHeaderTest, GeneratesV1IPv4Header) { // Make sure the wrapper utility generates the same output. testing::NiceMock connection; - connection.remote_address_ = Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - connection.local_address_ = Network::Utility::resolveUrl("tcp://172.0.0.1:80"); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:80")); Buffer::OwnedImpl util_buf; envoy::config::core::v3::ProxyProtocolConfig config; config.set_version(envoy::config::core::v3::ProxyProtocolConfig::V1); @@ -93,8 +95,10 @@ TEST(ProxyProtocolHeaderTest, GeneratesV2IPv6Header) { // Make sure the wrapper utility generates the same output. testing::NiceMock connection; - connection.remote_address_ = Network::Utility::resolveUrl("tcp://[1:2:3::4]:8"); - connection.local_address_ = Network::Utility::resolveUrl("tcp://[1:100:200:3::]:2"); + connection.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://[1:2:3::4]:8")); + connection.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://[1:100:200:3::]:2")); Buffer::OwnedImpl util_buf; envoy::config::core::v3::ProxyProtocolConfig config; config.set_version(envoy::config::core::v3::ProxyProtocolConfig::V2); diff --git a/test/extensions/common/proxy_protocol/proxy_protocol_regression_test.cc b/test/extensions/common/proxy_protocol/proxy_protocol_regression_test.cc index 65f948f22011..e5e0b392f0cb 100644 --- a/test/extensions/common/proxy_protocol/proxy_protocol_regression_test.cc +++ b/test/extensions/common/proxy_protocol/proxy_protocol_regression_test.cc @@ -49,10 +49,11 @@ class ProxyProtocolRegressionTest : public testing::TestWithParamlocalAddress())); + EXPECT_CALL(socket_factory_, localAddress()) + .WillOnce(ReturnRef(socket_->addressProvider().localAddress())); EXPECT_CALL(socket_factory_, getListenSocket()).WillOnce(Return(socket_)); connection_handler_->addListener(absl::nullopt, *this); - conn_ = dispatcher_->createClientConnection(socket_->localAddress(), + conn_ = dispatcher_->createClientConnection(socket_->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); conn_->addConnectionCallbacks(connection_callbacks_); @@ -202,8 +203,9 @@ TEST_P(ProxyProtocolRegressionTest, V1Basic) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), source_addr); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + source_addr); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -224,8 +226,9 @@ TEST_P(ProxyProtocolRegressionTest, V2Basic) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), source_addr); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + source_addr); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -240,11 +243,13 @@ TEST_P(ProxyProtocolRegressionTest, V2LocalConnection) { expectData("more data"); if (GetParam() == Envoy::Network::Address::IpVersion::v4) { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "127.0.0.1"); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "127.0.0.1"); } else { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "::1"); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "::1"); } - EXPECT_FALSE(server_connection_->localAddressRestored()); + EXPECT_FALSE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } diff --git a/test/extensions/filters/common/expr/context_test.cc b/test/extensions/filters/common/expr/context_test.cc index 3055b4ef0c0b..5d949add5b93 100644 --- a/test/extensions/filters/common/expr/context_test.cc +++ b/test/extensions/filters/common/expr/context_test.cc @@ -439,8 +439,8 @@ TEST(Context, ConnectionAttributes) { Network::Address::InstanceConstSharedPtr upstream_local_address = Network::Utility::parseInternetAddress("10.1.2.3", 1000, false); const std::string sni_name = "kittens.com"; - EXPECT_CALL(info, downstreamLocalAddress()).WillRepeatedly(ReturnRef(local)); - EXPECT_CALL(info, downstreamRemoteAddress()).WillRepeatedly(ReturnRef(remote)); + info.downstream_address_provider_->setLocalAddress(local); + info.downstream_address_provider_->setRemoteAddress(remote); EXPECT_CALL(info, downstreamSslConnection()).WillRepeatedly(Return(downstream_ssl_info)); EXPECT_CALL(info, upstreamSslConnection()).WillRepeatedly(Return(upstream_ssl_info)); EXPECT_CALL(info, upstreamHost()).WillRepeatedly(Return(upstream_host)); diff --git a/test/extensions/filters/common/ext_authz/check_request_utils_test.cc b/test/extensions/filters/common/ext_authz/check_request_utils_test.cc index 0077b8884e5b..ff72b173d61e 100644 --- a/test/extensions/filters/common/ext_authz/check_request_utils_test.cc +++ b/test/extensions/filters/common/ext_authz/check_request_utils_test.cc @@ -36,8 +36,8 @@ class CheckRequestUtilsTest : public testing::Test { void expectBasicHttp() { EXPECT_CALL(callbacks_, connection()).Times(2).WillRepeatedly(Return(&connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(Const(connection_), ssl()).Times(2).WillRepeatedly(Return(ssl_)); EXPECT_CALL(callbacks_, streamId()).WillOnce(Return(0)); EXPECT_CALL(callbacks_, decodingBuffer()).WillOnce(Return(buffer_.get())); @@ -107,8 +107,8 @@ class CheckRequestUtilsTest : public testing::Test { TEST_F(CheckRequestUtilsTest, BasicTcp) { envoy::service::auth::v3::CheckRequest request; EXPECT_CALL(net_callbacks_, connection()).Times(2).WillRepeatedly(ReturnRef(connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(Const(connection_), ssl()).Times(2).WillRepeatedly(Return(ssl_)); EXPECT_CALL(*ssl_, uriSanPeerCertificate()).WillOnce(Return(std::vector{"source"})); EXPECT_CALL(*ssl_, uriSanLocalCertificate()) @@ -124,8 +124,8 @@ TEST_F(CheckRequestUtilsTest, BasicTcp) { TEST_F(CheckRequestUtilsTest, TcpPeerCertificate) { envoy::service::auth::v3::CheckRequest request; EXPECT_CALL(net_callbacks_, connection()).Times(2).WillRepeatedly(ReturnRef(connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(Const(connection_), ssl()).Times(2).WillRepeatedly(Return(ssl_)); EXPECT_CALL(*ssl_, uriSanPeerCertificate()).WillOnce(Return(std::vector{"source"})); EXPECT_CALL(*ssl_, uriSanLocalCertificate()) @@ -254,8 +254,8 @@ TEST_F(CheckRequestUtilsTest, CheckAttrContextPeer) { {":path", "/bar"}}; envoy::service::auth::v3::CheckRequest request; EXPECT_CALL(callbacks_, connection()).WillRepeatedly(Return(&connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillRepeatedly(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillRepeatedly(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(Const(connection_), ssl()).WillRepeatedly(Return(ssl_)); EXPECT_CALL(callbacks_, streamId()).WillRepeatedly(Return(0)); EXPECT_CALL(callbacks_, streamInfo()).WillRepeatedly(ReturnRef(req_info_)); diff --git a/test/extensions/filters/common/original_src/original_src_socket_option_test.cc b/test/extensions/filters/common/original_src/original_src_socket_option_test.cc index 2a8dbb2ffce8..eed0724bc198 100644 --- a/test/extensions/filters/common/original_src/original_src_socket_option_test.cc +++ b/test/extensions/filters/common/original_src/original_src_socket_option_test.cc @@ -36,23 +36,23 @@ class OriginalSrcSocketOptionTest : public testing::Test { TEST_F(OriginalSrcSocketOptionTest, TestSetOptionPreBindSetsAddress) { const auto address = Network::Utility::parseInternetAddress("127.0.0.2"); auto option = makeOptionByAddress(address); - EXPECT_CALL(socket_, setLocalAddress(PointeesEq(address))); EXPECT_EQ(option->setOption(socket_, envoy::config::core::v3::SocketOption::STATE_PREBIND), true); + EXPECT_EQ(*socket_.address_provider_->localAddress(), *address); } TEST_F(OriginalSrcSocketOptionTest, TestSetOptionPreBindSetsAddressSecond) { const auto address = Network::Utility::parseInternetAddress("1.2.3.4"); auto option = makeOptionByAddress(address); - EXPECT_CALL(socket_, setLocalAddress(PointeesEq(address))); EXPECT_EQ(option->setOption(socket_, envoy::config::core::v3::SocketOption::STATE_PREBIND), true); + EXPECT_EQ(*socket_.address_provider_->localAddress(), *address); } TEST_F(OriginalSrcSocketOptionTest, TestSetOptionNotPrebindDoesNotSetAddress) { const auto address = Network::Utility::parseInternetAddress("1.2.3.4"); auto option = makeOptionByAddress(address); - EXPECT_CALL(socket_, setLocalAddress(_)).Times(0); EXPECT_EQ(option->setOption(socket_, envoy::config::core::v3::SocketOption::STATE_LISTENING), true); + EXPECT_NE(*socket_.address_provider_->localAddress(), *address); } TEST_F(OriginalSrcSocketOptionTest, TestIpv4HashKey) { diff --git a/test/extensions/filters/common/rbac/engine_impl_test.cc b/test/extensions/filters/common/rbac/engine_impl_test.cc index dc09323ef9ff..ec9f787f3575 100644 --- a/test/extensions/filters/common/rbac/engine_impl_test.cc +++ b/test/extensions/filters/common/rbac/engine_impl_test.cc @@ -177,11 +177,11 @@ TEST(RoleBasedAccessControlEngineImpl, AllowedAllowlist) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkEngine(engine, true, LogResult::Undecided, info, conn, headers); addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 456, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkEngine(engine, false, LogResult::Undecided, info, conn, headers); } @@ -200,11 +200,11 @@ TEST(RoleBasedAccessControlEngineImpl, DeniedDenylist) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkEngine(engine, false, LogResult::Undecided, info, conn, headers); addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 456, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkEngine(engine, true, LogResult::Undecided, info, conn, headers); } @@ -413,7 +413,7 @@ TEST(RoleBasedAccessControlEngineImpl, ConjunctiveCondition) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkEngine(engine, false, LogResult::Undecided, info, conn, headers); } @@ -445,11 +445,11 @@ TEST(RoleBasedAccessControlEngineImpl, LogIfMatched) { Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkEngine(engine, true, RBAC::LogResult::Yes, info, conn, headers); addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 456, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkEngine(engine, true, RBAC::LogResult::No, info, conn, headers); } diff --git a/test/extensions/filters/common/rbac/matchers_test.cc b/test/extensions/filters/common/rbac/matchers_test.cc index 52947461ae69..78ead6d94766 100644 --- a/test/extensions/filters/common/rbac/matchers_test.cc +++ b/test/extensions/filters/common/rbac/matchers_test.cc @@ -51,12 +51,12 @@ TEST(AndMatcher, Permission_Set) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkMatcher(RBAC::AndMatcher(set), true, conn, headers, info); addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 8080, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkMatcher(RBAC::AndMatcher(set), false, conn, headers, info); } @@ -78,12 +78,12 @@ TEST(AndMatcher, Principal_Set) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - EXPECT_CALL(Const(info), downstreamDirectRemoteAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setDirectRemoteAddressForTest(addr); checkMatcher(RBAC::AndMatcher(set), true, conn, headers, info); addr = Envoy::Network::Utility::parseInternetAddress("1.2.4.6", 123, false); - EXPECT_CALL(Const(info), downstreamDirectRemoteAddress()).WillOnce(ReturnRef(addr)); + info.downstream_address_provider_->setDirectRemoteAddressForTest(addr); checkMatcher(RBAC::AndMatcher(set), false, conn, headers, info); } @@ -98,7 +98,7 @@ TEST(OrMatcher, Permission_Set) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 456, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).Times(2).WillRepeatedly(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkMatcher(RBAC::OrMatcher(set), false, conn, headers, info); @@ -120,9 +120,7 @@ TEST(OrMatcher, Principal_Set) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.4.6", 456, false); - EXPECT_CALL(Const(info), downstreamDirectRemoteAddress()) - .Times(2) - .WillRepeatedly(ReturnRef(addr)); + info.downstream_address_provider_->setDirectRemoteAddressForTest(addr); checkMatcher(RBAC::OrMatcher(set), false, conn, headers, info); @@ -168,27 +166,21 @@ TEST(HeaderMatcher, HeaderMatcher) { } TEST(IPMatcher, IPMatcher) { - Envoy::Network::MockConnection conn; + NiceMock conn; Envoy::Http::TestRequestHeaderMapImpl headers; NiceMock info; - Envoy::Network::Address::InstanceConstSharedPtr connectionRemote = + Envoy::Network::Address::InstanceConstSharedPtr connection_remote = Envoy::Network::Utility::parseInternetAddress("12.13.14.15", 789, false); - Envoy::Network::Address::InstanceConstSharedPtr directLocal = + Envoy::Network::Address::InstanceConstSharedPtr direct_local = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - Envoy::Network::Address::InstanceConstSharedPtr directRemote = + Envoy::Network::Address::InstanceConstSharedPtr direct_remote = Envoy::Network::Utility::parseInternetAddress("4.5.6.7", 456, false); - Envoy::Network::Address::InstanceConstSharedPtr downstreamRemote = + Envoy::Network::Address::InstanceConstSharedPtr downstream_remote = Envoy::Network::Utility::parseInternetAddress("8.9.10.11", 456, false); - EXPECT_CALL(conn, remoteAddress()).Times(2).WillRepeatedly(ReturnRef(connectionRemote)); - EXPECT_CALL(Const(info), downstreamLocalAddress()) - .Times(2) - .WillRepeatedly(ReturnRef(directLocal)); - EXPECT_CALL(Const(info), downstreamDirectRemoteAddress()) - .Times(2) - .WillRepeatedly(ReturnRef(directRemote)); - EXPECT_CALL(Const(info), downstreamRemoteAddress()) - .Times(2) - .WillRepeatedly(ReturnRef(downstreamRemote)); + conn.stream_info_.downstream_address_provider_->setRemoteAddress(connection_remote); + info.downstream_address_provider_->setLocalAddress(direct_local); + info.downstream_address_provider_->setDirectRemoteAddressForTest(direct_remote); + info.downstream_address_provider_->setRemoteAddress(downstream_remote); envoy::config::core::v3::CidrRange connection_remote_cidr; connection_remote_cidr.set_address_prefix("12.13.14.15"); @@ -236,7 +228,7 @@ TEST(PortMatcher, PortMatcher) { NiceMock info; Envoy::Network::Address::InstanceConstSharedPtr addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 123, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).Times(2).WillRepeatedly(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkMatcher(PortMatcher(123), true, conn, headers, info); checkMatcher(PortMatcher(456), false, conn, headers, info); @@ -382,17 +374,17 @@ TEST(PolicyMatcher, PolicyMatcher) { EXPECT_CALL(*ssl, subjectPeerCertificate()).WillRepeatedly(ReturnRef(subject)); EXPECT_CALL(Const(conn), ssl()).Times(2).WillRepeatedly(Return(ssl)); - EXPECT_CALL(Const(info), downstreamLocalAddress()).Times(2).WillRepeatedly(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkMatcher(matcher, true, conn, headers, info); EXPECT_CALL(Const(conn), ssl()).Times(2).WillRepeatedly(Return(nullptr)); - EXPECT_CALL(Const(info), downstreamLocalAddress()).Times(2).WillRepeatedly(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkMatcher(matcher, false, conn, headers, info); addr = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", 789, false); - EXPECT_CALL(Const(info), downstreamLocalAddress()).Times(2).WillRepeatedly(ReturnRef(addr)); + info.downstream_address_provider_->setLocalAddress(addr); checkMatcher(matcher, false, conn, headers, info); } diff --git a/test/extensions/filters/http/common/fuzz/uber_per_filter.cc b/test/extensions/filters/http/common/fuzz/uber_per_filter.cc index 9ca63f3e236b..ba694d4632df 100644 --- a/test/extensions/filters/http/common/fuzz/uber_per_filter.cc +++ b/test/extensions/filters/http/common/fuzz/uber_per_filter.cc @@ -124,8 +124,8 @@ void UberFilterFuzzer::cleanFuzzedConfig(absl::string_view filter_name, void UberFilterFuzzer::perFilterSetup() { // Prepare expectations for the ext_authz filter. addr_ = std::make_shared("1.2.3.4", 1111); - ON_CALL(connection_, remoteAddress()).WillByDefault(testing::ReturnRef(addr_)); - ON_CALL(connection_, localAddress()).WillByDefault(testing::ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); ON_CALL(factory_context_, clusterManager()).WillByDefault(testing::ReturnRef(cluster_manager_)); ON_CALL(cluster_manager_.thread_local_cluster_.async_client_, send_(_, _, _)) .WillByDefault(Return(&async_request_)); diff --git a/test/extensions/filters/http/ext_authz/ext_authz_test.cc b/test/extensions/filters/http/ext_authz/ext_authz_test.cc index d0671967e180..677349a277ea 100644 --- a/test/extensions/filters/http/ext_authz/ext_authz_test.cc +++ b/test/extensions/filters/http/ext_authz/ext_authz_test.cc @@ -68,8 +68,8 @@ template class HttpFilterTestBase : public T { void prepareCheck() { ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); } NiceMock stats_store_; @@ -229,8 +229,8 @@ TEST_F(HttpFilterTest, ErrorFailClose) { )EOF"); ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -268,8 +268,8 @@ TEST_F(HttpFilterTest, ErrorCustomStatusCode) { )EOF"); ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -308,8 +308,8 @@ TEST_F(HttpFilterTest, ErrorOpen) { )EOF"); ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -342,8 +342,8 @@ TEST_F(HttpFilterTest, ImmediateErrorOpen) { )EOF"); ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); Filters::Common::ExtAuthz::Response response{}; response.status = Filters::Common::ExtAuthz::CheckStatus::Error; @@ -400,8 +400,6 @@ TEST_F(HttpFilterTest, RequestDataIsTooLarge) { ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); EXPECT_CALL(filter_callbacks_, setDecoderBufferLimit(_)); - EXPECT_CALL(connection_, remoteAddress()).Times(0); - EXPECT_CALL(connection_, localAddress()).Times(0); EXPECT_CALL(*client_, check(_, _, _, _)).Times(0); EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, @@ -433,8 +431,8 @@ TEST_F(HttpFilterTest, RequestDataWithPartialMessage) { ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); ON_CALL(filter_callbacks_, decodingBuffer()).WillByDefault(Return(&data_)); EXPECT_CALL(filter_callbacks_, setDecoderBufferLimit(_)).Times(0); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)); EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, @@ -475,8 +473,8 @@ TEST_F(HttpFilterTest, RequestDataWithPartialMessageThenContinueDecoding) { ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); ON_CALL(filter_callbacks_, decodingBuffer()).WillByDefault(Return(&data_)); EXPECT_CALL(filter_callbacks_, setDecoderBufferLimit(_)).Times(0); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); // The check call should only be called once. EXPECT_CALL(*client_, check(_, _, testing::A(), _)) @@ -531,8 +529,8 @@ TEST_F(HttpFilterTest, RequestDataWithSmallBuffer) { ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); ON_CALL(filter_callbacks_, decodingBuffer()).WillByDefault(Return(&data_)); EXPECT_CALL(filter_callbacks_, setDecoderBufferLimit(_)).Times(0); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)); EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, @@ -1574,8 +1572,6 @@ TEST_P(HttpFilterTestParam, DisabledOnRouteWithRequestBody) { ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); // When filter is not disabled, setDecoderBufferLimit is called. EXPECT_CALL(filter_callbacks_, setDecoderBufferLimit(_)); - EXPECT_CALL(connection_, remoteAddress()).Times(0); - EXPECT_CALL(connection_, localAddress()).Times(0); EXPECT_CALL(*client_, check(_, _, _, _)).Times(0); EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers_, false)); @@ -2077,8 +2073,6 @@ TEST_P(HttpFilterTestParam, DisableRequestBodyBufferingOnRoute) { ON_CALL(filter_callbacks_, connection()).WillByDefault(Return(&connection_)); // When request body buffering is not skipped, setDecoderBufferLimit is called. EXPECT_CALL(filter_callbacks_, setDecoderBufferLimit(_)); - EXPECT_CALL(connection_, remoteAddress()).Times(0); - EXPECT_CALL(connection_, localAddress()).Times(0); EXPECT_CALL(*client_, check(_, _, _, _)).Times(0); EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, filter_->decodeHeaders(request_headers_, false)); @@ -2087,8 +2081,8 @@ TEST_P(HttpFilterTestParam, DisableRequestBodyBufferingOnRoute) { test_disable_request_body_buffering(true); // When request body buffering is skipped, setDecoderBufferLimit is not called. EXPECT_CALL(filter_callbacks_, setDecoderBufferLimit(_)).Times(0); - EXPECT_CALL(connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(connection_, localAddress()).WillOnce(ReturnRef(addr_)); + connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)); EXPECT_EQ(Http::FilterHeadersStatus::StopAllIterationAndWatermark, filter_->decodeHeaders(request_headers_, false)); diff --git a/test/extensions/filters/http/lua/lua_filter_test.cc b/test/extensions/filters/http/lua/lua_filter_test.cc index 074f00afd84e..55fb35aca76f 100644 --- a/test/extensions/filters/http/lua/lua_filter_test.cc +++ b/test/extensions/filters/http/lua/lua_filter_test.cc @@ -1794,7 +1794,7 @@ TEST_F(LuaHttpFilterTest, SetGetDynamicMetadata) { Http::TestRequestHeaderMapImpl request_headers{{":path", "/"}}; Event::SimulatedTimeSystem test_time; - StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time.timeSystem(), nullptr); EXPECT_EQ(0, stream_info.dynamicMetadata().filter_metadata_size()); EXPECT_CALL(decoder_callbacks_, streamInfo()).WillOnce(ReturnRef(stream_info)); EXPECT_CALL(*filter_, scriptLog(spdlog::level::trace, StrEq("bar"))); diff --git a/test/extensions/filters/http/lua/wrappers_test.cc b/test/extensions/filters/http/lua/wrappers_test.cc index 1ab0eb5a4404..04f5deef048c 100644 --- a/test/extensions/filters/http/lua/wrappers_test.cc +++ b/test/extensions/filters/http/lua/wrappers_test.cc @@ -290,9 +290,8 @@ TEST_F(LuaStreamInfoWrapperTest, ReturnCurrentDownstreamAddresses) { new Network::Address::Ipv4Instance("127.0.0.1", 8000)}; auto downstream_direct_remote = Network::Address::InstanceConstSharedPtr{new Network::Address::Ipv4Instance("8.8.8.8", 3000)}; - ON_CALL(stream_info, downstreamLocalAddress()).WillByDefault(ReturnRef(address)); - ON_CALL(stream_info, downstreamDirectRemoteAddress()) - .WillByDefault(ReturnRef(downstream_direct_remote)); + stream_info.downstream_address_provider_->setLocalAddress(address); + stream_info.downstream_address_provider_->setDirectRemoteAddressForTest(downstream_direct_remote); Filters::Common::Lua::LuaDeathRef wrapper( StreamInfoWrapper::create(coroutine_->luaState(), stream_info), true); EXPECT_CALL(printer_, testPrint(address->asString())); @@ -327,7 +326,7 @@ TEST_F(LuaStreamInfoWrapperTest, SetGetAndIterateDynamicMetadata) { setup(SCRIPT); - StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); EXPECT_EQ(0, stream_info.dynamicMetadata().filter_metadata_size()); Filters::Common::Lua::LuaDeathRef wrapper( StreamInfoWrapper::create(coroutine_->luaState(), stream_info), true); @@ -369,7 +368,7 @@ TEST_F(LuaStreamInfoWrapperTest, SetGetComplexDynamicMetadata) { InSequence s; setup(SCRIPT); - StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); EXPECT_EQ(0, stream_info.dynamicMetadata().filter_metadata_size()); Filters::Common::Lua::LuaDeathRef wrapper( StreamInfoWrapper::create(coroutine_->luaState(), stream_info), true); @@ -417,7 +416,7 @@ TEST_F(LuaStreamInfoWrapperTest, BadTypesInTableForDynamicMetadata) { InSequence s; setup(SCRIPT); - StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); Filters::Common::Lua::LuaDeathRef wrapper( StreamInfoWrapper::create(coroutine_->luaState(), stream_info), true); EXPECT_THROW_WITH_MESSAGE(start("callMe"), Filters::Common::Lua::LuaException, @@ -438,7 +437,7 @@ TEST_F(LuaStreamInfoWrapperTest, ModifyDuringIterationForDynamicMetadata) { InSequence s; setup(SCRIPT); - StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); Filters::Common::Lua::LuaDeathRef wrapper( StreamInfoWrapper::create(coroutine_->luaState(), stream_info), true); EXPECT_THROW_WITH_MESSAGE( @@ -472,7 +471,7 @@ TEST_F(LuaStreamInfoWrapperTest, ModifyAfterIterationForDynamicMetadata) { setup(SCRIPT); - StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); EXPECT_EQ(0, stream_info.dynamicMetadata().filter_metadata_size()); Filters::Common::Lua::LuaDeathRef wrapper( StreamInfoWrapper::create(coroutine_->luaState(), stream_info), true); @@ -497,7 +496,7 @@ TEST_F(LuaStreamInfoWrapperTest, DontFinishIterationForDynamicMetadata) { InSequence s; setup(SCRIPT); - StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem()); + StreamInfo::StreamInfoImpl stream_info(Http::Protocol::Http2, test_time_.timeSystem(), nullptr); Filters::Common::Lua::LuaDeathRef wrapper( StreamInfoWrapper::create(coroutine_->luaState(), stream_info), true); EXPECT_THROW_WITH_MESSAGE( diff --git a/test/extensions/filters/http/original_src/original_src_test.cc b/test/extensions/filters/http/original_src/original_src_test.cc index def891c4094c..7b497ffd44a6 100644 --- a/test/extensions/filters/http/original_src/original_src_test.cc +++ b/test/extensions/filters/http/original_src/original_src_test.cc @@ -51,7 +51,8 @@ class OriginalSrcHttpTest : public testing::Test { } void setAddressToReturn(const std::string& address) { - callbacks_.stream_info_.downstream_remote_address_ = Network::Utility::resolveUrl(address); + callbacks_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl(address)); } protected: @@ -92,11 +93,11 @@ TEST_F(OriginalSrcHttpTest, DecodeHeadersIpv4AddressAddsOption) { EXPECT_EQ(filter->decodeHeaders(headers_, false), Http::FilterHeadersStatus::Continue); NiceMock socket; - EXPECT_CALL(socket, - setLocalAddress(PointeesEq(callbacks_.stream_info_.downstream_remote_address_))); for (const auto& option : *options) { option->setOption(socket, envoy::config::core::v3::SocketOption::STATE_PREBIND); } + EXPECT_EQ(*socket.addressProvider().localAddress(), + *callbacks_.stream_info_.downstream_address_provider_->remoteAddress()); } TEST_F(OriginalSrcHttpTest, DecodeHeadersIpv4AddressUsesCorrectAddress) { @@ -127,10 +128,10 @@ TEST_F(OriginalSrcHttpTest, DecodeHeadersIpv4AddressBleachesPort) { NiceMock socket; const auto expected_address = Network::Utility::parseInternetAddress("1.2.3.4"); - EXPECT_CALL(socket, setLocalAddress(PointeesEq(expected_address))); for (const auto& option : *options) { option->setOption(socket, envoy::config::core::v3::SocketOption::STATE_PREBIND); } + EXPECT_EQ(*socket.addressProvider().localAddress(), *expected_address); } TEST_F(OriginalSrcHttpTest, FilterAddsTransparentOption) { @@ -201,8 +202,8 @@ TEST_F(OriginalSrcHttpTest, TrailersAndDataEndStreamDoNothing) { // This will be invoked in decodeHeaders. EXPECT_CALL(callbacks, addUpstreamSocketOptions(_)); EXPECT_CALL(callbacks, streamInfo()); - callbacks.stream_info_.downstream_remote_address_ = - Network::Utility::parseInternetAddress("1.2.3.4"); + callbacks.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::parseInternetAddress("1.2.3.4")); filter->decodeHeaders(headers_, true); // No new expectations => no side effects from calling these. @@ -218,8 +219,8 @@ TEST_F(OriginalSrcHttpTest, TrailersAndDataNotEndStreamDoNothing) { // This will be invoked in decodeHeaders. EXPECT_CALL(callbacks, addUpstreamSocketOptions(_)); EXPECT_CALL(callbacks, streamInfo()); - callbacks.stream_info_.downstream_remote_address_ = - Network::Utility::parseInternetAddress("1.2.3.4"); + callbacks.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::parseInternetAddress("1.2.3.4")); filter->decodeHeaders(headers_, false); // No new expectations => no side effects from calling these. diff --git a/test/extensions/filters/http/rbac/rbac_filter_test.cc b/test/extensions/filters/http/rbac/rbac_filter_test.cc index 018ebd9319b8..9f7a181da239 100644 --- a/test/extensions/filters/http/rbac/rbac_filter_test.cc +++ b/test/extensions/filters/http/rbac/rbac_filter_test.cc @@ -64,7 +64,7 @@ class RoleBasedAccessControlFilterTest : public testing::Test { void setDestinationPort(uint16_t port) { address_ = Envoy::Network::Utility::parseInternetAddress("1.2.3.4", port, false); - ON_CALL(req_info_, downstreamLocalAddress()).WillByDefault(ReturnRef(address_)); + req_info_.downstream_address_provider_->setLocalAddress(address_); } void setRequestedServerName(std::string server_name) { diff --git a/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.cc b/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.cc index 95e3974fe626..3ca713522d41 100644 --- a/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.cc +++ b/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.cc @@ -8,35 +8,16 @@ Network::IoHandle& FakeConnectionSocket::ioHandle() { return *io_handle_; } const Network::IoHandle& FakeConnectionSocket::ioHandle() const { return *io_handle_; } -void FakeConnectionSocket::setLocalAddress( - const Network::Address::InstanceConstSharedPtr& local_address) { - local_address_ = local_address; - if (local_address_ != nullptr) { - addr_type_ = local_address_->type(); - } -} - -void FakeConnectionSocket::setRemoteAddress( - const Network::Address::InstanceConstSharedPtr& remote_address) { - remote_address_ = remote_address; -} - -const Network::Address::InstanceConstSharedPtr& FakeConnectionSocket::localAddress() const { - return local_address_; -} - -const Network::Address::InstanceConstSharedPtr& FakeConnectionSocket::remoteAddress() const { - return remote_address_; +Network::Address::Type FakeConnectionSocket::addressType() const { + return address_provider_->localAddress()->type(); } -Network::Address::Type FakeConnectionSocket::addressType() const { return addr_type_; } - absl::optional FakeConnectionSocket::ipVersion() const { - if (local_address_ == nullptr || addr_type_ != Network::Address::Type::Ip) { + if (address_provider_->localAddress() == nullptr || addressType() != Network::Address::Type::Ip) { return absl::nullopt; } - return local_address_->ip()->version(); + return address_provider_->localAddress()->ip()->version(); } void FakeConnectionSocket::setDetectedTransportProtocol(absl::string_view protocol) { diff --git a/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.h b/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.h index ee3ede59681f..21303a72eacb 100644 --- a/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.h +++ b/test/extensions/filters/listener/common/fuzz/listener_filter_fakes.h @@ -14,8 +14,7 @@ static constexpr int kFakeSocketFd = 42; class FakeConnectionSocket : public Network::MockConnectionSocket { public: FakeConnectionSocket() - : io_handle_(std::make_unique(kFakeSocketFd)), - local_address_(nullptr), remote_address_(nullptr) {} + : io_handle_(std::make_unique(kFakeSocketFd)) {} ~FakeConnectionSocket() override { io_handle_->close(); } @@ -23,14 +22,6 @@ class FakeConnectionSocket : public Network::MockConnectionSocket { const Network::IoHandle& ioHandle() const override; - void setLocalAddress(const Network::Address::InstanceConstSharedPtr& local_address) override; - - void setRemoteAddress(const Network::Address::InstanceConstSharedPtr& remote_address) override; - - const Network::Address::InstanceConstSharedPtr& localAddress() const override; - - const Network::Address::InstanceConstSharedPtr& remoteAddress() const override; - Network::Address::Type addressType() const override; absl::optional ipVersion() const override; @@ -53,9 +44,6 @@ class FakeConnectionSocket : public Network::MockConnectionSocket { private: const Network::IoHandlePtr io_handle_; - Network::Address::InstanceConstSharedPtr local_address_; - Network::Address::InstanceConstSharedPtr remote_address_; - Network::Address::Type addr_type_; std::vector application_protocols_; std::string transport_protocol_; std::string server_name_; diff --git a/test/extensions/filters/listener/common/fuzz/listener_filter_fuzzer.cc b/test/extensions/filters/listener/common/fuzz/listener_filter_fuzzer.cc index 08280b013e53..be4154ba804d 100644 --- a/test/extensions/filters/listener/common/fuzz/listener_filter_fuzzer.cc +++ b/test/extensions/filters/listener/common/fuzz/listener_filter_fuzzer.cc @@ -8,14 +8,16 @@ void ListenerFilterFuzzer::fuzz( Network::ListenerFilter& filter, const test::extensions::filters::listener::FilterFuzzTestCase& input) { try { - socket_.setLocalAddress(Network::Utility::resolveUrl(input.sock().local_address())); + socket_.addressProvider().setLocalAddress( + Network::Utility::resolveUrl(input.sock().local_address())); } catch (const EnvoyException& e) { - socket_.setLocalAddress(Network::Utility::resolveUrl("tcp://0.0.0.0:0")); + socket_.addressProvider().setLocalAddress(Network::Utility::resolveUrl("tcp://0.0.0.0:0")); } try { - socket_.setRemoteAddress(Network::Utility::resolveUrl(input.sock().remote_address())); + socket_.addressProvider().setRemoteAddress( + Network::Utility::resolveUrl(input.sock().remote_address())); } catch (const EnvoyException& e) { - socket_.setRemoteAddress(Network::Utility::resolveUrl("tcp://0.0.0.0:0")); + socket_.addressProvider().setRemoteAddress(Network::Utility::resolveUrl("tcp://0.0.0.0:0")); } FuzzedInputStream data(input); diff --git a/test/extensions/filters/listener/original_src/original_src_test.cc b/test/extensions/filters/listener/original_src/original_src_test.cc index 0e9180012fc2..212d16331aa3 100644 --- a/test/extensions/filters/listener/original_src/original_src_test.cc +++ b/test/extensions/filters/listener/original_src/original_src_test.cc @@ -39,7 +39,7 @@ class OriginalSrcTest : public testing::Test { } void setAddressToReturn(const std::string& address) { - callbacks_.socket_.remote_address_ = Network::Utility::resolveUrl(address); + callbacks_.socket_.address_provider_->setRemoteAddress(Network::Utility::resolveUrl(address)); } protected: @@ -81,8 +81,9 @@ TEST_F(OriginalSrcTest, OnNewConnectionIpv4AddressAddsOption) { ASSERT_NE(options->at(0), nullptr); NiceMock socket; - EXPECT_CALL(socket, setLocalAddress(PointeesEq(callbacks_.socket_.remote_address_))); options->at(0)->setOption(socket, envoy::config::core::v3::SocketOption::STATE_PREBIND); + EXPECT_EQ(*socket.addressProvider().localAddress(), + *callbacks_.socket_.addressProvider().remoteAddress()); } TEST_F(OriginalSrcTest, OnNewConnectionIpv4AddressUsesCorrectAddress) { @@ -111,11 +112,11 @@ TEST_F(OriginalSrcTest, OnNewConnectionIpv4AddressBleachesPort) { NiceMock socket; const auto expected_address = Network::Utility::parseInternetAddress("1.2.3.4"); - EXPECT_CALL(socket, setLocalAddress(PointeesEq(expected_address))); // not ideal -- we're assuming that the original_src option is first, but it's a fair assumption // for now. options->at(0)->setOption(socket, envoy::config::core::v3::SocketOption::STATE_PREBIND); + EXPECT_EQ(*socket.addressProvider().localAddress(), *expected_address); } TEST_F(OriginalSrcTest, FilterAddsTransparentOption) { diff --git a/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc b/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc index 56a2e6081276..9d997d96ba92 100644 --- a/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc +++ b/test/extensions/filters/listener/proxy_protocol/proxy_protocol_test.cc @@ -64,10 +64,11 @@ class ProxyProtocolTest : public testing::TestWithParamlocalAddress())); + EXPECT_CALL(socket_factory_, localAddress()) + .WillOnce(ReturnRef(socket_->addressProvider().localAddress())); EXPECT_CALL(socket_factory_, getListenSocket()).WillOnce(Return(socket_)); connection_handler_->addListener(absl::nullopt, *this); - conn_ = dispatcher_->createClientConnection(socket_->localAddress(), + conn_ = dispatcher_->createClientConnection(socket_->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); conn_->addConnectionCallbacks(connection_callbacks_); @@ -219,8 +220,9 @@ TEST_P(ProxyProtocolTest, V1Basic) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "1.2.3.4"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "1.2.3.4"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -232,11 +234,13 @@ TEST_P(ProxyProtocolTest, V1Minimal) { expectData("more data"); if (GetParam() == Envoy::Network::Address::IpVersion::v4) { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "127.0.0.1"); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "127.0.0.1"); } else { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "::1"); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "::1"); } - EXPECT_FALSE(server_connection_->localAddressRestored()); + EXPECT_FALSE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -252,8 +256,9 @@ TEST_P(ProxyProtocolTest, V2Basic) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "1.2.3.4"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "1.2.3.4"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -264,8 +269,9 @@ TEST_P(ProxyProtocolTest, BasicV6) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "1:2:3::4"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "1:2:3::4"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -283,8 +289,9 @@ TEST_P(ProxyProtocolTest, V2BasicV6) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "1:2:3::4"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "1:2:3::4"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -445,14 +452,16 @@ TEST_P(ProxyProtocolTest, V2LocalConnection) { connect(); write(buffer, sizeof(buffer)); expectData("more data"); - if (server_connection_->remoteAddress()->ip()->version() == + if (server_connection_->addressProvider().remoteAddress()->ip()->version() == Envoy::Network::Address::IpVersion::v6) { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "::1"); - } else if (server_connection_->remoteAddress()->ip()->version() == + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "::1"); + } else if (server_connection_->addressProvider().remoteAddress()->ip()->version() == Envoy::Network::Address::IpVersion::v4) { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "127.0.0.1"); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "127.0.0.1"); } - EXPECT_FALSE(server_connection_->localAddressRestored()); + EXPECT_FALSE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -464,14 +473,16 @@ TEST_P(ProxyProtocolTest, V2LocalConnectionExtension) { connect(); write(buffer, sizeof(buffer)); expectData("more data"); - if (server_connection_->remoteAddress()->ip()->version() == + if (server_connection_->addressProvider().remoteAddress()->ip()->version() == Envoy::Network::Address::IpVersion::v6) { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "::1"); - } else if (server_connection_->remoteAddress()->ip()->version() == + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "::1"); + } else if (server_connection_->addressProvider().remoteAddress()->ip()->version() == Envoy::Network::Address::IpVersion::v4) { - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "127.0.0.1"); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "127.0.0.1"); } - EXPECT_FALSE(server_connection_->localAddressRestored()); + EXPECT_FALSE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -691,8 +702,9 @@ TEST_P(ProxyProtocolTest, Fragmented) { // the results. Since we must have data we might as well check that we get it. expectData("..."); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "254.254.254.254"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "254.254.254.254"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -712,8 +724,9 @@ TEST_P(ProxyProtocolTest, V2Fragmented1) { write(buffer + 20, 17); expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "1.2.3.4"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "1.2.3.4"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -733,8 +746,9 @@ TEST_P(ProxyProtocolTest, V2Fragmented2) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "1.2.3.4"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "1.2.3.4"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -897,8 +911,9 @@ TEST_P(ProxyProtocolTest, PartialRead) { expectData("..."); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "254.254.254.254"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "254.254.254.254"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -921,8 +936,9 @@ TEST_P(ProxyProtocolTest, V2PartialRead) { expectData("moredata"); - EXPECT_EQ(server_connection_->remoteAddress()->ip()->addressAsString(), "1.2.3.4"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->ip()->addressAsString(), + "1.2.3.4"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -1287,12 +1303,13 @@ class WildcardProxyProtocolTest : public testing::TestWithParamlocalAddress()->ip()->port())), + socket_->addressProvider().localAddress()->ip()->port())), connection_handler_(new Server::ConnectionHandlerImpl(*dispatcher_, absl::nullopt)), name_("proxy"), filter_chain_(Network::Test::createEmptyFilterChainWithRawBufferSockets()), init_manager_(nullptr) { EXPECT_CALL(socket_factory_, socketType()).WillOnce(Return(Network::Socket::Type::Stream)); - EXPECT_CALL(socket_factory_, localAddress()).WillOnce(ReturnRef(socket_->localAddress())); + EXPECT_CALL(socket_factory_, localAddress()) + .WillOnce(ReturnRef(socket_->addressProvider().localAddress())); EXPECT_CALL(socket_factory_, getListenSocket()).WillOnce(Return(socket_)); connection_handler_->addListener(absl::nullopt, *this); conn_ = dispatcher_->createClientConnection(local_dst_address_, @@ -1419,9 +1436,10 @@ TEST_P(WildcardProxyProtocolTest, Basic) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->asString(), "1.2.3.4:65535"); - EXPECT_EQ(server_connection_->localAddress()->asString(), "254.254.254.254:1234"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->asString(), "1.2.3.4:65535"); + EXPECT_EQ(server_connection_->addressProvider().localAddress()->asString(), + "254.254.254.254:1234"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -1432,9 +1450,9 @@ TEST_P(WildcardProxyProtocolTest, BasicV6) { expectData("more data"); - EXPECT_EQ(server_connection_->remoteAddress()->asString(), "[1:2:3::4]:65535"); - EXPECT_EQ(server_connection_->localAddress()->asString(), "[5:6::7:8]:1234"); - EXPECT_TRUE(server_connection_->localAddressRestored()); + EXPECT_EQ(server_connection_->addressProvider().remoteAddress()->asString(), "[1:2:3::4]:65535"); + EXPECT_EQ(server_connection_->addressProvider().localAddress()->asString(), "[5:6::7:8]:1234"); + EXPECT_TRUE(server_connection_->addressProvider().localAddressRestored()); disconnect(); } @@ -1453,7 +1471,7 @@ TEST(ProxyProtocolConfigFactoryTest, TestCreateFactory) { key: "PP2_TYPE_ALPN" - tlv_type: 0x1a on_tlv_present: - key: "PP2_TYPE_CUSTOMER_A" + key: "PP2_TYPE_CUSTOMER_A" )EOF"; ProtobufTypes::MessagePtr proto_config = factory->createEmptyConfigProto(); diff --git a/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc b/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc index e589381be4fa..2b8c8cbcc2ae 100644 --- a/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc +++ b/test/extensions/filters/network/client_ssl_auth/client_ssl_auth_test.cc @@ -161,8 +161,8 @@ TEST_F(ClientSslAuthFilterTest, Ssl) { // Create a new filter for an SSL connection, with no backing auth data yet. createAuthFilter(); ON_CALL(filter_callbacks_.connection_, ssl()).WillByDefault(Return(ssl_)); - filter_callbacks_.connection_.remote_address_ = - std::make_shared("192.168.1.1"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("192.168.1.1")); std::string expected_sha_1("digest"); EXPECT_CALL(*ssl_, sha256PeerCertificateDigest()).WillOnce(ReturnRef(expected_sha_1)); EXPECT_CALL(filter_callbacks_.connection_, close(Network::ConnectionCloseType::NoFlush)); @@ -184,8 +184,8 @@ TEST_F(ClientSslAuthFilterTest, Ssl) { // Create a new filter for an SSL connection with an authorized cert. createAuthFilter(); - filter_callbacks_.connection_.remote_address_ = - std::make_shared("192.168.1.1"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("192.168.1.1")); std::string expected_sha_2("1b7d42ef0025ad89c1c911d6c10d7e86a4cb7c5863b2980abcbad1895f8b5314"); EXPECT_CALL(*ssl_, sha256PeerCertificateDigest()).WillOnce(ReturnRef(expected_sha_2)); EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection()); @@ -197,8 +197,8 @@ TEST_F(ClientSslAuthFilterTest, Ssl) { // White list case. createAuthFilter(); - filter_callbacks_.connection_.remote_address_ = - std::make_shared("1.2.3.4"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("1.2.3.4")); EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection()); EXPECT_CALL(filter_callbacks_, continueReading()); filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::Connected); @@ -208,8 +208,8 @@ TEST_F(ClientSslAuthFilterTest, Ssl) { // IPv6 White list case. createAuthFilter(); - filter_callbacks_.connection_.remote_address_ = - std::make_shared("2001:abcd::1"); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + std::make_shared("2001:abcd::1")); EXPECT_EQ(Network::FilterStatus::StopIteration, instance_->onNewConnection()); EXPECT_CALL(filter_callbacks_, continueReading()); filter_callbacks_.connection_.raiseEvent(Network::ConnectionEvent::Connected); diff --git a/test/extensions/filters/network/common/fuzz/uber_per_readfilter.cc b/test/extensions/filters/network/common/fuzz/uber_per_readfilter.cc index d90c82e2d41a..f6976aedf6b9 100644 --- a/test/extensions/filters/network/common/fuzz/uber_per_readfilter.cc +++ b/test/extensions/filters/network/common/fuzz/uber_per_readfilter.cc @@ -85,11 +85,15 @@ void UberFilterFuzzer::perFilterSetup(const std::string& filter_name) { .WillOnce(Invoke([&](const envoy::config::core::v3::GrpcService&, Stats::Scope&, bool) { return std::move(async_client_factory_); })); - read_filter_callbacks_->connection_.local_address_ = pipe_addr_; - read_filter_callbacks_->connection_.remote_address_ = pipe_addr_; + read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setLocalAddress( + pipe_addr_); + read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + pipe_addr_); } else if (filter_name == NetworkFilterNames::get().HttpConnectionManager) { - read_filter_callbacks_->connection_.local_address_ = pipe_addr_; - read_filter_callbacks_->connection_.remote_address_ = pipe_addr_; + read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setLocalAddress( + pipe_addr_); + read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + pipe_addr_); } else if (filter_name == NetworkFilterNames::get().RateLimit) { async_client_factory_ = std::make_unique(); async_client_ = std::make_unique(); @@ -114,8 +118,10 @@ void UberFilterFuzzer::perFilterSetup(const std::string& filter_name) { .WillOnce(Invoke([&](const envoy::config::core::v3::GrpcService&, Stats::Scope&, bool) { return std::move(async_client_factory_); })); - read_filter_callbacks_->connection_.local_address_ = pipe_addr_; - read_filter_callbacks_->connection_.remote_address_ = pipe_addr_; + read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setLocalAddress( + pipe_addr_); + read_filter_callbacks_->connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + pipe_addr_); } } diff --git a/test/extensions/filters/network/ext_authz/ext_authz_fuzz_test.cc b/test/extensions/filters/network/ext_authz/ext_authz_fuzz_test.cc index c2e816c748d5..37982575ecca 100644 --- a/test/extensions/filters/network/ext_authz/ext_authz_fuzz_test.cc +++ b/test/extensions/filters/network/ext_authz/ext_authz_fuzz_test.cc @@ -75,8 +75,8 @@ DEFINE_PROTO_FUZZER(const envoy::extensions::filters::network::ext_authz::ExtAut static Network::Address::InstanceConstSharedPtr addr = std::make_shared("/test/test.sock"); - ON_CALL(filter_callbacks.connection_, remoteAddress()).WillByDefault(ReturnRef(addr)); - ON_CALL(filter_callbacks.connection_, localAddress()).WillByDefault(ReturnRef(addr)); + filter_callbacks.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr); + filter_callbacks.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr); for (const auto& action : input.actions()) { switch (action.action_selector_case()) { diff --git a/test/extensions/filters/network/ext_authz/ext_authz_test.cc b/test/extensions/filters/network/ext_authz/ext_authz_test.cc index 813dc8b4159f..053d84d3c04a 100644 --- a/test/extensions/filters/network/ext_authz/ext_authz_test.cc +++ b/test/extensions/filters/network/ext_authz/ext_authz_test.cc @@ -66,8 +66,9 @@ class ExtAuthzFilterTest : public testing::Test { } void expectOKWithOnData() { - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, testing::A(), _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -179,8 +180,8 @@ TEST_F(ExtAuthzFilterTest, DeniedWithOnData) { initialize(default_yaml_string_); InSequence s; - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -220,8 +221,8 @@ TEST_F(ExtAuthzFilterTest, FailOpen) { initialize(default_yaml_string_); InSequence s; - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -254,8 +255,8 @@ TEST_F(ExtAuthzFilterTest, FailClose) { // Explicitly set the failure_mode_allow to false. config_->setFailModeAllow(false); - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -285,8 +286,8 @@ TEST_F(ExtAuthzFilterTest, DoNotCallCancelonRemoteClose) { initialize(default_yaml_string_); InSequence s; - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -320,8 +321,8 @@ TEST_F(ExtAuthzFilterTest, VerifyCancelOnRemoteClose) { initialize(default_yaml_string_); InSequence s; - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( WithArgs<0>(Invoke([&](Filters::Common::ExtAuthz::RequestCallbacks& callbacks) -> void { @@ -350,8 +351,8 @@ TEST_F(ExtAuthzFilterTest, ImmediateOK) { initialize(default_yaml_string_); InSequence s; - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(filter_callbacks_, continueReading()).Times(0); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( @@ -382,8 +383,8 @@ TEST_F(ExtAuthzFilterTest, ImmediateNOK) { initialize(default_yaml_string_); InSequence s; - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(filter_callbacks_, continueReading()).Times(0); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( @@ -410,8 +411,8 @@ TEST_F(ExtAuthzFilterTest, ImmediateErrorFailOpen) { initialize(default_yaml_string_); InSequence s; - EXPECT_CALL(filter_callbacks_.connection_, remoteAddress()).WillOnce(ReturnRef(addr_)); - EXPECT_CALL(filter_callbacks_.connection_, localAddress()).WillOnce(ReturnRef(addr_)); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress(addr_); + filter_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress(addr_); EXPECT_CALL(filter_callbacks_, continueReading()).Times(0); EXPECT_CALL(*client_, check(_, _, _, _)) .WillOnce( diff --git a/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc b/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc index 2499cd362e0d..8d80c48b1d4d 100644 --- a/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc +++ b/test/extensions/stats_sinks/common/statsd/udp_statsd_test.cc @@ -63,7 +63,7 @@ TEST(UdpOverUdsStatsdSinkTest, InitWithPipeAddress) { sink.flush(snapshot); // Start the server. - Network::SocketImpl sock(Network::Socket::Type::Datagram, uds_address); + Network::SocketImpl sock(Network::Socket::Type::Datagram, uds_address, nullptr); RELEASE_ASSERT(sock.setBlockingForTest(false).rc_ != -1, ""); sock.bind(uds_address); diff --git a/test/extensions/stats_sinks/hystrix/hystrix_test.cc b/test/extensions/stats_sinks/hystrix/hystrix_test.cc index 38f88019602c..c6b72f1a5078 100644 --- a/test/extensions/stats_sinks/hystrix/hystrix_test.cc +++ b/test/extensions/stats_sinks/hystrix/hystrix_test.cc @@ -522,7 +522,7 @@ TEST_F(HystrixSinkTest, HystrixEventStreamHandler) { ON_CALL(admin_stream_mock, http1StreamEncoderOptions()) .WillByDefault(Return(Http::Http1StreamEncoderOptionsOptRef(stream_encoder_options))); ON_CALL(callbacks_, connection()).WillByDefault(Return(&connection_mock)); - ON_CALL(connection_mock, remoteAddress()).WillByDefault(ReturnRef(addr_instance_)); + connection_mock.stream_info_.downstream_address_provider_->setRemoteAddress(addr_instance_); EXPECT_CALL(stream_encoder_options, disableChunkEncoding()); ASSERT_EQ(sink_->handlerHystrixEventStream(path_and_query, response_headers, diff --git a/test/extensions/transport_sockets/proxy_protocol/proxy_protocol_test.cc b/test/extensions/transport_sockets/proxy_protocol/proxy_protocol_test.cc index 7a6e2f53419c..d23ad4a8961f 100644 --- a/test/extensions/transport_sockets/proxy_protocol/proxy_protocol_test.cc +++ b/test/extensions/transport_sockets/proxy_protocol/proxy_protocol_test.cc @@ -54,10 +54,10 @@ class ProxyProtocolTest : public testing::Test { // Test injects PROXY protocol header only once TEST_F(ProxyProtocolTest, InjectesHeaderOnlyOnce) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://172.0.0.1:80"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:80")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("174.2.2.222", "172.0.0.1", 50000, 80, Network::Address::IpVersion::v4, expected_buff); @@ -84,10 +84,10 @@ TEST_F(ProxyProtocolTest, InjectesHeaderOnlyOnce) { // Test returned bytes processed includes the PROXY protocol header TEST_F(ProxyProtocolTest, BytesProcessedIncludesProxyProtocolHeader) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://172.0.0.1:80"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:80")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("174.2.2.222", "172.0.0.1", 50000, 80, Network::Address::IpVersion::v4, expected_buff); @@ -117,10 +117,10 @@ TEST_F(ProxyProtocolTest, BytesProcessedIncludesProxyProtocolHeader) { // Test returns KeepOpen action when write error is Again TEST_F(ProxyProtocolTest, ReturnsKeepOpenWhenWriteErrorIsAgain) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://172.0.0.1:80"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:80")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("174.2.2.222", "172.0.0.1", 50000, 80, Network::Address::IpVersion::v4, expected_buff); @@ -153,10 +153,10 @@ TEST_F(ProxyProtocolTest, ReturnsKeepOpenWhenWriteErrorIsAgain) { // Test returns Close action when write error is not Again TEST_F(ProxyProtocolTest, ReturnsCloseWhenWriteErrorIsNotAgain) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://172.0.0.1:80"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:80")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("174.2.2.222", "172.0.0.1", 50000, 80, Network::Address::IpVersion::v4, expected_buff); @@ -179,10 +179,10 @@ TEST_F(ProxyProtocolTest, ReturnsCloseWhenWriteErrorIsNotAgain) { // Test injects V1 PROXY protocol using upstream addresses when transport options are null TEST_F(ProxyProtocolTest, V1IPV4LocalAddressWhenTransportOptionsAreNull) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://172.0.0.1:80"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:80")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("174.2.2.222", "172.0.0.1", 50000, 80, Network::Address::IpVersion::v4, expected_buff); @@ -202,10 +202,10 @@ TEST_F(ProxyProtocolTest, V1IPV4LocalAddressWhenTransportOptionsAreNull) { // Test injects V1 PROXY protocol using upstream addresses when header options are null TEST_F(ProxyProtocolTest, V1IPV4LocalAddressesWhenHeaderOptionsAreNull) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://172.0.0.1:80"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:80")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("174.2.2.222", "172.0.0.1", 50000, 80, Network::Address::IpVersion::v4, expected_buff); @@ -226,10 +226,10 @@ TEST_F(ProxyProtocolTest, V1IPV4LocalAddressesWhenHeaderOptionsAreNull) { // Test injects V1 PROXY protocol using upstream addresses when header options are null TEST_F(ProxyProtocolTest, V1IPV6LocalAddressesWhenHeaderOptionsAreNull) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://[a:b:c:d::]:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://[a:b:c:d::]:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("a:b:c:d::", "e:b:c:f::", 50000, 8080, Network::Address::IpVersion::v6, expected_buff); @@ -259,10 +259,10 @@ TEST_F(ProxyProtocolTest, V1IPV4DownstreamAddresses) { "", std::vector{}, std::vector{}, std::vector{}, absl::optional( Network::ProxyProtocolData{src_addr, dst_addr})); - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://174.2.2.222:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://172.0.0.1:8080"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://174.2.2.222:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://172.0.0.1:8080")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("202.168.0.13", "174.2.2.222", 52000, 80, Network::Address::IpVersion::v4, expected_buff); @@ -291,10 +291,10 @@ TEST_F(ProxyProtocolTest, V1IPV6DownstreamAddresses) { "", std::vector{}, std::vector{}, std::vector{}, absl::optional( Network::ProxyProtocolData{src_addr, dst_addr})); - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://[a:b:c:d::]:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://[a:b:c:d::]:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV1Header("1::2:3", "a:b:c:d::", 52000, 80, Network::Address::IpVersion::v6, expected_buff); @@ -314,10 +314,10 @@ TEST_F(ProxyProtocolTest, V1IPV6DownstreamAddresses) { // Test injects V2 PROXY protocol using upstream addresses when transport options are null TEST_F(ProxyProtocolTest, V2IPV4LocalCommandWhenTransportOptionsAreNull) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://1.2.3.4:773"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://0.1.1.2:513"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://1.2.3.4:773")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://0.1.1.2:513")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV2LocalHeader(expected_buff); initialize(ProxyProtocolConfig_Version::ProxyProtocolConfig_Version_V2, nullptr); @@ -336,10 +336,10 @@ TEST_F(ProxyProtocolTest, V2IPV4LocalCommandWhenTransportOptionsAreNull) { // Test injects V2 PROXY protocol using upstream addresses when header options are null TEST_F(ProxyProtocolTest, V2IPV4LocalCommandWhenHeaderOptionsAreNull) { - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://1.2.3.4:773"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://0.1.1.2:513"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://1.2.3.4:773")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://0.1.1.2:513")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV2LocalHeader(expected_buff); initialize(ProxyProtocolConfig_Version::ProxyProtocolConfig_Version_V2, @@ -368,10 +368,10 @@ TEST_F(ProxyProtocolTest, V2IPV4DownstreamAddresses) { "", std::vector{}, std::vector{}, std::vector{}, absl::optional( Network::ProxyProtocolData{src_addr, dst_addr})); - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://0.1.1.2:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://3.3.3.3:80"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://0.1.1.2:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://3.3.3.3:80")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV2Header("1.2.3.4", "0.1.1.2", 773, 513, Network::Address::IpVersion::v4, expected_buff); @@ -400,10 +400,10 @@ TEST_F(ProxyProtocolTest, V2IPV6DownstreamAddresses) { "", std::vector{}, std::vector{}, std::vector{}, absl::optional( Network::ProxyProtocolData{src_addr, dst_addr})); - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://[1:100:200:3::]:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://[1:100:200:3::]:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080")); Buffer::OwnedImpl expected_buff{}; Common::ProxyProtocol::generateV2Header("1:2:3::4", "1:100:200:3::", 8, 2, Network::Address::IpVersion::v6, expected_buff); @@ -432,10 +432,10 @@ TEST_F(ProxyProtocolTest, OnConnectedCallsInnerOnConnected) { "", std::vector{}, std::vector{}, std::vector{}, absl::optional( Network::ProxyProtocolData{src_addr, dst_addr})); - transport_callbacks_.connection_.local_address_ = - Network::Utility::resolveUrl("tcp://[1:100:200:3::]:50000"); - transport_callbacks_.connection_.remote_address_ = - Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080"); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setLocalAddress( + Network::Utility::resolveUrl("tcp://[1:100:200:3::]:50000")); + transport_callbacks_.connection_.stream_info_.downstream_address_provider_->setRemoteAddress( + Network::Utility::resolveUrl("tcp://[e:b:c:f::]:8080")); initialize(ProxyProtocolConfig_Version::ProxyProtocolConfig_Version_V2, socket_options); EXPECT_CALL(*inner_socket_, onConnected()); diff --git a/test/extensions/transport_sockets/tap/tap_config_impl_test.cc b/test/extensions/transport_sockets/tap/tap_config_impl_test.cc index 99f10e518e8d..b753b610f820 100644 --- a/test/extensions/transport_sockets/tap/tap_config_impl_test.cc +++ b/test/extensions/transport_sockets/tap/tap_config_impl_test.cc @@ -48,8 +48,8 @@ class MockSocketTapConfig : public SocketTapConfig { class PerSocketTapperImplTest : public testing::Test { public: void setup(bool streaming) { - connection_.local_address_ = - std::make_shared("127.0.0.1", 1000); + connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("127.0.0.1", 1000)); ON_CALL(connection_, id()).WillByDefault(Return(1)); EXPECT_CALL(*config_, createPerTapSinkHandleManager_(1)).WillOnce(Return(sink_manager_)); EXPECT_CALL(*config_, createMatchStatusVector()) diff --git a/test/extensions/transport_sockets/tls/handshaker_test.cc b/test/extensions/transport_sockets/tls/handshaker_test.cc index 8822d778e76b..96fdba339cd2 100644 --- a/test/extensions/transport_sockets/tls/handshaker_test.cc +++ b/test/extensions/transport_sockets/tls/handshaker_test.cc @@ -51,8 +51,9 @@ class MockHandshakeCallbacks : public Ssl::HandshakeCallbacks { class HandshakerTest : public SslCertsTest { protected: HandshakerTest() - : dispatcher_(api_->allocateDispatcher("test_thread")), stream_info_(api_->timeSource()), - client_ctx_(SSL_CTX_new(TLS_method())), server_ctx_(SSL_CTX_new(TLS_method())) {} + : dispatcher_(api_->allocateDispatcher("test_thread")), + stream_info_(api_->timeSource(), nullptr), client_ctx_(SSL_CTX_new(TLS_method())), + server_ctx_(SSL_CTX_new(TLS_method())) {} void SetUp() override { // Set up key and cert, initialize two SSL objects and a pair of BIOs for diff --git a/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc index 14a9c49370f6..16896443a6a8 100644 --- a/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc +++ b/test/extensions/transport_sockets/tls/integration/ssl_integration_test.cc @@ -608,11 +608,11 @@ TEST_P(SslTapIntegrationTest, TwoRequestsWithBinaryProto) { EXPECT_EQ(256, response->body().size()); checkStats(); envoy::config::core::v3::Address expected_local_address; - Network::Utility::addressToProtobufAddress(*codec_client_->connection()->remoteAddress(), - expected_local_address); + Network::Utility::addressToProtobufAddress( + *codec_client_->connection()->addressProvider().remoteAddress(), expected_local_address); envoy::config::core::v3::Address expected_remote_address; - Network::Utility::addressToProtobufAddress(*codec_client_->connection()->localAddress(), - expected_remote_address); + Network::Utility::addressToProtobufAddress( + *codec_client_->connection()->addressProvider().localAddress(), expected_remote_address); codec_client_->close(); test_server_->waitForCounterGe("http.config_test.downstream_cx_destroy", 1); envoy::data::tap::v3::TraceWrapper trace; diff --git a/test/extensions/transport_sockets/tls/ssl_socket_test.cc b/test/extensions/transport_sockets/tls/ssl_socket_test.cc index 32eed8ca6880..e080412caa3e 100644 --- a/test/extensions/transport_sockets/tls/ssl_socket_test.cc +++ b/test/extensions/transport_sockets/tls/ssl_socket_test.cc @@ -335,7 +335,7 @@ void testUtil(const TestUtilOptions& options) { ClientSslSocketFactory client_ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), client_ssl_socket_factory.createTransportSocket(nullptr), nullptr); Network::ConnectionPtr server_connection; Network::MockConnectionCallbacks server_connection_callbacks; @@ -644,7 +644,7 @@ const std::string testUtilV2(const TestUtilOptionsV2& options) { ClientSslSocketFactory client_ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), client_ssl_socket_factory.createTransportSocket(options.transportSocketOptions()), nullptr); if (!options.clientSession().empty()) { @@ -821,7 +821,8 @@ class SslSocketTest : public SslCertsTest, public testing::WithParamInterface { protected: SslSocketTest() - : dispatcher_(api_->allocateDispatcher("test_thread")), stream_info_(api_->timeSource()) {} + : dispatcher_(api_->allocateDispatcher("test_thread")), + stream_info_(api_->timeSource(), nullptr) {} void testClientSessionResumption(const std::string& server_ctx_yaml, const std::string& client_ctx_yaml, bool expect_reuse, @@ -2440,7 +2441,7 @@ TEST_P(SslSocketTest, FlushCloseDuringHandshake) { dispatcher_->createListener(socket, callbacks, true, ENVOY_TCP_BACKLOG_SIZE); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->connect(); Network::MockConnectionCallbacks client_connection_callbacks; @@ -2509,7 +2510,7 @@ TEST_P(SslSocketTest, HalfClose) { ClientSslSocketFactory client_ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), client_ssl_socket_factory.createTransportSocket(nullptr), nullptr); client_connection->enableHalfClose(true); client_connection->addReadFilter(client_read_filter); @@ -2592,7 +2593,7 @@ TEST_P(SslSocketTest, ShutdownWithCloseNotify) { ClientSslSocketFactory client_ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), client_ssl_socket_factory.createTransportSocket(nullptr), nullptr); Network::MockConnectionCallbacks client_connection_callbacks; client_connection->enableHalfClose(true); @@ -2681,7 +2682,7 @@ TEST_P(SslSocketTest, ShutdownWithoutCloseNotify) { ClientSslSocketFactory client_ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), client_ssl_socket_factory.createTransportSocket(nullptr), nullptr); Network::MockConnectionCallbacks client_connection_callbacks; client_connection->enableHalfClose(true); @@ -2788,7 +2789,7 @@ TEST_P(SslSocketTest, ClientAuthMultipleCAs) { Stats::TestUtil::TestStore client_stats_store; ClientSslSocketFactory ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), ssl_socket_factory.createTransportSocket(nullptr), nullptr); // Verify that server sent list with 2 acceptable client certificate CA names. @@ -2887,7 +2888,7 @@ void testTicketSessionResumption(const std::string& server_ctx_yaml1, std::make_unique(client_tls_context, client_factory_context); ClientSslSocketFactory ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher->createClientConnection( - socket1->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket1->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), ssl_socket_factory.createTransportSocket(nullptr), nullptr); Network::MockConnectionCallbacks client_connection_callbacks; @@ -2896,12 +2897,13 @@ void testTicketSessionResumption(const std::string& server_ctx_yaml1, SSL_SESSION* ssl_session = nullptr; Network::ConnectionPtr server_connection; - StreamInfo::StreamInfoImpl stream_info(time_system); + StreamInfo::StreamInfoImpl stream_info(time_system, nullptr); EXPECT_CALL(callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void { - Network::TransportSocketFactory& tsf = socket->localAddress() == socket1->localAddress() - ? server_ssl_socket_factory1 - : server_ssl_socket_factory2; + Network::TransportSocketFactory& tsf = + socket->addressProvider().localAddress() == socket1->addressProvider().localAddress() + ? server_ssl_socket_factory1 + : server_ssl_socket_factory2; server_connection = dispatcher->createServerConnection( std::move(socket), tsf.createTransportSocket(nullptr), stream_info); })); @@ -2928,7 +2930,7 @@ void testTicketSessionResumption(const std::string& server_ctx_yaml1, EXPECT_EQ(0UL, client_stats_store.counter("ssl.session_reused").value()); client_connection = dispatcher->createClientConnection( - socket2->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket2->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), ssl_socket_factory.createTransportSocket(nullptr), nullptr); client_connection->addConnectionCallbacks(client_connection_callbacks); const SslHandshakerImpl* ssl_socket = @@ -2939,12 +2941,13 @@ void testTicketSessionResumption(const std::string& server_ctx_yaml1, client_connection->connect(); Network::MockConnectionCallbacks server_connection_callbacks; - StreamInfo::StreamInfoImpl stream_info2(time_system); + StreamInfo::StreamInfoImpl stream_info2(time_system, nullptr); EXPECT_CALL(callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void { - Network::TransportSocketFactory& tsf = socket->localAddress() == socket1->localAddress() - ? server_ssl_socket_factory1 - : server_ssl_socket_factory2; + Network::TransportSocketFactory& tsf = + socket->addressProvider().localAddress() == socket1->addressProvider().localAddress() + ? server_ssl_socket_factory1 + : server_ssl_socket_factory2; server_connection = dispatcher->createServerConnection( std::move(socket), tsf.createTransportSocket(nullptr), stream_info2); server_connection->addConnectionCallbacks(server_connection_callbacks); @@ -3023,14 +3026,14 @@ void testSupportForStatelessSessionResumption(const std::string& server_ctx_yaml std::make_unique(client_tls_context, client_factory_context); ClientSslSocketFactory ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher->createClientConnection( - tcp_socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + tcp_socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), ssl_socket_factory.createTransportSocket(nullptr), nullptr); Network::MockConnectionCallbacks client_connection_callbacks; client_connection->addConnectionCallbacks(client_connection_callbacks); client_connection->connect(); - StreamInfo::StreamInfoImpl stream_info(time_system); + StreamInfo::StreamInfoImpl stream_info(time_system, nullptr); Network::ConnectionPtr server_connection; EXPECT_CALL(callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& socket) -> void { @@ -3470,7 +3473,7 @@ TEST_P(SslSocketTest, ClientAuthCrossListenerSessionResumption) { Stats::TestUtil::TestStore client_stats_store; ClientSslSocketFactory ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), ssl_socket_factory.createTransportSocket(nullptr), nullptr); Network::MockConnectionCallbacks client_connection_callbacks; @@ -3482,9 +3485,10 @@ TEST_P(SslSocketTest, ClientAuthCrossListenerSessionResumption) { Network::MockConnectionCallbacks server_connection_callbacks; EXPECT_CALL(callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& accepted_socket) -> void { - Network::TransportSocketFactory& tsf = - accepted_socket->localAddress() == socket->localAddress() ? server_ssl_socket_factory - : server2_ssl_socket_factory; + Network::TransportSocketFactory& tsf = accepted_socket->addressProvider().localAddress() == + socket->addressProvider().localAddress() + ? server_ssl_socket_factory + : server2_ssl_socket_factory; server_connection = dispatcher_->createServerConnection( std::move(accepted_socket), tsf.createTransportSocket(nullptr), stream_info_); server_connection->addConnectionCallbacks(server_connection_callbacks); @@ -3510,7 +3514,7 @@ TEST_P(SslSocketTest, ClientAuthCrossListenerSessionResumption) { EXPECT_EQ(1UL, client_stats_store.counter("ssl.handshake").value()); client_connection = dispatcher_->createClientConnection( - socket2->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket2->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), ssl_socket_factory.createTransportSocket(nullptr), nullptr); client_connection->addConnectionCallbacks(client_connection_callbacks); const SslHandshakerImpl* ssl_socket = @@ -3522,9 +3526,10 @@ TEST_P(SslSocketTest, ClientAuthCrossListenerSessionResumption) { EXPECT_CALL(callbacks, onAccept_(_)) .WillOnce(Invoke([&](Network::ConnectionSocketPtr& accepted_socket) -> void { - Network::TransportSocketFactory& tsf = - accepted_socket->localAddress() == socket->localAddress() ? server_ssl_socket_factory - : server2_ssl_socket_factory; + Network::TransportSocketFactory& tsf = accepted_socket->addressProvider().localAddress() == + socket->addressProvider().localAddress() + ? server_ssl_socket_factory + : server2_ssl_socket_factory; server_connection = dispatcher_->createServerConnection( std::move(accepted_socket), tsf.createTransportSocket(nullptr), stream_info_); server_connection->addConnectionCallbacks(server_connection_callbacks); @@ -3587,7 +3592,7 @@ void SslSocketTest::testClientSessionResumption(const std::string& server_ctx_ya ClientSslSocketFactory client_ssl_socket_factory(std::move(client_cfg), manager, client_stats_store); Network::ClientConnectionPtr client_connection = dispatcher->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), client_ssl_socket_factory.createTransportSocket(nullptr), nullptr); Network::MockConnectionCallbacks client_connection_callbacks; @@ -3649,7 +3654,7 @@ void SslSocketTest::testClientSessionResumption(const std::string& server_ctx_ya close_count = 0; client_connection = dispatcher->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), client_ssl_socket_factory.createTransportSocket(nullptr), nullptr); client_connection->addConnectionCallbacks(client_connection_callbacks); client_connection->connect(); @@ -3832,7 +3837,7 @@ TEST_P(SslSocketTest, SslError) { dispatcher_->createListener(socket, callbacks, true, ENVOY_TCP_BACKLOG_SIZE); Network::ClientConnectionPtr client_connection = dispatcher_->createClientConnection( - socket->localAddress(), Network::Address::InstanceConstSharedPtr(), + socket->addressProvider().localAddress(), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), nullptr); client_connection->connect(); Buffer::OwnedImpl bad_data("bad_handshake_data"); @@ -4831,8 +4836,9 @@ class SslReadBufferLimitTest : public SslSocketTest { std::move(client_cfg), *manager_, client_stats_store_); auto transport_socket = client_ssl_socket_factory_->createTransportSocket(nullptr); client_transport_socket_ = transport_socket.get(); - client_connection_ = dispatcher_->createClientConnection( - socket_->localAddress(), source_address_, std::move(transport_socket), nullptr); + client_connection_ = + dispatcher_->createClientConnection(socket_->addressProvider().localAddress(), + source_address_, std::move(transport_socket), nullptr); client_connection_->addConnectionCallbacks(client_callbacks_); client_connection_->connect(); read_filter_ = std::make_shared(); @@ -5056,7 +5062,8 @@ TEST_P(SslReadBufferLimitTest, TestBind) { .WillOnce(Invoke([&](Network::ConnectionEvent) -> void { dispatcher_->exit(); })); dispatcher_->run(Event::Dispatcher::RunType::Block); - EXPECT_EQ(address_string, server_connection_->remoteAddress()->ip()->addressAsString()); + EXPECT_EQ(address_string, + server_connection_->addressProvider().remoteAddress()->ip()->addressAsString()); disconnect(); } diff --git a/test/extensions/upstreams/http/tcp/upstream_request_test.cc b/test/extensions/upstreams/http/tcp/upstream_request_test.cc index f6a9c808f377..555f93a6e750 100644 --- a/test/extensions/upstreams/http/tcp/upstream_request_test.cc +++ b/test/extensions/upstreams/http/tcp/upstream_request_test.cc @@ -144,10 +144,10 @@ TEST_F(TcpUpstreamTest, V1Header) { envoy::config::core::v3::ProxyProtocolConfig* proxy_config = mock_router_filter_.route_entry_.connect_config_->mutable_proxy_protocol_config(); proxy_config->set_version(envoy::config::core::v3::ProxyProtocolConfig::V1); - mock_router_filter_.client_connection_.remote_address_ = - std::make_shared("1.2.3.4", 5); - mock_router_filter_.client_connection_.local_address_ = - std::make_shared("4.5.6.7", 8); + mock_router_filter_.client_connection_.stream_info_.downstream_address_provider_ + ->setRemoteAddress(std::make_shared("1.2.3.4", 5)); + mock_router_filter_.client_connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("4.5.6.7", 8)); Buffer::OwnedImpl expected_data; Extensions::Common::ProxyProtocol::generateProxyProtoHeader( @@ -167,10 +167,10 @@ TEST_F(TcpUpstreamTest, V2Header) { envoy::config::core::v3::ProxyProtocolConfig* proxy_config = mock_router_filter_.route_entry_.connect_config_->mutable_proxy_protocol_config(); proxy_config->set_version(envoy::config::core::v3::ProxyProtocolConfig::V2); - mock_router_filter_.client_connection_.remote_address_ = - std::make_shared("1.2.3.4", 5); - mock_router_filter_.client_connection_.local_address_ = - std::make_shared("4.5.6.7", 8); + mock_router_filter_.client_connection_.stream_info_.downstream_address_provider_ + ->setRemoteAddress(std::make_shared("1.2.3.4", 5)); + mock_router_filter_.client_connection_.stream_info_.downstream_address_provider_->setLocalAddress( + std::make_shared("4.5.6.7", 8)); Buffer::OwnedImpl expected_data; Extensions::Common::ProxyProtocol::generateProxyProtoHeader( diff --git a/test/integration/http2_flood_integration_test.cc b/test/integration/http2_flood_integration_test.cc index 9442fa5f92b3..ede1f86253be 100644 --- a/test/integration/http2_flood_integration_test.cc +++ b/test/integration/http2_flood_integration_test.cc @@ -201,7 +201,7 @@ void Http2FloodMitigationTest::floodClient(const Http2Frame& frame, uint32_t num // Make Envoy's writes into the upstream connection to return EAGAIN writev_matcher_->setSourcePort( - fake_upstream_connection_->connection().remoteAddress()->ip()->port()); + fake_upstream_connection_->connection().addressProvider().remoteAddress()->ip()->port()); auto buf = serializeFrames(frame, num_frames); @@ -304,7 +304,7 @@ Http2FloodMitigationTest::prefillOutboundUpstreamQueue(uint32_t frame_count) { // Make Envoy's writes into the upstream connection to return EAGAIN writev_matcher_->setSourcePort( - fake_upstream_connection_->connection().remoteAddress()->ip()->port()); + fake_upstream_connection_->connection().addressProvider().remoteAddress()->ip()->port()); auto buf = serializeFrames(Http2Frame::makePingFrame(), frame_count); @@ -1527,7 +1527,7 @@ TEST_P(Http2FloodMitigationTest, RequestMetadata) { // Make Envoy's writes into the upstream connection to return EAGAIN, preventing proxying of the // METADATA frames writev_matcher_->setSourcePort( - fake_upstream_connection_->connection().remoteAddress()->ip()->port()); + fake_upstream_connection_->connection().addressProvider().remoteAddress()->ip()->port()); writev_matcher_->setWritevReturnsEgain(); diff --git a/test/integration/integration_test.cc b/test/integration/integration_test.cc index deefe009901e..f662744274f9 100644 --- a/test/integration/integration_test.cc +++ b/test/integration/integration_test.cc @@ -67,7 +67,7 @@ TEST_P(IntegrationTest, BadPrebindSocketOptionWithReusePort) { auto* listener = bootstrap.mutable_static_resources()->mutable_listeners(0); listener->set_reuse_port(true); listener->mutable_address()->mutable_socket_address()->set_port_value( - addr_socket.second->localAddress()->ip()->port()); + addr_socket.second->addressProvider().localAddress()->ip()->port()); auto socket_option = listener->add_socket_options(); socket_option->set_state(envoy::config::core::v3::SocketOption::STATE_PREBIND); socket_option->set_level(10000); // Invalid level. @@ -89,7 +89,7 @@ TEST_P(IntegrationTest, BadPostbindSocketOptionWithReusePort) { auto* listener = bootstrap.mutable_static_resources()->mutable_listeners(0); listener->set_reuse_port(true); listener->mutable_address()->mutable_socket_address()->set_port_value( - addr_socket.second->localAddress()->ip()->port()); + addr_socket.second->addressProvider().localAddress()->ip()->port()); auto socket_option = listener->add_socket_options(); socket_option->set_state(envoy::config::core::v3::SocketOption::STATE_BOUND); socket_option->set_level(10000); // Invalid level. @@ -1140,8 +1140,11 @@ TEST_P(IntegrationTest, TestBind) { 1024); ASSERT_TRUE(fake_upstreams_[0]->waitForHttpConnection(*dispatcher_, fake_upstream_connection_)); ASSERT_NE(fake_upstream_connection_, nullptr); - std::string address = - fake_upstream_connection_->connection().remoteAddress()->ip()->addressAsString(); + std::string address = fake_upstream_connection_->connection() + .addressProvider() + .remoteAddress() + ->ip() + ->addressAsString(); EXPECT_EQ(address, address_string); ASSERT_TRUE(fake_upstream_connection_->waitForNewStream(*dispatcher_, upstream_request_)); ASSERT_NE(upstream_request_, nullptr); diff --git a/test/integration/socket_interface_integration_test.cc b/test/integration/socket_interface_integration_test.cc index 93a5db5aff84..bcb54fb2bfd0 100644 --- a/test/integration/socket_interface_integration_test.cc +++ b/test/integration/socket_interface_integration_test.cc @@ -117,7 +117,8 @@ TEST_P(SocketInterfaceIntegrationTest, UdpRecvFromInternalAddressWithSocketInter Network::Address::InstanceConstSharedPtr address = std::make_shared("listener_0", sock_interface); - ASSERT_DEATH(std::make_unique(Network::Socket::Type::Datagram, address), ""); + ASSERT_DEATH( + std::make_unique(Network::Socket::Type::Datagram, address, nullptr), ""); } // Test that send to internal address will return io error. @@ -131,8 +132,8 @@ TEST_P(SocketInterfaceIntegrationTest, UdpSendToInternalAddressWithSocketInterfa Network::Address::InstanceConstSharedPtr local_valid_address = Network::Test::getCanonicalLoopbackAddress(version_); - auto socket = - std::make_unique(Network::Socket::Type::Datagram, local_valid_address); + auto socket = std::make_unique(Network::Socket::Type::Datagram, + local_valid_address, nullptr); Buffer::OwnedImpl buffer; Buffer::RawSlice iovec; diff --git a/test/mocks/network/connection.cc b/test/mocks/network/connection.cc index ad6327d58d88..54b318559ee4 100644 --- a/test/mocks/network/connection.cc +++ b/test/mocks/network/connection.cc @@ -56,6 +56,8 @@ void MockConnectionBase::runLowWatermarkCallbacks() { template static void initializeMockConnection(T& connection) { ON_CALL(connection, addressProvider()) .WillByDefault(ReturnPointee(connection.stream_info_.downstream_address_provider_)); + ON_CALL(connection, addressProviderSharedPtr()) + .WillByDefault(ReturnPointee(&connection.stream_info_.downstream_address_provider_)); ON_CALL(connection, dispatcher()).WillByDefault(ReturnRef(connection.dispatcher_)); ON_CALL(connection, readEnabled()).WillByDefault(ReturnPointee(&connection.read_enabled_)); ON_CALL(connection, addConnectionCallbacks(_)) diff --git a/test/mocks/network/connection.h b/test/mocks/network/connection.h index 8e1b1e1012ce..a3ea7a83a039 100644 --- a/test/mocks/network/connection.h +++ b/test/mocks/network/connection.h @@ -64,8 +64,8 @@ class MockConnectionBase { MOCK_METHOD(void, readDisable, (bool disable)); \ MOCK_METHOD(void, detectEarlyCloseWhenReadDisabled, (bool)); \ MOCK_METHOD(bool, readEnabled, (), (const)); \ - MOCK_METHOD(const SocketAddressProvider&, addressProvider, (), (const)); \ - MOCK_METHOD(SocketAddressProviderConstSharedPtr, addressProviderSharedPtr, (), (const)); \ + MOCK_METHOD(const SocketAddressProviderGetters&, addressProvider, (), (const)); \ + MOCK_METHOD(SocketAddressProviderGettersSharedPtr, addressProviderSharedPtr, (), (const)); \ MOCK_METHOD(absl::optional, \ unixSocketPeerCredentials, (), (const)); \ MOCK_METHOD(void, setConnectionStats, (const ConnectionStats& stats)); \ diff --git a/test/mocks/network/mocks.h b/test/mocks/network/mocks.h index 82a3d0890cbf..95c973b4a6f3 100644 --- a/test/mocks/network/mocks.h +++ b/test/mocks/network/mocks.h @@ -224,8 +224,10 @@ class MockListenSocket : public Socket { void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProvider& addressProvider() const override { return *address_provider_; } - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + const SocketAddressProviderGetters& addressProvider() const override { + return *address_provider_; + } + SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return address_provider_; } MOCK_METHOD(IoHandle&, ioHandle, ()); @@ -276,8 +278,10 @@ class MockConnectionSocket : public ConnectionSocket { void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProvider& addressProvider() const override { return *address_provider_; } - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + const SocketAddressProviderGetters& addressProvider() const override { + return *address_provider_; + } + SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return address_provider_; } MOCK_METHOD(void, setDetectedTransportProtocol, (absl::string_view)); diff --git a/test/mocks/network/socket.h b/test/mocks/network/socket.h index f7db519ff5d4..7d13d5651e2d 100644 --- a/test/mocks/network/socket.h +++ b/test/mocks/network/socket.h @@ -15,8 +15,10 @@ class MockSocket : public Socket { ~MockSocket() override; SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProvider& addressProvider() const override { return *address_provider_; } - SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + const SocketAddressProviderGetters& addressProvider() const override { + return *address_provider_; + } + SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return address_provider_; } IoHandle& ioHandle() override; diff --git a/test/mocks/stream_info/mocks.cc b/test/mocks/stream_info/mocks.cc index d686f538735a..b7b235d7563c 100644 --- a/test/mocks/stream_info/mocks.cc +++ b/test/mocks/stream_info/mocks.cc @@ -1,7 +1,6 @@ #include "test/mocks/stream_info/mocks.h" #include "common/network/address_impl.h" -#include "common/network/socket_impl.h" #include "gmock/gmock.h" #include "gtest/gtest.h" diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index 7eee31ad94f9..21f63093ee33 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -2,9 +2,9 @@ #include "envoy/config/core/v3/base.pb.h" #include "envoy/http/request_id_extension.h" -#include "envoy/network/socket.h" #include "envoy/stream_info/stream_info.h" +#include "common/network/socket_impl.h" #include "common/stream_info/filter_state_impl.h" #include "test/mocks/upstream/host.h" @@ -119,7 +119,7 @@ class MockStreamInfo : public StreamInfo { uint64_t bytes_received_{}; uint64_t bytes_sent_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; - Network::SocketAddressProviderSharedPtr downstream_address_provider_; + std::shared_ptr downstream_address_provider_; Ssl::ConnectionInfoConstSharedPtr downstream_connection_info_; Ssl::ConnectionInfoConstSharedPtr upstream_connection_info_; std::string requested_server_name_; diff --git a/test/server/filter_chain_benchmark_test.cc b/test/server/filter_chain_benchmark_test.cc index df9b11288506..78190cf44c53 100644 --- a/test/server/filter_chain_benchmark_test.cc +++ b/test/server/filter_chain_benchmark_test.cc @@ -79,7 +79,7 @@ class MockConnectionSocket : public Network::ConnectionSocket { const Network::SocketAddressProvider& addressProvider() const override { return *address_provider_; } - Network::SocketAddressProviderConstSharedPtr addressProviderSharedPtr() const override { + Network::SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { return address_provider_; } diff --git a/test/tools/router_check/router.cc b/test/tools/router_check/router.cc index 3b5178ff87fa..19b2a92f33e1 100644 --- a/test/tools/router_check/router.cc +++ b/test/tools/router_check/router.cc @@ -9,6 +9,7 @@ #include "envoy/type/v3/percent.pb.h" #include "common/common/random_generator.h" +#include "common/network/socket_impl.h" #include "common/network/utility.h" #include "common/protobuf/message_validator_impl.h" #include "common/protobuf/utility.h" @@ -220,9 +221,11 @@ bool RouterCheckTool::compareEntries(const std::string& expected_routes) { validation_config.tests()) { active_runtime_ = check_config.input().runtime(); headers_finalized_ = false; + auto address_provider = std::make_shared( + nullptr, Network::Utility::getCanonicalIpv4LoopbackAddress()); Envoy::StreamInfo::StreamInfoImpl stream_info(Envoy::Http::Protocol::Http11, - factory_context_->dispatcher().timeSource()); - stream_info.setDownstreamRemoteAddress(Network::Utility::getCanonicalIpv4LoopbackAddress()); + factory_context_->dispatcher().timeSource(), + address_provider); ToolConfig tool_config = ToolConfig::create(check_config); tool_config.route_ = config_->route(*tool_config.request_headers_, stream_info, tool_config.random_value_); From dd386cef0b99c0c42c30d15c314b58099e531ce3 Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Wed, 6 Jan 2021 21:17:53 +0000 Subject: [PATCH 7/8] comments Signed-off-by: Matt Klein --- include/envoy/network/connection.h | 4 ++-- include/envoy/network/socket.h | 16 +++++++-------- include/envoy/stream_info/stream_info.h | 2 +- source/common/http/filter_manager.h | 14 ++++++------- source/common/network/connection_impl.h | 4 ++-- source/common/network/socket_impl.cc | 5 ++--- source/common/network/socket_impl.h | 18 ++++++++--------- source/common/stream_info/stream_info_impl.h | 18 ++++++++--------- source/common/upstream/health_checker_impl.cc | 2 +- source/common/upstream/health_checker_impl.h | 2 +- .../quic_filter_manager_connection_impl.h | 4 ++-- source/server/api_listener_impl.h | 8 ++++---- test/common/grpc/async_client_impl_test.cc | 2 +- .../grpc/google_async_client_impl_test.cc | 2 +- test/common/stream_info/test_util.h | 6 +++--- test/fuzz/utility.h | 2 +- test/mocks/network/connection.h | 4 ++-- test/mocks/network/mocks.cc | 8 ++++---- test/mocks/network/mocks.h | 20 ++++++++----------- test/mocks/network/socket.h | 10 ++++------ test/mocks/stream_info/mocks.cc | 2 +- test/mocks/stream_info/mocks.h | 4 ++-- test/server/filter_chain_benchmark_test.cc | 10 +++++----- test/tools/router_check/router.cc | 2 +- 24 files changed, 80 insertions(+), 89 deletions(-) diff --git a/include/envoy/network/connection.h b/include/envoy/network/connection.h index 092e8106f2c3..f70fe1a56907 100644 --- a/include/envoy/network/connection.h +++ b/include/envoy/network/connection.h @@ -191,8 +191,8 @@ class Connection : public Event::DeferredDeletable, public FilterManager { /** * @return the address provider backing this connection. */ - virtual const SocketAddressProviderGetters& addressProvider() const PURE; - virtual SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const PURE; + virtual const SocketAddressProvider& addressProvider() const PURE; + virtual SocketAddressProviderSharedPtr addressProviderSharedPtr() const PURE; /** * Credentials of the peer of a socket as decided by SO_PEERCRED. diff --git a/include/envoy/network/socket.h b/include/envoy/network/socket.h index a9a2c0d6fb6a..2a192a18a014 100644 --- a/include/envoy/network/socket.h +++ b/include/envoy/network/socket.h @@ -47,9 +47,9 @@ struct SocketOptionName { * and a getters + setters interface. This is so that only the getters portion can be overridden * in certain cases. */ -class SocketAddressProviderGetters { +class SocketAddressProvider { public: - virtual ~SocketAddressProviderGetters() = default; + virtual ~SocketAddressProvider() = default; /** * @return the local address of the socket. @@ -74,7 +74,7 @@ class SocketAddressProviderGetters { virtual const Address::InstanceConstSharedPtr& directRemoteAddress() const PURE; }; -class SocketAddressProvider : public SocketAddressProviderGetters { +class SocketAddressSetter : public SocketAddressProvider { public: /** * Set the local address of the socket. On accepted sockets the local address defaults to the @@ -103,8 +103,8 @@ class SocketAddressProvider : public SocketAddressProviderGetters { virtual void setRemoteAddress(const Address::InstanceConstSharedPtr& remote_address) PURE; }; -using SocketAddressProviderSharedPtr = std::shared_ptr; -using SocketAddressProviderGettersSharedPtr = std::shared_ptr; +using SocketAddressSetterSharedPtr = std::shared_ptr; +using SocketAddressProviderSharedPtr = std::shared_ptr; /** * Base class for Sockets @@ -121,9 +121,9 @@ class Socket { /** * @return the address provider backing this socket. */ - virtual SocketAddressProvider& addressProvider() PURE; - virtual const SocketAddressProviderGetters& addressProvider() const PURE; - virtual SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const PURE; + virtual SocketAddressSetter& addressProvider() PURE; + virtual const SocketAddressProvider& addressProvider() const PURE; + virtual SocketAddressProviderSharedPtr addressProviderSharedPtr() const PURE; /** * @return IoHandle for the underlying connection diff --git a/include/envoy/stream_info/stream_info.h b/include/envoy/stream_info/stream_info.h index 9fb19fe0e111..066862221f6b 100644 --- a/include/envoy/stream_info/stream_info.h +++ b/include/envoy/stream_info/stream_info.h @@ -454,7 +454,7 @@ class StreamInfo { /** * @return the downstream address provider. */ - virtual const Network::SocketAddressProviderGetters& downstreamAddressProvider() const PURE; + virtual const Network::SocketAddressProvider& downstreamAddressProvider() const PURE; /** * @param connection_info sets the downstream ssl connection. diff --git a/source/common/http/filter_manager.h b/source/common/http/filter_manager.h index 6cd84b590432..3047772768b4 100644 --- a/source/common/http/filter_manager.h +++ b/source/common/http/filter_manager.h @@ -598,9 +598,11 @@ class FilterManagerCallbacks { /** * This class allows the remote address to be overridden for HTTP stream info. This is used for * XFF handling. This is required to avoid providing stream info with a non-const address provider. + * Private inheritance from SocketAddressProvider is used to make sure users get the address + * provider via the normal getter. */ -class OverridableRemoteSocketAddressProviderStreamInfo : public StreamInfo::StreamInfoImpl, - Network::SocketAddressProviderGetters { +class OverridableRemoteSocketAddressSetterStreamInfo : public StreamInfo::StreamInfoImpl, + private Network::SocketAddressProvider { public: using StreamInfoImpl::StreamInfoImpl; @@ -611,11 +613,9 @@ class OverridableRemoteSocketAddressProviderStreamInfo : public StreamInfo::Stre } // StreamInfo::StreamInfo - const Network::SocketAddressProviderGetters& downstreamAddressProvider() const override { - return *this; - } + const Network::SocketAddressProvider& downstreamAddressProvider() const override { return *this; } - // Network::SocketAddressProviderGetters + // Network::SocketAddressProvider const Network::Address::InstanceConstSharedPtr& localAddress() const override { return StreamInfoImpl::downstreamAddressProvider().localAddress(); } @@ -987,7 +987,7 @@ class FilterManager : public ScopeTrackedObject, FilterChainFactory& filter_chain_factory_; const LocalReply::LocalReply& local_reply_; - OverridableRemoteSocketAddressProviderStreamInfo stream_info_; + OverridableRemoteSocketAddressSetterStreamInfo stream_info_; // TODO(snowp): Once FM has been moved to its own file we'll make these private classes of FM, // at which point they no longer need to be friends. friend ActiveStreamFilterBase; diff --git a/source/common/network/connection_impl.h b/source/common/network/connection_impl.h index fde5330f1fcf..28bb6918c89e 100644 --- a/source/common/network/connection_impl.h +++ b/source/common/network/connection_impl.h @@ -68,10 +68,10 @@ class ConnectionImpl : public ConnectionImplBase, public TransportSocketCallback void readDisable(bool disable) override; void detectEarlyCloseWhenReadDisabled(bool value) override { detect_early_close_ = value; } bool readEnabled() const override; - const SocketAddressProviderGetters& addressProvider() const override { + const SocketAddressProvider& addressProvider() const override { return socket_->addressProvider(); } - SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return socket_->addressProviderSharedPtr(); } absl::optional unixSocketPeerCredentials() const override; diff --git a/source/common/network/socket_impl.cc b/source/common/network/socket_impl.cc index 8c44690f2789..5b2127bae3b9 100644 --- a/source/common/network/socket_impl.cc +++ b/source/common/network/socket_impl.cc @@ -13,15 +13,14 @@ SocketImpl::SocketImpl(Socket::Type sock_type, const Address::InstanceConstSharedPtr& address_for_io_handle, const Address::InstanceConstSharedPtr& remote_address) : io_handle_(ioHandleForAddr(sock_type, address_for_io_handle)), - address_provider_(std::make_shared(nullptr, remote_address)), + address_provider_(std::make_shared(nullptr, remote_address)), sock_type_(sock_type), addr_type_(address_for_io_handle->type()) {} SocketImpl::SocketImpl(IoHandlePtr&& io_handle, const Address::InstanceConstSharedPtr& local_address, const Address::InstanceConstSharedPtr& remote_address) : io_handle_(std::move(io_handle)), - address_provider_( - std::make_shared(local_address, remote_address)) { + address_provider_(std::make_shared(local_address, remote_address)) { if (address_provider_->localAddress() != nullptr) { addr_type_ = address_provider_->localAddress()->type(); diff --git a/source/common/network/socket_impl.h b/source/common/network/socket_impl.h index c916f50fd6ee..21c94310f8e4 100644 --- a/source/common/network/socket_impl.h +++ b/source/common/network/socket_impl.h @@ -7,10 +7,10 @@ namespace Envoy { namespace Network { -class SocketAddressProviderImpl : public SocketAddressProvider { +class SocketAddressSetterImpl : public SocketAddressSetter { public: - SocketAddressProviderImpl(const Address::InstanceConstSharedPtr& local_address, - const Address::InstanceConstSharedPtr& remote_address) + SocketAddressSetterImpl(const Address::InstanceConstSharedPtr& local_address, + const Address::InstanceConstSharedPtr& remote_address) : local_address_(local_address), remote_address_(remote_address), direct_remote_address_(remote_address) {} @@ -18,7 +18,7 @@ class SocketAddressProviderImpl : public SocketAddressProvider { direct_remote_address_ = direct_remote_address; } - // SocketAddressProvider + // SocketAddressSetter const Address::InstanceConstSharedPtr& localAddress() const override { return local_address_; } void setLocalAddress(const Address::InstanceConstSharedPtr& local_address) override { local_address_ = local_address; @@ -49,11 +49,9 @@ class SocketImpl : public virtual Socket { const Address::InstanceConstSharedPtr& remote_address); // Network::Socket - SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProviderGetters& addressProvider() const override { - return *address_provider_; - } - SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + SocketAddressSetter& addressProvider() override { return *address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return address_provider_; } SocketPtr duplicate() override { @@ -103,7 +101,7 @@ class SocketImpl : public virtual Socket { const Address::InstanceConstSharedPtr& remote_address); const IoHandlePtr io_handle_; - const SocketAddressProviderSharedPtr address_provider_; + const SocketAddressSetterSharedPtr address_provider_; OptionsSharedPtr options_; Socket::Type sock_type_; Address::Type addr_type_; diff --git a/source/common/stream_info/stream_info_impl.h b/source/common/stream_info/stream_info_impl.h index 494d184cc1c3..e4c9512bea3a 100644 --- a/source/common/stream_info/stream_info_impl.h +++ b/source/common/stream_info/stream_info_impl.h @@ -36,18 +36,18 @@ const ReplacementMap& emptySpaceReplacement() { struct StreamInfoImpl : public StreamInfo { StreamInfoImpl(TimeSource& time_source, - const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider, + const Network::SocketAddressProviderSharedPtr& downstream_address_provider, FilterState::LifeSpan life_span = FilterState::LifeSpan::FilterChain) : StreamInfoImpl(absl::nullopt, time_source, downstream_address_provider, std::make_shared(life_span)) {} StreamInfoImpl(Http::Protocol protocol, TimeSource& time_source, - const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider) + const Network::SocketAddressProviderSharedPtr& downstream_address_provider) : StreamInfoImpl(protocol, time_source, downstream_address_provider, std::make_shared(FilterState::LifeSpan::FilterChain)) {} StreamInfoImpl(Http::Protocol protocol, TimeSource& time_source, - const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider, + const Network::SocketAddressProviderSharedPtr& downstream_address_provider, FilterStateSharedPtr parent_filter_state, FilterState::LifeSpan life_span) : StreamInfoImpl( protocol, time_source, downstream_address_provider, @@ -193,7 +193,7 @@ struct StreamInfoImpl : public StreamInfo { void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } - const Network::SocketAddressProviderGetters& downstreamAddressProvider() const override { + const Network::SocketAddressProvider& downstreamAddressProvider() const override { return *downstream_address_provider_; } @@ -303,14 +303,14 @@ struct StreamInfoImpl : public StreamInfo { std::string route_name_; private: - static Network::SocketAddressProviderGettersSharedPtr emptyDownstreamAddressProvider() { + static Network::SocketAddressProviderSharedPtr emptyDownstreamAddressProvider() { MUTABLE_CONSTRUCT_ON_FIRST_USE( - Network::SocketAddressProviderGettersSharedPtr, - std::make_shared(nullptr, nullptr)); + Network::SocketAddressProviderSharedPtr, + std::make_shared(nullptr, nullptr)); } StreamInfoImpl(absl::optional protocol, TimeSource& time_source, - const Network::SocketAddressProviderGettersSharedPtr& downstream_address_provider, + const Network::SocketAddressProviderSharedPtr& downstream_address_provider, FilterStateSharedPtr filter_state) : time_source_(time_source), start_time_(time_source.systemTime()), start_time_monotonic_(time_source.monotonicTime()), protocol_(protocol), @@ -323,7 +323,7 @@ struct StreamInfoImpl : public StreamInfo { uint64_t bytes_received_{}; uint64_t bytes_sent_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; - const Network::SocketAddressProviderGettersSharedPtr downstream_address_provider_; + const Network::SocketAddressProviderSharedPtr downstream_address_provider_; Ssl::ConnectionInfoConstSharedPtr downstream_ssl_info_; Ssl::ConnectionInfoConstSharedPtr upstream_ssl_info_; std::string requested_server_name_; diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index c5f2f0adb9b0..65c97b032cb9 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -216,7 +216,7 @@ HttpHealthCheckerImpl::HttpActiveHealthCheckSession::HttpActiveHealthCheckSessio : ActiveHealthCheckSession(parent, host), parent_(parent), hostname_(getHostname(host, parent_.host_value_, parent_.cluster_.info())), protocol_(codecClientTypeToProtocol(parent_.codec_client_type_)), - local_address_provider_(std::make_shared( + local_address_provider_(std::make_shared( Network::Utility::getCanonicalIpv4LoopbackAddress(), Network::Utility::getCanonicalIpv4LoopbackAddress())) {} diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index f9a8357318f6..8066cc9e9b8f 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -125,7 +125,7 @@ class HttpHealthCheckerImpl : public HealthCheckerImplBase { Http::ResponseHeaderMapPtr response_headers_; const std::string& hostname_; const Http::Protocol protocol_; - Network::SocketAddressProviderGettersSharedPtr local_address_provider_; + Network::SocketAddressProviderSharedPtr local_address_provider_; bool expect_reset_{}; }; diff --git a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h index 202d0c28b393..7cd66c14d22c 100644 --- a/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h +++ b/source/extensions/quic_listeners/quiche/quic_filter_manager_connection_impl.h @@ -45,10 +45,10 @@ class QuicFilterManagerConnectionImpl : public Network::ConnectionImplBase { void readDisable(bool /*disable*/) override { NOT_REACHED_GCOVR_EXCL_LINE; } void detectEarlyCloseWhenReadDisabled(bool /*value*/) override { NOT_REACHED_GCOVR_EXCL_LINE; } bool readEnabled() const override { return true; } - const Network::SocketAddressProvider& addressProvider() const override { + const Network::SocketAddressSetter& addressProvider() const override { return quic_connection_->connectionSocket()->addressProvider(); } - Network::SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + Network::SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return quic_connection_->connectionSocket()->addressProviderSharedPtr(); } absl::optional diff --git a/source/server/api_listener_impl.h b/source/server/api_listener_impl.h index 7e2864111a97..30b390532180 100644 --- a/source/server/api_listener_impl.h +++ b/source/server/api_listener_impl.h @@ -74,7 +74,7 @@ class ApiListenerImplBase : public ApiListener, class SyntheticConnection : public Network::Connection { public: SyntheticConnection(SyntheticReadCallbacks& parent) - : parent_(parent), address_provider_(std::make_shared( + : parent_(parent), address_provider_(std::make_shared( parent.parent_.address_, parent.parent_.address_)), stream_info_(parent_.parent_.factory_context_.timeSource(), address_provider_), options_(std::make_shared>()) {} @@ -115,10 +115,10 @@ class ApiListenerImplBase : public ApiListener, void readDisable(bool) override {} void detectEarlyCloseWhenReadDisabled(bool) override { NOT_IMPLEMENTED_GCOVR_EXCL_LINE; } bool readEnabled() const override { return true; } - const Network::SocketAddressProvider& addressProvider() const override { + const Network::SocketAddressSetter& addressProvider() const override { return *address_provider_; } - Network::SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + Network::SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return address_provider_; } absl::optional @@ -145,7 +145,7 @@ class ApiListenerImplBase : public ApiListener, absl::optional lastRoundTripTime() const override { return {}; }; SyntheticReadCallbacks& parent_; - Network::SocketAddressProviderSharedPtr address_provider_; + Network::SocketAddressSetterSharedPtr address_provider_; StreamInfo::StreamInfoImpl stream_info_; Network::ConnectionSocket::OptionsSharedPtr options_; std::list callbacks_; diff --git a/test/common/grpc/async_client_impl_test.cc b/test/common/grpc/async_client_impl_test.cc index 882cc2598047..a2ef2f7a3420 100644 --- a/test/common/grpc/async_client_impl_test.cc +++ b/test/common/grpc/async_client_impl_test.cc @@ -129,7 +129,7 @@ TEST_F(EnvoyAsyncClientImplTest, MetadataIsInitialized) { .WillOnce(Invoke([&http_callbacks](Http::HeaderMap&, bool) { http_callbacks->onReset(); })); // Prepare the parent context of this call. - auto address_provider = std::make_shared( + auto address_provider = std::make_shared( std::make_shared(expected_downstream_local_address), nullptr); StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem(), address_provider}; Http::AsyncClient::ParentContext parent_context{&stream_info}; diff --git a/test/common/grpc/google_async_client_impl_test.cc b/test/common/grpc/google_async_client_impl_test.cc index 9a540c6badc2..c54e2d2aea5b 100644 --- a/test/common/grpc/google_async_client_impl_test.cc +++ b/test/common/grpc/google_async_client_impl_test.cc @@ -121,7 +121,7 @@ TEST_F(EnvoyGoogleAsyncClientImplTest, MetadataIsInitialized) { EXPECT_CALL(grpc_callbacks, onRemoteClose(Status::WellKnownGrpcStatus::Unavailable, "")); // Prepare the parent context of this call. - auto address_provider = std::make_shared( + auto address_provider = std::make_shared( std::make_shared(expected_downstream_local_address), nullptr); StreamInfo::StreamInfoImpl stream_info{test_time_.timeSystem(), address_provider}; Http::AsyncClient::ParentContext parent_context{&stream_info}; diff --git a/test/common/stream_info/test_util.h b/test/common/stream_info/test_util.h index 88c73b8dd90d..4db468bf4ca0 100644 --- a/test/common/stream_info/test_util.h +++ b/test/common/stream_info/test_util.h @@ -75,7 +75,7 @@ class TestStreamInfo : public StreamInfo::StreamInfo { } bool healthCheck() const override { return health_check_request_; } void healthCheck(bool is_health_check) override { health_check_request_ = is_health_check; } - const Network::SocketAddressProvider& downstreamAddressProvider() const override { + const Network::SocketAddressSetter& downstreamAddressProvider() const override { return *downstream_address_provider_; } void @@ -241,8 +241,8 @@ class TestStreamInfo : public StreamInfo::StreamInfo { bool health_check_request_{}; std::string route_name_; Network::Address::InstanceConstSharedPtr upstream_local_address_; - Network::SocketAddressProviderSharedPtr downstream_address_provider_{ - std::make_shared(nullptr, nullptr)}; + Network::SocketAddressSetterSharedPtr downstream_address_provider_{ + std::make_shared(nullptr, nullptr)}; Ssl::ConnectionInfoConstSharedPtr downstream_connection_info_; Ssl::ConnectionInfoConstSharedPtr upstream_connection_info_; const Router::RouteEntry* route_entry_{}; diff --git a/test/fuzz/utility.h b/test/fuzz/utility.h index 4962fe2d782a..cfa95039e114 100644 --- a/test/fuzz/utility.h +++ b/test/fuzz/utility.h @@ -167,7 +167,7 @@ inline std::unique_ptr fromStreamInfo(const test::fuzz::StreamIn : Network::Utility::resolveUrl("tcp://10.0.0.1:10000"); test_stream_info->upstream_local_address_ = upstream_local_address; test_stream_info->downstream_address_provider_ = - std::make_shared(address, address); + std::make_shared(address, address); auto connection_info = std::make_shared>(); ON_CALL(*connection_info, subjectPeerCertificate()) .WillByDefault(testing::ReturnRef(TestSubjectPeer)); diff --git a/test/mocks/network/connection.h b/test/mocks/network/connection.h index a3ea7a83a039..b0b8486fb0ec 100644 --- a/test/mocks/network/connection.h +++ b/test/mocks/network/connection.h @@ -64,8 +64,8 @@ class MockConnectionBase { MOCK_METHOD(void, readDisable, (bool disable)); \ MOCK_METHOD(void, detectEarlyCloseWhenReadDisabled, (bool)); \ MOCK_METHOD(bool, readEnabled, (), (const)); \ - MOCK_METHOD(const SocketAddressProviderGetters&, addressProvider, (), (const)); \ - MOCK_METHOD(SocketAddressProviderGettersSharedPtr, addressProviderSharedPtr, (), (const)); \ + MOCK_METHOD(const SocketAddressProvider&, addressProvider, (), (const)); \ + MOCK_METHOD(SocketAddressProviderSharedPtr, addressProviderSharedPtr, (), (const)); \ MOCK_METHOD(absl::optional, \ unixSocketPeerCredentials, (), (const)); \ MOCK_METHOD(void, setConnectionStats, (const ConnectionStats& stats)); \ diff --git a/test/mocks/network/mocks.cc b/test/mocks/network/mocks.cc index 2dc630226a9c..0c4170cde561 100644 --- a/test/mocks/network/mocks.cc +++ b/test/mocks/network/mocks.cc @@ -132,7 +132,7 @@ MockFilterChainFactory::~MockFilterChainFactory() = default; MockListenSocket::MockListenSocket() : io_handle_(std::make_unique()), - address_provider_(std::make_shared( + address_provider_(std::make_shared( std::make_shared(80), nullptr)) { ON_CALL(*this, options()).WillByDefault(ReturnRef(options_)); ON_CALL(*this, ioHandle()).WillByDefault(ReturnRef(*io_handle_)); @@ -153,9 +153,9 @@ MockSocketOption::~MockSocketOption() = default; MockConnectionSocket::MockConnectionSocket() : io_handle_(std::make_unique()), - address_provider_(std::make_shared( - std::make_shared(80), - std::make_shared(80))) { + address_provider_( + std::make_shared(std::make_shared(80), + std::make_shared(80))) { ON_CALL(*this, ioHandle()).WillByDefault(ReturnRef(*io_handle_)); ON_CALL(testing::Const(*this), ioHandle()).WillByDefault(ReturnRef(*io_handle_)); ON_CALL(*this, ipVersion()) diff --git a/test/mocks/network/mocks.h b/test/mocks/network/mocks.h index 95c973b4a6f3..c6e949687972 100644 --- a/test/mocks/network/mocks.h +++ b/test/mocks/network/mocks.h @@ -223,11 +223,9 @@ class MockListenSocket : public Socket { void addOption(const Socket::OptionConstSharedPtr& option) override { addOption_(option); } void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } - SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProviderGetters& addressProvider() const override { - return *address_provider_; - } - SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + SocketAddressSetter& addressProvider() override { return *address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return address_provider_; } MOCK_METHOD(IoHandle&, ioHandle, ()); @@ -252,7 +250,7 @@ class MockListenSocket : public Socket { MOCK_METHOD(Api::SysCallIntResult, setBlockingForTest, (bool)); IoHandlePtr io_handle_; - Network::SocketAddressProviderSharedPtr address_provider_; + Network::SocketAddressSetterSharedPtr address_provider_; OptionsSharedPtr options_; bool socket_is_open_ = true; }; @@ -277,11 +275,9 @@ class MockConnectionSocket : public ConnectionSocket { void addOption(const Socket::OptionConstSharedPtr& option) override { addOption_(option); } void addOptions(const Socket::OptionsSharedPtr& options) override { addOptions_(options); } - SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProviderGetters& addressProvider() const override { - return *address_provider_; - } - SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + SocketAddressSetter& addressProvider() override { return *address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return address_provider_; } MOCK_METHOD(void, setDetectedTransportProtocol, (absl::string_view)); @@ -313,7 +309,7 @@ class MockConnectionSocket : public ConnectionSocket { MOCK_METHOD(absl::optional, lastRoundTripTime, ()); IoHandlePtr io_handle_; - Network::SocketAddressProviderSharedPtr address_provider_; + Network::SocketAddressSetterSharedPtr address_provider_; bool is_closed_; }; diff --git a/test/mocks/network/socket.h b/test/mocks/network/socket.h index 7d13d5651e2d..6c62ce040573 100644 --- a/test/mocks/network/socket.h +++ b/test/mocks/network/socket.h @@ -14,11 +14,9 @@ class MockSocket : public Socket { MockSocket(); ~MockSocket() override; - SocketAddressProvider& addressProvider() override { return *address_provider_; } - const SocketAddressProviderGetters& addressProvider() const override { - return *address_provider_; - } - SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + SocketAddressSetter& addressProvider() override { return *address_provider_; } + const SocketAddressProvider& addressProvider() const override { return *address_provider_; } + SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return address_provider_; } IoHandle& ioHandle() override; @@ -43,7 +41,7 @@ class MockSocket : public Socket { MOCK_METHOD(void, addOptions, (const Socket::OptionsSharedPtr&), (override)); const std::unique_ptr io_handle_; - Network::SocketAddressProviderSharedPtr address_provider_; + Network::SocketAddressSetterSharedPtr address_provider_; }; } // namespace Network diff --git a/test/mocks/stream_info/mocks.cc b/test/mocks/stream_info/mocks.cc index b7b235d7563c..45abe90b33e8 100644 --- a/test/mocks/stream_info/mocks.cc +++ b/test/mocks/stream_info/mocks.cc @@ -18,7 +18,7 @@ namespace StreamInfo { MockStreamInfo::MockStreamInfo() : start_time_(ts_.systemTime()), filter_state_(std::make_shared(FilterState::LifeSpan::FilterChain)), - downstream_address_provider_(std::make_shared( + downstream_address_provider_(std::make_shared( std::make_shared("127.0.0.2"), std::make_shared("127.0.0.1"))) { ON_CALL(*this, setResponseFlag(_)).WillByDefault(Invoke([this](ResponseFlag response_flag) { diff --git a/test/mocks/stream_info/mocks.h b/test/mocks/stream_info/mocks.h index 21f63093ee33..fde8a86e31f0 100644 --- a/test/mocks/stream_info/mocks.h +++ b/test/mocks/stream_info/mocks.h @@ -65,7 +65,7 @@ class MockStreamInfo : public StreamInfo { MOCK_METHOD(const Network::Address::InstanceConstSharedPtr&, upstreamLocalAddress, (), (const)); MOCK_METHOD(bool, healthCheck, (), (const)); MOCK_METHOD(void, healthCheck, (bool is_health_check)); - MOCK_METHOD(const Network::SocketAddressProviderGetters&, downstreamAddressProvider, (), (const)); + MOCK_METHOD(const Network::SocketAddressProvider&, downstreamAddressProvider, (), (const)); MOCK_METHOD(void, setDownstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); MOCK_METHOD(Ssl::ConnectionInfoConstSharedPtr, downstreamSslConnection, (), (const)); MOCK_METHOD(void, setUpstreamSslConnection, (const Ssl::ConnectionInfoConstSharedPtr&)); @@ -119,7 +119,7 @@ class MockStreamInfo : public StreamInfo { uint64_t bytes_received_{}; uint64_t bytes_sent_{}; Network::Address::InstanceConstSharedPtr upstream_local_address_; - std::shared_ptr downstream_address_provider_; + std::shared_ptr downstream_address_provider_; Ssl::ConnectionInfoConstSharedPtr downstream_connection_info_; Ssl::ConnectionInfoConstSharedPtr upstream_connection_info_; std::string requested_server_name_; diff --git a/test/server/filter_chain_benchmark_test.cc b/test/server/filter_chain_benchmark_test.cc index 78190cf44c53..2277ac18201c 100644 --- a/test/server/filter_chain_benchmark_test.cc +++ b/test/server/filter_chain_benchmark_test.cc @@ -41,7 +41,7 @@ class MockFilterChainFactoryBuilder : public FilterChainFactoryBuilder { class MockConnectionSocket : public Network::ConnectionSocket { public: MockConnectionSocket() - : address_provider_(std::make_shared(nullptr, nullptr)) {} + : address_provider_(std::make_shared(nullptr, nullptr)) {} static std::unique_ptr createMockConnectionSocket(uint16_t destination_port, const std::string& destination_address, @@ -75,11 +75,11 @@ class MockConnectionSocket : public Network::ConnectionSocket { const std::vector& requestedApplicationProtocols() const override { return application_protocols_; } - Network::SocketAddressProvider& addressProvider() override { return *address_provider_; } - const Network::SocketAddressProvider& addressProvider() const override { + Network::SocketAddressSetter& addressProvider() override { return *address_provider_; } + const Network::SocketAddressSetter& addressProvider() const override { return *address_provider_; } - Network::SocketAddressProviderGettersSharedPtr addressProviderSharedPtr() const override { + Network::SocketAddressProviderSharedPtr addressProviderSharedPtr() const override { return address_provider_; } @@ -121,7 +121,7 @@ class MockConnectionSocket : public Network::ConnectionSocket { private: Network::IoHandlePtr io_handle_; OptionsSharedPtr options_; - Network::SocketAddressProviderSharedPtr address_provider_; + Network::SocketAddressSetterSharedPtr address_provider_; std::string server_name_; std::string transport_protocol_; std::vector application_protocols_; diff --git a/test/tools/router_check/router.cc b/test/tools/router_check/router.cc index 19b2a92f33e1..d468b338805e 100644 --- a/test/tools/router_check/router.cc +++ b/test/tools/router_check/router.cc @@ -221,7 +221,7 @@ bool RouterCheckTool::compareEntries(const std::string& expected_routes) { validation_config.tests()) { active_runtime_ = check_config.input().runtime(); headers_finalized_ = false; - auto address_provider = std::make_shared( + auto address_provider = std::make_shared( nullptr, Network::Utility::getCanonicalIpv4LoopbackAddress()); Envoy::StreamInfo::StreamInfoImpl stream_info(Envoy::Http::Protocol::Http11, factory_context_->dispatcher().timeSource(), From 0ed22d86f6a26a33500619026d91a17227183d65 Mon Sep 17 00:00:00 2001 From: Matt Klein Date: Wed, 6 Jan 2021 23:49:14 +0000 Subject: [PATCH 8/8] fix Signed-off-by: Matt Klein --- source/common/network/BUILD | 2 +- source/common/network/listen_socket_impl.h | 8 +++----- source/common/network/socket_impl.h | 11 ++++++++++- test/common/network/connection_impl_test.cc | 13 ++++++++----- 4 files changed, 22 insertions(+), 12 deletions(-) diff --git a/source/common/network/BUILD b/source/common/network/BUILD index f9c4266e8ddd..a78cbd427637 100644 --- a/source/common/network/BUILD +++ b/source/common/network/BUILD @@ -234,6 +234,7 @@ envoy_cc_library( "//include/envoy/network:socket_interface_interface", "//source/common/api:os_sys_calls_lib", "//source/common/common:assert_lib", + "//source/common/common:dump_state_utils", "//source/common/common:utility_lib", ], ) @@ -248,7 +249,6 @@ envoy_cc_library( "//include/envoy/network:exception_interface", "//include/envoy/network:listen_socket_interface", "//source/common/common:assert_lib", - "//source/common/common:dump_state_utils", "@envoy_api//envoy/config/core/v3:pkg_cc_proto", ], ) diff --git a/source/common/network/listen_socket_impl.h b/source/common/network/listen_socket_impl.h index b29c7f02df9f..0673f50788e3 100644 --- a/source/common/network/listen_socket_impl.h +++ b/source/common/network/listen_socket_impl.h @@ -126,11 +126,9 @@ class ConnectionSocketImpl : public SocketImpl, public ConnectionSocket { void dumpState(std::ostream& os, int indent_level) const override { const char* spaces = spacesForLevel(indent_level); - os << spaces << "ListenSocketImpl " << this - << DUMP_NULLABLE_MEMBER(remote_address_, remote_address_->asStringView()) - << DUMP_NULLABLE_MEMBER(direct_remote_address_, direct_remote_address_->asStringView()) - << DUMP_NULLABLE_MEMBER(local_address_, local_address_->asStringView()) - << DUMP_MEMBER(transport_protocol_) << DUMP_MEMBER(server_name_) << "\n"; + os << spaces << "ListenSocketImpl " << this << DUMP_MEMBER(transport_protocol_) + << DUMP_MEMBER(server_name_) << "\n"; + DUMP_DETAILS(address_provider_); } protected: diff --git a/source/common/network/socket_impl.h b/source/common/network/socket_impl.h index 21c94310f8e4..082c7d793248 100644 --- a/source/common/network/socket_impl.h +++ b/source/common/network/socket_impl.h @@ -3,6 +3,7 @@ #include "envoy/network/socket.h" #include "common/common/assert.h" +#include "common/common/dump_state_utils.h" namespace Envoy { namespace Network { @@ -18,6 +19,14 @@ class SocketAddressSetterImpl : public SocketAddressSetter { direct_remote_address_ = direct_remote_address; } + void dumpState(std::ostream& os, int indent_level) const { + const char* spaces = spacesForLevel(indent_level); + os << spaces << "SocketAddressSetterImpl " << this + << DUMP_NULLABLE_MEMBER(remote_address_, remote_address_->asStringView()) + << DUMP_NULLABLE_MEMBER(direct_remote_address_, direct_remote_address_->asStringView()) + << DUMP_NULLABLE_MEMBER(local_address_, local_address_->asStringView()) << "\n"; + } + // SocketAddressSetter const Address::InstanceConstSharedPtr& localAddress() const override { return local_address_; } void setLocalAddress(const Address::InstanceConstSharedPtr& local_address) override { @@ -101,7 +110,7 @@ class SocketImpl : public virtual Socket { const Address::InstanceConstSharedPtr& remote_address); const IoHandlePtr io_handle_; - const SocketAddressSetterSharedPtr address_provider_; + const std::shared_ptr address_provider_; OptionsSharedPtr options_; Socket::Type sock_type_; Address::Type addr_type_; diff --git a/test/common/network/connection_impl_test.cc b/test/common/network/connection_impl_test.cc index ac0433fec1e6..63361228acbe 100644 --- a/test/common/network/connection_impl_test.cc +++ b/test/common/network/connection_impl_test.cc @@ -1886,18 +1886,21 @@ TEST_P(ConnectionImplTest, NetworkSocketDumpsWithoutAllocatingMemory) { EXPECT_EQ(memory_test.consumedBytes(), 0); // Check socket dump - EXPECT_THAT(ostream.contents(), HasSubstr("ListenSocketImpl")); + const auto contents = ostream.contents(); + EXPECT_THAT(contents, HasSubstr("ListenSocketImpl")); + EXPECT_THAT(contents, HasSubstr("transport_protocol_: , server_name_: envoyproxy.io")); + EXPECT_THAT(contents, HasSubstr("SocketAddressSetterImpl")); if (GetParam() == Network::Address::IpVersion::v4) { EXPECT_THAT( - ostream.contents(), + contents, HasSubstr( "remote_address_: 1.1.1.1:80, direct_remote_address_: 1.1.1.1:80, local_address_: " - "1.2.3.4:56789, transport_protocol_: , server_name_: envoyproxy.io")); + "1.2.3.4:56789")); } else { EXPECT_THAT( - ostream.contents(), + contents, HasSubstr("remote_address_: [::1]:80, direct_remote_address_: [::1]:80, local_address_: " - "[::1:2:3:4]:56789, transport_protocol_: , server_name_: envoyproxy.io")); + "[::1:2:3:4]:56789")); } }