chore(all): make code compilable for other platforms than Linux

This commit is contained in:
Quentin McGaw
2026-01-24 13:48:15 +00:00
parent de38d759a4
commit fe3d4a94d4
35 changed files with 192 additions and 194 deletions
+1 -1
View File
@@ -581,7 +581,7 @@ type Linker interface {
LinkDel(link netlink.Link) (err error)
LinkSetUp(link netlink.Link) (linkIndex int, err error)
LinkSetDown(link netlink.Link) (err error)
LinkSetMTU(link netlink.Link, mtu int) error
LinkSetMTU(link netlink.Link, mtu uint32) error
}
type clier interface {
-2
View File
@@ -1,5 +1,3 @@
//go:build linux || darwin
package netlink
import (
-13
View File
@@ -1,13 +0,0 @@
//go:build !linux && !darwin
package netlink
func (n *NetLink) AddrList(link Link, family int) (
addresses []Addr, err error,
) {
panic("not implemented")
}
func (n *NetLink) AddrReplace(Link, Addr) error {
panic("not implemented")
}
-6
View File
@@ -4,12 +4,6 @@ import (
"fmt"
)
const (
FamilyAll = 0
FamilyV4 = 2
FamilyV6 = 10
)
func FamilyToString(family int) string {
switch family {
case FamilyAll:
+9
View File
@@ -0,0 +1,9 @@
package netlink
import "golang.org/x/sys/unix"
const (
FamilyAll = unix.AF_UNSPEC
FamilyV4 = unix.AF_INET
FamilyV6 = unix.AF_INET6
)
+2 -4
View File
@@ -1,5 +1,3 @@
//go:build linux || darwin
package netlink
import "github.com/vishvananda/netlink"
@@ -62,8 +60,8 @@ func (n *NetLink) LinkSetDown(link Link) (err error) {
return netlink.LinkSetDown(linkToNetlinkLink(&link))
}
func (n *NetLink) LinkSetMTU(link Link, mtu int) error {
return netlink.LinkSetMTU(linkToNetlinkLink(&link), mtu)
func (n *NetLink) LinkSetMTU(link Link, mtu uint32) error {
return netlink.LinkSetMTU(linkToNetlinkLink(&link), int(mtu))
}
type netlinkLinkImpl struct {
-31
View File
@@ -1,31 +0,0 @@
//go:build !linux && !darwin
package netlink
func (n *NetLink) LinkList() (links []Link, err error) {
panic("not implemented")
}
func (n *NetLink) LinkByName(name string) (link Link, err error) {
panic("not implemented")
}
func (n *NetLink) LinkByIndex(index int) (link Link, err error) {
panic("not implemented")
}
func (n *NetLink) LinkAdd(link Link) (linkIndex int, err error) {
panic("not implemented")
}
func (n *NetLink) LinkDel(link Link) (err error) {
panic("not implemented")
}
func (n *NetLink) LinkSetUp(link Link) (linkIndex int, err error) {
panic("not implemented")
}
func (n *NetLink) LinkSetDown(link Link) (err error) {
panic("not implemented")
}
+31
View File
@@ -0,0 +1,31 @@
//go:build !linux
package netlink
const (
// FamilyAll is a placeholder only and should not
// be used.
FamilyAll = iota
// FamilyV4 is a placeholder only and should not
// be used.
FamilyV4
// FamilyV6 is a placeholder only and should not
// be used.
FamilyV6
)
func (n *NetLink) RuleList(family int) (rules []Rule, err error) {
panic("not implemented")
}
func (n *NetLink) RuleAdd(rule Rule) error {
panic("not implemented")
}
func (n *NetLink) RuleDel(rule Rule) error {
panic("not implemented")
}
func (n *NetLink) IsWireguardSupported() bool {
panic("not implemented")
}
-2
View File
@@ -1,5 +1,3 @@
//go:build linux || darwin
package netlink
import (
-21
View File
@@ -1,21 +0,0 @@
//go:build !linux && !darwin
package netlink
func (n *NetLink) RouteList(family int) (
routes []Route, err error,
) {
panic("not implemented")
}
func (n *NetLink) RouteAdd(route Route) error {
panic("not implemented")
}
func (n *NetLink) RouteDel(route Route) error {
panic("not implemented")
}
func (n *NetLink) RouteReplace(route Route) error {
panic("not implemented")
}
-36
View File
@@ -1,5 +1,3 @@
//go:build linux
package netlink
import (
@@ -18,40 +16,6 @@ func NewRule() Rule {
}
}
func (n *NetLink) RuleList(family int) (rules []Rule, err error) {
switch family {
case FamilyAll:
n.debugLogger.Debug("ip -4 rule list")
n.debugLogger.Debug("ip -6 rule list")
case FamilyV4:
n.debugLogger.Debug("ip -4 rule list")
case FamilyV6:
n.debugLogger.Debug("ip -6 rule list")
}
netlinkRules, err := netlink.RuleList(family)
if err != nil {
return nil, err
}
rules = make([]Rule, len(netlinkRules))
for i := range netlinkRules {
rules[i] = netlinkRuleToRule(netlinkRules[i])
}
return rules, nil
}
func (n *NetLink) RuleAdd(rule Rule) error {
n.debugLogger.Debug(ruleDbgMsg(true, rule))
netlinkRule := ruleToNetlinkRule(rule)
return netlink.RuleAdd(&netlinkRule)
}
func (n *NetLink) RuleDel(rule Rule) error {
n.debugLogger.Debug(ruleDbgMsg(false, rule))
netlinkRule := ruleToNetlinkRule(rule)
return netlink.RuleDel(&netlinkRule)
}
func ruleToNetlinkRule(rule Rule) (netlinkRule netlink.Rule) {
netlinkRule = *netlink.NewRule()
netlinkRule.Priority = rule.Priority
+37
View File
@@ -0,0 +1,37 @@
package netlink
import "github.com/vishvananda/netlink"
func (n *NetLink) RuleList(family int) (rules []Rule, err error) {
switch family {
case FamilyAll:
n.debugLogger.Debug("ip -4 rule list")
n.debugLogger.Debug("ip -6 rule list")
case FamilyV4:
n.debugLogger.Debug("ip -4 rule list")
case FamilyV6:
n.debugLogger.Debug("ip -6 rule list")
}
netlinkRules, err := netlink.RuleList(family)
if err != nil {
return nil, err
}
rules = make([]Rule, len(netlinkRules))
for i := range netlinkRules {
rules[i] = netlinkRuleToRule(netlinkRules[i])
}
return rules, nil
}
func (n *NetLink) RuleAdd(rule Rule) error {
n.debugLogger.Debug(ruleDbgMsg(true, rule))
netlinkRule := ruleToNetlinkRule(rule)
return netlink.RuleAdd(&netlinkRule)
}
func (n *NetLink) RuleDel(rule Rule) error {
n.debugLogger.Debug(ruleDbgMsg(false, rule))
netlinkRule := ruleToNetlinkRule(rule)
return netlink.RuleDel(&netlinkRule)
}
-19
View File
@@ -1,19 +0,0 @@
//go:build !linux
package netlink
func NewRule() Rule {
return Rule{}
}
func (n *NetLink) RuleList(family int) (rules []Rule, err error) {
panic("not implemented")
}
func (n *NetLink) RuleAdd(rule Rule) error {
panic("not implemented")
}
func (n *NetLink) RuleDel(rule Rule) error {
panic("not implemented")
}
@@ -1,5 +1,3 @@
//go:build linux
package netlink
import (
@@ -1,7 +0,0 @@
//go:build !linux
package netlink
func (n *NetLink) IsWireguardSupported() (ok bool, err error) {
panic("not implemented")
}
+1 -2
View File
@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"os/exec"
"syscall"
"github.com/qdm12/gluetun/internal/constants/openvpn"
)
@@ -33,7 +32,7 @@ func start(ctx context.Context, starter CmdStarter, version string, flags []stri
args := []string{"--config", configPath}
args = append(args, flags...)
cmd := exec.CommandContext(ctx, bin, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
setCmdSysProcAttr(cmd)
return starter.Start(cmd)
}
+10
View File
@@ -0,0 +1,10 @@
package openvpn
import (
"os/exec"
"syscall"
)
func setCmdSysProcAttr(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
+12
View File
@@ -0,0 +1,12 @@
//go:build !linux
package openvpn
import (
"os/exec"
"syscall"
)
func setCmdSysProcAttr(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
+1 -1
View File
@@ -13,7 +13,7 @@ var (
ErrICMPNextHopMTUTooHigh = errors.New("ICMP Next Hop MTU is too high")
)
func checkMTU(mtu, minMTU, physicalLinkMTU int) (err error) {
func checkMTU(mtu, minMTU, physicalLinkMTU uint32) (err error) {
switch {
case mtu < minMTU:
return fmt.Errorf("%w: %d", ErrICMPNextHopMTUTooLow, mtu)
-2
View File
@@ -1,5 +1,3 @@
//go:build linux
package pmtud
import (
+5 -5
View File
@@ -17,8 +17,8 @@ import (
const (
// see https://en.wikipedia.org/wiki/Maximum_transmission_unit#MTUs_for_common_media
minIPv4MTU = 68
icmpv4Protocol = 1
minIPv4MTU uint32 = 68
icmpv4Protocol int = 1
)
func listenICMPv4(ctx context.Context) (conn net.PacketConn, err error) {
@@ -51,8 +51,8 @@ func listenICMPv4(ctx context.Context) (conn net.PacketConn, err error) {
}
func findIPv4NextHopMTU(ctx context.Context, ip netip.Addr,
physicalLinkMTU int, pingTimeout time.Duration, logger Logger,
) (mtu int, err error) {
physicalLinkMTU uint32, pingTimeout time.Duration, logger Logger,
) (mtu uint32, err error) {
if ip.Is6() {
panic("IP address is not v4")
}
@@ -124,7 +124,7 @@ func findIPv4NextHopMTU(ctx context.Context, ip netip.Addr,
// See https://datatracker.ietf.org/doc/html/rfc1191#section-4
// Note: the go library does not handle this NextHopMTU section.
nextHopMTU := packetBytes[6:8]
mtu = int(binary.BigEndian.Uint16(nextHopMTU))
mtu = uint32(binary.BigEndian.Uint16(nextHopMTU))
err = checkMTU(mtu, minIPv4MTU, physicalLinkMTU)
if err != nil {
return 0, fmt.Errorf("checking next-hop-mtu found: %w", err)
+4 -4
View File
@@ -31,8 +31,8 @@ func listenICMPv6(ctx context.Context) (conn net.PacketConn, err error) {
}
func getIPv6PacketTooBig(ctx context.Context, ip netip.Addr,
physicalLinkMTU int, pingTimeout time.Duration, logger Logger,
) (mtu int, err error) {
physicalLinkMTU uint32, pingTimeout time.Duration, logger Logger,
) (mtu uint32, err error) {
if ip.Is4() {
panic("IP address is not v6")
}
@@ -84,7 +84,7 @@ func getIPv6PacketTooBig(ctx context.Context, ip netip.Addr,
switch typedBody := inboundMessage.Body.(type) {
case *icmp.PacketTooBig:
// https://datatracker.ietf.org/doc/html/rfc1885#section-3.2
mtu = typedBody.MTU
mtu = uint32(typedBody.MTU) //nolint:gosec
err = checkMTU(mtu, minIPv6MTU, physicalLinkMTU)
if err != nil {
return 0, fmt.Errorf("checking MTU: %w", err)
@@ -96,7 +96,7 @@ func getIPv6PacketTooBig(ctx context.Context, ip netip.Addr,
if err != nil {
return 0, fmt.Errorf("checking invoking message: %w", err)
}
return typedBody.MTU, nil
return uint32(typedBody.MTU), nil //nolint:gosec
case *icmp.DstUnreach:
// https://datatracker.ietf.org/doc/html/rfc1885#section-3.1
idMatch, err := checkInvokingReplyIDMatch(icmpv6Protocol, packetBytes, outboundMessage)
+2 -2
View File
@@ -11,7 +11,7 @@ import (
"golang.org/x/net/ipv6"
)
func buildMessageToSend(ipVersion string, mtu int) (id uint16, message *icmp.Message) {
func buildMessageToSend(ipVersion string, mtu uint32) (id uint16, message *icmp.Message) {
var seed [32]byte
_, _ = cryptorand.Read(seed[:])
randomSource := rand.NewChaCha8(seed)
@@ -21,7 +21,7 @@ func buildMessageToSend(ipVersion string, mtu int) (id uint16, message *icmp.Mes
_, _ = randomSource.Read(idBytes)
id = binary.BigEndian.Uint16(idBytes)
var ipHeaderLength int
var ipHeaderLength uint32
var icmpType icmp.Type
switch ipVersion {
case "v4":
+9 -9
View File
@@ -21,8 +21,8 @@ var ErrMTUNotFound = errors.New("path MTU discovery failed to find MTU")
// If the logger is nil, a no-op logger is used.
// It returns [ErrMTUNotFound] if the MTU could not be determined.
func PathMTUDiscover(ctx context.Context, ip netip.Addr,
physicalLinkMTU int, pingTimeout time.Duration, logger Logger) (
mtu int, err error,
physicalLinkMTU uint32, pingTimeout time.Duration, logger Logger) (
mtu uint32, err error,
) {
if physicalLinkMTU == 0 {
const ethernetStandardMTU = 1500
@@ -68,16 +68,16 @@ func PathMTUDiscover(ctx context.Context, ip netip.Addr,
}
type pmtudTestUnit struct {
mtu int
mtu uint32
echoID uint16
sentBytes int
ok bool
}
func pmtudMultiSizes(ctx context.Context, ip netip.Addr,
minMTU, maxPossibleMTU int, pingTimeout time.Duration,
minMTU, maxPossibleMTU uint32, pingTimeout time.Duration,
logger Logger,
) (maxMTU int, err error) {
) (maxMTU uint32, err error) {
var ipVersion string
var conn net.PacketConn
if ip.Is4() {
@@ -164,22 +164,22 @@ func pmtudMultiSizes(ctx context.Context, ip netip.Addr,
// with a total search space of 1728 MTUs which is enough;
// to find it in 2 searches requires 37 parallel queries which
// could be blocked by firewalls.
func makeMTUsToTest(minMTU, maxMTU int) (mtus []int) {
func makeMTUsToTest(minMTU, maxMTU uint32) (mtus []uint32) {
const mtusLength = 11 // find the final MTU in 3 searches
diff := maxMTU - minMTU
switch {
case minMTU > maxMTU:
panic("minMTU > maxMTU")
case diff <= mtusLength:
mtus = make([]int, 0, diff)
mtus = make([]uint32, 0, diff)
for mtu := minMTU; mtu <= maxMTU; mtu++ {
mtus = append(mtus, mtu)
}
default:
step := float64(diff) / float64(mtusLength-1)
mtus = make([]int, 0, mtusLength)
mtus = make([]uint32, 0, mtusLength)
for mtu := float64(minMTU); len(mtus) < mtusLength-1; mtu += step {
mtus = append(mtus, int(math.Round(mtu)))
mtus = append(mtus, uint32(math.Round(mtu)))
}
mtus = append(mtus, maxMTU) // last element is the maxMTU
}
+10 -10
View File
@@ -10,37 +10,37 @@ func Test_makeMTUsToTest(t *testing.T) {
t.Parallel()
testCases := map[string]struct {
minMTU int
maxMTU int
mtus []int
minMTU uint32
maxMTU uint32
mtus []uint32
}{
"0_0": {
mtus: []int{0},
mtus: []uint32{0},
},
"0_1": {
maxMTU: 1,
mtus: []int{0, 1},
mtus: []uint32{0, 1},
},
"0_8": {
maxMTU: 8,
mtus: []int{0, 1, 2, 3, 4, 5, 6, 7, 8},
mtus: []uint32{0, 1, 2, 3, 4, 5, 6, 7, 8},
},
"0_12": {
maxMTU: 12,
mtus: []int{0, 1, 2, 4, 5, 6, 7, 8, 10, 11, 12},
mtus: []uint32{0, 1, 2, 4, 5, 6, 7, 8, 10, 11, 12},
},
"0_80": {
maxMTU: 80,
mtus: []int{0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80},
mtus: []uint32{0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80},
},
"0_100": {
maxMTU: 100,
mtus: []int{0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
mtus: []uint32{0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100},
},
"1280_1500": {
minMTU: 1280,
maxMTU: 1500,
mtus: []int{1280, 1302, 1324, 1346, 1368, 1390, 1412, 1434, 1456, 1478, 1500},
mtus: []uint32{1280, 1302, 1324, 1346, 1368, 1390, 1412, 1434, 1456, 1478, 1500},
},
}
+1 -2
View File
@@ -6,7 +6,6 @@ import (
"net/netip"
"github.com/qdm12/gluetun/internal/netlink"
"golang.org/x/sys/unix"
)
var ErrRouteDefaultNotFound = errors.New("default route not found")
@@ -30,7 +29,7 @@ func (r *Routing) DefaultRoutes() (defaultRoutes []DefaultRoute, err error) {
}
for _, route := range routes {
if route.Table != unix.RT_TABLE_MAIN {
if route.Table != tableMain {
// ignore non-main table
continue
}
+1 -2
View File
@@ -6,7 +6,6 @@ import (
"net/netip"
"github.com/qdm12/gluetun/internal/netlink"
"golang.org/x/sys/unix"
)
var (
@@ -48,7 +47,7 @@ func (r *Routing) LocalNetworks() (localNetworks []LocalNetwork, err error) {
}
for _, route := range routes {
if route.Table != unix.RT_TABLE_MAIN ||
if route.Table != tableMain ||
(route.Gw.IsValid() && !route.Gw.IsUnspecified()) ||
(route.Dst.IsValid() && route.Dst.Addr().IsUnspecified()) {
continue
+8
View File
@@ -0,0 +1,8 @@
package routing
import "golang.org/x/sys/unix"
const (
tableMain = unix.RT_TABLE_MAIN
tableLocal = unix.RT_TABLE_LOCAL
)
+8
View File
@@ -0,0 +1,8 @@
//go:build !linux
package routing
const (
tableMain = 0
tableLocal = 0
)
+1 -2
View File
@@ -6,7 +6,6 @@ import (
"net/netip"
"github.com/qdm12/gluetun/internal/netlink"
"golang.org/x/sys/unix"
)
var (
@@ -35,7 +34,7 @@ func (r *Routing) VPNLocalGatewayIP(vpnIntf string) (ip netip.Addr, err error) {
return route.Gw, nil
case route.Dst.IsSingleIP() &&
route.Dst.Addr().Compare(route.Src) == 0 &&
route.Table == unix.RT_TABLE_LOCAL: // Wireguard
route.Table == tableLocal: // Wireguard
route.Src = route.Src.Unmap()
if route.Src.Is6() {
return netip.Addr{}, fmt.Errorf("%w: %s", ErrVPNLocalGatewayIPv6NotSupported, route.Src)
+1 -1
View File
@@ -81,7 +81,7 @@ type Linker interface {
LinkDel(link netlink.Link) (err error)
LinkSetUp(link netlink.Link) (linkIndex int, err error)
LinkSetDown(link netlink.Link) (err error)
LinkSetMTU(link netlink.Link, mtu int) (err error)
LinkSetMTU(link netlink.Link, mtu uint32) (err error)
}
type DNSLoop interface {
+2 -2
View File
@@ -157,7 +157,7 @@ func updateToMaxMTU(ctx context.Context, vpnInterface string,
// Note: no point testing for an MTU of 1500, it will never work due to the VPN
// protocol overhead, so start lower than 1500 according to the protocol used.
const physicalLinkMTU = 1500
const physicalLinkMTU uint32 = 1500
vpnLinkMTU := physicalLinkMTU
switch vpnType {
case "wireguard":
@@ -183,7 +183,7 @@ func updateToMaxMTU(ctx context.Context, vpnInterface string,
case err == nil:
logger.Infof("setting VPN interface %s MTU to maximum valid MTU %d", vpnInterface, vpnLinkMTU)
case errors.Is(err, pmtud.ErrMTUNotFound) || errors.Is(err, pmtud.ErrICMPNotPermitted):
vpnLinkMTU = int(originalMTU)
vpnLinkMTU = uint32(originalMTU)
logger.Infof("reverting VPN interface %s MTU to %d (due to: %s)",
vpnInterface, originalMTU, err)
default:
+4 -6
View File
@@ -7,10 +7,8 @@ import (
"net"
"github.com/qdm12/gluetun/internal/netlink"
"golang.org/x/sys/unix"
"golang.zx2c4.com/wireguard/conn"
"golang.zx2c4.com/wireguard/device"
"golang.zx2c4.com/wireguard/ipc"
"golang.zx2c4.com/wireguard/tun"
"golang.zx2c4.com/wireguard/wgctrl"
)
@@ -106,7 +104,7 @@ func (w *Wireguard) Run(ctx context.Context, waitError chan<- error, ready chan<
if *w.settings.IPv6 {
// requires net.ipv6.conf.all.disable_ipv6=0
ruleCleanup6, err := w.addRule(w.settings.RulePriority,
w.settings.FirewallMark, unix.AF_INET6)
w.settings.FirewallMark, netlink.FamilyV6)
if err != nil {
waitError <- fmt.Errorf("adding IPv6 rule: %w", err)
return
@@ -115,7 +113,7 @@ func (w *Wireguard) Run(ctx context.Context, waitError chan<- error, ready chan<
}
ruleCleanup, err := w.addRule(w.settings.RulePriority,
w.settings.FirewallMark, unix.AF_INET)
w.settings.FirewallMark, netlink.FamilyV4)
if err != nil {
waitError <- fmt.Errorf("adding IPv4 rule: %w", err)
return
@@ -217,14 +215,14 @@ func setupUserSpace(ctx context.Context,
return nil
})
uapiFile, err := ipc.UAPIOpen(interfaceName)
uapiFile, err := uapiOpen(interfaceName)
if err != nil {
return link, nil, fmt.Errorf("%w: %s", ErrUAPISocketOpening, err)
}
closers.add("closing UAPI file", stepThree, uapiFile.Close)
uapiListener, err := ipc.UAPIListen(interfaceName, uapiFile)
uapiListener, err := uapiListen(interfaceName, uapiFile)
if err != nil {
return link, nil, fmt.Errorf("%w: %s", ErrUAPIListen, err)
}
+16
View File
@@ -0,0 +1,16 @@
package wireguard
import (
"net"
"os"
"golang.zx2c4.com/wireguard/ipc"
)
func uapiOpen(name string) (*os.File, error) {
return ipc.UAPIOpen(name)
}
func uapiListen(interfaceName string, uapiFile *os.File) (net.Listener, error) {
return ipc.UAPIListen(interfaceName, uapiFile)
}
@@ -0,0 +1,16 @@
//go:build !linux
package wireguard
import (
"net"
"os"
)
func uapiOpen(name string) (*os.File, error) {
panic("not implemented")
}
func uapiListen(interfaceName string, uapiFile *os.File) (net.Listener, error) {
panic("not implemented")
}