[PATCH v2 00/22] More flow table preliminaries: address handling improvements
Here's another batch of cleanups and tweaks in preparation for the flow table. This set focuses on improved helpers for handling addresses, particularly in the TCP splice path. Changes since v1: * Rebased, and reordered in a way I hope is clearer * Add patch to rename port_fwd.[ch] * Added doc comments to clarify flow life cycle * Added uniform logging of flow start / end to match that lifecycle * union inany_addr typed special address constants * inany based tests for unspecified and multicast addresses, as well as loopback * Dropped patch allowing NULL parameter to inany_from_af(), turned out not to be that useful * Dropped sockaddr_any_init function, turned out not to be very useful in that form * Added patch enforcing no loopback addresses on tap interface * Added logic to sanity check TCP endpoint addresses * Moved socket creation into tcp_splice_connect() * Moved epoll ref parsing into tcp_listen_handler() * Allowed IN4_IS_*() helpers to work on void * addresses David Gibson (22): treewide: Use sa_family_t for address family variables inany: Helper to test for various address types inany: Add inany_ntop() helper inany: Provide more conveniently typed constants for special addresses inany: Introduce union sockaddr_inany util: Allow IN4_IS_* macros to operate on untyped addresses tcp, udp: Don't precompute port remappings in epoll references flow: Add helper to determine a flow's protocol tcp_splice: Simplify clean up logic tcp_splice: Don't use flow_trace() before setting flow type flow: Clarify flow entry life cycle, introduce uniform logging tcp, tcp_splice: Helpers for getting sockets from the pools tcp_splice: More specific variable names in new splice path tcp_splice: Merge tcp_splice_new() into its caller tcp_splice: Make tcp_splice_connect() create its own sockets tcp_splice: Improve error reporting on connect path tcp_splice: Improve logic deciding when to splice tcp, tcp_splice: Parse listening socket epoll ref in tcp_listen_handler() tcp: Validate TCP endpoint addresses tap: Disallow loopback addresses on tap interface port_fwd: Fix copypasta error in port_fwd_scan_udp() comments fwd: Rename port_fwd.[ch] and their contents Makefile | 14 +-- conf.c | 8 +- flow.c | 83 +++++++++++++++++- flow.h | 9 ++ port_fwd.c => fwd.c | 32 +++---- port_fwd.h => fwd.h | 24 +++--- icmp.c | 24 ++---- icmp.h | 4 +- inany.c | 50 +++++++++++ inany.h | 99 ++++++++++++++++++--- passt.h | 2 +- tap.c | 19 ++++ tcp.c | 158 ++++++++++++++++++++++++--------- tcp.h | 8 +- tcp_conn.h | 4 +- tcp_splice.c | 206 +++++++++++++++++++++++++------------------- tcp_splice.h | 7 +- udp.c | 34 ++++---- udp.h | 12 +-- util.c | 2 +- util.h | 10 +-- 21 files changed, 569 insertions(+), 240 deletions(-) rename port_fwd.c => fwd.c (83%) rename port_fwd.h => fwd.h (62%) create mode 100644 inany.c -- 2.43.0
Sometimes we use sa_family_t for variables and parameters containing a
socket address family, other times we use a plain int. Since sa_family_t
is what's actually used in struct sockaddr and friends, standardise on
that.
Signed-off-by: David Gibson
Add helpers to determine if an inany is loopback, unspecified or multicast,
regardless of whether it's a "true" IPv6 address or an IPv4 address
represented as v4-mapped.
Sometimes we need to know if an inany is a loopback address, unspecified or
some other particular kind of address, but we don't really care if it is
IPv4.
Use the loopback helper to simplify tcp_splice_conn_from_sock() slightly.
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:14 +1100
David Gibson
Add helpers to determine if an inany is loopback, unspecified or multicast, regardless of whether it's a "true" IPv6 address or an IPv4 address represented as v4-mapped. Sometimes we need to know if an inany is a loopback address, unspecified or some other particular kind of address, but we don't really care if it is IPv4.
Use the loopback helper to simplify tcp_splice_conn_from_sock() slightly.
Signed-off-by: David Gibson
--- inany.h | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ tcp_splice.c | 15 +++------------ 2 files changed, 53 insertions(+), 12 deletions(-) diff --git a/inany.h b/inany.h index fe652ff7..2058f145 100644 --- a/inany.h +++ b/inany.h @@ -55,6 +55,56 @@ static inline bool inany_equals(const union inany_addr *a, return IN6_ARE_ADDR_EQUAL(&a->a6, &b->a6); }
+/** inany_is_loopback - Check if address is loopback
Nit: inany_is_loopback() (and four occurrences below).
+ * @a: IPv[46] address + * + * Return: true if @a is either ::1 or in 127.0.0.1/8 + */ +static inline bool inany_is_loopback(const union inany_addr *a) +{ + const struct in_addr *v4 = inany_v4(a); + + return IN6_IS_ADDR_LOOPBACK(&a->a6) || (v4 && IN4_IS_ADDR_LOOPBACK(v4)); +} + +/** inany_is_unspecified - Check if address is unspecified + * @a: IPv[46] address + * + * Return: true if @a is either :: or 0.0.0.0 + */ +static inline bool inany_is_unspecified(const union inany_addr *a) +{ + const struct in_addr *v4 = inany_v4(a); + + return IN6_IS_ADDR_UNSPECIFIED(&a->a6) || + (v4 && IN4_IS_ADDR_UNSPECIFIED(v4)); +} + +/** inany_is_multicast - Check if address is multicast or broadcast + * @a: IPv[46] address + * + * Return: true if @a is IPv6 multicast or IPv4 multicast or broadcast + */ +static inline bool inany_is_multicast(const union inany_addr *a) +{ + const struct in_addr *v4 = inany_v4(a); + + return IN6_IS_ADDR_MULTICAST(&a->a6) || + (v4 && (IN4_IS_ADDR_MULTICAST(v4) || + IN4_IS_ADDR_BROADCAST(v4))); +} + +/** inany_is_unicast - Check if address is specified and unicast + * @a: IPv[46] address + * + * Return: true if @a is specified and a unicast address + */ +/* cppcheck-suppress unusedFunction */ +static inline bool inany_is_unicast(const union inany_addr *a) +{ + return !inany_is_unspecified(a) && !inany_is_multicast(a); +} + /** inany_from_af - Set IPv[46] address from IPv4 or IPv6 address * @aa: Pointer to store IPv[46] address * @af: Address family of @addr diff --git a/tcp_splice.c b/tcp_splice.c index cc9745e8..4ecc178b 100644 --- a/tcp_splice.c +++ b/tcp_splice.c @@ -440,29 +440,20 @@ bool tcp_splice_conn_from_sock(const struct ctx *c, struct tcp_splice_conn *conn, int s, const struct sockaddr *sa) { - const struct in_addr *a4; union inany_addr aany; in_port_t port;
ASSERT(c->mode == MODE_PASTA);
inany_from_sockaddr(&aany, &port, sa); - a4 = inany_v4(&aany); - - if (a4) { - if (!IN4_IS_ADDR_LOOPBACK(a4)) - return false; - conn->flags = 0; - } else { - if (!IN6_IS_ADDR_LOOPBACK(&aany.a6)) - return false; - conn->flags = SPLICE_V6; - } + if (!inany_is_loopback(&aany)) + return false;
if (setsockopt(s, SOL_TCP, TCP_QUICKACK, &((int){ 1 }), sizeof(int))) flow_trace(conn, "failed to set TCP_QUICKACK on %i", s);
conn->f.type = FLOW_TCP_SPLICE; + conn->flags = inany_v4(&aany) ? 0 : SPLICE_V6; conn->s[0] = s;
if (tcp_splice_new(c, conn, ref.port, ref.pif))
On Sun, Feb 18, 2024 at 09:58:44PM +0100, Stefano Brivio wrote:
On Tue, 6 Feb 2024 12:17:14 +1100 David Gibson
wrote: Add helpers to determine if an inany is loopback, unspecified or multicast, regardless of whether it's a "true" IPv6 address or an IPv4 address represented as v4-mapped. Sometimes we need to know if an inany is a loopback address, unspecified or some other particular kind of address, but we don't really care if it is IPv4.
Use the loopback helper to simplify tcp_splice_conn_from_sock() slightly.
Signed-off-by: David Gibson
--- inany.h | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ tcp_splice.c | 15 +++------------ 2 files changed, 53 insertions(+), 12 deletions(-) diff --git a/inany.h b/inany.h index fe652ff7..2058f145 100644 --- a/inany.h +++ b/inany.h @@ -55,6 +55,56 @@ static inline bool inany_equals(const union inany_addr *a, return IN6_ARE_ADDR_EQUAL(&a->a6, &b->a6); }
+/** inany_is_loopback - Check if address is loopback
Nit: inany_is_loopback() (and four occurrences below).
Corrected, thanks. -- David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
Add this helper to format an inany into either IPv4 or IPv6 text format as
appropriate.
Signed-off-by: David Gibson
Our inany_addr type is used in some places to represent either IPv4 or
IPv6 addresses, and we plan to use it more widely. We don't yet
provide constants of this type for special addresses (loopback and
"any"). Add some of these, both the IPv4 and IPv6 variants of those
addresses, but typed as union inany_addr.
To avoid actually adding more things to .data we can use some macros and
casting to overlay the IPv6 versions of these with the standard library's
in6addr_loopback and in6addr_any. For the IPv4 versions we need to create
new constant globals.
For complicated historical reasons, the standard library doesn't provide
constants for IPv4 loopback and any addresses as struct in_addr. It just
has macros of type in_addr_t == uint32_t, which has confusing semantics
w.r.t. endianness. We can use some more macros to address this lack,
using macros to effectively create these IPv4 constants as pieces of the
inany constants above.
We use this last to avoid some awkward temporary variables just used to
get an address of an IPv4 loopback address.
Signed-off-by: David Gibson
There are a number of places where we want to handle either a sockaddr_in
or a sockaddr_in6. In some of those we use a void *, which works ok and
matches some standard library interfaces, but doesn't give a signature
level hint that we're dealing with only sockaddr_in or sockaddr_in6, not
(say) sockaddr_un or another type of socket address. Other places we use a
sockaddr_storage, which also works, but has the same problem in addition to
allocating more on the stack than we need to.
Introduce union sockaddr_inany to explictly handle this case: it has
variants for sockaddr_in and sockaddr_in6. Use it in a number of
places where it's easy to do so.
Signed-off-by: David Gibson
The IN4_IS_*() macros expect a pointer to a struct in_addr. That makes
sense, but sometimes we have an IPv4 address as a void * pointer or union
type which makes these less convenient. More importantly, this doesn't
match the behaviour of the standard library's IN6_IS_*() macros on which
they're modelled, nor our own IN4_ARE_ADDR_EQUAL().
Signed-off-by: David Gibson
The epoll references for both TCP listening sockets and UDP sockets
includes a port number. This gives the destination port that traffic to
that socket will be sent to on the other side. That will usually be the
same as the socket's bound port, but might not if the -t, -u, -T or -U
options are given with different original and forwarded port numbers.
As we move towards a more flexible forwarding model for passt, it's going
to become possible for that destination port to vary depending on more
things (for example the source or destination address). So, it will no
longer make sense to have a fixed value for a listening socket.
Change to simpler semantics where this field in the reference gives the
bound port of the socket. We apply the translations to the correct
destination port later on, when we're actually forwarding.
Signed-off-by: David Gibson
Each flow already has a type field. This implies the protocol the flow
represents, but also has more information: we have two ways to represent
TCP flows, "tap" and "spliced". In order to generalise some of the flow
mechanics, we'll need to determine a flow's protocol in terms of the IP
(L4) protocol number.
Introduce a constant table and helper macro to derive this from the flow
type.
Signed-off-by: David Gibson
Currently tcp_splice_flow_defer() contains specific logic to determine if
we're far enough initialised that we need to close pipes and/or sockets.
This is potentially fragile if we change something about the order in which
we do things. We can simplify this by initialising the pipe and socket
fields to -1 very early, then close()ing them if and only if they're non
negative.
This lets us remove a special case cleanup if our connect() fails. This
will already trigger a CLOSING event, and the socket fd in question is
populated in the connection structure. Thus we can let the new cleanup
logic handle it rather than requiring an explicit close().
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:21 +1100
David Gibson
Currently tcp_splice_flow_defer() contains specific logic to determine if we're far enough initialised that we need to close pipes and/or sockets. This is potentially fragile if we change something about the order in which we do things. We can simplify this by initialising the pipe and socket fields to -1 very early, then close()ing them if and only if they're non negative.
This lets us remove a special case cleanup if our connect() fails. This will already trigger a CLOSING event, and the socket fd in question is populated in the connection structure. Thus we can let the new cleanup logic handle it rather than requiring an explicit close().
Signed-off-by: David Gibson
--- tcp_splice.c | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/tcp_splice.c b/tcp_splice.c index 40ecb5d4..f0343eb5 100644 --- a/tcp_splice.c +++ b/tcp_splice.c @@ -246,16 +246,14 @@ bool tcp_splice_flow_defer(union flow *flow) return false;
for (side = 0; side < SIDES; side++) { - if (conn->events & SPLICE_ESTABLISHED) { - /* Flushing might need to block: don't recycle them. */ - if (conn->pipe[side][0] != -1) { - close(conn->pipe[side][0]); - close(conn->pipe[side][1]); - conn->pipe[side][0] = conn->pipe[side][1] = -1; - } + /* Flushing might need to block: don't recycle them. */ + if (conn->pipe[side][0] >= 0) { + close(conn->pipe[side][0]); + close(conn->pipe[side][1]); + conn->pipe[side][0] = conn->pipe[side][1] = -1; }
- if (side == 0 || conn->events & SPLICE_CONNECT) { + if (conn->s[side] >= 0) { close(conn->s[side]); conn->s[side] = -1; } @@ -284,8 +282,6 @@ static int tcp_splice_connect_finish(const struct ctx *c, int i = 0;
for (side = 0; side < SIDES; side++) { - conn->pipe[side][0] = conn->pipe[side][1] = -1; - for (; i < TCP_SPLICE_PIPE_POOL_SIZE; i++) { if (splice_pipe_pool[i][0] >= 0) { SWAP(conn->pipe[side][0], @@ -361,12 +357,8 @@ static int tcp_splice_connect(const struct ctx *c, struct tcp_splice_conn *conn, }
if (connect(conn->s[1], sa, sl)) { - if (errno != EINPROGRESS) { - int ret = -errno; - - close(sock_conn); - return ret; - } + if (errno != EINPROGRESS) + return -errno;
Nit: a newline here would be nice.
conn_event(c, conn, SPLICE_CONNECT); } else { conn_event(c, conn, SPLICE_ESTABLISHED); @@ -459,6 +451,9 @@ bool tcp_splice_conn_from_sock(const struct ctx *c, conn->f.type = FLOW_TCP_SPLICE; conn->flags = inany_v4(&aany) ? 0 : SPLICE_V6; conn->s[0] = s; + conn->s[1] = -1; + conn->pipe[0][0] = conn->pipe[0][1] = -1; + conn->pipe[1][0] = conn->pipe[1][1] = -1;
if (tcp_splice_new(c, conn, ref.port, ref.pif)) conn_flag(c, conn, CLOSING);
On Sun, Feb 18, 2024 at 09:59:37PM +0100, Stefano Brivio wrote:
On Tue, 6 Feb 2024 12:17:21 +1100 David Gibson
wrote: Currently tcp_splice_flow_defer() contains specific logic to determine if we're far enough initialised that we need to close pipes and/or sockets. This is potentially fragile if we change something about the order in which we do things. We can simplify this by initialising the pipe and socket fields to -1 very early, then close()ing them if and only if they're non negative.
This lets us remove a special case cleanup if our connect() fails. This will already trigger a CLOSING event, and the socket fd in question is populated in the connection structure. Thus we can let the new cleanup logic handle it rather than requiring an explicit close().
Signed-off-by: David Gibson
--- tcp_splice.c | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/tcp_splice.c b/tcp_splice.c index 40ecb5d4..f0343eb5 100644 --- a/tcp_splice.c +++ b/tcp_splice.c @@ -246,16 +246,14 @@ bool tcp_splice_flow_defer(union flow *flow) return false;
for (side = 0; side < SIDES; side++) { - if (conn->events & SPLICE_ESTABLISHED) { - /* Flushing might need to block: don't recycle them. */ - if (conn->pipe[side][0] != -1) { - close(conn->pipe[side][0]); - close(conn->pipe[side][1]); - conn->pipe[side][0] = conn->pipe[side][1] = -1; - } + /* Flushing might need to block: don't recycle them. */ + if (conn->pipe[side][0] >= 0) { + close(conn->pipe[side][0]); + close(conn->pipe[side][1]); + conn->pipe[side][0] = conn->pipe[side][1] = -1; }
- if (side == 0 || conn->events & SPLICE_CONNECT) { + if (conn->s[side] >= 0) { close(conn->s[side]); conn->s[side] = -1; } @@ -284,8 +282,6 @@ static int tcp_splice_connect_finish(const struct ctx *c, int i = 0;
for (side = 0; side < SIDES; side++) { - conn->pipe[side][0] = conn->pipe[side][1] = -1; - for (; i < TCP_SPLICE_PIPE_POOL_SIZE; i++) { if (splice_pipe_pool[i][0] >= 0) { SWAP(conn->pipe[side][0], @@ -361,12 +357,8 @@ static int tcp_splice_connect(const struct ctx *c, struct tcp_splice_conn *conn, }
if (connect(conn->s[1], sa, sl)) { - if (errno != EINPROGRESS) { - int ret = -errno; - - close(sock_conn); - return ret; - } + if (errno != EINPROGRESS) + return -errno;
Nit: a newline here would be nice.
Done, thanks. -- David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
In tcp_splice_conn_from_sock() we can call flow_trace() if there's an
error setting TCP_QUICKACK. However, we do so before we've set the flow
type in the flow entry. That means that flow_trace() will print nonsense
when it tries to print the flow type.
There's no reason the setsockopt() has to happen before initialising the
flow entry, so just move it after.
Signed-off-by: David Gibson
Our allocation scheme for flow entries means there are some non-obvious
constraints on when what things can be done with an entry. Add a big doc
comment explaining the life cycle.
In addition, make a FLOW_START() macro to mark one of the important
transitions. This encourages correct usage, by making it natural to only
access the flow type specific structure after calling it. It also logs
that a new flow has been created, which is useful for debugging.
We also add logging when a flow's lifecycle ends. This doesn't need a new
helper, because it can only happen either from flow_alloc_cancel() or from
the flow deferred handler.
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:23 +1100
David Gibson
Our allocation scheme for flow entries means there are some non-obvious constraints on when what things can be done with an entry. Add a big doc comment explaining the life cycle.
In addition, make a FLOW_START() macro to mark one of the important transitions. This encourages correct usage, by making it natural to only access the flow type specific structure after calling it. It also logs that a new flow has been created, which is useful for debugging.
We also add logging when a flow's lifecycle ends. This doesn't need a new helper, because it can only happen either from flow_alloc_cancel() or from the flow deferred handler.
Signed-off-by: David Gibson
--- flow.c | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++-- flow.h | 5 ++++ tcp.c | 15 +++++------ tcp_splice.c | 11 ++++---- tcp_splice.h | 5 ++-- 5 files changed, 94 insertions(+), 18 deletions(-) diff --git a/flow.c b/flow.c index beb9749c..a155b54b 100644 --- a/flow.c +++ b/flow.c @@ -34,6 +34,45 @@ static_assert(ARRAY_SIZE(flow_proto) == FLOW_NUM_TYPES,
/* Global Flow Table */
+/** + * DOC: Theory of Operation - flow entry life cycle + * + * An individual flow table entry moves through these logical states, usually in + * this order. + * + * FREE - Part of the general pool of free flow table entries + * Operations: + * - flow_alloc() finds an entry and moves it to ALLOC state + * + * ALLOC - A tentatively allocated entry + * Operations: + * - flow_alloc_cancel() returns the entry to FREE state + * - FLOW_START() set the entry's type and moves to START state + * Caveats: + * - It's not safe to write fields in the flow entry + * - It's not safe to allocate other entries with flow_alloc()
I'm not entirely sure what you mean here -- is this in the sense of s/other/further/ ?
+ * - It's not safe to return to the main epoll loop
..."before FLOW_START() is called on the entry"? -- Stefano
On Sun, Feb 18, 2024 at 10:00:04PM +0100, Stefano Brivio wrote:
On Tue, 6 Feb 2024 12:17:23 +1100 David Gibson
wrote: Our allocation scheme for flow entries means there are some non-obvious constraints on when what things can be done with an entry. Add a big doc comment explaining the life cycle.
In addition, make a FLOW_START() macro to mark one of the important transitions. This encourages correct usage, by making it natural to only access the flow type specific structure after calling it. It also logs that a new flow has been created, which is useful for debugging.
We also add logging when a flow's lifecycle ends. This doesn't need a new helper, because it can only happen either from flow_alloc_cancel() or from the flow deferred handler.
Signed-off-by: David Gibson
--- flow.c | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++-- flow.h | 5 ++++ tcp.c | 15 +++++------ tcp_splice.c | 11 ++++---- tcp_splice.h | 5 ++-- 5 files changed, 94 insertions(+), 18 deletions(-) diff --git a/flow.c b/flow.c index beb9749c..a155b54b 100644 --- a/flow.c +++ b/flow.c @@ -34,6 +34,45 @@ static_assert(ARRAY_SIZE(flow_proto) == FLOW_NUM_TYPES,
/* Global Flow Table */
+/** + * DOC: Theory of Operation - flow entry life cycle + * + * An individual flow table entry moves through these logical states, usually in + * this order. + * + * FREE - Part of the general pool of free flow table entries + * Operations: + * - flow_alloc() finds an entry and moves it to ALLOC state + * + * ALLOC - A tentatively allocated entry + * Operations: + * - flow_alloc_cancel() returns the entry to FREE state + * - FLOW_START() set the entry's type and moves to START state + * Caveats: + * - It's not safe to write fields in the flow entry + * - It's not safe to allocate other entries with flow_alloc()
I'm not entirely sure what you mean here -- is this in the sense of s/other/further/ ?
Yes. I've changed the word to "further", which I agree is clearer.
+ * - It's not safe to return to the main epoll loop
..."before FLOW_START() is called on the entry"?
Right, because FLOW_START() moves to START state, where returning to the epoll loop *is* allowed. I've added a note which I hope makes that clearer. -- David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
We maintain pools of ready-to-connect sockets in both the original and
(for pasta) guest namespace to reduce latency when starting new TCP
connections. If we exhaust those pools we have to take a higher
latency path to get a new socket.
Currently we open-code that fallback in the places we need it. To
improve clarity encapsulate that into helper functions.
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:24 +1100
David Gibson
We maintain pools of ready-to-connect sockets in both the original and (for pasta) guest namespace to reduce latency when starting new TCP connections. If we exhaust those pools we have to take a higher latency path to get a new socket.
Currently we open-code that fallback in the places we need it. To improve clarity encapsulate that into helper functions.
Signed-off-by: David Gibson
--- tcp.c | 29 ++++++++++++++++++++++++----- tcp_conn.h | 2 +- tcp_splice.c | 46 +++++++++++++++++++++++++--------------------- 3 files changed, 50 insertions(+), 27 deletions(-) diff --git a/tcp.c b/tcp.c index e15b932f..c06d1cc4 100644 --- a/tcp.c +++ b/tcp.c @@ -1792,7 +1792,7 @@ int tcp_conn_pool_sock(int pool[]) * * Return: socket number on success, negative code if socket creation failed */ -int tcp_conn_new_sock(const struct ctx *c, sa_family_t af) +static int tcp_conn_new_sock(const struct ctx *c, sa_family_t af) { int s;
@@ -1811,6 +1811,27 @@ int tcp_conn_new_sock(const struct ctx *c, sa_family_t af) return s; }
+/** + * tcp_conn_sock() - Obtain a connectable socket in the host/init namespace + * @c: Execution context + * @af: Address family (AF_INET or AF_INET6) + * + * Return: Socket fd on success, -errno on failure + */ +int tcp_conn_sock(const struct ctx *c, sa_family_t af) +{ + int *pool = af == AF_INET6 ? init_sock_pool6 : init_sock_pool4; + int s; + + if ((s = tcp_conn_pool_sock(pool)) >= 0) + return s; + + /* If the pool is empty we just open a new one without refilling the + * pool to keep latency down. + */ + return tcp_conn_new_sock(c, af); +} + /** * tcp_conn_tap_mss() - Get MSS value advertised by tap/guest * @conn: Connection pointer @@ -1909,7 +1930,6 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, const struct tcphdr *th, const char *opts, size_t optlen, const struct timespec *now) { - int *pool = af == AF_INET6 ? init_sock_pool6 : init_sock_pool4; struct sockaddr_in addr4 = { .sin_family = AF_INET, .sin_port = th->dest, @@ -1931,9 +1951,8 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, if (!(flow = flow_alloc())) return;
- if ((s = tcp_conn_pool_sock(pool)) < 0) - if ((s = tcp_conn_new_sock(c, af)) < 0) - goto cancel; + if ((s = tcp_conn_sock(c, af)) < 0) + goto cancel;
if (!c->no_map_gw) { if (af == AF_INET && IN4_ARE_ADDR_EQUAL(daddr, &c->ip4.gw)) diff --git a/tcp_conn.h b/tcp_conn.h index 20c7cb8b..e55edafe 100644 --- a/tcp_conn.h +++ b/tcp_conn.h @@ -159,7 +159,7 @@ bool tcp_flow_defer(union flow *flow); bool tcp_splice_flow_defer(union flow *flow); void tcp_splice_timer(const struct ctx *c, union flow *flow); int tcp_conn_pool_sock(int pool[]); -int tcp_conn_new_sock(const struct ctx *c, sa_family_t af); +int tcp_conn_sock(const struct ctx *c, sa_family_t af); void tcp_sock_refill_pool(const struct ctx *c, int pool[], sa_family_t af); void tcp_splice_refill(const struct ctx *c);
diff --git a/tcp_splice.c b/tcp_splice.c index 576fe9be..609f3242 100644 --- a/tcp_splice.c +++ b/tcp_splice.c @@ -90,7 +90,7 @@ static const char *tcp_splice_flag_str[] __attribute((__unused__)) = { };
/* Forward declaration */ -static int tcp_sock_refill_ns(void *arg); +static int tcp_conn_sock_ns(const struct ctx *c, sa_family_t af);
/** * tcp_splice_conn_epoll_events() - epoll events masks for given state @@ -380,36 +380,19 @@ static int tcp_splice_connect(const struct ctx *c, struct tcp_splice_conn *conn, static int tcp_splice_new(const struct ctx *c, struct tcp_splice_conn *conn, in_port_t port, uint8_t pif) { + sa_family_t af = CONN_V6(conn) ? AF_INET6 : AF_INET; int s = -1;
- /* If the pool is empty we take slightly different approaches - * for init or ns sockets. For init sockets we just open a - * new one without refilling the pool to keep latency down. - * For ns sockets, we're going to incur the latency of - * entering the ns anyway, so we might as well refill the - * pool. - */ if (pif == PIF_SPLICE) { - int *p = CONN_V6(conn) ? init_sock_pool6 : init_sock_pool4; - sa_family_t af = CONN_V6(conn) ? AF_INET6 : AF_INET; - port += c->tcp.fwd_out.delta[port];
- s = tcp_conn_pool_sock(p); - if (s < 0) - s = tcp_conn_new_sock(c, af); + s = tcp_conn_sock(c, af); } else { - int *p = CONN_V6(conn) ? ns_sock_pool6 : ns_sock_pool4; - ASSERT(pif == PIF_HOST);
port += c->tcp.fwd_in.delta[port];
- /* If pool is empty, refill it first */ - if (p[TCP_SOCK_POOL_SIZE-1] < 0) - NS_CALL(tcp_sock_refill_ns, c); - - s = tcp_conn_pool_sock(p); + s = tcp_conn_sock_ns(c, af); }
if (s < 0) { @@ -709,6 +692,27 @@ static int tcp_sock_refill_ns(void *arg) return 0; }
+/** + * tcp_conn_sock_ns() - Obtain a connectable socket in the namespace + * @c: Execution context + * @af: Address family (AF_INET or AF_INET6) + * + * Return: Socket fd in the namespace on success, -errno on failure + */ +static int tcp_conn_sock_ns(const struct ctx *c, sa_family_t af) +{ + int *p = af == AF_INET6 ? ns_sock_pool6 : ns_sock_pool4; + + /* If the pool is empty we have to incur the latency of entering the ns. + * Therefore, we might as well refill the whole pool while we're at it, + * which differs from tcp_conn_sock(). + */ + if (p[TCP_SOCK_POOL_SIZE-1] < 0)
Nit, for consistency (but yes, it was already like this): if (p[TCP_SOCK_POOL_SIZE - 1] < 0) -- Stefano
On Sun, Feb 18, 2024 at 10:00:29PM +0100, Stefano Brivio wrote:
On Tue, 6 Feb 2024 12:17:24 +1100 David Gibson
wrote: We maintain pools of ready-to-connect sockets in both the original and (for pasta) guest namespace to reduce latency when starting new TCP connections. If we exhaust those pools we have to take a higher latency path to get a new socket.
Currently we open-code that fallback in the places we need it. To improve clarity encapsulate that into helper functions.
Signed-off-by: David Gibson
--- tcp.c | 29 ++++++++++++++++++++++++----- tcp_conn.h | 2 +- tcp_splice.c | 46 +++++++++++++++++++++++++--------------------- 3 files changed, 50 insertions(+), 27 deletions(-) diff --git a/tcp.c b/tcp.c index e15b932f..c06d1cc4 100644 --- a/tcp.c +++ b/tcp.c @@ -1792,7 +1792,7 @@ int tcp_conn_pool_sock(int pool[]) * * Return: socket number on success, negative code if socket creation failed */ -int tcp_conn_new_sock(const struct ctx *c, sa_family_t af) +static int tcp_conn_new_sock(const struct ctx *c, sa_family_t af) { int s;
@@ -1811,6 +1811,27 @@ int tcp_conn_new_sock(const struct ctx *c, sa_family_t af) return s; }
+/** + * tcp_conn_sock() - Obtain a connectable socket in the host/init namespace + * @c: Execution context + * @af: Address family (AF_INET or AF_INET6) + * + * Return: Socket fd on success, -errno on failure + */ +int tcp_conn_sock(const struct ctx *c, sa_family_t af) +{ + int *pool = af == AF_INET6 ? init_sock_pool6 : init_sock_pool4; + int s; + + if ((s = tcp_conn_pool_sock(pool)) >= 0) + return s; + + /* If the pool is empty we just open a new one without refilling the + * pool to keep latency down. + */ + return tcp_conn_new_sock(c, af); +} + /** * tcp_conn_tap_mss() - Get MSS value advertised by tap/guest * @conn: Connection pointer @@ -1909,7 +1930,6 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, const struct tcphdr *th, const char *opts, size_t optlen, const struct timespec *now) { - int *pool = af == AF_INET6 ? init_sock_pool6 : init_sock_pool4; struct sockaddr_in addr4 = { .sin_family = AF_INET, .sin_port = th->dest, @@ -1931,9 +1951,8 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, if (!(flow = flow_alloc())) return;
- if ((s = tcp_conn_pool_sock(pool)) < 0) - if ((s = tcp_conn_new_sock(c, af)) < 0) - goto cancel; + if ((s = tcp_conn_sock(c, af)) < 0) + goto cancel;
if (!c->no_map_gw) { if (af == AF_INET && IN4_ARE_ADDR_EQUAL(daddr, &c->ip4.gw)) diff --git a/tcp_conn.h b/tcp_conn.h index 20c7cb8b..e55edafe 100644 --- a/tcp_conn.h +++ b/tcp_conn.h @@ -159,7 +159,7 @@ bool tcp_flow_defer(union flow *flow); bool tcp_splice_flow_defer(union flow *flow); void tcp_splice_timer(const struct ctx *c, union flow *flow); int tcp_conn_pool_sock(int pool[]); -int tcp_conn_new_sock(const struct ctx *c, sa_family_t af); +int tcp_conn_sock(const struct ctx *c, sa_family_t af); void tcp_sock_refill_pool(const struct ctx *c, int pool[], sa_family_t af); void tcp_splice_refill(const struct ctx *c);
diff --git a/tcp_splice.c b/tcp_splice.c index 576fe9be..609f3242 100644 --- a/tcp_splice.c +++ b/tcp_splice.c @@ -90,7 +90,7 @@ static const char *tcp_splice_flag_str[] __attribute((__unused__)) = { };
/* Forward declaration */ -static int tcp_sock_refill_ns(void *arg); +static int tcp_conn_sock_ns(const struct ctx *c, sa_family_t af);
/** * tcp_splice_conn_epoll_events() - epoll events masks for given state @@ -380,36 +380,19 @@ static int tcp_splice_connect(const struct ctx *c, struct tcp_splice_conn *conn, static int tcp_splice_new(const struct ctx *c, struct tcp_splice_conn *conn, in_port_t port, uint8_t pif) { + sa_family_t af = CONN_V6(conn) ? AF_INET6 : AF_INET; int s = -1;
- /* If the pool is empty we take slightly different approaches - * for init or ns sockets. For init sockets we just open a - * new one without refilling the pool to keep latency down. - * For ns sockets, we're going to incur the latency of - * entering the ns anyway, so we might as well refill the - * pool. - */ if (pif == PIF_SPLICE) { - int *p = CONN_V6(conn) ? init_sock_pool6 : init_sock_pool4; - sa_family_t af = CONN_V6(conn) ? AF_INET6 : AF_INET; - port += c->tcp.fwd_out.delta[port];
- s = tcp_conn_pool_sock(p); - if (s < 0) - s = tcp_conn_new_sock(c, af); + s = tcp_conn_sock(c, af); } else { - int *p = CONN_V6(conn) ? ns_sock_pool6 : ns_sock_pool4; - ASSERT(pif == PIF_HOST);
port += c->tcp.fwd_in.delta[port];
- /* If pool is empty, refill it first */ - if (p[TCP_SOCK_POOL_SIZE-1] < 0) - NS_CALL(tcp_sock_refill_ns, c); - - s = tcp_conn_pool_sock(p); + s = tcp_conn_sock_ns(c, af); }
if (s < 0) { @@ -709,6 +692,27 @@ static int tcp_sock_refill_ns(void *arg) return 0; }
+/** + * tcp_conn_sock_ns() - Obtain a connectable socket in the namespace + * @c: Execution context + * @af: Address family (AF_INET or AF_INET6) + * + * Return: Socket fd in the namespace on success, -errno on failure + */ +static int tcp_conn_sock_ns(const struct ctx *c, sa_family_t af) +{ + int *p = af == AF_INET6 ? ns_sock_pool6 : ns_sock_pool4; + + /* If the pool is empty we have to incur the latency of entering the ns. + * Therefore, we might as well refill the whole pool while we're at it, + * which differs from tcp_conn_sock(). + */ + if (p[TCP_SOCK_POOL_SIZE-1] < 0)
Nit, for consistency (but yes, it was already like this):
if (p[TCP_SOCK_POOL_SIZE - 1] < 0)
Adjusted, thanks. -- David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
In tcp_splice_conn_from_sock(), the 'port' variable stores the source port
of the connection on the originating side. In tcp_splice_new(), called
directly from it, the 'port' parameter gives the _destination_ port of the
originating connection and is then updated to the destination port of the
connection on the other side.
Similarly, in tcp_splice_conn_from_sock(), 's' is the fd of the accetped
socket (on side 0), whereas in tcp_splice_new(), 's' is the fd of the
connecting socket (side 1).
I, for one, find having the same variable name with different meanings in
such close proximity in the flow of control pretty confusing. Alter the
names for greater specificity and clarity.
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:25 +1100
David Gibson
In tcp_splice_conn_from_sock(), the 'port' variable stores the source port of the connection on the originating side. In tcp_splice_new(), called directly from it, the 'port' parameter gives the _destination_ port of the originating connection and is then updated to the destination port of the connection on the other side.
Similarly, in tcp_splice_conn_from_sock(), 's' is the fd of the accetped socket (on side 0), whereas in tcp_splice_new(), 's' is the fd of the connecting socket (side 1).
I, for one, find having the same variable name with different meanings in such close proximity in the flow of control pretty confusing.
Yeah, same here, it took me a while to check that what you're changing to 'dstport' is actually a destination port (and not just because a comment says that). -- Stefano
On Sun, Feb 18, 2024 at 10:00:55PM +0100, Stefano Brivio wrote:
On Tue, 6 Feb 2024 12:17:25 +1100 David Gibson
wrote: In tcp_splice_conn_from_sock(), the 'port' variable stores the source port of the connection on the originating side. In tcp_splice_new(), called directly from it, the 'port' parameter gives the _destination_ port of the originating connection and is then updated to the destination port of the connection on the other side.
Similarly, in tcp_splice_conn_from_sock(), 's' is the fd of the accetped socket (on side 0), whereas in tcp_splice_new(), 's' is the fd of the connecting socket (side 1).
I, for one, find having the same variable name with different meanings in such close proximity in the flow of control pretty confusing.
Yeah, same here, it took me a while to check that what you're changing to 'dstport' is actually a destination port (and not just because a comment says that).
Yeah, I had a lot of confusion until I did that trace and realised these were different things with the same name. Hence the patch. -- David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
The only caller of tcp_splice_new() is tcp_splice_conn_from_sock(). Both
are quite short, and the division of responsibilities between the two isn't
particularly obvious. Simplify by merging the former into the latter.
Signed-off-by: David Gibson
Currently creating the connected socket for a splice is split between
tcp_splice_conn_from_sock(), which opens the socket, and
tcp_splice_connect() which connects it. Alter tcp_splice_connect() to
open its own socket based on an address family and pif we pass it.
This does require a second conditional on pif, but makes for a more logical
split of functionality: tcp_splice_conn_from_sock() picks the target,
tcp_splice_connect() creates the connection. While we're there improve
reporting of errors
Signed-off-by: David Gibson
This makes a number of changes to improve error reporting while connecting
a new spliced socket:
* We use flow_err() and similar functions so all messages include info
on which specific flow was affected
* We use strerror() to interpret raw error values
* We now report errors on connection (at "trace" level, since this would
allow spamming the logs)
* We also look up and report some details on EPOLLERR events, which can
include connection errors, since we use a non-blocking connect(). Again
we use "trace" level since this can spam the logs.
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:28 +1100
David Gibson
This makes a number of changes to improve error reporting while connecting a new spliced socket: * We use flow_err() and similar functions so all messages include info on which specific flow was affected * We use strerror() to interpret raw error values * We now report errors on connection (at "trace" level, since this would allow spamming the logs) * We also look up and report some details on EPOLLERR events, which can include connection errors, since we use a non-blocking connect(). Again we use "trace" level since this can spam the logs.
Signed-off-by: David Gibson
--- tcp_splice.c | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/tcp_splice.c b/tcp_splice.c index 5ba9c8ea..49075e5c 100644 --- a/tcp_splice.c +++ b/tcp_splice.c @@ -349,8 +349,9 @@ static int tcp_splice_connect(const struct ctx *c, struct tcp_splice_conn *conn, ASSERT(0);
if (conn->s[1] < 0) { - warn("Couldn't open connectable socket for splice (%d)", - conn->s[1]); + flow_err(conn, + "Couldn't open connectable socket for splice: %s", + strerror(-conn->s[1]));
It took me a bit to convince myself that we actually store negative error codes in pools, which sounds like a neat idea, except for two things: - in tcp_sock_refill_pool(), once we get an error from tcp_conn_new_sock(), should we really continue to call it and try to get more sockets? Presumably, that will have something to do with some kind of resource exhaustion, so perhaps we shouldn't risk making it worse and just stop refilling the pool. If we do, we might have up to one negative error code in the pool, I guess. - if we have an error code in the pool, that error might have occurred a while ago, but here, we're logging it at the moment we need that socket. Maybe it would be simpler and saner to just have -1 values in the pool (error or no socket available) and report errors in tcp_conn_new_sock() instead? I'm still reviewing patches 17/22 to 22/22, sorry for the delay. -- Stefano
On Sun, Feb 18, 2024 at 10:01:24PM +0100, Stefano Brivio wrote:
On Tue, 6 Feb 2024 12:17:28 +1100 David Gibson
wrote: This makes a number of changes to improve error reporting while connecting a new spliced socket: * We use flow_err() and similar functions so all messages include info on which specific flow was affected * We use strerror() to interpret raw error values * We now report errors on connection (at "trace" level, since this would allow spamming the logs) * We also look up and report some details on EPOLLERR events, which can include connection errors, since we use a non-blocking connect(). Again we use "trace" level since this can spam the logs.
Signed-off-by: David Gibson
--- tcp_splice.c | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/tcp_splice.c b/tcp_splice.c index 5ba9c8ea..49075e5c 100644 --- a/tcp_splice.c +++ b/tcp_splice.c @@ -349,8 +349,9 @@ static int tcp_splice_connect(const struct ctx *c, struct tcp_splice_conn *conn, ASSERT(0);
if (conn->s[1] < 0) { - warn("Couldn't open connectable socket for splice (%d)", - conn->s[1]); + flow_err(conn, + "Couldn't open connectable socket for splice: %s", + strerror(-conn->s[1]));
It took me a bit to convince myself that we actually store negative error codes in pools, which sounds like a neat idea, except for two things:
Yeah, it took me a while to discover that too :)
- in tcp_sock_refill_pool(), once we get an error from tcp_conn_new_sock(), should we really continue to call it and try to get more sockets?
Presumably, that will have something to do with some kind of resource exhaustion, so perhaps we shouldn't risk making it worse and just stop refilling the pool. If we do, we might have up to one negative error code in the pool, I guess.
Some sort of exhaustion is certainly the most likely cause, yes.
- if we have an error code in the pool, that error might have occurred a while ago, but here, we're logging it at the moment we need that socket.
Fair point.
Maybe it would be simpler and saner to just have -1 values in the pool (error or no socket available) and report errors in tcp_conn_new_sock() instead?
Yeah, that makes sense. I'll rework to that goal.
I'm still reviewing patches 17/22 to 22/22, sorry for the delay.
-- David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
This makes several tweaks to improve the logic which decides whether we're
able to use the splice method for a new connection.
* Rather than only calling tcp_splice_conn_from_sock() in pasta mode, we
check for pasta mode within it, better localising the checks.
* Previously if we got a connection from a non-loopback address we'd
always fall back to the "tap" path, even if the connection was on a
socket in the namespace. If we did get a non-loopback address on a
namespace socket, something has gone wrong and the "tap" path certainly
won't be able to handle it. Report the error and close, rather than
passing it along to tap.
Signed-off-by: David Gibson
tcp_listen_handler() uses the epoll reference for the listening socket it
handles, and also passes on one variant of it to tcp_tap_conn_from_sock()
and tcp_splice_conn_from_sock(). The latter two functions only need a
couple of specific fields from the reference.
Pass those specific values instead of the whole reference, which localises
the handling of the listening (as opposed to accepted) socket and its
reference entirely within tcp_listen_handler().
Signed-off-by: David Gibson
TCP connections should typically not have wildcard addresses (0.0.0.0 or
::) nor a zero port number for either endpoint. It's not entirely clear
(at least to me) if it's strictly against the RFCs to do so, but at any
rate the socket interfaces often treat those values specially[1], so it's
not really possible to manipulate such connections. Likewise they should
not have broadcast or multicast addresses for either endpoint.
However, nothing prevents a guest from creating a SYN packet with such
values, and it's not entirely clear what the effect on passt would be. To
ensure sane behaviour, explicitly check for this case and drop such
packets, logging a debug warning (we don't want a higher level, because
that would allow a guest to spam the logs).
We never expect such an address on an accept()ed socket either, but just
in case, check for it as well.
[1] Depending on context as "unknown", "match any" or "kernel, pick
something for me"
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:31 +1100
David Gibson
TCP connections should typically not have wildcard addresses (0.0.0.0 or ::) nor a zero port number for either endpoint.
This is only true for non-local connections, see also: https://archives.passt.top/passt-dev/20240119105630.089c5d34@elisabeth/ Just looking at RFC 6890, which should be sufficient: +----------------------+----------------------------+ | Attribute | Value | +----------------------+----------------------------+ | Address Block | 0.0.0.0/8 | | Name | "This host on this network"| | RFC | [RFC1122], Section 3.2.1.3 | | Allocation Date | September 1981 | | Termination Date | N/A | | Source | True | | Destination | False | | Forwardable | False | | Global | False | | Reserved-by-Protocol | True | +----------------------+----------------------------+ ...it can be used as source, but surely not by a non-loopback interface, so not by the guest. About using it as destination: the table says it can't be done, but: $ nc -l -p 8818 & echo abcd | nc 0.0.0.0 8818 [2] 2624647 abcd and: # tcpdump -ni lo tcp port 8818 tcpdump: verbose output suppressed, use -v[v]... for full protocol decode listening on lo, link-type EN10MB (Ethernet), snapshot length 262144 bytes 13:24:51.379436 IP 127.0.0.1.58574 > 127.0.0.1.8818: Flags [S], seq 3285989360, win 65495, options [mss 65495,sackOK,TS val 1253719321 ecr 0,nop,wscale 7], length 0 13:24:51.379447 IP 127.0.0.1.8818 > 127.0.0.1.58574: Flags [S.], seq 3128422158, ack 3285989361, win 65483, options [mss 65495,sackOK,TS val 1253719321 ecr 1253719321,nop,wscale 7], length 0 13:24:51.379457 IP 127.0.0.1.58574 > 127.0.0.1.8818: Flags [.], ack 1, win 512, options [nop,nop,TS val 1253719321 ecr 1253719321], length 0 13:24:51.379508 IP 127.0.0.1.58574 > 127.0.0.1.8818: Flags [P.], seq 1:6, ack 1, win 512, options [nop,nop,TS val 1253719321 ecr 1253719321], length 5 13:24:51.379513 IP 127.0.0.1.8818 > 127.0.0.1.58574: Flags [.], ack 6, win 512, options [nop,nop,TS val 1253719321 ecr 1253719321], length 0 it's not effectively used, but the kernel understands what I mean by 0.0.0.0: connect(3, {sa_family=AF_INET, sin_port=htons(8818), sin_addr=inet_addr("0.0.0.0")}, 16) = -1 EINPROGRESS (Operation now in progress) So I wouldn't exclude its usage in tcp_listen_handler() -- even though sure, the kernel translates that, so I don't think it can ever become a practical issue. If it annoys you in the perspective of the flow table, maybe we can turn it into a loopback address, when we see it's used as source or destination? If that's problematic as well, I can totally live with this patch, though. About IPv6: +----------------------+---------------------+ | Attribute | Value | +----------------------+---------------------+ | Address Block | ::/128 | | Name | Unspecified Address | | RFC | [RFC4291] | | Allocation Date | February 2006 | | Termination Date | N/A | | Source | True | | Destination | False | | Forwardable | False | | Global | False | | Reserved-by-Protocol | True | +----------------------+---------------------+ ...this is more specific, and its usage as source address is exemplified in RFC 4291, 2.5.2: One example of its use is in the Source Address field of any IPv6 packets sent by an initializing host before it has learned its own address. ...which should never be the case for any flow passt has to handle, so I think it's fine to refuse it in tcp_listen_handler(). The rest of the series, up to 22/22, looks good to me.
It's not entirely clear (at least to me) if it's strictly against the RFCs to do so, but at any rate the socket interfaces often treat those values specially[1], so it's not really possible to manipulate such connections. Likewise they should not have broadcast or multicast addresses for either endpoint.
However, nothing prevents a guest from creating a SYN packet with such values, and it's not entirely clear what the effect on passt would be. To ensure sane behaviour, explicitly check for this case and drop such packets, logging a debug warning (we don't want a higher level, because that would allow a guest to spam the logs).
We never expect such an address on an accept()ed socket either, but just in case, check for it as well.
[1] Depending on context as "unknown", "match any" or "kernel, pick something for me"
Signed-off-by: David Gibson
--- tcp.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 67 insertions(+), 7 deletions(-) diff --git a/tcp.c b/tcp.c index 31d4e87b..236a8d23 100644 --- a/tcp.c +++ b/tcp.c @@ -284,6 +284,7 @@ #include
#include #include +#include #include
/* For struct tcp_info */ @@ -1930,27 +1931,59 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, const struct tcphdr *th, const char *opts, size_t optlen, const struct timespec *now) { + in_port_t srcport = ntohs(th->source); + in_port_t dstport = ntohs(th->dest); struct sockaddr_in addr4 = { .sin_family = AF_INET, - .sin_port = th->dest, + .sin_port = htons(dstport), .sin_addr = *(struct in_addr *)daddr, }; struct sockaddr_in6 addr6 = { .sin6_family = AF_INET6, - .sin6_port = th->dest, + .sin6_port = htons(dstport), .sin6_addr = *(struct in6_addr *)daddr, }; const struct sockaddr *sa; struct tcp_tap_conn *conn; union flow *flow; + int s = -1, mss; socklen_t sl; - int s, mss; - - (void)saddr;
if (!(flow = flow_alloc())) return;
+ if (af == AF_INET) { + if (IN4_IS_ADDR_UNSPECIFIED(saddr) || + IN4_IS_ADDR_BROADCAST(saddr) || + IN4_IS_ADDR_MULTICAST(saddr) || srcport == 0 || + IN4_IS_ADDR_UNSPECIFIED(daddr) || + IN4_IS_ADDR_BROADCAST(daddr) || + IN4_IS_ADDR_MULTICAST(daddr) || dstport == 0) { + char sstr[INET_ADDRSTRLEN], dstr[INET_ADDRSTRLEN]; + + debug("Invalid endpoint in TCP SYN: %s:%hu -> %s:%hu", + inet_ntop(AF_INET, saddr, sstr, sizeof(sstr)), + srcport, + inet_ntop(AF_INET, daddr, dstr, sizeof(dstr)), + dstport); + goto cancel; + } + } else if (af == AF_INET6) { + if (IN6_IS_ADDR_UNSPECIFIED(saddr) || + IN6_IS_ADDR_MULTICAST(saddr) || srcport == 0 || + IN6_IS_ADDR_UNSPECIFIED(daddr) || + IN6_IS_ADDR_MULTICAST(daddr) || dstport == 0) { + char sstr[INET6_ADDRSTRLEN], dstr[INET6_ADDRSTRLEN]; + + debug("Invalid endpoint in TCP SYN: %s:%hu -> %s:%hu", + inet_ntop(AF_INET6, saddr, sstr, sizeof(sstr)), + srcport, + inet_ntop(AF_INET6, daddr, dstr, sizeof(dstr)), + dstport); + goto cancel; + } + } + if ((s = tcp_conn_sock(c, af)) < 0) goto cancel;
@@ -2001,8 +2034,8 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, sl = sizeof(addr6); }
- conn->fport = ntohs(th->dest); - conn->eport = ntohs(th->source); + conn->fport = dstport; + conn->eport = srcport;
conn->seq_init_from_tap = ntohl(th->seq); conn->seq_from_tap = conn->seq_init_from_tap + 1; @@ -2732,6 +2765,33 @@ void tcp_listen_handler(struct ctx *c, union epoll_ref ref, if (s < 0) goto cancel;
+ if (sa.sa_family == AF_INET) { + const struct in_addr *addr = &sa.sa4.sin_addr; + in_port_t port = sa.sa4.sin_port; + + if (IN4_IS_ADDR_UNSPECIFIED(addr) || + IN4_IS_ADDR_BROADCAST(addr) || + IN4_IS_ADDR_MULTICAST(addr) || port == 0) { + char str[INET_ADDRSTRLEN]; + + err("Invalid endpoint from TCP accept(): %s:%hu", + inet_ntop(AF_INET, addr, str, sizeof(str)), port); + goto cancel; + } + } else if (sa.sa_family == AF_INET6) { + const struct in6_addr *addr = &sa.sa6.sin6_addr; + in_port_t port = sa.sa6.sin6_port; + + if (IN6_IS_ADDR_UNSPECIFIED(addr) || + IN6_IS_ADDR_MULTICAST(addr) || port == 0) { + char str[INET6_ADDRSTRLEN]; + + err("Invalid endpoint from TCP accept(): %s:%hu", + inet_ntop(AF_INET6, addr, str, sizeof(str)), port); + goto cancel; + } + } + if (tcp_splice_conn_from_sock(c, ref.tcp_listen.pif, ref.tcp_listen.port, flow, s, &sa)) return;
-- Stefano
On Thu, Feb 22, 2024 at 01:45:44PM +0100, Stefano Brivio wrote:
On Tue, 6 Feb 2024 12:17:31 +1100 David Gibson
wrote: TCP connections should typically not have wildcard addresses (0.0.0.0 or ::) nor a zero port number for either endpoint.
This is only true for non-local connections, see also: https://archives.passt.top/passt-dev/20240119105630.089c5d34@elisabeth/
Just looking at RFC 6890, which should be sufficient:
+----------------------+----------------------------+ | Attribute | Value | +----------------------+----------------------------+ | Address Block | 0.0.0.0/8 | | Name | "This host on this network"| | RFC | [RFC1122], Section 3.2.1.3 | | Allocation Date | September 1981 | | Termination Date | N/A | | Source | True | | Destination | False | | Forwardable | False | | Global | False | | Reserved-by-Protocol | True | +----------------------+----------------------------+
It's unclear to me from either rfc 6890 or rfc 1122 whether this is describing something meaningful on the wire, or only something meaningful in APIs.
...it can be used as source, but surely not by a non-loopback interface, so not by the guest.
About using it as destination: the table says it can't be done, but:
$ nc -l -p 8818 & echo abcd | nc 0.0.0.0 8818 [2] 2624647 abcd
and:
# tcpdump -ni lo tcp port 8818 tcpdump: verbose output suppressed, use -v[v]... for full protocol decode listening on lo, link-type EN10MB (Ethernet), snapshot length 262144 bytes 13:24:51.379436 IP 127.0.0.1.58574 > 127.0.0.1.8818: Flags [S], seq 3285989360, win 65495, options [mss 65495,sackOK,TS val 1253719321 ecr 0,nop,wscale 7], length 0 13:24:51.379447 IP 127.0.0.1.8818 > 127.0.0.1.58574: Flags [S.], seq 3128422158, ack 3285989361, win 65483, options [mss 65495,sackOK,TS val 1253719321 ecr 1253719321,nop,wscale 7], length 0 13:24:51.379457 IP 127.0.0.1.58574 > 127.0.0.1.8818: Flags [.], ack 1, win 512, options [nop,nop,TS val 1253719321 ecr 1253719321], length 0 13:24:51.379508 IP 127.0.0.1.58574 > 127.0.0.1.8818: Flags [P.], seq 1:6, ack 1, win 512, options [nop,nop,TS val 1253719321 ecr 1253719321], length 5 13:24:51.379513 IP 127.0.0.1.8818 > 127.0.0.1.58574: Flags [.], ack 6, win 512, options [nop,nop,TS val 1253719321 ecr 1253719321], length 0
it's not effectively used, but the kernel understands what I mean by 0.0.0.0:
Right: the 0.0.0.0 means something at the API level, but not AFAICT, at the wire level. At least for the "from tap" side of this change, it's the wire level that I'm checking.
connect(3, {sa_family=AF_INET, sin_port=htons(8818), sin_addr=inet_addr("0.0.0.0")}, 16) = -1 EINPROGRESS (Operation now in progress)
So I wouldn't exclude its usage in tcp_listen_handler() -- even though sure, the kernel translates that, so I don't think it can ever become a practical issue.
Hmm. In listen_handler() it's not "on the wire", but reading from an API still seems different from sending to an API to me. At the very least 0.0.0.0 doesn't have the same meaning in all API contexts, which makes it, IMO, unsafe to carry around from one API to another.
If it annoys you in the perspective of the flow table, maybe we can turn it into a loopback address, when we see it's used as source or destination?
It appears the kernel already does that (IMO, correctly). If we do see a 0.0.0.0 here, I think that would be the kernel indicating some sort of special case that would need special handling. So, again, I don't think we should just blindly copy this address to other APIs.
If that's problematic as well, I can totally live with this patch, though.
About IPv6:
+----------------------+---------------------+ | Attribute | Value | +----------------------+---------------------+ | Address Block | ::/128 | | Name | Unspecified Address | | RFC | [RFC4291] | | Allocation Date | February 2006 | | Termination Date | N/A | | Source | True | | Destination | False | | Forwardable | False | | Global | False | | Reserved-by-Protocol | True | +----------------------+---------------------+
...this is more specific, and its usage as source address is exemplified in RFC 4291, 2.5.2:
One example of its use is in the Source Address field of any IPv6 packets sent by an initializing host before it has learned its own address.
...which should never be the case for any flow passt has to handle, so I think it's fine to refuse it in tcp_listen_handler().
Well, depends how broadly you define "flow". We may need to handle this for NDP and/or DHCPv6. But this is specifically for TCP.
The rest of the series, up to 22/22, looks good to me.
It's not entirely clear (at least to me) if it's strictly against the RFCs to do so, but at any rate the socket interfaces often treat those values specially[1], so it's not really possible to manipulate such connections. Likewise they should not have broadcast or multicast addresses for either endpoint.
However, nothing prevents a guest from creating a SYN packet with such values, and it's not entirely clear what the effect on passt would be. To ensure sane behaviour, explicitly check for this case and drop such packets, logging a debug warning (we don't want a higher level, because that would allow a guest to spam the logs).
We never expect such an address on an accept()ed socket either, but just in case, check for it as well.
[1] Depending on context as "unknown", "match any" or "kernel, pick something for me"
Signed-off-by: David Gibson
--- tcp.c | 74 +++++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 67 insertions(+), 7 deletions(-) diff --git a/tcp.c b/tcp.c index 31d4e87b..236a8d23 100644 --- a/tcp.c +++ b/tcp.c @@ -284,6 +284,7 @@ #include
#include #include +#include #include
/* For struct tcp_info */ @@ -1930,27 +1931,59 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, const struct tcphdr *th, const char *opts, size_t optlen, const struct timespec *now) { + in_port_t srcport = ntohs(th->source); + in_port_t dstport = ntohs(th->dest); struct sockaddr_in addr4 = { .sin_family = AF_INET, - .sin_port = th->dest, + .sin_port = htons(dstport), .sin_addr = *(struct in_addr *)daddr, }; struct sockaddr_in6 addr6 = { .sin6_family = AF_INET6, - .sin6_port = th->dest, + .sin6_port = htons(dstport), .sin6_addr = *(struct in6_addr *)daddr, }; const struct sockaddr *sa; struct tcp_tap_conn *conn; union flow *flow; + int s = -1, mss; socklen_t sl; - int s, mss; - - (void)saddr;
if (!(flow = flow_alloc())) return;
+ if (af == AF_INET) { + if (IN4_IS_ADDR_UNSPECIFIED(saddr) || + IN4_IS_ADDR_BROADCAST(saddr) || + IN4_IS_ADDR_MULTICAST(saddr) || srcport == 0 || + IN4_IS_ADDR_UNSPECIFIED(daddr) || + IN4_IS_ADDR_BROADCAST(daddr) || + IN4_IS_ADDR_MULTICAST(daddr) || dstport == 0) { + char sstr[INET_ADDRSTRLEN], dstr[INET_ADDRSTRLEN]; + + debug("Invalid endpoint in TCP SYN: %s:%hu -> %s:%hu", + inet_ntop(AF_INET, saddr, sstr, sizeof(sstr)), + srcport, + inet_ntop(AF_INET, daddr, dstr, sizeof(dstr)), + dstport); + goto cancel; + } + } else if (af == AF_INET6) { + if (IN6_IS_ADDR_UNSPECIFIED(saddr) || + IN6_IS_ADDR_MULTICAST(saddr) || srcport == 0 || + IN6_IS_ADDR_UNSPECIFIED(daddr) || + IN6_IS_ADDR_MULTICAST(daddr) || dstport == 0) { + char sstr[INET6_ADDRSTRLEN], dstr[INET6_ADDRSTRLEN]; + + debug("Invalid endpoint in TCP SYN: %s:%hu -> %s:%hu", + inet_ntop(AF_INET6, saddr, sstr, sizeof(sstr)), + srcport, + inet_ntop(AF_INET6, daddr, dstr, sizeof(dstr)), + dstport); + goto cancel; + } + } + if ((s = tcp_conn_sock(c, af)) < 0) goto cancel;
@@ -2001,8 +2034,8 @@ static void tcp_conn_from_tap(struct ctx *c, sa_family_t af, sl = sizeof(addr6); }
- conn->fport = ntohs(th->dest); - conn->eport = ntohs(th->source); + conn->fport = dstport; + conn->eport = srcport;
conn->seq_init_from_tap = ntohl(th->seq); conn->seq_from_tap = conn->seq_init_from_tap + 1; @@ -2732,6 +2765,33 @@ void tcp_listen_handler(struct ctx *c, union epoll_ref ref, if (s < 0) goto cancel;
+ if (sa.sa_family == AF_INET) { + const struct in_addr *addr = &sa.sa4.sin_addr; + in_port_t port = sa.sa4.sin_port; + + if (IN4_IS_ADDR_UNSPECIFIED(addr) || + IN4_IS_ADDR_BROADCAST(addr) || + IN4_IS_ADDR_MULTICAST(addr) || port == 0) { + char str[INET_ADDRSTRLEN]; + + err("Invalid endpoint from TCP accept(): %s:%hu", + inet_ntop(AF_INET, addr, str, sizeof(str)), port); + goto cancel; + } + } else if (sa.sa_family == AF_INET6) { + const struct in6_addr *addr = &sa.sa6.sin6_addr; + in_port_t port = sa.sa6.sin6_port; + + if (IN6_IS_ADDR_UNSPECIFIED(addr) || + IN6_IS_ADDR_MULTICAST(addr) || port == 0) { + char str[INET6_ADDRSTRLEN]; + + err("Invalid endpoint from TCP accept(): %s:%hu", + inet_ntop(AF_INET6, addr, str, sizeof(str)), port); + goto cancel; + } + } + if (tcp_splice_conn_from_sock(c, ref.tcp_listen.pif, ref.tcp_listen.port, flow, s, &sa)) return;
-- David Gibson | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you. NOT _the_ _other_ | _way_ _around_! http://www.ozlabs.org/~dgibson
The "tap" interface, whether it's actually a tuntap device or a qemu
socket, presents a virtual external link between different network hosts.
Hence, loopback addresses make no sense there. However, nothing prevents
the guest from putting bogus packets with loopback addresses onto the
interface and it's not entirely clear what effect that will have on passt.
Explicitly test for such packets and drop them.
Signed-off-by: David Gibson
port_fwd_scan_udp() handles UDP, as the name suggests, but its function
comment has the wrong function name and references TCP, due to a bad
copy/pasta from port_fwd_scan_tcp().
Signed-off-by: David Gibson
Currently port_fwd.[ch] contains helpers related to port forwarding,
particular automatic port forwarding. We're planning to allow much more
flexible sorts of forwarding, including both port translation and NAT based
on the flow table. This will subsume the existing port forwarding logic,
so rename port_fwd.[ch] to fwd.[ch] with matching updates to all the names
within.
Signed-off-by: David Gibson
On Tue, 6 Feb 2024 12:17:12 +1100
David Gibson
Here's another batch of cleanups and tweaks in preparation for the flow table. This set focuses on improved helpers for handling addresses, particularly in the TCP splice path.
Sorry for the delay, I made sure I'm done reviewing this and I have no further comments -- I'm fine with 19/22 as it is. Please post v3 so that I can apply this. -- Stefano
participants (2)
-
David Gibson
-
Stefano Brivio