diff options
Diffstat (limited to 'udp_flow.c')
| -rw-r--r-- | udp_flow.c | 28 |
1 files changed, 24 insertions, 4 deletions
@@ -74,10 +74,26 @@ static int udp_flow_sock(const struct ctx *c, { const struct flowside *side = &uflow->f.side[sidei]; uint8_t pif = uflow->f.pif[sidei]; + /* A guest-initiated flow keeps the guest's source port on the host + * side. Bind it exclusively: without SO_REUSEADDR the bind fails if + * any other socket in this network namespace holds the port, such as + * another passt instance's flow towards the same destination (typically + * the same DNS resolver). Two sockets with an identical 4-tuple would + * steal each other's replies. In that case let the kernel pick a free + * port instead, and udp_flow_new() records it. Listening sockets and + * the flows they initiate keep SO_REUSEADDR, as they must share ports. + */ + bool exclusive = sidei == TGTSIDE && uflow->f.pif[INISIDE] == PIF_TAP; int rc; int s; - s = flowside_sock_l4(c, EPOLL_TYPE_UDP, pif, side); + 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 (s < 0) { flow_perror_ratelimit(uflow, now, "Couldn't open flow specific socket"); @@ -162,13 +178,15 @@ static flow_sidx_t udp_flow_new(const struct ctx *c, union flow *flow, goto cancel; } - if (uflow->s[TGTSIDE] >= 0 && inany_is_unspecified(&tgt->oaddr)) { + if (uflow->s[TGTSIDE] >= 0 && + (inany_is_unspecified(&tgt->oaddr) || !tgt->oport)) { /* When we target a socket, we connect() it, but might not * always bind(), leaving the kernel to pick our address. In * that case connect() will implicitly bind() the socket, but we * need to determine its local address so that we can match * reply packets back to the correct flow. Update the flow with - * the information from getsockname() */ + * the information from getsockname(). The same applies to the + * port if udp_flow_sock() had to let the kernel pick one. */ union sockaddr_inany sa; socklen_t sl = sizeof(sa); in_port_t port; @@ -179,7 +197,9 @@ static flow_sidx_t udp_flow_new(const struct ctx *c, union flow *flow, flow_perror(uflow, "Unable to determine local address"); goto cancel; } - if (port != tgt->oport) { + if (!tgt->oport) { + uflow->f.side[TGTSIDE].oport = port; + } else if (port != tgt->oport) { flow_err_ratelimit(uflow, now, "Unexpected local port"); goto cancel; } |
