Use all your internet connections at once on Windows, macOS, Linux and Android: per-connection load balancing over Wi-Fi, Ethernet, mobile data and phone tethers
Go androidbandwidth-aggregationdownloadergolanglinuxload-balancingmacosnet-mergenetworkingtetheringtunwifiwindowswintun
Windows: keep pinned connections working on weak host / forwarding adapters (#10) (#22)
Rohit Mahtoe5340f8d9e0f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f15fe5b..54854ee 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -91,6 +91,22 @@ jobs:if: always()run: cat /tmp/net-merge-smoke*.log 2>/dev/null || true+ # System-wide mode for real, as admin: Wintun, routes, the internet probe over pinned sockets,+ # relaying and off; also with the NIC demoted to secondary and with weak host send/forwarding on.+ windows-smoke:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: go.mod+ - shell: pwsh+ run: |+ scripts/fetch-wintun.ps1 -OutDir dist+ go build -o dist/net-merge.exe ./cmd/net-merge+ go build -o dist/winfakeup.exe ./scripts/winfakeup+ scripts/windows-smoke.ps1 dist\net-merge.exe+# The Linux packages for every CPU and the apt, dnf/zypper, Alpine and Arch repositories, tried for# real: build them, serve them on localhost, then install net-merge from them on Ubuntu (here),# Debian, Fedora, Rocky, openSUSE, Alpine and Arch.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c850e2f..b934789 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -18,6 +18,12 @@ entry here before pushing a version tag.Windows line and every manual way.### Fixed+- **Windows: turning on merging could stop all internet, with every adapter showing "no internet"**+ (#10). On an adapter with *weak host send* or *forwarding* turned on, which Mobile Hotspot, Internet+ Connection Sharing, Hyper-V and some VPNs do, Windows ignores the adapter a connection is pinned to, so+ net-merge's own connections went back into its virtual adapter. While merging, net-merge now turns those+ two settings off on the adapters it uses and puts them back afterwards (sharing that connection pauses+ meanwhile). It also re-applies its virtual adapter's address when Windows drops it right after start.- `sudo net-merge install` refused on Macs where `/usr/local/bin` is writable by your user (Intel Macswith Homebrew). It now puts its root-owned copy in `/opt/net-merge/bin` there, and links `net-merge` into`/usr/local/bin`.diff --git a/internal/tun/tun_windows.go b/internal/tun/tun_windows.goindex 77d4279..f258516 100644--- a/internal/tun/tun_windows.go+++ b/internal/tun/tun_windows.go@@ -3,9 +3,12 @@ package tunimport ("fmt""net"+ "os""os/exec"+ "path/filepath""strconv""strings"+ "sync""syscall""time"@@ -13,6 +16,7 @@ import (wun "golang.zx2c4.com/wireguard/tun""net-merge/internal/logx"+ "net-merge/internal/nics")const openHint = "needs admin and wintun.dll next to net-merge.exe"@@ -21,6 +25,7 @@ const openHint = "needs admin and wintun.dll next to net-merge.exe"var routes4win = [][2]string{{"0.0.0.0", "128.0.0.0"}, {"128.0.0.0", "128.0.0.0"}}func init() {+ staleHook = restoreStrongHostwun.WintunTunnelType = "net-merge"// A fixed GUID keeps one Windows network profile instead of a new "Unidentified network" per run.if g, err := windows.GUIDFromString("{3f0d5a7e-9b1c-4e52-8a47-1c6b2d9e5f30}"); err == nil {@@ -38,6 +43,20 @@ func configure(name string, mtu int) (int, error) {if err != nil {return 0, err}+ // Windows now and then drops an address set the moment the adapter appears, and without it+ // nothing routed into the adapter can be sent (all traffic dies), so make sure it stuck.+ for try := 1; !hasAddr(ifc, tunIP); try++ {+ if try > 20 {+ return ifc.Index, fmt.Errorf("adapter %q did not keep its address %s", name, tunIP)+ }+ if try%4 == 0 {+ run("netsh", "interface", "ipv4", "set", "address", "name="+name, "source=static",+ "address="+tunIP, "mask="+tunMask, "store=active")+ }+ time.Sleep(250 * time.Millisecond)+ }+ // Before the capture routes: our pinned sockets must keep working the moment they exist.+ startStrongHost(ifc.Index)// Windows gives Wintun adapters an MTU of 65535. Match the stack's MTU, so Windows sizes TCP// segments to it and fragments bigger UDP datagrams instead of sending packets the stack drops.idx := strconv.Itoa(ifc.Index)@@ -67,6 +86,7 @@ func configure(name string, mtu int) (int, error) {}func delRoutes(idx int) {+ defer stopStrongHost()for _, dst := range routes4win {run("route", "delete", dst[0], "mask", dst[1], "0.0.0.0", "if", strconv.Itoa(idx))}@@ -98,3 +118,127 @@ func waitIface(name string, d time.Duration) (*net.Interface, error) {time.Sleep(50 * time.Millisecond)}}++func hasAddr(ifc *net.Interface, ip string) bool {+ addrs, _ := ifc.Addrs()+ for _, a := range addrs {+ if n, ok := a.(*net.IPNet); ok && n.IP.String() == ip {+ return true+ }+ }+ return false+}++// On an adapter with weak host send or forwarding turned on (Mobile Hotspot, Internet Connection+// Sharing, Hyper-V and some VPNs do that), Windows ignores a socket's bound address and+// IP_UNICAST_IF and routes by destination only, so once the capture routes exist our own pinned+// flows go back into the TUN: every adapter shows "no internet" and all traffic stops. While+// capture is on, both are turned off on the adapters we use, and put back on off, or on the next+// start after a crash (the file below remembers them).+var strongHost struct {+ mu sync.Mutex+ checked map[int]bool+ restore []string // "family index weakhostsend=X forwarding=Y", to put back+ stop chan struct{}+}++var strongHostFile = filepath.Join(os.TempDir(), "net-merge-weakhost.txt")++func startStrongHost(tunIdx int) {+ stop := make(chan struct{})+ strongHost.mu.Lock()+ strongHost.checked, strongHost.restore, strongHost.stop = map[int]bool{tunIdx: true}, nil, stop+ strongHost.mu.Unlock()+ syncStrongHost(stop)+ go func() {+ t := time.NewTicker(5 * time.Second) // a tether plugged in later+ defer t.Stop()+ for {+ select {+ case <-stop:+ return+ case <-t.C:+ syncStrongHost(stop)+ }+ }+ }()+}++func syncStrongHost(stop chan struct{}) {+ found, _ := nics.DiscoverNics(nil, nil)+ strongHost.mu.Lock()+ defer strongHost.mu.Unlock()+ if strongHost.stop != stop {+ return // capture was switched off meanwhile+ }+ var idx []string+ for _, n := range found {+ if !strongHost.checked[n.Index] {+ strongHost.checked[n.Index] = true+ idx = append(idx, strconv.Itoa(n.Index))+ }+ }+ if len(idx) == 0 {+ return+ }+ // Get-NetIPInterface prints enum names, which unlike netsh's output are not translated.+ out, err := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command",+ "Get-NetIPInterface -InterfaceIndex "+strings.Join(idx, ",")+" -ErrorAction SilentlyContinue | "++ "Where-Object { $_.WeakHostSend -eq 'Enabled' -or $_.Forwarding -eq 'Enabled' } | "++ "ForEach-Object { '{0} {1} {2} {3}' -f $_.AddressFamily, $_.InterfaceIndex, $_.WeakHostSend, $_.Forwarding }").Output()+ if err != nil {+ logx.Printf("warning: could not check the adapters' weak host setting: %v\n", err)+ return+ }+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {+ f := strings.Fields(line) // IPv4 14 Enabled Disabled+ if len(f) != 4 {+ continue+ }+ fam := strings.ToLower(f[0])+ if fam != "ipv4" && fam != "ipv6" {+ continue+ }+ if err := run("netsh", "interface", fam, "set", "interface", "interface="+f[1],+ "weakhostsend=disabled", "forwarding=disabled", "store=active"); err != nil {+ logx.Printf("warning: %v\n", err)+ continue+ }+ strongHost.restore = append(strongHost.restore, fmt.Sprintf("%s %s weakhostsend=%s forwarding=%s",+ fam, f[1], strings.ToLower(f[2]), strings.ToLower(f[3])))+ logx.Printf("note: turned off weak host send and forwarding on adapter %s (%s) while merging; "++ "Windows ignores pinned connections there. Sharing its connection (Mobile Hotspot) pauses until net-merge is off.\n", f[1], f[0])+ }+ os.WriteFile(strongHostFile, []byte(strings.Join(strongHost.restore, "\n")), 0o600)+}++func stopStrongHost() {+ strongHost.mu.Lock()+ defer strongHost.mu.Unlock()+ if strongHost.stop != nil {+ close(strongHost.stop)+ strongHost.stop = nil+ }+ putBack(strongHost.restore)+ strongHost.restore = nil+ os.Remove(strongHostFile)+}++// restoreStrongHost puts back what a crashed run turned off.+func restoreStrongHost() {+ b, err := os.ReadFile(strongHostFile)+ if err != nil {+ return+ }+ putBack(strings.Split(strings.TrimSpace(string(b)), "\n"))+ os.Remove(strongHostFile)+}++func putBack(lines []string) {+ for _, l := range lines {+ f := strings.Fields(l) // ipv4 14 weakhostsend=enabled forwarding=disabled+ if len(f) == 4 {+ run("netsh", "interface", f[0], "set", "interface", "interface="+f[1], f[2], f[3], "store=active")+ }+ }+}diff --git a/scripts/windows-smoke.ps1 b/scripts/windows-smoke.ps1new file mode 100644index 0000000..a867613--- /dev/null+++ b/scripts/windows-smoke.ps1@@ -0,0 +1,116 @@+# Smoke test of system-wide mode on Windows (CI runs it on windows-latest, as admin). The runner has+# one NIC, so this checks the TUN, routes, the per-adapter internet probe over pinned sockets while+# capture is on, relaying, and off; not balancing.+#+# usage: scripts/windows-smoke.ps1 dist\net-merge.exe+param([string]$Bin = 'dist\net-merge.exe')+$ErrorActionPreference = 'Continue'+$Bin = (Resolve-Path $Bin).Path+$state = Join-Path $env:TEMP 'net-merge-smoke'+$script:fails = 0+function Pass($m) { Write-Host "PASS $m" }+function Fail($m) { Write-Host "FAIL $m"; $script:fails++ }+function Http { try { (Invoke-WebRequest https://example.com -UseBasicParsing -TimeoutSec 10).StatusCode } catch { 0 } }++# A TCP connect to 1.1.1.1:443 the way net-merge pins its sockets: bound to the adapter's address,+# with IP_UNICAST_IF (31) set to its index, or only one of the two.+function Pinned([string]$src, [int]$idx) {+ $s = New-Object Net.Sockets.Socket([Net.Sockets.AddressFamily]::InterNetwork, [Net.Sockets.SocketType]::Stream, [Net.Sockets.ProtocolType]::Tcp)+ try {+ if ($idx -gt 0) { $s.SetSocketOption([Net.Sockets.SocketOptionLevel]::IP, [Net.Sockets.SocketOptionName]31, [Net.IPAddress]::HostToNetworkOrder($idx)) }+ if ($src) { $s.Bind((New-Object Net.IPEndPoint([Net.IPAddress]::Parse($src), 0))) }+ $r = $s.BeginConnect('1.1.1.1', 443, $null, $null)+ return ($r.AsyncWaitHandle.WaitOne(3000) -and $s.Connected)+ } catch { return $false } finally { $s.Close() }+}++$nic = Get-NetIPConfiguration | Where-Object { $_.IPv4DefaultGateway } | Select-Object -First 1+$ip = $nic.IPv4Address.IPAddress; $idx = $nic.InterfaceIndex+Write-Host "== real adapter: $($nic.InterfaceAlias) $ip (index $idx)"+& $Bin list+Write-Host (" pinned connects before: bind+if {0}, bind {1}, if {2}" -f (Pinned $ip $idx), (Pinned $ip 0), (Pinned '' $idx))++Write-Host '== system-wide ON'+Remove-Item -Recurse -Force $state -ErrorAction SilentlyContinue+$p = Start-Process $Bin -ArgumentList 'run', '-state-dir', $state, '-log', "$state\net-merge.log", '-stats', '0', '-for', '150s' -PassThru -WindowStyle Hidden+for ($i = 0; $i -lt 60 -and -not ((& $Bin status -state-dir $state 2>$null | Out-String) -match 'is ON'); $i++) { Start-Sleep -Milliseconds 500 }+Start-Sleep 6 # let the internet probes run+$status = & $Bin status -state-dir $state | Out-String+Write-Host $status+if ($status -match 'is ON') { Pass 'net-merge turned on' } else { Fail 'net-merge did not turn on' }+route print -4 | Select-String ' 0.0.0.0 | 128.0.0.0 '+function TunAddr { Get-NetIPAddress -InterfaceAlias 'net-merge' -AddressFamily IPv4 -ErrorAction SilentlyContinue | ForEach-Object { "$($_.IPAddress)/$($_.AddressState)" } }+Write-Host " TUN IPv4 address: [$(TunAddr)] interface: $((Get-NetIPInterface -InterfaceAlias 'net-merge' -AddressFamily IPv4 -ErrorAction SilentlyContinue).ConnectionState)"+Write-Host (" pinned connects while ON: bind+if {0}, bind {1}, if {2}" -f (Pinned $ip $idx), (Pinned $ip 0), (Pinned '' $idx))+if ($status -match 'v4 up') { Pass 'the adapter probe reaches the internet over its pinned socket while capture is on' }+else { Fail 'the adapter probe fails while capture is on' }+$code = Http+if ($code -ne 200) {+ for ($i = 0; $i -lt 6 -and $code -ne 200; $i++) { Start-Sleep 5; $code = Http; Write-Host " retry $i HTTPS $code, TUN IPv4 address: [$(TunAddr)]" }+}+if ($code -eq 200) { Pass 'HTTPS works through net-merge' } else { Fail 'HTTPS through net-merge' }++Write-Host '== off'+& $Bin off -state-dir $state+Start-Sleep 3+if (-not (route print -4 | Select-String ' 128.0.0.0 ')) { Pass 'capture routes removed' } else { Fail 'capture routes left behind' }+if ((Http) -eq 200) { Pass 'internet works after off' } else { Fail 'internet after off' }+if (-not $p.HasExited) { Stop-Process $p -Force }+# ---- weak host send and forwarding on the real NIC (Mobile Hotspot, ICS and Hyper-V turn these on):+# Windows then ignores pinned sockets, so net-merge turns both off while merging and puts them back.+Write-Host '== weak host send + forwarding on the real NIC'+Set-NetIPInterface -InterfaceIndex $idx -AddressFamily IPv4 -WeakHostSend Enabled -Forwarding Enabled+Remove-Item -Recurse -Force "$state-w" -ErrorAction SilentlyContinue+$pw = Start-Process $Bin -ArgumentList "run -state-dir `"$state-w`" -log `"$state-w\net-merge.log`" -stats 0 -for 40s" -PassThru -WindowStyle Hidden+for ($i = 0; $i -lt 60 -and -not ((& $Bin status -state-dir "$state-w" 2>$null | Out-String) -match 'is ON'); $i++) { Start-Sleep -Milliseconds 500 }+Start-Sleep 6+$statusw = & $Bin status -state-dir "$state-w" | Out-String+Write-Host $statusw+Get-NetIPInterface -InterfaceIndex $idx -AddressFamily IPv4 | Format-Table -AutoSize InterfaceAlias, WeakHostSend, Forwarding | Out-String | Write-Host+if ($statusw -match 'v4 up') { Pass 'weak host adapter: the probe works while capture is on' } else { Fail 'weak host adapter: the probe fails while capture is on' }+if ((Http) -eq 200) { Pass 'weak host adapter: HTTPS works through net-merge' } else { Fail 'weak host adapter: HTTPS through net-merge' }+& $Bin off -state-dir "$state-w"+if (-not $pw.HasExited) { Stop-Process $pw -Force }+Start-Sleep 2+$after = Get-NetIPInterface -InterfaceIndex $idx -AddressFamily IPv4+if ($after.WeakHostSend -eq 'Enabled' -and $after.Forwarding -eq 'Enabled') { Pass 'off put weak host send and forwarding back' }+else { Fail "off did not put the settings back (weak host send $($after.WeakHostSend), forwarding $($after.Forwarding))" }+Get-Content "$state-w\net-merge.log" -ErrorAction SilentlyContinue | Select-String 'weak host'+Set-NetIPInterface -InterfaceIndex $idx -AddressFamily IPv4 -WeakHostSend Disabled -Forwarding Disabled+Start-Sleep 2++# ---- the real NIC as a secondary adapter: a fake adapter's default route wins (for about a minute)+Write-Host '== secondary adapter: a fake adapter holds the best default route'+$fake = Start-Process (Join-Path (Split-Path $Bin) 'winfakeup.exe') -ArgumentList '75s' -PassThru -WindowStyle Hidden -RedirectStandardOutput "$env:TEMP\fakeup.log"+for ($i = 0; $i -lt 40 -and -not (Get-NetAdapter -Name fakeup -ErrorAction SilentlyContinue); $i++) { Start-Sleep -Milliseconds 500 }+Start-Sleep 3+Set-NetIPInterface -InterfaceIndex $idx -AddressFamily IPv4 -InterfaceMetric 50+Start-Sleep 2+route print -4 | Select-String ' 0.0.0.0 '+Write-Host (" secondary, net-merge off: bind+if {0}, bind {1}, if {2}" -f (Pinned $ip $idx), (Pinned $ip 0), (Pinned '' $idx))+Remove-Item -Recurse -Force "$state-2" -ErrorAction SilentlyContinue+# one string: Start-Process does not quote list items, and the adapter name has a space+$p2 = Start-Process $Bin -ArgumentList "run -include `"$($nic.InterfaceAlias)`" -state-dir `"$state-2`" -log `"$state-2\net-merge.log`" -stats 0 -for 40s" -PassThru -WindowStyle Hidden+for ($i = 0; $i -lt 60 -and -not ((& $Bin status -state-dir "$state-2" 2>$null | Out-String) -match 'is ON'); $i++) { Start-Sleep -Milliseconds 500 }+Start-Sleep 6+$status2 = & $Bin status -state-dir "$state-2" | Out-String+Write-Host $status2+Write-Host (" secondary, net-merge ON: bind+if {0}, bind {1}, if {2}" -f (Pinned $ip $idx), (Pinned $ip 0), (Pinned '' $idx))+if ($status2 -match 'v4 up') { Pass 'a secondary adapter reaches the internet over its pinned socket while capture is on' }+else { Fail 'a secondary adapter fails its probe while capture is on' }+if ((Http) -eq 200) { Pass 'HTTPS works through net-merge over the secondary adapter' } else { Fail 'HTTPS through net-merge over the secondary adapter' }+& $Bin off -state-dir "$state-2"+if (-not $p2.HasExited) { Stop-Process $p2 -Force }+if (-not $fake.HasExited) { Stop-Process $fake -Force }+Set-NetIPInterface -InterfaceIndex $idx -AddressFamily IPv4 -AutomaticMetric Enabled+Start-Sleep 3+if ((Http) -eq 200) { Pass 'internet works again after the secondary-adapter test' } else { Fail 'internet after the secondary-adapter test' }+Get-Content "$env:TEMP\fakeup.log" -ErrorAction SilentlyContinue+Get-Content "$state-2\net-merge.log" -ErrorAction SilentlyContinue | Select-Object -Last 20++Write-Host '== net-merge log'+Get-Content "$state\net-merge.log" -ErrorAction SilentlyContinue | Select-Object -Last 40++Write-Host ''+if ($script:fails -eq 0) { Write-Host 'ALL CHECKS PASSED' } else { Write-Host "$($script:fails) CHECK(S) FAILED" }+exit $script:failsdiff --git a/scripts/winfakeup/main.go b/scripts/winfakeup/main.gonew file mode 100644index 0000000..3ffd962--- /dev/null+++ b/scripts/winfakeup/main.go@@ -0,0 +1,45 @@+//go:build windows++// winfakeup is a CI helper: a Wintun adapter with a default route that wins over the real NIC's+// and drops everything sent to it, so the real NIC becomes a secondary adapter (like a USB tether+// next to Wi-Fi). It exits, and Windows removes the adapter and route, after the given duration.+package main++import (+ "fmt"+ "os"+ "os/exec"+ "time"++ "golang.zx2c4.com/wireguard/tun"+)++func main() {+ life, err := time.ParseDuration(os.Args[1])+ if err != nil {+ panic(err)+ }+ dev, err := tun.CreateTUN("fakeup", 1500)+ if err != nil {+ panic(err)+ }+ defer dev.Close()+ name, _ := dev.Name()+ for _, a := range [][]string{+ {"netsh", "interface", "ipv4", "set", "address", "name=" + name, "source=static", "address=10.99.0.2", "mask=255.255.255.0", "gateway=10.99.0.1", "gwmetric=1"},+ {"netsh", "interface", "ipv4", "set", "interface", name, "metric=1"},+ } {+ out, err := exec.Command(a[0], a[1:]...).CombinedOutput()+ fmt.Println(a, err, string(out))+ }+ fmt.Println("fakeup ready")+ go func() {+ bufs, sizes := [][]byte{make([]byte, 65536)}, []int{0}+ for {+ if _, err := dev.Read(bufs, sizes, 0); err != nil {+ return+ }+ }+ }()+ time.Sleep(life)+}