mirror of
https://github.com/netbirdio/netbird.git
synced 2026-04-16 07:16:38 +00:00
The Relayed connection setup is optimistic. It does not have any confirmation of an established end-to-end connection. Peers start sending WireGuard handshake packets immediately after the successful offer-answer handshake. Meanwhile, for successful P2P connection negotiation, we change the WireGuard endpoint address, but this change does not trigger new handshake initiation. Because the peer switched from Relayed connection to P2P, the packets from the Relay server are dropped and must wait for the next WireGuard handshake via P2P. To avoid this scenario, the relayed WireGuard proxy no longer drops the packets. Instead, it rewrites the source address to the new P2P endpoint and continues forwarding the packets. We still have one corner case: if the Relayed server negotiation chooses a server that has not been used before. In this case, one side of the peer connection will be slower to reach the Relay server, and the Relay server will drop the handshake packet. If everything goes well we should see exactly 5 seconds improvements between the WireGuard configuration time and the handshake time.
51 lines
1.3 KiB
Go
51 lines
1.3 KiB
Go
//go:build linux && !android
|
|
|
|
package rawsocket
|
|
|
|
import (
|
|
"fmt"
|
|
"net"
|
|
"os"
|
|
"syscall"
|
|
|
|
nbnet "github.com/netbirdio/netbird/client/net"
|
|
)
|
|
|
|
func PrepareSenderRawSocket() (net.PacketConn, error) {
|
|
// Create a raw socket.
|
|
fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_RAW, syscall.IPPROTO_RAW)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("creating raw socket failed: %w", err)
|
|
}
|
|
|
|
// Set the IP_HDRINCL option on the socket to tell the kernel that headers are included in the packet.
|
|
err = syscall.SetsockoptInt(fd, syscall.IPPROTO_IP, syscall.IP_HDRINCL, 1)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("setting IP_HDRINCL failed: %w", err)
|
|
}
|
|
|
|
// Bind the socket to the "lo" interface.
|
|
err = syscall.SetsockoptString(fd, syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, "lo")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("binding to lo interface failed: %w", err)
|
|
}
|
|
|
|
// Set the fwmark on the socket.
|
|
err = nbnet.SetSocketOpt(fd)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("setting fwmark failed: %w", err)
|
|
}
|
|
|
|
// Convert the file descriptor to a PacketConn.
|
|
file := os.NewFile(uintptr(fd), fmt.Sprintf("fd %d", fd))
|
|
if file == nil {
|
|
return nil, fmt.Errorf("converting fd to file failed")
|
|
}
|
|
packetConn, err := net.FilePacketConn(file)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("converting file to packet conn failed: %w", err)
|
|
}
|
|
|
|
return packetConn, nil
|
|
}
|