mirror of
https://github.com/tailscale/tailscale.git
synced 2026-11-20 08:41:19 -08:00
Tailscale needs disco, STUN and WireGuard to share one UDP 4-tuple, so that the NAT mappings disco discovers are the ones WireGuard uses. So let tailscaled create and bind the socket itself and hand its fd to the device, as L2TP allows for its tunnel sockets. The new TSWGDEVICE_A_SOCK_FD4 and TSWGDEVICE_A_SOCK_FD6 attributes, nested in a new WGDEVICE_A_TSWG attribute numbered 64 to stay clear of future upstream attributes, take the fd of a bound UDP socket (IPV6_V6ONLY for IPv6). The device hooks the socket's UDP encap_rcv, consumes WireGuard messages (a first byte of 1 through 4 and three zero bytes), and returns everything else to the normal UDP path for userspace to read. Userspace can send its own datagrams on the socket as usual. The device keeps a reference to the struct sock, not the file, and drops the socket from its encap_destroy hook when userspace closes it, so the socket lives exactly as long as userspace's fd. Passing -1 detaches the socket, restoring it to plain UDP, and the device goes back to creating its own sockets. User sockets persist across ifdown/ifup, and changing the listen port while one is attached fails with EBUSY. Dumps report which families have a user socket in TSWGDEVICE_A_FLAGS. A global mutex serializes attach and detach, including detach from encap_destroy, which runs from the user's close() with none of our locks held. Tested by TestTSWGGokrazySharedSocket (7.2.8) and TestTSWGUbuntuSharedSocket (6.8) in tailscale.com's natlab vmtests. Updates #426 Signed-off-by: Brad Fitzpatrick <[email protected]> Change-Id: I2e7a97952ced03df4bc954ba398a49daf9128d41