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
Add macOS support (#4)
Rohit Mahtob5f5763eedcc
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2903263..457eb69 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -9,15 +9,23 @@ jobs:strategy:fail-fast: falsematrix:- os: [windows-latest, ubuntu-latest]+ os: [windows-latest, ubuntu-latest, macos-latest]runs-on: ${{ matrix.os }}steps:- uses: actions/checkout@v4- uses: actions/setup-go@v5with:go-version-file: go.mod+ - name: Loopback aliases for the engine tests+ if: runner.os == 'macOS'+ run: |+ sudo ifconfig lo0 alias 127.0.0.2/32+ sudo ifconfig lo0 alias 127.0.0.3/32- run: go vet ./...- run: go test ./...+ - name: Cross-build darwin/amd64+ if: runner.os == 'macOS'+ run: CGO_ENABLED=1 GOARCH=amd64 go build -o /dev/null ./cmd/net-merge- name: Cross-build linux/arm64if: runner.os == 'Linux'run: GOARCH=arm64 go build -o /dev/null ./cmd/net-merge@@ -36,6 +44,20 @@ jobs:if: always()run: cat /tmp/net-merge-e2e/*.log 2>/dev/null || true+ # System-wide mode for real, as root: utun, routes, relaying, off, kill -9. One NIC, so no balancing.+ macos-smoke:+ runs-on: macos-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: go.mod+ - run: go build -o net-merge ./cmd/net-merge+ - run: bash scripts/macos-smoke.sh ./net-merge+ - name: net-merge logs+ if: always()+ run: cat /tmp/net-merge-smoke*.log 2>/dev/null || true+nix:runs-on: ubuntu-lateststeps:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 21803ad..7b68550 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -41,3 +41,27 @@ jobs:} else {gh release create $tag $files --title $title --notes-file release-notes.md}++ # Adds the macOS build to the release the Windows job creates.+ macos:+ needs: release+ runs-on: macos-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: go.mod+ - name: Build universal binary+ run: |+ v='${{ github.ref_name }}'; v=${v#v}+ for arch in arm64 amd64; do+ CGO_ENABLED=1 GOARCH=$arch go build -ldflags "-s -w -X main.version=$v" -o net-merge-$arch ./cmd/net-merge+ done+ lipo -create -output net-merge net-merge-arm64 net-merge-amd64+ codesign --force --sign - net-merge # ad-hoc: lipo invalidates the per-arch signatures+ mkdir dist+ tar -czf dist/net-merge-$v-macos-universal.tar.gz net-merge LICENSE THIRD-PARTY-NOTICES.md+ - name: Upload to the release+ env:+ GH_TOKEN: ${{ github.token }}+ run: gh release upload '${{ github.ref_name }}' dist/net-merge-*-macos-universal.tar.gz --clobberdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 107ed25..755d73b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,11 @@ entry here before pushing a version tag.## [Unreleased]### Added+- **macOS support** (Apple Silicon and Intel). System-wide mode, the menu-bar tray, the SOCKS5 proxy, live+ per-adapter speeds and start at login (a LaunchAgent) all work. The TUN is a utun, flows are pinned with+ `IP_BOUND_IF` plus a scoped default route per adapter, and adapters come from the routing table. iPhone+ hotspot over USB works as is; Android USB tethering needs the TetherKit app. `sudo net-merge install`+ sets up a passwordless rule for `net-merge tray`.- **Linux support**, including NixOS. System-wide mode, the tray icon (any desktop withStatusNotifierItem support: KDE, GNOME with the AppIndicator extension, XFCE, Cinnamon, ...), theSOCKS5 proxy, live per-adapter speeds and autostart (XDG autostart entry) all work. The TUN and@@ -16,6 +21,8 @@ entry here before pushing a version tag.graphical session.### Changed+- Clicking the tray icon no longer turns merging on or off (it was easy to hit by accident). Open the+ menu (right-click) and choose *Pause merging* / *Start merging*.- The source is split into packages: `cmd/net-merge` (the command) and `internal/...` (engine, nics,tun, tray, platform, state, icon, logx). Build with `go build ./cmd/net-merge`.diff --git a/README.md b/README.mdindex 4f38edb..1f95603 100644--- a/README.md+++ b/README.md@@ -1,6 +1,6 @@# net-merge-Use all your network adapters at once on Windows and Linux (including NixOS). Every new connection (TCP and UDP, IPv4 and IPv6) is+Use all your network adapters at once on Windows, macOS and Linux (including NixOS). Every new connection (TCP and UDP, IPv4 and IPv6) ispinned to one adapter (Wi-Fi, Ethernet, USB tether, phone hotspot), so many parallel connections(browsers, Steam, updates, downloads) run over all your links at the same time. A single connection isstill limited to one link.@@ -18,7 +18,7 @@ No server, VPN or account is involved: connections go straight out of the adapte## Features-- **Combines any adapters**: Wi-Fi, Ethernet, USB tethering, phone hotspots. Plug one in and it is used+- **Combines any adapters**: Wi-Fi, Ethernet, USB tethering, phone hotspots (iPhone and Android). Plug one in and it is usedwithin seconds; unplug it and its connections move to the others. VPN and virtual adapters (Tailscale,WireGuard, Hyper-V, WSL) are ignored.- **System-wide**: every app, TCP and UDP, IPv4 and IPv6. No proxy settings, nothing to configure per app.@@ -27,7 +27,7 @@ No server, VPN or account is involved: connections go straight out of the adapteWi-Fi) gets nothing until it recovers.- **Live speeds on hover**: each adapter's download/upload and the total. These are the adapters' realtraffic from the OS, so apps that bypass net-merge (qBittorrent binds to adapters itself) still count.-- **One click on and off**, and optional start at sign-in (on Windows without a UAC prompt).+- **On and off from the tray menu**, and optional start at sign-in (on Windows without a UAC prompt).- **Safe to crash**: the virtual adapter and its routes disappear with the process, so a crash or a killnever leaves the PC without internet.- **Light on CPU**: about 0.18 cores per 100 Mbit/s.@@ -46,6 +46,49 @@ Download `net-merge-setup-x.y.z.exe` from the [releases page](../../releases) anIt is not code-signed yet, so SmartScreen will warn: *More info > Run anyway*. A portable zip is alsopublished. What changed in each version: [CHANGELOG.md](CHANGELOG.md).+### macOS++Works on Apple Silicon and Intel Macs. Download `net-merge-x.y.z-macos-universal.tar.gz` from the+[releases page](../../releases), unpack it, and run these once:++```+xattr -d com.apple.quarantine net-merge # only if macOS refuses to open it (it is not notarized yet)+sudo ./net-merge install # copies it to /usr/local/bin and lets you start the tray without a password+net-merge tray # a green/grey icon appears in the menu bar+net-merge autostart on # optional: start at login+```++`sudo net-merge install` adds one rule that lets your user run only `net-merge tray` and `net-merge cleanup`+as root. Remove everything with `sudo net-merge uninstall` (and `net-merge autostart off`). Without+`install`, `net-merge tray` asks for your administrator password every time and start at login is not+available. To build it yourself: `go build -o net-merge ./cmd/net-merge` (needs the Xcode command line tools).++#### Getting a second connection on a Mac++net-merge needs two or more real connections. Wi-Fi plus one of these:++**iPhone (nothing to install)**+1. Plug the iPhone in with a cable. Tap *Trust* on the iPhone if it asks.+2. On the iPhone: *Settings > Personal Hotspot > Allow Others to Join*. Turn it on.+3. An **iPhone USB** network appears on the Mac. When it gets an address, net-merge adds it within a few+ seconds. `net-merge list` and `net-merge status` show it as `en5` (the number can differ).++**Android (needs TetherKit)**++macOS cannot use Android's USB tethering by itself, so Android needs a separate Mac app called+**TetherKit**, which lets the Mac talk to the phone.+1. Install and open TetherKit.+2. Plug the phone in and turn on *USB tethering* in the phone's settings.+3. Click **Apply** in TetherKit. A new network appears (`feth0`) and net-merge adds it within a few seconds.++**Important with TetherKit:** start net-merge first, then connect the phone. macOS drops the TetherKit+connection every time net-merge's virtual adapter is created or removed, which is when net-merge starts,+quits, or is paused and resumed. If the phone disappears, just click **Apply** in TetherKit again. The+iPhone is not affected the same way.++A tethered phone uses its mobile data, so net-merge sends part of your traffic through it while it runs.+Quit net-merge when you don't want that.+### NixOSAdd the flake and enable the module. It installs `net-merge` as a capability wrapper@@ -87,8 +130,8 @@ unsolicited input, trust the `net-merge` interface (e.g. `firewall-cmd --zone=tr## How to use-On Linux, start it with `net-merge tray` (or from your autostart); there is no admin prompt when the-capability is set. The rest is the same.+On Linux and macOS, start it with `net-merge tray` (or from your autostart); there is no admin prompt when+the capability (Linux) or `net-merge install` (macOS) is set up. The rest is the same.1. Start **net-merge** from the Start menu and approve the admin prompt. A tray icon appears (if youdon't see it, it is behind the `^` arrow next to the clock; drag it onto the taskbar).@@ -96,10 +139,9 @@ capability is set. The rest is the same.They are picked up automatically.3. Use the tray icon:- **green** = merging, **grey** = paused- - **left-click** pauses or starts merging- **hover** shows each adapter's speed and the total- - **right-click** shows the same with full adapter names, how many connections net-merge has put- on each adapter, the IPv6 option, *Pause merging* / *Start merging*, and *Quit*+ - **right-click** (or click) opens the menu: full adapter names with their speeds, how many connections+ net-merge has put on each adapter, the IPv6 option, *Pause merging* / *Start merging*, and *Quit*4. To start it at sign-in, tick *Start net-merge when I sign in* in the installer, or run`net-merge autostart on` (on Linux this writes an XDG autostart entry; on NixOS prefer`programs.net-merge.autostart`).@@ -125,6 +167,7 @@ net-merge tray tray app (asks for admin once)net-merge run system-wide in a console windownet-merge socks plain SOCKS5 proxy on 127.0.0.1:1080 (no admin, per-app)net-merge cleanup remove leftover routes after a crash+net-merge install macOS only: sudo net-merge install, lets the tray start without a passwordnet-merge version```@@ -134,17 +177,17 @@ Flags for `tray`/`run`/`socks`: `-include "WiFi,Ethernet"` (only these adapters)## How it works-- ON creates a virtual adapter `net-merge` (Wintun on Windows, a kernel TUN on Linux) and two `/1` routes per IP family that beat the default route+- ON creates a virtual adapter `net-merge` (Wintun on Windows, a kernel TUN on Linux, a utun on macOS) and two `/1` routes per IP family that beat the default routewithout touching it. OFF deletes them. If the process dies the adapter and routes die with it, so acrash can't leave the machine without internet.- Flows entering the TUN are terminated in a userland TCP/IP stack (tun2socks/gVisor) and re-dialed froma chosen adapter: the socket is bound to that adapter's source IP and forced out of it with- `IP_UNICAST_IF` (Windows) or `SO_BINDTOIFINDEX` (Linux), so it can never loop back into the TUN.+ `IP_UNICAST_IF` (Windows), `SO_BINDTOIFINDEX` (Linux) or `IP_BOUND_IF` (macOS, plus a scoped default route per adapter so the bound lookup still works), so it can never loop back into the TUN.- The virtual adapter runs at MTU 9000 (both the OS and the userland stack). Its traffic never leavesthe machine, so the links' 1500 doesn't apply, and bigger packets cost far less CPU: measured about3x less CPU per Mbit/s than at 1500 (0.18 vs 0.54 cores per 100 Mbit/s). `-mtu` changes it.- Adapters are detected automatically and re-scanned every 3 s. Only real hardware with a default route- is used (on Linux: interfaces backed by a device in sysfs, with a default route in any routing table): tunnels, VPNs (Tailscale, WireGuard, ...), virtual switches and LAN-only adapters are skipped+ is used (on Linux: interfaces backed by a device in sysfs, with a default route in any routing table; on macOS: `enN` interfaces, and TetherKit's `fethN`, with a default route): tunnels, VPNs (Tailscale, WireGuard, ...), virtual switches and LAN-only adapters are skipped(`net-merge list` shows why).- Each adapter and each address family is probed for real internet access. A tether with no data or acaptive-portal Wi-Fi gets no flows; a recovered link rejoins within seconds.@@ -162,7 +205,7 @@ Flags for `tray`/`run`/`socks`: `-include "WiFi,Ethernet"` (only these adapters)- One connection = one adapter. A single big download won't speed up; many connections will.- With adapters that differ in IPv6 support, IPv6-only hosts are unreachable in `auto` mode (see above).- Sites that tie a login to one IP may see a different IP per connection and ask you to re-verify.-- Needs admin (for the TUN). Windows 10/11 x64, or Linux (x86_64, aarch64) with root or+- Needs admin (for the TUN). Windows 10/11 x64, macOS (Apple Silicon or Intel) or Linux (x86_64, aarch64) with root or`CAP_NET_ADMIN`.## Build@@ -171,7 +214,7 @@ Needs Go (see `go.mod`) and, for the Windows installer, [Inno Setup 6](https://j```go test ./... # uses loopback aliases as fake adapters; no second link needed-go build -o net-merge ./cmd/net-merge # Linux+go build -o net-merge ./cmd/net-merge # Linux, macOS (macOS needs the Xcode command line tools)nix build # Linux, with Nix: result/bin/net-mergescripts\build.ps1 -Version 0.1.0 # dist\: net-merge.exe, net-merge-tray.exe, installer, portable zip```@@ -190,7 +233,7 @@ without it (`scripts\release-notes.ps1 -Version X.Y.Z` previews them).Layout: `cmd/net-merge` is the command line; `internal/engine` the scheduler, balancer, probes andSOCKS5 front-end; `internal/nics` adapter discovery, counters and egress pinning; `internal/tun` thesystem-wide front-end; `internal/tray` the tray icon; `internal/platform` privileges, single instance-and autostart. OS-specific code lives in `_windows.go` / `_linux.go` files next to the shared code. The+and autostart. OS-specific code lives in `_windows.go` / `_linux.go` / `_darwin.go` files next to the shared code. TheNix package and NixOS module are in `nix/`; after changing Go dependencies, update `vendorHash` in`nix/package.nix` (`nix build` prints the new one).diff --git a/cmd/net-merge/main.go b/cmd/net-merge/main.goindex 0d24b51..75bc698 100644--- a/cmd/net-merge/main.go+++ b/cmd/net-merge/main.go@@ -22,7 +22,7 @@ import (const usage = `net-merge: use all your network adapters at once.- net-merge tray tray icon: left-click toggles system-wide ON/OFF, right-click shows speeds+ net-merge tray tray icon: its menu turns system-wide ON/OFF and shows speedsnet-merge run system-wide ON in a console window (asks for admin/root); Ctrl+C or "off" turns it OFFnet-merge on|off turn system-wide mode on/off in a running tray (off also works for run)net-merge quit turn it off and exit the tray@@ -31,6 +31,7 @@ const usage = `net-merge: use all your network adapters at once.net-merge list show detected adaptersnet-merge autostart on|off|status start the tray at sign-in (Windows: no UAC prompt)net-merge cleanup remove leftover routes after a crash (admin/root)+ net-merge install macOS: sudo net-merge install lets the tray start without a passwordnet-merge versionFlags for run/socks: -include "WiFi,Ethernet 3" -weight "Name=3" -auto-weight=false -stats 5s@@ -96,7 +97,8 @@ func (c *common) nics() ([]nics.Nic, error) {// setup opens the log file (if any) and the state dir.func (c *common) setup() error {- if err := os.MkdirAll(c.stateDir, 0o755); err != nil {+ // Without admin (`socks`) there may be no state dir to make, e.g. the root-owned one on macOS.+ if err := state.Prepare(c.stateDir); err != nil && platform.IsAdmin() {return err}if c.logFile != "" {@@ -222,6 +224,10 @@ func main() {switch cmd {case "version":fmt.Println("net-merge", version)+ case "install", "uninstall":+ if err := platform.Install(cmd == "uninstall"); err != nil {+ die(err)+ }case "autostart":if len(args) != 1 || (args[0] != "on" && args[0] != "off" && args[0] != "status") {fmt.Fprintln(os.Stderr, "usage: net-merge autostart on|off|status")@@ -319,7 +325,7 @@ func cmdRun(args []string) {// Re-run elevated, handing over where to log and keep state.child := append([]string{"run"}, args...)child = append(child, "-state-dir", c.stateDir)- os.MkdirAll(c.stateDir, 0o755) // as this user, so `net-merge off` can still drop markers in it+ state.Prepare(c.stateDir) // as this user, so `net-merge off` can still drop markers in itif err := platform.RelaunchElevated(child, *hidden); err != nil {die(fmt.Errorf("could not start elevated: %w", err))}diff --git a/cmd/net-merge/tray.go b/cmd/net-merge/tray.goindex 368417e..dcbd426 100644--- a/cmd/net-merge/tray.go+++ b/cmd/net-merge/tray.go@@ -4,11 +4,14 @@ import ("flag""fmt""os"+ "os/signal""path/filepath"+ "syscall""time""net-merge/internal/logx""net-merge/internal/platform"+ "net-merge/internal/state""net-merge/internal/tray""net-merge/internal/tun")@@ -23,11 +26,13 @@ func cmdTray(args []string) {if !platform.IsAdmin() {child := append([]string{"tray"}, args...)- child = append(child, "-state-dir", c.stateDir)+ if c.stateDir != state.DefaultDir() { // the macOS passwordless rule only matches a bare `tray`+ child = append(child, "-state-dir", c.stateDir)+ }if err := platform.RelaunchTray(child, *hidden); err != nil {die(err)}- fmt.Println("Approve the UAC prompt. Look for the net-merge icon in the system tray (^ overflow arrow).")+ fmt.Println("Approve the admin prompt. Look for the net-merge icon in the system tray (^ overflow arrow) or menu bar.")return}if !platform.SingleInstance() {@@ -75,5 +80,13 @@ func cmdTray(args []string) {os.Exit(4)}}()+ sig := make(chan os.Signal, 1)+ signal.Notify(sig, os.Interrupt, syscall.SIGTERM)+ go func() { // logout, `launchctl bootout`, kill: turn off cleanly instead of leaving routes behind+ <-sig+ t.Off()+ state.Clear(c.stateDir)+ os.Exit(0)+ }()tray.Run(t, sched, bal, c.stateDir, !*startOff, ready)}diff --git a/go.mod b/go.modindex aa8c55a..5b42885 100644--- a/go.mod+++ b/go.mod@@ -6,6 +6,7 @@ require (fyne.io/systray v1.12.2github.com/vishvananda/netlink v1.3.1github.com/xjasonlyu/tun2socks/v2 v2.7.0+ golang.org/x/net v0.56.0golang.org/x/sys v0.46.0golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446gvisor.dev/gvisor v0.0.0-20260701204157-69c2d17aea96@@ -20,7 +21,6 @@ require (go.uber.org/multierr v1.11.0 // indirectgo.uber.org/zap v1.28.0 // indirectgolang.org/x/exp v0.0.0-20260611194520-c48552f49976 // indirect- golang.org/x/net v0.56.0 // indirectgolang.org/x/time v0.15.0 // indirectgolang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect)diff --git a/internal/engine/sched_test.go b/internal/engine/sched_test.goindex a89781a..91a9535 100644--- a/internal/engine/sched_test.go+++ b/internal/engine/sched_test.go@@ -119,6 +119,7 @@ func TestProbeStateTiers(t *testing.T) {}func TestProbeAgainstLocalListener(t *testing.T) {+ needLoopbackAliases(t)ln, err := net.Listen("tcp4", "127.0.0.1:0")if err != nil {t.Fatal(err)diff --git a/internal/engine/socks5_test.go b/internal/engine/socks5_test.goindex b083b65..0549019 100644--- a/internal/engine/socks5_test.go+++ b/internal/engine/socks5_test.go@@ -36,8 +36,22 @@ func startTarget(t *testing.T) int {return ln.Addr().(*net.TCPAddr).Port}+// needLoopbackAliases skips when 127.0.0.2/3 can't be bound. Linux and Windows answer for all of+// 127/8; macOS needs `sudo ifconfig lo0 alias 127.0.0.2/32` (and .3) first.+func needLoopbackAliases(t testing.TB) {+ t.Helper()+ for _, ip := range []string{"127.0.0.2", "127.0.0.3"} {+ ln, err := net.Listen("tcp4", ip+":0")+ if err != nil {+ t.Skipf("%s is not bindable; on macOS run: sudo ifconfig lo0 alias %s/32", ip, ip)+ }+ ln.Close()+ }+}+func startProxy(t *testing.T, nics []nics.Nic) (*Scheduler, string) {t.Helper()+ needLoopbackAliases(t)s := NewScheduler(nics)b := NewBalancer(s)b.ConnectTimeout = 2 * time.Second@@ -233,6 +247,7 @@ func TestHalfCloseStillDeliversReply(t *testing.T) {// Raw relay throughput through the proxy over loopback (the CPU ceiling of the data path).func benchRelay(b *testing.B, streams int) {+ needLoopbackAliases(b)ln, _ := net.Listen("tcp4", "127.0.0.1:0")defer ln.Close()chunk := make([]byte, 256<<10)diff --git a/internal/nics/counters_darwin.go b/internal/nics/counters_darwin.gonew file mode 100644index 0000000..ccec912--- /dev/null+++ b/internal/nics/counters_darwin.go@@ -0,0 +1,40 @@+package nics++import (+ "encoding/binary"+ "syscall"++ "golang.org/x/sys/unix"+)++// if_msghdr2 on darwin: 32 bytes of header, then if_data64, whose ibytes/obytes sit at +64/+72.+// The 64-bit counters matter: if_data's 32-bit ones wrap every 4 GB.+const (+ rtmIfInfo2 = 0x12+ offIBytes = 32 + 64+ offOBytes = 32 + 72+)++// Octets reads the kernel's byte counters for an adapter. They cover every app's traffic, not+// just what net-merge relays: apps that bind to each adapter directly bypass the TUN but still+// show up here.+func Octets(idx int) (in, out uint64, ok bool) {+ if idx <= 0 {+ return 0, 0, false+ }+ rib, err := syscall.RouteRIB(unix.NET_RT_IFLIST2, idx)+ if err != nil {+ return 0, 0, false+ }+ for len(rib) >= 4 {+ n := int(binary.LittleEndian.Uint16(rib))+ if n < 4 || n > len(rib) {+ return 0, 0, false+ }+ if rib[3] == rtmIfInfo2 && n >= offOBytes+8 && int(binary.LittleEndian.Uint16(rib[12:])) == idx {+ return binary.LittleEndian.Uint64(rib[offIBytes:]), binary.LittleEndian.Uint64(rib[offOBytes:]), true+ }+ rib = rib[n:]+ }+ return 0, 0, false+}diff --git a/internal/nics/egress_darwin.go b/internal/nics/egress_darwin.gonew file mode 100644index 0000000..f9c79f9--- /dev/null+++ b/internal/nics/egress_darwin.go@@ -0,0 +1,28 @@+package nics++import (+ "syscall"++ "golang.org/x/sys/unix"+)++// ForceEgress binds a socket to an interface, so our own outbound flows can never be captured by+// the TUN's routes (no routing loop): the kernel only considers routes scoped to that interface.+func ForceEgress(idx int, v6 bool) func(network, address string, c syscall.RawConn) error {+ if idx <= 0 {+ return nil+ }+ level, opt := unix.IPPROTO_IP, unix.IP_BOUND_IF+ if v6 {+ level, opt = unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF+ }+ return func(network, address string, c syscall.RawConn) error {+ var serr error+ if err := c.Control(func(fd uintptr) {+ serr = unix.SetsockoptInt(int(fd), level, opt, idx)+ }); err != nil {+ return err+ }+ return serr+ }+}diff --git a/internal/nics/info_darwin.go b/internal/nics/info_darwin.gonew file mode 100644index 0000000..9dc6d1a--- /dev/null+++ b/internal/nics/info_darwin.go@@ -0,0 +1,177 @@+package nics++import (+ "net"+ "os/exec"+ "regexp"+ "strings"+ "sync"+ "syscall"+ "time"++ "golang.org/x/net/route"+ "golang.org/x/sys/unix"+)++// adapterInfo is what macOS knows about an adapter beyond what package net exposes.+type adapterInfo struct {+ v4, v6 bool // has an IPv4 / IPv6 default route (can reach the internet over that family)+ virtual string // why this is not real network hardware; empty if it is+ desc string // System Settings' name for it, e.g. "Wi-Fi", "iPhone USB"+}++// Wi-Fi, Ethernet, USB tethers and Thunderbolt/USB NICs are all enN. fethN is how TetherKit (the+// userspace RNDIS driver that makes Android USB tethering work) shows a phone; it only counts once+// it has a default route, like any other. Everything else (utun, bridge, awdl, llw, gif, stf, anpi,+// ap, lo) is a tunnel, bridge or Apple's own plumbing.+var hardwareName = regexp.MustCompile(`^(en|feth)\d+$`)++// adapterInfos returns, per interface index, the default-route families, whether it looks like+// hardware, and its System Settings name. macOS keeps a scoped default route (flag I) for every+// service that has a router, so those count too: a tether that is not the primary service still+// has one.+func adapterInfos() (map[int]adapterInfo, error) {+ ifaces, err := net.Interfaces()+ if err != nil {+ return nil, err+ }+ m := map[int]adapterInfo{}+ for _, ifc := range ifaces {+ info := adapterInfo{desc: portName(ifc.Name)}+ if !hardwareName.MatchString(ifc.Name) {+ info.virtual = "tunnel/virtual interface (not an enN/fethN device)"+ }+ m[ifc.Index] = info+ }+ routes, err := DefaultRoutes()+ if err != nil {+ return nil, err+ }+ for _, r := range routes {+ cur, ok := m[r.Index]+ if !ok {+ continue+ }+ if r.V6 {+ cur.v6 = true+ } else {+ cur.v4 = true+ }+ m[r.Index] = cur+ }+ return m, nil+}++// DefaultRoute is a default route from the routing table. GW is nil when it has no IP gateway+// (e.g. a "link#N" default on a tunnel).+type DefaultRoute struct {+ Index int+ Name string+ GW net.IP+ V6 bool+ Scoped bool // flag I: only used by sockets bound to this interface (IP_BOUND_IF)+}++// DefaultRoutes lists every default route, scoped ones included.+func DefaultRoutes() ([]DefaultRoute, error) {+ rib, err := route.FetchRIB(syscall.AF_UNSPEC, route.RIBTypeRoute, 0)+ if err != nil {+ return nil, err+ }+ msgs, err := route.ParseRIB(route.RIBTypeRoute, rib)+ if err != nil {+ return nil, err+ }+ var out []DefaultRoute+ for _, msg := range msgs {+ rm, ok := msg.(*route.RouteMessage)+ if !ok || rm.Flags&(syscall.RTF_HOST|syscall.RTF_REJECT|syscall.RTF_BLACKHOLE) != 0 || len(rm.Addrs) <= syscall.RTAX_NETMASK {+ continue+ }+ var v6 bool+ switch dst := rm.Addrs[syscall.RTAX_DST].(type) {+ case *route.Inet4Addr:+ if dst.IP != [4]byte{} {+ continue+ }+ case *route.Inet6Addr:+ if dst.IP != [16]byte{} {+ continue+ }+ v6 = true+ default:+ continue+ }+ if !zeroMask(rm.Addrs[syscall.RTAX_NETMASK]) {+ continue+ }+ ifc, err := net.InterfaceByIndex(rm.Index)+ if err != nil {+ continue+ }+ r := DefaultRoute{Index: rm.Index, Name: ifc.Name, V6: v6, Scoped: rm.Flags&unix.RTF_IFSCOPE != 0}+ if len(rm.Addrs) > syscall.RTAX_GATEWAY {+ switch gw := rm.Addrs[syscall.RTAX_GATEWAY].(type) {+ case *route.Inet4Addr:+ r.GW = net.IP(gw.IP[:])+ case *route.Inet6Addr:+ ip := net.IP(append([]byte(nil), gw.IP[:]...))+ if ip.IsLinkLocalUnicast() {+ ip[2], ip[3] = 0, 0 // the kernel's embedded scope id (KAME style)+ }+ r.GW = ip+ }+ }+ out = append(out, r)+ }+ return out, nil+}++func zeroMask(a route.Addr) bool {+ switch a := a.(type) {+ case nil:+ return true+ case *route.Inet4Addr:+ return a.IP == [4]byte{}+ case *route.Inet6Addr:+ return a.IP == [16]byte{}+ }+ return false+}++// networksetup is slow-ish and the answer rarely changes, so remember it and re-ask only when an+// interface it has not seen appears (at most every 10 s).+var ports struct {+ mu sync.Mutex+ at time.Time+ names map[string]string+}++func portName(ifname string) string {+ ports.mu.Lock()+ defer ports.mu.Unlock()+ if n, ok := ports.names[ifname]; ok || !hardwareName.MatchString(ifname) {+ return n+ }+ if time.Since(ports.at) > 10*time.Second {+ ports.at, ports.names = time.Now(), listPorts()+ }+ return ports.names[ifname]+}++func listPorts() map[string]string {+ out, err := exec.Command("/usr/sbin/networksetup", "-listallhardwareports").Output()+ if err != nil {+ return nil+ }+ names := map[string]string{}+ var port string+ for _, line := range strings.Split(string(out), "\n") {+ if v, ok := strings.CutPrefix(line, "Hardware Port: "); ok {+ port = v+ } else if v, ok := strings.CutPrefix(line, "Device: "); ok && port != "" {+ names[strings.TrimSpace(v)] = port+ }+ }+ return names+}diff --git a/internal/platform/autostart_darwin.go b/internal/platform/autostart_darwin.gonew file mode 100644index 0000000..b0aa96c--- /dev/null+++ b/internal/platform/autostart_darwin.go@@ -0,0 +1,83 @@+package platform++import (+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "strconv"+)++const agentLabel = "io.github.rohit267.net-merge"++func agentPath() (string, error) {+ home, err := os.UserHomeDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(home, "Library", "LaunchAgents", agentLabel+".plist"), nil+}++// Autostart turns start-at-sign-in "on" or "off", or prints its "status". It is a LaunchAgent+// running `sudo -n net-merge tray`, which only works once `sudo net-merge install` has added the+// passwordless rule; otherwise sign-in would need a password the agent can't type.+func Autostart(action string) error {+ if os.Geteuid() == 0 {+ return errors.New("run this as your normal user, not with sudo")+ }+ path, err := agentPath()+ if err != nil {+ return err+ }+ domain := "gui/" + strconv.Itoa(os.Getuid())+ _, statErr := os.Stat(path)+ switch action {+ case "status":+ if statErr == nil {+ fmt.Println("autostart is ON (" + path + ").")+ } else {+ fmt.Println("autostart is OFF.")+ }+ return nil+ case "off":+ exec.Command("/bin/launchctl", "bootout", domain+"/"+agentLabel).Run() // not loaded is fine+ if statErr != nil {+ fmt.Println("autostart is already OFF.")+ return nil+ }+ if err := os.Remove(path); err != nil {+ return err+ }+ fmt.Println("autostart is OFF.")+ return nil+ }+ if exec.Command("/usr/bin/sudo", "-n", "-l", InstalledExe, "tray").Run() != nil {+ return errors.New("the tray can't start at sign-in without the passwordless rule; run once: sudo net-merge install")+ }+ home, _ := os.UserHomeDir()+ plist := `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0"><dict>+<key>Label</key><string>` + agentLabel + `</string>+<key>ProgramArguments</key><array><string>/usr/bin/sudo</string><string>-n</string><string>` + InstalledExe + `</string><string>tray</string></array>+<key>RunAtLoad</key><true/>+<key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>+<key>ThrottleInterval</key><integer>30</integer>+<key>StandardOutPath</key><string>` + filepath.Join(home, "Library", "Logs", "net-merge.log") + `</string>+<key>StandardErrorPath</key><string>` + filepath.Join(home, "Library", "Logs", "net-merge.log") + `</string>+</dict></plist>+`+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {+ return err+ }+ if err := os.WriteFile(path, []byte(plist), 0o644); err != nil {+ return err+ }+ exec.Command("/bin/launchctl", "bootout", domain+"/"+agentLabel).Run()+ if out, err := exec.Command("/bin/launchctl", "bootstrap", domain, path).CombinedOutput(); err != nil {+ return fmt.Errorf("launchctl bootstrap: %w: %s", err, out)+ }+ fmt.Println("autostart is ON: net-merge starts at sign-in (" + path + ").")+ return nil+}diff --git a/internal/platform/install_darwin.go b/internal/platform/install_darwin.gonew file mode 100644index 0000000..9c19c80--- /dev/null+++ b/internal/platform/install_darwin.go@@ -0,0 +1,102 @@+package platform++import (+ "errors"+ "fmt"+ "io"+ "os"+ "os/exec"+ "path/filepath"+ "regexp"+ "strings"+ "syscall"+)++const sudoersPath = "/etc/sudoers.d/net-merge"++var safeUser = regexp.MustCompile(`^[A-Za-z0-9._-]+$`)++// Install (run as `sudo net-merge install`) copies this binary to a root-owned path and lets the+// invoking user run exactly `net-merge tray` and `net-merge cleanup` there without a password.+// No wildcards: with `tray *` any process of the user could pass `-log /etc/...` and make root+// overwrite files. Uninstall removes both.+func Install(uninstall bool) error {+ if !IsAdmin() {+ return errors.New("run: sudo net-merge install")+ }+ if uninstall {+ for _, p := range []string{sudoersPath, InstalledExe} {+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {+ return err+ }+ }+ fmt.Println("removed " + sudoersPath + " and " + InstalledExe + ". Turn off start at sign-in with `net-merge autostart off`.")+ return nil+ }+ user := os.Getenv("SUDO_USER")+ if user == "" || user == "root" || !safeUser.MatchString(user) {+ return errors.New("run it through sudo from your own account: sudo net-merge install")+ }+ if err := copyRootOwned(InstalledExe); err != nil {+ return err+ }+ rule := fmt.Sprintf("# Written by `net-merge install`: %s may start the tray without a password.\n"++ "%s ALL=(root) NOPASSWD: %s tray, %s cleanup\n", user, user, InstalledExe, InstalledExe)+ tmp := sudoersPath + ".tmp"+ if err := os.WriteFile(tmp, []byte(rule), 0o440); err != nil {+ return err+ }+ defer os.Remove(tmp)+ // A broken sudoers file locks everyone out of sudo, so only move it into place once it parses.+ if out, err := exec.Command("/usr/sbin/visudo", "-cf", tmp).CombinedOutput(); err != nil {+ return fmt.Errorf("sudoers rule rejected, nothing installed: %s", strings.TrimSpace(string(out)))+ }+ if err := os.Rename(tmp, sudoersPath); err != nil {+ return err+ }+ fmt.Printf("installed %s and %s.\nStart the tray with `net-merge tray` (no password), and at sign-in with `net-merge autostart on`.\n", InstalledExe, sudoersPath)+ return nil+}++// copyRootOwned puts this binary at dst, root:wheel 0755, refusing if any directory above it+// could be changed by a non-root user (the copy is run as root, so that would be a root hole).+func copyRootOwned(dst string) error {+ for d := filepath.Dir(dst); d != "/"; d = filepath.Dir(d) {+ fi, err := os.Stat(d)+ if err != nil {+ return err+ }+ if st, ok := fi.Sys().(*syscall.Stat_t); !ok || st.Uid != 0 || fi.Mode().Perm()&0o022 != 0 {+ return fmt.Errorf("%s is writable by non-root users; refusing to install a root-run binary there", d)+ }+ }+ src, err := os.Executable()+ if err != nil {+ return err+ }+ if src == dst {+ return nil+ }+ in, err := os.Open(src)+ if err != nil {+ return err+ }+ defer in.Close()+ tmp := dst + ".tmp"+ out, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o755)+ if err != nil {+ return err+ }+ defer os.Remove(tmp)+ if _, err := io.Copy(out, in); err != nil {+ out.Close()+ return err+ }+ if err := out.Close(); err != nil {+ return err+ }+ if err := os.Chown(tmp, 0, 0); err != nil {+ return err+ }+ return os.Rename(tmp, dst)+}diff --git a/internal/platform/install_other.go b/internal/platform/install_other.gonew file mode 100644index 0000000..a043431--- /dev/null+++ b/internal/platform/install_other.go@@ -0,0 +1,8 @@+//go:build !darwin++package platform++import "errors"++// Install is the macOS-only setup of the passwordless tray (see install_darwin.go).+func Install(uninstall bool) error { return errors.New("install is only needed on macOS") }diff --git a/internal/platform/platform_darwin.go b/internal/platform/platform_darwin.gonew file mode 100644index 0000000..93db50c--- /dev/null+++ b/internal/platform/platform_darwin.go@@ -0,0 +1,120 @@+package platform++import (+ "fmt"+ "log"+ "os"+ "os/exec"+ "strings"+ "syscall"+ "time"++ "golang.org/x/sys/unix"+)++// IsAdmin reports whether this process may create the utun and its routes, i.e. runs as root.+func IsAdmin() bool { return os.Geteuid() == 0 }++// The single-instance lock is a flock on a root-created file: visible to every user, and+// released by the kernel when the process dies, so a crash never leaves a stale lock behind.+const lockPath = "/var/run/net-merge.lock"++var lockFile *os.File++// SingleInstance is false if another net-merge (run or tray) already owns the utun.+// The file is intentionally kept open for the life of the process.+func SingleInstance() bool {+ f, err := os.OpenFile(lockPath, os.O_CREATE|os.O_RDWR, 0o644)+ if err != nil {+ return false+ }+ if unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB) != nil {+ f.Close()+ return false+ }+ lockFile = f+ return true+}++// InstanceRunning reports whether a net-merge holds the lock; works for any user, since the+// file is world-readable and flock doesn't need write access.+func InstanceRunning() bool {+ f, err := os.Open(lockPath)+ if err != nil {+ return false+ }+ defer f.Close()+ if unix.Flock(int(f.Fd()), unix.LOCK_SH|unix.LOCK_NB) != nil {+ return true+ }+ unix.Flock(int(f.Fd()), unix.LOCK_UN)+ return false+}++// RedirectStd points stdout/stderr (including the runtime's panic output) at f, for a process+// started with no terminal (LaunchAgent).+func RedirectStd(f *os.File) {+ os.Stdout, os.Stderr = f, f+ log.SetOutput(f) // the std logger captured the old stderr at init; the tray library logs through it+ unix.Dup2(int(f.Fd()), 1)+ unix.Dup2(int(f.Fd()), 2)+}++// InstalledExe is where `net-merge install` puts the root-owned copy that sudoers allows.+const InstalledExe = "/usr/local/bin/net-merge"++// RelaunchElevated replaces this process with itself run as root: sudo in a terminal, the+// administrator password dialog otherwise. It only returns on failure.+func RelaunchElevated(args []string, hidden bool) error {+ exe, err := os.Executable()+ if err != nil {+ return err+ }+ if HasConsole() {+ return syscall.Exec("/usr/bin/sudo", append([]string{"sudo", exe}, args...), os.Environ())+ }+ cmd := shQuote(exe)+ for _, a := range args {+ cmd += " " + shQuote(a)+ }+ // Detached: the dialog returns at once and the root process keeps running without us.+ script := `do shell script "` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(cmd+" >/dev/null 2>&1 &") + `" with administrator privileges`+ if out, err := exec.Command("/usr/bin/osascript", "-e", script).CombinedOutput(); err != nil {+ return fmt.Errorf("administrator prompt failed: %s", strings.TrimSpace(string(out)))+ }+ return nil+}++// RelaunchTray is RelaunchElevated for the tray, but first tries the passwordless sudoers rule+// that `sudo net-merge install` sets up. That rule matches exactly `net-merge tray`, so it only+// applies when the tray was started without flags.+func RelaunchTray(args []string, hidden bool) error {+ if len(args) == 1 && args[0] == "tray" {+ if exec.Command("/usr/bin/sudo", "-n", "-l", InstalledExe, "tray").Run() == nil {+ return syscall.Exec("/usr/bin/sudo", []string{"sudo", "-n", InstalledExe, "tray"}, os.Environ())+ }+ }+ return RelaunchElevated(args, hidden)+}++func shQuote(s string) string { return `'` + strings.ReplaceAll(s, `'`, `'\''`) + `'` }++// HasConsole reports whether stderr is a terminal.+func HasConsole() bool {+ _, err := unix.IoctlGetTermios(2, unix.TIOCGETA)+ return err == nil+}++// ShowError reports a fatal error to a user with no terminal, as a notification (the error is+// in the log file either way).+func ShowError(msg string) {+ exec.Command("/usr/bin/osascript",+ "-e", "on run argv", "-e", `display notification (item 1 of argv) with title "net-merge"`, "-e", "end run",+ msg).Run()+}++// CheckDriver is a no-op: utun is built into macOS.+func CheckDriver() error { return nil }++// WaitForTray is a no-op: the menu bar exists as soon as the login session does.+func WaitForTray(max time.Duration) bool { return true }diff --git a/internal/state/state.go b/internal/state/state.goindex d63ccf4..8823118 100644--- a/internal/state/state.go+++ b/internal/state/state.go@@ -4,6 +4,7 @@ import ("encoding/json""os""path/filepath"+ "runtime""time""net-merge/internal/engine"@@ -23,6 +24,11 @@ type Status struct {}func DefaultDir() string {+ // The macOS tray runs as root but is commanded by the user, so its state can't live in a+ // user-owned directory (root would follow a planted symlink): a fixed root-owned path.+ if runtime.GOOS == "darwin" {+ return "/var/run/net-merge"+ }base, err := os.UserCacheDir()if err != nil {base = os.TempDir()@@ -30,6 +36,16 @@ func DefaultDir() string {return filepath.Join(base, "net-merge")}+// Prepare creates the state dir, with markers going in a sticky world-writable ctl/ inside it, so+// a normal user can drop one without being able to touch anything else there.+func Prepare(dir string) error {+ ctl := filepath.Join(dir, "ctl")+ if err := os.MkdirAll(ctl, 0o755); err != nil {+ return err+ }+ return os.Chmod(ctl, os.ModeSticky|0o777)+}+func Write(dir string, st Status) {b, err := json.Marshal(st)if err != nil {@@ -57,11 +73,11 @@ func Read(dir string) (*Status, bool) {}func SendMarker(dir, name string) error {- if err := os.MkdirAll(dir, 0o755); err != nil {+ if err := os.MkdirAll(filepath.Join(dir, "ctl"), 0o755); err != nil {return err}- return os.WriteFile(filepath.Join(dir, name), nil, 0o644)+ return os.WriteFile(filepath.Join(dir, "ctl", name), nil, 0o666)}// TakeMarker consumes a marker, reporting whether it was there.-func TakeMarker(dir, name string) bool { return os.Remove(filepath.Join(dir, name)) == nil }+func TakeMarker(dir, name string) bool { return os.Remove(filepath.Join(dir, "ctl", name)) == nil }diff --git a/internal/tray/tray.go b/internal/tray/tray.goindex 87d5a2a..6848995 100644--- a/internal/tray/tray.go+++ b/internal/tray/tray.go@@ -23,20 +23,21 @@ const trayRows = 4 // adapters shown in the menu; extra rows stay hidden// closes ready once the icon exists.func Run(t *tun.Tun, sched *engine.Scheduler, bal *engine.Balancer, stateDir string, startOn bool, ready chan struct{}) {ui := &trayUI{tun: t, sched: sched, bal: bal, stateDir: stateDir, startOn: startOn,- iconOn: icon.Tray(true), iconOff: icon.Tray(false), toggleReq: make(chan struct{}, 1), ready: ready}- systray.Run(ui.onReady, func() { t.Off(); state.Clear(stateDir) })+ iconOn: icon.Tray(true), iconOff: icon.Tray(false), ready: ready}+ exit := func() { t.Off(); state.Clear(stateDir) }+ systray.Run(ui.onReady, exit)+ exit() // macOS's Run returns on Quit without calling onExit; both are idempotent}type trayUI struct {- tun *tun.Tun- bal *engine.Balancer- sched *engine.Scheduler- stateDir string- startOn bool- iconOn []byte- iconOff []byte- toggleReq chan struct{}- ready chan struct{} // closed once the tray icon exists+ tun *tun.Tun+ bal *engine.Balancer+ sched *engine.Scheduler+ stateDir string+ startOn bool+ iconOn []byte+ iconOff []byte+ ready chan struct{} // closed once the tray icon existsheader, toggleItem, v6Item *systray.MenuItemrows []*systray.MenuItem@@ -65,14 +66,8 @@ func (u *trayUI) onReady() {}systray.AddSeparator()u.v6Item = systray.AddMenuItemCheckbox("Use all adapters (IPv6 only if every adapter has it)", "Ticked: apps are pushed to IPv4 so every adapter is used. Unticked: IPv6 is allowed and funnels onto the adapters that have it.", u.bal.V6Mode() == engine.V6Auto)- u.toggleItem = systray.AddMenuItem("Start merging", "Left-click the tray icon does the same")+ u.toggleItem = systray.AddMenuItem("Start merging", "")quit := systray.AddMenuItem("Quit", "Turns system-wide mode off and exits")- systray.SetOnTapped(func() {- select {- case u.toggleReq <- struct{}{}:- default:- }- })go func() {if u.startOn {@@ -85,8 +80,6 @@ func (u *trayUI) onReady() {select {case <-u.toggleItem.ClickedCh:u.turn(!u.tun.IsOn())- case <-u.toggleReq:- u.turn(!u.tun.IsOn())case <-u.v6Item.ClickedCh:if u.v6Item.Checked() {u.v6Item.Uncheck()diff --git a/internal/tun/tun.go b/internal/tun/tun.goindex 5f9fb1e..7e60d1f 100644--- a/internal/tun/tun.go+++ b/internal/tun/tun.go@@ -36,6 +36,12 @@ const (tunIP6 = "fd6e:6d65:7267::1")+// openName is what the OS is asked to call the adapter; macOS only accepts "utunN" and picks the number.+var openName = tunName++// staleHook, if set by a platform, also clears what a crashed run left outside the adapter.+var staleHook func()+// Two /1 routes per family beat any default route (/0) without touching it, so Off() is just// deleting these.var (@@ -105,7 +111,7 @@ func (t *Tun) On() (err error) {tunnel.T().SetUDPTimeout(udpSessionTimeout)CleanupStale()- dev, err := tun.Open(tunName, uint32(t.MTU))+ dev, err := tun.Open(openName, uint32(t.MTU))if err != nil {return fmt.Errorf("open TUN (%s): %w", openHint, err)}@@ -127,7 +133,7 @@ func (t *Tun) On() (err error) {}()tunnel.T().SetProxy(tunProxy{t.B})- if t.idx, err = configure(t.MTU); err != nil {+ if t.idx, err = configure(dev.Name(), t.MTU); err != nil {return err}t.on = true@@ -161,6 +167,9 @@ func (t *Tun) teardown() {// CleanupStale removes routes left on a surviving net-merge adapter (e.g. after a crash).func CleanupStale() {+ if staleHook != nil {+ staleHook()+ }if ifc, err := net.InterfaceByName(tunName); err == nil {delRoutes(ifc.Index)}diff --git a/internal/tun/tun_darwin.go b/internal/tun/tun_darwin.gonew file mode 100644index 0000000..03865d7--- /dev/null+++ b/internal/tun/tun_darwin.go@@ -0,0 +1,216 @@+package tun++import (+ "fmt"+ "net"+ "os/exec"+ "regexp"+ "strings"+ "sync"+ "time"++ "net-merge/internal/logx"+ "net-merge/internal/nics"+)++const openHint = "needs root"++// macOS only accepts "utun" or "utunN" as a TUN name; "utun" lets the kernel pick the number.+func init() {+ openName = "utun"+ staleHook = cleanupScoped+}++// configure gives the new utun its addresses and capture routes, and returns its index.+// ponytail: shells out to ifconfig/route (once per on/off); PF_ROUTE messages if that ever matters.+func configure(name string, _ int) (int, error) {+ ifc, err := net.InterfaceByName(name)+ if err != nil {+ return 0, fmt.Errorf("adapter %q did not appear: %w", name, err)+ }+ // Before the capture routes: pinned sockets need these the moment the /1 routes exist.+ if err := startScopedSync(); err != nil {+ return ifc.Index, err+ }+ if err := run("/sbin/ifconfig", name, "inet", tunIP, tunIP, "up"); err != nil {+ return ifc.Index, err+ }+ for _, dst := range routes4 {+ if err := run("/sbin/route", "-q", "-n", "add", "-inet", dst, "-interface", name); err != nil {+ return ifc.Index, err+ }+ }+ // IPv6 is best-effort: if it can't be set up, IPv4 still works and IPv6 stays on its normal path.+ if err := run("/sbin/ifconfig", name, "inet6", tunIP6, "prefixlen", "64", "alias"); err != nil {+ logx.Printf("warning: IPv6 not captured: %v\n", err)+ return ifc.Index, nil+ }+ for _, dst := range routes6 {+ if err := run("/sbin/route", "-q", "-n", "add", "-inet6", dst, "-interface", name); err != nil {+ logx.Printf("warning: IPv6 route %s: %v\n", dst, err)+ }+ }+ return ifc.Index, nil+}++// delRoutes removes the capturing routes. Closing the utun removes them anyway, but deleting+// them first stops capture before the stack goes away.+func delRoutes(idx int) {+ defer stopScopedSync()+ ifc, err := net.InterfaceByIndex(idx)+ if err != nil {+ return // adapter already gone, and its routes with it+ }+ for _, dst := range routes4 {+ run("/sbin/route", "-q", "-n", "delete", "-inet", dst, "-interface", ifc.Name)+ }+ for _, dst := range routes6 {+ run("/sbin/route", "-q", "-n", "delete", "-inet6", dst, "-interface", ifc.Name)+ }+}++func run(name string, args ...string) error {+ out, err := exec.Command(name, args...).CombinedOutput()+ if err != nil {+ return fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))+ }+ return nil+}++// Our own sockets are bound to an adapter (IP_BOUND_IF), and the kernel then looks routes up+// among that adapter's scoped routes. macOS only keeps a scoped default for non-primary services;+// the primary one has just an unscoped default, which the bound lookup falls back to until the+// more specific /1 capture routes shadow it ("no route to host", network dead). So every adapter+// with a default route also gets a scoped one, kept in step with gateway changes.+var realName = regexp.MustCompile(`^(en|feth)\d+$`)++type scopedKey struct {+ name string+ v6 bool+}++var scoped struct {+ mu sync.Mutex+ added map[scopedKey]string // scoped defaults we added, with their gateway+ stop chan struct{} // non-nil while capture is on+}++func scopedArgs(verb string, k scopedKey, gw string) []string {+ fam := "-inet"+ if k.v6 {+ fam, gw = "-inet6", gw+"%"+k.name+ }+ return []string{"-q", "-n", verb, fam, "default", gw, "-ifscope", k.name}+}++func startScopedSync() error {+ stop := make(chan struct{})+ scoped.mu.Lock()+ scoped.stop, scoped.added = stop, map[scopedKey]string{}+ scoped.mu.Unlock()+ if err := syncScoped(stop); err != nil {+ stopScopedSync()+ return fmt.Errorf("scoped routes: %w", err)+ }+ go func() {+ t := time.NewTicker(3 * time.Second)+ defer t.Stop()+ for {+ select {+ case <-stop:+ return+ case <-t.C:+ if err := syncScoped(stop); err != nil {+ logx.Printf("warning: scoped routes: %v\n", err)+ }+ }+ }+ }()+ return nil+}++func stopScopedSync() {+ scoped.mu.Lock()+ defer scoped.mu.Unlock()+ if scoped.stop != nil {+ close(scoped.stop)+ scoped.stop = nil+ }+ for k, gw := range scoped.added {+ run("/sbin/route", scopedArgs("delete", k, gw)...)+ }+ scoped.added = nil+}++func syncScoped(stop chan struct{}) error {+ routes, err := nics.DefaultRoutes()+ if err != nil {+ return err+ }+ want := map[scopedKey]string{}+ have := map[scopedKey]bool{}+ for _, r := range routes {+ if !realName.MatchString(r.Name) {+ continue+ }+ k := scopedKey{r.Name, r.V6}+ if r.Scoped {+ have[k] = true+ } else if r.GW != nil {+ want[k] = r.GW.String()+ }+ }+ scoped.mu.Lock()+ defer scoped.mu.Unlock()+ if scoped.stop != stop {+ return nil // capture was switched off meanwhile+ }+ var first error+ for k, gw := range want {+ old, ours := scoped.added[k]+ switch {+ case ours && old == gw && have[k]:+ continue+ case !ours && have[k]:+ continue // macOS keeps its own scoped default here+ case ours:+ run("/sbin/route", scopedArgs("delete", k, old)...)+ delete(scoped.added, k)+ }+ if err := run("/sbin/route", scopedArgs("add", k, gw)...); err != nil && !strings.Contains(err.Error(), "File exists") {+ if first == nil {+ first = err+ }+ continue+ }+ scoped.added[k] = gw+ }+ for k, gw := range scoped.added {+ if _, ok := want[k]; !ok {+ run("/sbin/route", scopedArgs("delete", k, gw)...)+ delete(scoped.added, k)+ }+ }+ return first+}++// cleanupScoped removes scoped defaults a crashed run left behind: on a primary adapter any scoped+// default that just repeats its unscoped one is ours, since macOS makes none there.+func cleanupScoped() {+ routes, err := nics.DefaultRoutes()+ if err != nil {+ return+ }+ unscoped := map[scopedKey]string{}+ for _, r := range routes {+ if !r.Scoped && r.GW != nil && realName.MatchString(r.Name) {+ unscoped[scopedKey{r.Name, r.V6}] = r.GW.String()+ }+ }+ for _, r := range routes {+ k := scopedKey{r.Name, r.V6}+ if gw, ok := unscoped[k]; ok && r.Scoped && r.GW != nil && r.GW.String() == gw {+ run("/sbin/route", scopedArgs("delete", k, gw)...)+ }+ }+}diff --git a/internal/tun/tun_linux.go b/internal/tun/tun_linux.goindex 358fe26..9dbe412 100644--- a/internal/tun/tun_linux.go+++ b/internal/tun/tun_linux.go@@ -15,10 +15,10 @@ const openHint = "needs root or CAP_NET_ADMIN, and /dev/net/tun"// configure gives the new adapter its addresses and routes, and returns its index. tun2socks has// already set the MTU. Everything goes through netlink rather than `ip`, so it also works when the// privilege is a file capability, which child processes don't inherit.-func configure(int) (int, error) {- link, err := netlink.LinkByName(tunName)+func configure(name string, _ int) (int, error) {+ link, err := netlink.LinkByName(name)if err != nil {- return 0, fmt.Errorf("adapter %q did not appear: %w", tunName, err)+ return 0, fmt.Errorf("adapter %q did not appear: %w", name, err)}idx := link.Attrs().Indexif err := netlink.AddrReplace(link, &netlink.Addr{IPNet: hostCIDR(tunIP + "/24")}); err != nil {diff --git a/internal/tun/tun_windows.go b/internal/tun/tun_windows.goindex ddc0977..77d4279 100644--- a/internal/tun/tun_windows.go+++ b/internal/tun/tun_windows.go@@ -29,12 +29,12 @@ func init() {}// configure gives the new adapter its addresses, MTU and routes, and returns its index.-func configure(mtu int) (int, error) {- if err := run("netsh", "interface", "ipv4", "set", "address", "name="+tunName, "source=static",+func configure(name string, mtu int) (int, error) {+ if err := run("netsh", "interface", "ipv4", "set", "address", "name="+name, "source=static","address="+tunIP, "mask="+tunMask, "store=active"); err != nil {return 0, err}- ifc, err := waitIface(tunName, 5*time.Second)+ ifc, err := waitIface(name, 5*time.Second)if err != nil {return 0, err}diff --git a/nix/package.nix b/nix/package.nixindex 46100c7..e1098ab 100644--- a/nix/package.nix+++ b/nix/package.nix@@ -19,7 +19,7 @@];};- vendorHash = "sha256-rJelc2cmpkvc02bmMBVicoPDvuhzJsjaq7xI3JQBWRI=";+ vendorHash = "sha256-jbafKGjgOXZAcyQVILbZ3ZUUMhD8gpz+NGBT48Du7mA=";subPackages = [ "cmd/net-merge" ];env.CGO_ENABLED = 0;ldflags = [diff --git a/scripts/macos-smoke.sh b/scripts/macos-smoke.shnew file mode 100755index 0000000..5d4e3ef--- /dev/null+++ b/scripts/macos-smoke.sh@@ -0,0 +1,70 @@+#!/usr/bin/env bash+# Smoke test of system-wide mode on macOS (CI runs it on macos-latest). Needs sudo and internet+# access. The runner has one NIC, so this checks the TUN, routes, relaying, off and crash safety,+# not balancing (that needs a second uplink: plug in a tether and watch `net-merge status`).+#+# usage: scripts/macos-smoke.sh ./net-merge+set -uo pipefail+BIN=$(cd "$(dirname "${1:-./net-merge}")" && pwd)/$(basename "${1:-./net-merge}")+STATE=/tmp/net-merge-smoke+fails=0+pass() { echo "PASS $*"; }+fail() { echo "FAIL $*"; fails=$((fails + 1)); }++cleanup() { sudo pkill -f "$BIN run" 2>/dev/null; sudo "$BIN" cleanup >/dev/null 2>&1; }+trap cleanup EXIT++wait_on() { # wait until `net-merge status` reports ON+ for _ in $(seq 1 40); do+ "$BIN" status -state-dir "$STATE" 2>/dev/null | grep -q 'is ON' && return 0+ sleep 0.5+ done+ return 1+}+http() { curl -4 -s --max-time 10 -o /dev/null -w '%{http_code}' https://example.com; }+captured() { netstat -rn -f inet | grep -cE '^(0/1|128.0/1) '; }+scoped_defaults() { netstat -rn -f inet | grep -E '^default' | grep -cE 'UG[A-Za-z]*I'; }++rm -rf "$STATE"+echo "== adapters"+"$BIN" list | grep -E '^(USE|skip en)'++echo "== system-wide ON"+sudo "$BIN" run -state-dir "$STATE" -log "$STATE.log" -stats 0 -for 150s &+wait_on && pass "net-merge turned on" || { fail "net-merge did not turn on"; cat "$STATE.log"; exit 1; }+sleep 4 # let the internet probes finish+"$BIN" status -state-dir "$STATE"++[ "$(captured)" = 2 ] && pass "capture routes 0/1 + 128.0/1 present" || fail "capture routes: $(captured), want 2"+tun=$(ifconfig -l | tr ' ' '\n' | grep '^utun' | while read -r i; do ifconfig "$i" | grep -q 'inet 198.18.0.1' && echo "$i"; done)+[ -n "$tun" ] && pass "utun $tun has 198.18.0.1" || fail "no utun with 198.18.0.1"+mtu=$(ifconfig "$tun" 2>/dev/null | sed -n 's/.*mtu \([0-9]*\).*/\1/p')+[ "$mtu" = 9000 ] && pass "TUN MTU is 9000" || fail "TUN MTU is $mtu, want 9000"+[ "$(http)" = 200 ] && pass "HTTPS works through net-merge" || fail "HTTPS through net-merge failed"+dig +short +time=3 +tries=1 @1.1.1.1 example.com | grep -qE '^[0-9.]+$' &&+ pass "UDP DNS to 1.1.1.1 works through net-merge" || fail "UDP DNS through net-merge failed"+relayed=$(jq '[.NICs[].Total] | add' /var/run/net-merge/status.json 2>/dev/null || jq '[.NICs[].Total] | add' "$STATE/status.json")+[ "${relayed:-0}" -ge 1 ] && pass "flows were relayed by net-merge ($relayed)" || fail "no flow went through net-merge"++echo "== off: adapter, routes and scoped defaults go away, internet still works"+"$BIN" off -state-dir "$STATE"+sleep 1+[ "$(captured)" = 0 ] && pass "capture routes removed" || fail "capture routes still present"+[ "$(scoped_defaults)" = 0 ] && pass "scoped default routes removed" || fail "scoped default routes left behind"+ifconfig "$tun" >/dev/null 2>&1 && fail "$tun still exists after off" || pass "utun removed after off"+[ "$(http)" = 200 ] && pass "internet works after off" || fail "internet after off failed"++echo "== crash: kill -9 must not leave the machine without internet"+sudo "$BIN" run -state-dir "$STATE" -log "$STATE-2.log" -stats 0 -for 120s &+wait_on || fail "second start did not turn on"+pid=$(jq -r .PID "$STATE/status.json" 2>/dev/null)+sudo kill -9 "$pid"+sleep 1+[ "$(captured)" = 0 ] && pass "capture routes gone after kill -9" || fail "capture routes survived kill -9"+[ "$(http)" = 200 ] && pass "internet works after kill -9" || fail "internet after kill -9 failed"+sudo "$BIN" cleanup >/dev/null+[ "$(scoped_defaults)" = 0 ] && pass "cleanup removed the leftover scoped defaults" || fail "scoped defaults left after cleanup"++echo+[ "$fails" -eq 0 ] && echo "ALL CHECKS PASSED" || echo "$fails CHECK(S) FAILED"+exit "$fails"