aboutgitcodebugslistschat
path: root/udp_flow.c
diff options
context:
space:
mode:
Diffstat (limited to 'udp_flow.c')
-rw-r--r--udp_flow.c53
1 files changed, 49 insertions, 4 deletions
diff --git a/udp_flow.c b/udp_flow.c
index a9fab7a..57e159f 100644
--- a/udp_flow.c
+++ b/udp_flow.c
@@ -60,6 +60,37 @@ void udp_flow_close(const struct ctx *c, struct udp_flow *uflow)
}
/**
+ * udp_flow_port_listening() - Do we have a listening socket on a flow's port?
+ * @c: Execution context
+ * @pif: Interface of the flow side
+ * @side: Flow side, giving our address and port on @pif
+ *
+ * Return: true if we're forwarding UDP from the address and port of @side on
+ * @pif, and the corresponding listening socket is actually open
+ */
+static bool udp_flow_port_listening(const struct ctx *c, uint8_t pif,
+ const struct flowside *side)
+{
+ const struct fwd_table *fwd = c->fwd[pif];
+ const struct flowside ini = {
+ .oaddr = side->oaddr,
+ .oport = side->oport,
+ };
+ const struct fwd_rule *rule;
+ unsigned idx;
+
+ if (!fwd || !side->oport)
+ return false;
+
+ rule = fwd_rule_search(fwd, &ini, IPPROTO_UDP, FWD_NO_HINT);
+ if (!rule)
+ return false;
+
+ idx = rule - fwd->rules;
+ return fwd->rulesocks[idx][side->oport - rule->first] >= 0;
+}
+
+/**
* udp_flow_sock() - Create, bind and connect a flow specific UDP socket
* @c: Execution context
* @uflow: UDP flow to open socket for
@@ -89,10 +120,24 @@ static int udp_flow_sock(const struct ctx *c,
s = flowside_sock_l4(c, EPOLL_TYPE_UDP, pif, side, exclusive);
if (s == -EADDRINUSE && exclusive && side->oport) {
- flow_dbg(uflow, "Host port %hu in use, using an ephemeral port",
- side->oport);
- uflow->f.side[sidei].oport = 0;
- s = flowside_sock_l4(c, EPOLL_TYPE_UDP, pif, side, exclusive);
+ if (udp_flow_port_listening(c, pif, side)) {
+ /* The port is held by our own listening socket: sharing
+ * it is safe, as the connected flow socket always takes
+ * precedence for replies from its peer, and preserving
+ * the port matters here, as peers might reach us back
+ * at the source port of our packets (e.g. BitTorrent's
+ * DHT).
+ */
+ s = flowside_sock_l4(c, EPOLL_TYPE_UDP, pif, side,
+ false);
+ } else {
+ flow_dbg(uflow,
+ "Host port %hu in use, using ephemeral port",
+ side->oport);
+ uflow->f.side[sidei].oport = 0;
+ s = flowside_sock_l4(c, EPOLL_TYPE_UDP, pif, side,
+ exclusive);
+ }
}
if (s < 0) {
flow_perror_ratelimit(uflow, now,