Skip to content

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

Port to Linux and NixOS; split the source into packages

sidharthify0d4ab9f7a47f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 8359a17..0686407 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,7 +6,11 @@ on:
jobs:
test:
- runs-on: windows-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [windows-latest, ubuntu-latest]
+ runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
@@ -14,3 +18,14 @@ jobs:
go-version-file: go.mod
- run: go vet ./...
- run: go test ./...
+ - name: Cross-build linux/arm64
+ if: runner.os == 'Linux'
+ run: GOARCH=arm64 go build -o /dev/null ./cmd/net-merge
+
+ nix:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: cachix/install-nix-action@v31
+ - run: nix build -L .#net-merge
+ - run: nix flake check -L
diff --git a/.gitignore b/.gitignore
index c9f82ce..58c3d8d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
*.exe
wintun.dll
dist/
+result
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 872c4ee..107ed25 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,22 @@
What changed in each release. Each version's section becomes its GitHub release notes, so add the
entry here before pushing a version tag.
+## [Unreleased]
+
+### Added
+- **Linux support**, including NixOS. System-wide mode, the tray icon (any desktop with
+ StatusNotifierItem support: KDE, GNOME with the AppIndicator extension, XFCE, Cinnamon, ...), the
+ SOCKS5 proxy, live per-adapter speeds and autostart (XDG autostart entry) all work. The TUN and
+ its routes are set up over netlink, flows are pinned with `SO_BINDTOIFINDEX`, and adapters are
+ detected from sysfs and the routing tables. Needs root or `CAP_NET_ADMIN` (`setcap`).
+- **Nix flake** with a package and a NixOS module: `programs.net-merge.enable` installs a capability
+ wrapper so the tray runs without root, and `programs.net-merge.autostart` starts it in every
+ graphical session.
+
+### Changed
+- 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`.
+
## [0.1.1] - 2026-10-14
### Added
diff --git a/README.md b/README.md
index 2e5f9a1..eb0644e 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
# net-merge
-Use all your network adapters at once on Windows. Every new connection (TCP and UDP, IPv4 and IPv6) is
+Use all your network adapters at once on Windows and Linux (including NixOS). Every new connection (TCP and UDP, IPv4 and IPv6) is
pinned 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 is
still limited to one link.
@@ -26,8 +26,8 @@ No server, VPN or account is involved: connections go straight out of the adapte
tracked separately for IPv4 and IPv6. A link with no internet (tether without data, captive-portal
Wi-Fi) gets nothing until it recovers.
- **Live speeds on hover**: each adapter's download/upload and the total. These are the adapters' real
- traffic from Windows, so apps that bypass net-merge (qBittorrent binds to adapters itself) still count.
-- **One click on and off**, and optional start at sign-in without a UAC prompt.
+ traffic 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).
- **Safe to crash**: the virtual adapter and its routes disappear with the process, so a crash or a kill
never leaves the PC without internet.
- **Light on CPU**: about 0.18 cores per 100 Mbit/s.
@@ -40,12 +40,56 @@ No server, VPN or account is involved: connections go straight out of the adapte
## Install
+### Windows
+
Download `net-merge-setup-x.y.z.exe` from the [releases page](../../releases) and run it (needs admin).
It is not code-signed yet, so SmartScreen will warn: *More info > Run anyway*. A portable zip is also
published. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
+### NixOS
+
+Add the flake and enable the module. It installs `net-merge` as a capability wrapper
+(`/run/wrappers/bin/net-merge` with `CAP_NET_ADMIN`), so the tray and `net-merge run` work without
+root, and trusts the `net-merge` interface in the firewall:
+
+```nix
+# flake.nix
+inputs.net-merge.url = "github:sidharthify/net-merge";
+
+# configuration.nix (with `inputs` passed via specialArgs)
+imports = [ inputs.net-merge.nixosModules.default ];
+programs.net-merge = {
+ enable = true;
+ autostart = true; # optional: start the tray in every graphical session (systemd user service)
+ # extraArgs = [ "-ipv6" "on" ];
+};
+```
+
+To try it without installing: `sudo nix run github:sidharthify/net-merge -- run`.
+
+### Other Linux distributions
+
+Build it (see [Build](#build)), put it on your `PATH`, and give it the capability once so it runs
+without root:
+
+```
+go build -o net-merge ./cmd/net-merge
+sudo install -m 755 net-merge /usr/local/bin/
+sudo setcap cap_net_admin,cap_net_raw+ep /usr/local/bin/net-merge
+```
+
+Without the capability, `net-merge run` asks for your password through `sudo` (or `pkexec` without a
+terminal); the tray can't run as root, because its icon lives on your desktop session's D-Bus. The
+tray icon needs a desktop with StatusNotifierItem support: KDE, XFCE, Cinnamon, LXQt, Budgie, or GNOME
+with the *AppIndicator and KStatusNotifierItem Support* extension. If you use a firewall that drops
+unsolicited input, trust the `net-merge` interface (e.g. `firewall-cmd --zone=trusted
+--add-interface=net-merge`).
+
## 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.
+
1. Start **net-merge** from the Start menu and approve the admin prompt. A tray icon appears (if you
don't see it, it is behind the `^` arrow next to the clock; drag it onto the taskbar).
2. Connect more links: plug in your phone with USB tethering on, join a second Wi-Fi, plug in Ethernet.
@@ -57,7 +101,8 @@ published. What changed in each version: [CHANGELOG.md](CHANGELOG.md).
- **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*
4. To start it at sign-in, tick *Start net-merge when I sign in* in the installer, or run
- `net-merge autostart on`.
+ `net-merge autostart on` (on Linux this writes an XDG autostart entry; on NixOS prefer
+ `programs.net-merge.autostart`).
Tips:
- It helps most when an app opens many connections at once: Steam, browsers, cloud uploads, download
@@ -89,17 +134,17 @@ Flags for `tray`/`run`/`socks`: `-include "WiFi,Ethernet"` (only these adapters)
## How it works
-- ON creates a Wintun adapter `net-merge` 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) and two `/1` routes per IP family that beat the default route
without touching it. OFF deletes them. If the process dies the adapter and routes die with it, so a
crash can't leave the machine without internet.
- Flows entering the TUN are terminated in a userland TCP/IP stack (tun2socks/gVisor) and re-dialed from
a chosen adapter: the socket is bound to that adapter's source IP and forced out of it with
- `IP_UNICAST_IF`, so it can never loop back into the TUN.
-- The virtual adapter runs at MTU 9000 (both Windows and the userland stack). Its traffic never leaves
+ `IP_UNICAST_IF` (Windows) or `SO_BINDTOIFINDEX` (Linux), 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 leaves
the machine, so the links' 1500 doesn't apply, and bigger packets cost far less CPU: measured about
3x 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 gateway
- is used: tunnels, VPNs (Tailscale, WireGuard, ...), virtual switches and LAN-only adapters are skipped
+- 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
(`net-merge list` shows why).
- Each adapter and each address family is probed for real internet access. A tether with no data or a
captive-portal Wi-Fi gets no flows; a recovered link rejoins within seconds.
@@ -117,14 +162,17 @@ 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 only.
+- Needs admin (for the TUN). Windows 10/11 x64, or Linux (x86_64, aarch64) with root or
+ `CAP_NET_ADMIN`.
## Build
-Needs Go (see `go.mod`) and, for the installer, [Inno Setup 6](https://jrsoftware.org/isinfo.php).
+Needs Go (see `go.mod`) and, for the Windows installer, [Inno Setup 6](https://jrsoftware.org/isinfo.php).
```
go test ./... # uses loopback aliases as fake adapters; no second link needed
+go build -o net-merge ./cmd/net-merge # Linux
+nix build # Linux, with Nix: result/bin/net-merge
scripts\build.ps1 -Version 0.1.0 # dist\: net-merge.exe, net-merge-tray.exe, installer, portable zip
```
@@ -132,13 +180,20 @@ scripts\build.ps1 -Version 0.1.0 # dist\: net-merge.exe, net-merge-tray.exe,
WireGuard LLC signature. To run from source, put it next to the exe:
```
-go build -o net-merge.exe .
+go build -o net-merge.exe .\cmd\net-merge
scripts\fetch-wintun.ps1 -OutDir .
```
Releases are built by GitHub Actions when a `vX.Y.Z` tag is pushed (`.github/workflows/release.yml`).
Add the version's section to `CHANGELOG.md` first: it becomes the release notes, and the release fails
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 and
+SOCKS5 front-end; `internal/nics` adapter discovery, counters and egress pinning; `internal/tun` the
+system-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
+Nix package and NixOS module are in `nix/`; after changing Go dependencies, update `vendorHash` in
+`nix/package.nix` (`nix build` prints the new one).
+
`go test -run xxx -bench Relay ./...` measures the relay data path (about 3 GB/s over loopback).
Don't benchmark against speed.cloudflare.com repeatedly: it rate-limits the IP (HTTP 429) after a few
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 36fe8cb..374be14 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -9,7 +9,8 @@ licenses (license texts are in each project's repository and in the Go module ca
| [gVisor](https://github.com/google/gvisor) (netstack) | Apache-2.0 | userland TCP/IP stack |
| [wireguard-go](https://git.zx2c4.com/wireguard-go) / [wintun Go bindings](https://git.zx2c4.com/wintun-go) | MIT | Windows TUN device access |
| [fyne.io/systray](https://github.com/fyne-io/systray) | Apache-2.0 | system tray icon |
-| golang.org/x/sys, golang.org/x/net, golang.org/x/time, golang.org/x/crypto | BSD-3-Clause | Windows APIs and support code |
+| [vishvananda/netlink](https://github.com/vishvananda/netlink) | Apache-2.0 | Linux TUN addresses and routes, default-route discovery |
+| golang.org/x/sys, golang.org/x/net, golang.org/x/time, golang.org/x/crypto | BSD-3-Clause | Windows and Linux system APIs, support code |
| Other transitive modules (see `go.mod` / `go.sum`) | MIT / Apache-2.0 / BSD | |
## Wintun
diff --git a/main.go b/cmd/net-merge/main.go
similarity index 74%
rename from main.go
rename to cmd/net-merge/main.go
index c5aeb6e..0d24b51 100644
--- a/main.go
+++ b/cmd/net-merge/main.go
@@ -3,35 +3,39 @@ package main
import (
"flag"
"fmt"
- "io"
+ "net"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
+
+ "net-merge/internal/engine"
+ "net-merge/internal/icon"
+ "net-merge/internal/logx"
+ "net-merge/internal/nics"
+ "net-merge/internal/platform"
+ "net-merge/internal/state"
+ "net-merge/internal/tun"
)
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 run system-wide ON in a console window (asks for admin); Ctrl+C or "off" turns it OFF
+ net-merge run system-wide ON in a console window (asks for admin/root); Ctrl+C or "off" turns it OFF
net-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
net-merge status show whether it is on, and per-adapter load
net-merge socks plain SOCKS5 proxy on 127.0.0.1:1080 (no admin, per-app)
net-merge list show detected adapters
- net-merge autostart on|off|status start the tray at sign-in (no UAC prompt)
- net-merge cleanup remove leftover routes after a crash (admin)
+ net-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 version
Flags for run/socks: -include "WiFi,Ethernet 3" -weight "Name=3" -auto-weight=false -stats 5s
`
-var out io.Writer = os.Stdout
-
-func logf(format string, a ...any) { fmt.Fprintf(out, format, a...) }
-
type weightFlags map[string]float64
func (w weightFlags) String() string { return "" }
@@ -69,23 +73,23 @@ func (c *common) register(fs *flag.FlagSet) {
fs.DurationVar(&c.stats, "stats", 5*time.Second, "stats print interval (0 = off)")
fs.BoolVar(&c.auto, "auto-weight", true, "weight adapters by measured throughput (off when -weight is given)")
fs.StringVar(&c.ipv6, "ipv6", "auto", "auto: IPv6 only if every adapter has it (else apps use IPv4 on all adapters); on: always; off: never")
- fs.IntVar(&c.mtu, "mtu", defaultMTU, "MTU of the virtual adapter (1280-65535); larger means fewer packets and less CPU")
+ fs.IntVar(&c.mtu, "mtu", tun.DefaultMTU, "MTU of the virtual adapter (1280-65535); larger means fewer packets and less CPU")
fs.StringVar(&c.pprof, "pprof", "", "serve Go's profiler on this loopback address, e.g. 127.0.0.1:6060")
fs.StringVar(&c.logFile, "log", "", "write output to this file instead of the console")
- fs.StringVar(&c.stateDir, "state-dir", defaultStateDir(), "where status/off marker files live")
+ fs.StringVar(&c.stateDir, "state-dir", state.DefaultDir(), "where status/off marker files live")
}
-func (c *common) nicsDetailed() ([]Nic, []Skip, error) {
+func (c *common) nicsDetailed() ([]nics.Nic, []nics.Skip, error) {
var inc []string
for _, s := range strings.Split(c.include, ",") {
if s = strings.TrimSpace(s); s != "" {
inc = append(inc, s)
}
}
- return DiscoverNicsDetailed(inc, c.weights)
+ return nics.DiscoverNicsDetailed(inc, c.weights)
}
-func (c *common) nics() ([]Nic, error) {
+func (c *common) nics() ([]nics.Nic, error) {
nics, _, err := c.nicsDetailed()
return nics, err
}
@@ -100,15 +104,15 @@ func (c *common) setup() error {
if err != nil {
return err
}
- out = f
- redirectStd(f)
+ logx.SetOutput(f)
+ platform.RedirectStd(f)
}
return nil
}
// boot discovers adapters and starts the background loops: re-scan, 1s throughput sampling
// (which also drives auto-weights and the status file), and periodic stats printing.
-func (c *common) boot(mode func() string) (*Scheduler, *Balancer, error) {
+func (c *common) boot(mode func() string) (*engine.Scheduler, *engine.Balancer, error) {
if c.mtu < 1280 || c.mtu > 65535 {
return nil, nil, fmt.Errorf("-mtu must be between 1280 and 65535, got %d", c.mtu)
}
@@ -124,17 +128,17 @@ func (c *common) boot(mode func() string) (*Scheduler, *Balancer, error) {
if len(nics) == 0 {
return nil, nil, fmt.Errorf("no usable IPv4 adapters found (try: net-merge list)")
}
- sched := NewScheduler(nics)
+ sched := engine.NewScheduler(nics)
sched.SetAuto(c.auto && len(c.weights) == 0)
for _, n := range nics {
- logf(" + %s\n", describeNic(n))
+ logx.Printf(" + %s\n", describeNic(n))
}
if len(nics) == 1 {
- logf(" note: only one adapter found, nothing to aggregate yet\n")
+ logx.Printf(" note: only one adapter found, nothing to aggregate yet\n")
}
- bal := NewBalancer(sched)
- v6, ok := ParseV6Mode(c.ipv6)
+ bal := engine.NewBalancer(sched)
+ v6, ok := engine.ParseV6Mode(c.ipv6)
if !ok {
return nil, nil, fmt.Errorf(`-ipv6 must be auto, on or off, got %q`, c.ipv6)
}
@@ -156,7 +160,7 @@ func (c *common) boot(mode func() string) (*Scheduler, *Balancer, error) {
last = now
if mode != nil {
if m := mode(); m != "" {
- writeStatus(c.stateDir, Status{PID: os.Getpid(), Mode: m, V6: bal.V6State(), Since: since, Updated: now, NICs: sched.Snapshot()})
+ state.Write(c.stateDir, state.Status{PID: os.Getpid(), Mode: m, V6: bal.V6State(), Since: since, Updated: now, NICs: sched.Snapshot()})
}
}
}
@@ -164,14 +168,14 @@ func (c *common) boot(mode func() string) (*Scheduler, *Balancer, error) {
if c.stats > 0 {
go func() {
for range time.Tick(c.stats) {
- logf("--- %s\n%s", time.Now().Format("15:04:05"), formatNICs(sched.Snapshot()))
+ logx.Printf("--- %s\n%s", time.Now().Format("15:04:05"), formatNICs(sched.Snapshot()))
}
}()
}
return sched, bal, nil
}
-func describeNic(n Nic) string {
+func describeNic(n nics.Nic) string {
s := n.Name
if n.IP != nil {
s += " v4 " + n.IP.String()
@@ -182,7 +186,7 @@ func describeNic(n Nic) string {
return s
}
-func formatNICs(snap []SlotStats) string {
+func formatNICs(snap []engine.SlotStats) string {
var sb strings.Builder
for _, s := range snap {
gone := ""
@@ -219,12 +223,18 @@ func main() {
case "version":
fmt.Println("net-merge", version)
case "autostart":
- cmdAutostart(args)
+ if len(args) != 1 || (args[0] != "on" && args[0] != "off" && args[0] != "status") {
+ fmt.Fprintln(os.Stderr, "usage: net-merge autostart on|off|status")
+ os.Exit(2)
+ }
+ if err := platform.Autostart(args[0]); err != nil {
+ die(err)
+ }
case "_icon": // build helper: writes the tray icon as an .ico
if len(args) != 1 {
os.Exit(2)
}
- if err := os.WriteFile(args[0], trayIcon(true), 0o644); err != nil {
+ if err := os.WriteFile(args[0], icon.ICO(true), 0o644); err != nil {
die(err)
}
case "tray":
@@ -249,8 +259,8 @@ func main() {
func die(err error) {
fmt.Fprintln(os.Stderr, "error:", err)
- if !hasConsole() {
- showError(err.Error())
+ if !platform.HasConsole() {
+ platform.ShowError(err.Error())
}
os.Exit(1)
}
@@ -288,12 +298,12 @@ func cmdSocks(args []string) {
if err != nil {
die(err)
}
- ln, err := listenTCP(*listen)
+ ln, err := net.Listen("tcp4", *listen)
if err != nil {
die(err)
}
- logf("net-merge SOCKS5 listening on %s\n", *listen)
- die(serveSocks5(ln, bal))
+ logx.Printf("net-merge SOCKS5 listening on %s\n", *listen)
+ die(engine.ServeSocks5(ln, bal))
}
func cmdRun(args []string) {
@@ -305,41 +315,42 @@ func cmdRun(args []string) {
runFor := fs.Duration("for", 0, "turn off automatically after this long (0 = until stopped)")
fs.Parse(args)
- if !isAdmin() {
+ if !platform.IsAdmin() {
// Re-run elevated, handing over where to log and keep state.
child := append([]string{"run"}, args...)
child = append(child, "-state-dir", c.stateDir)
- if err := relaunchElevated(child, *hidden); err != nil {
- die(fmt.Errorf("could not start elevated (UAC declined?): %w", err))
+ os.MkdirAll(c.stateDir, 0o755) // as this user, so `net-merge off` can still drop markers in it
+ if err := platform.RelaunchElevated(child, *hidden); err != nil {
+ die(fmt.Errorf("could not start elevated: %w", err))
}
fmt.Println("Approve the UAC prompt. System-wide mode runs in the new window; `net-merge off` turns it off.")
return
}
- if !singleInstance() {
+ if !platform.SingleInstance() {
fmt.Println("net-merge is already running (check the system tray, or run `net-merge off`).")
return
}
if err := c.setup(); err != nil {
die(err)
}
- if err := checkWintun(); err != nil {
- logf("error: %v\n", err)
+ if err := platform.CheckDriver(); err != nil {
+ logx.Printf("error: %v\n", err)
os.Exit(1)
}
- takeMarker(c.stateDir, "off") // drop a stale marker
+ state.TakeMarker(c.stateDir, "off") // drop a stale marker
_, bal, err := c.boot(func() string { return "system-wide" })
if err != nil {
- logf("error: %v\n", err)
+ logx.Printf("error: %v\n", err)
os.Exit(1)
}
- tun := NewTun(bal)
- tun.mtu = c.mtu
- if err := tun.On(); err != nil {
- logf("error: %v\n", err)
+ t := tun.New(bal)
+ t.MTU = c.mtu
+ if err := t.On(); err != nil {
+ logx.Printf("error: %v\n", err)
os.Exit(1)
}
- logf("net-merge is ON: all IPv4 traffic is balanced across the adapters above. Ctrl+C or `net-merge off` to stop.\n")
+ logx.Printf("net-merge is ON: all IPv4 traffic is balanced across the adapters above. Ctrl+C or `net-merge off` to stop.\n")
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
@@ -359,37 +370,37 @@ func cmdRun(args []string) {
case <-crash:
os.Exit(3) // simulates a crash: no teardown runs
case <-poll.C:
- if !takeMarker(c.stateDir, "off") && !takeMarker(c.stateDir, "quit") {
+ if !state.TakeMarker(c.stateDir, "off") && !state.TakeMarker(c.stateDir, "quit") {
continue
}
}
break
}
- tun.Off()
- clearStatus(c.stateDir)
- logf("net-merge is OFF.\n")
+ t.Off()
+ state.Clear(c.stateDir)
+ logx.Printf("net-merge is OFF.\n")
}
// cmdControl implements `on`, `off` and `quit` against a running tray/run instance.
func cmdControl(name string, args []string) {
fs := flag.NewFlagSet(name, flag.ExitOnError)
- dir := fs.String("state-dir", defaultStateDir(), "state directory")
+ dir := fs.String("state-dir", state.DefaultDir(), "state directory")
fs.Parse(args)
- if !instanceRunning() {
+ if !platform.InstanceRunning() {
if name == "off" || name == "quit" {
fmt.Println("net-merge is not running (already off).")
return
}
die(fmt.Errorf("net-merge is not running; start it with `net-merge tray`"))
}
- _, wasOn := readStatus(*dir)
- if err := sendMarker(*dir, name); err != nil {
+ _, wasOn := state.Read(*dir)
+ if err := state.SendMarker(*dir, name); err != nil {
die(err)
}
want := name == "on"
for i := 0; i < 60; i++ {
time.Sleep(150 * time.Millisecond)
- _, on := readStatus(*dir)
+ _, on := state.Read(*dir)
switch {
case name == "on" && on == want:
fmt.Println("net-merge is ON.")
@@ -405,9 +416,9 @@ func cmdControl(name string, args []string) {
func cmdStatus(args []string) {
fs := flag.NewFlagSet("status", flag.ExitOnError)
- dir := fs.String("state-dir", defaultStateDir(), "state directory")
+ dir := fs.String("state-dir", state.DefaultDir(), "state directory")
fs.Parse(args)
- st, on := readStatus(*dir)
+ st, on := state.Read(*dir)
if !on {
fmt.Println("net-merge is OFF.")
return
@@ -416,12 +427,12 @@ func cmdStatus(args []string) {
}
func cmdCleanup() {
- if !isAdmin() {
- if err := relaunchElevated([]string{"cleanup"}, false); err != nil {
+ if !platform.IsAdmin() {
+ if err := platform.RelaunchElevated([]string{"cleanup"}, false); err != nil {
die(err)
}
return
}
- cleanupStale()
+ tun.CleanupStale()
fmt.Println("done.")
}
diff --git a/pprof.go b/cmd/net-merge/pprof.go
similarity index 89%
rename from pprof.go
rename to cmd/net-merge/pprof.go
index 92ad8da..3f1fc18 100644
--- a/pprof.go
+++ b/cmd/net-merge/pprof.go
@@ -5,6 +5,8 @@ import (
"net"
"net/http"
_ "net/http/pprof" // registers /debug/pprof/ on the default mux
+
+ "net-merge/internal/logx"
)
// startPprof serves Go's profiler for diagnosing CPU use, e.g.
@@ -25,6 +27,6 @@ func startPprof(addr string) error {
return err
}
go http.Serve(ln, nil)
- logf("pprof on http://%s/debug/pprof/\n", addr)
+ logx.Printf("pprof on http://%s/debug/pprof/\n", addr)
return nil
}
diff --git a/cmd/net-merge/tray.go b/cmd/net-merge/tray.go
new file mode 100644
index 0000000..368417e
--- /dev/null
+++ b/cmd/net-merge/tray.go
@@ -0,0 +1,79 @@
+package main
+
+import (
+ "flag"
+ "fmt"
+ "os"
+ "path/filepath"
+ "time"
+
+ "net-merge/internal/logx"
+ "net-merge/internal/platform"
+ "net-merge/internal/tray"
+ "net-merge/internal/tun"
+)
+
+func cmdTray(args []string) {
+ fs := flag.NewFlagSet("tray", flag.ExitOnError)
+ var c common
+ c.register(fs)
+ hidden := fs.Bool("hidden", true, "hide the console window of the elevated process")
+ startOff := fs.Bool("off", false, "start with system-wide mode OFF (default: ON)")
+ fs.Parse(args)
+
+ if !platform.IsAdmin() {
+ child := append([]string{"tray"}, args...)
+ 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).")
+ return
+ }
+ if !platform.SingleInstance() {
+ fmt.Println("net-merge is already running.")
+ return
+ }
+ if c.logFile == "" {
+ c.stats = 0 // nobody is watching a hidden console
+ if !platform.HasConsole() {
+ c.logFile = filepath.Join(c.stateDir, "net-merge.log") // windowless build: keep a log for diagnosis
+ }
+ }
+ if err := c.setup(); err != nil {
+ die(err)
+ }
+ if err := platform.CheckDriver(); err != nil {
+ die(err)
+ }
+
+ t := tun.New(nil)
+ t.MTU = c.mtu
+ mode := func() string {
+ if t.IsOn() {
+ return "system-wide (tray)"
+ }
+ return ""
+ }
+ sched, bal, err := c.boot(mode)
+ if err != nil {
+ die(err)
+ }
+ t.B = bal
+
+ // Started at sign-in this process can beat the desktop shell by a fraction of a second. With no
+ // taskbar the tray library fails to create the icon and never becomes ready, so wait for it.
+ if !platform.WaitForTray(3 * time.Minute) {
+ logx.Printf("warning: taskbar not found after 3 minutes, trying anyway\n")
+ }
+ ready := make(chan struct{})
+ go func() { // safety net: if the icon still can't be created, exit so autostart can retry
+ select {
+ case <-ready:
+ case <-time.After(30 * time.Second):
+ logx.Printf("error: tray icon did not initialise within 30s; exiting so autostart can restart it\n")
+ os.Exit(4)
+ }
+ }()
+ tray.Run(t, sched, bal, c.stateDir, !*startOff, ready)
+}
diff --git a/flake.lock b/flake.lock
new file mode 100644
index 0000000..cd19318
--- /dev/null
+++ b/flake.lock
@@ -0,0 +1,27 @@
+{
+ "nodes": {
+ "nixpkgs": {
+ "locked": {
+ "lastModified": 1791734076,
+ "narHash": "sha256-i5qk1kLiit98rRbh1AXmWBNT9QXC/y4l5Wk/u5EdpDQ=",
+ "owner": "NixOS",
+ "repo": "nixpkgs",
+ "rev": "7fd4004d0511991fff3a0524856a9be09e28c5f0",
+ "type": "github"
+ },
+ "original": {
+ "owner": "NixOS",
+ "ref": "nixos-unstable",
+ "repo": "nixpkgs",
+ "type": "github"
+ }
+ },
+ "root": {
+ "inputs": {
+ "nixpkgs": "nixpkgs"
+ }
+ }
+ },
+ "root": "root",
+ "version": 7
+}
diff --git a/flake.nix b/flake.nix
new file mode 100644
index 0000000..538ec81
--- /dev/null
+++ b/flake.nix
@@ -0,0 +1,33 @@
+{
+ description = "net-merge: use all your network adapters at once";
+
+ inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
+
+ outputs =
+ { self, nixpkgs }:
+ let
+ systems = [
+ "x86_64-linux"
+ "aarch64-linux"
+ ];
+ forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f nixpkgs.legacyPackages.${system});
+ version = self.shortRev or self.dirtyShortRev or "dev";
+ in
+ {
+ packages = forAllSystems (pkgs: rec {
+ net-merge = pkgs.callPackage ./nix/package.nix { inherit version; };
+ default = net-merge;
+ });
+
+ nixosModules = rec {
+ net-merge = import ./nix/module.nix self;
+ default = net-merge;
+ };
+
+ devShells = forAllSystems (pkgs: {
+ default = pkgs.mkShell { packages = [ pkgs.go_1_27 ]; };
+ });
+
+ formatter = forAllSystems (pkgs: pkgs.nixfmt-rfc-style);
+ };
+}
diff --git a/go.mod b/go.mod
index df9c586..aa8c55a 100644
--- a/go.mod
+++ b/go.mod
@@ -4,6 +4,7 @@ go 1.27
require (
fyne.io/systray v1.12.2
+ github.com/vishvananda/netlink v1.3.1
github.com/xjasonlyu/tun2socks/v2 v2.7.0
golang.org/x/sys v0.46.0
golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446
@@ -14,6 +15,7 @@ require (
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/google/uuid v1.6.0 // indirect
+ github.com/vishvananda/netns v0.0.5 // indirect
go.uber.org/atomic v1.11.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.uber.org/zap v1.28.0 // indirect
diff --git a/go.sum b/go.sum
index 279a99e..f832121 100644
--- a/go.sum
+++ b/go.sum
@@ -12,6 +12,10 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
+github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
+github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
+github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
+github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/xjasonlyu/tun2socks/v2 v2.7.0 h1:fYEN0Q1sSanuoID8xvUTsMODbKLJJH/J5ywYoMRxIPw=
github.com/xjasonlyu/tun2socks/v2 v2.7.0/go.mod h1:XHgJ3wbs63mZxGbJawt6jjNX65aPDl+Qhn2ePPEE4KI=
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
@@ -28,6 +32,8 @@ golang.org/x/exp v0.0.0-20260611194520-c48552f49976 h1:X8Hz2ImujgbmetVuW+w2YkyZC
golang.org/x/exp v0.0.0-20260611194520-c48552f49976/go.mod h1:vnf4pv9iKZXY58sQE1L86zmNWJ4159e1RkcWiLCkeEY=
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
+golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
diff --git a/balancer.go b/internal/engine/balancer.go
similarity index 93%
rename from balancer.go
rename to internal/engine/balancer.go
index 0778305..d6406ad 100644
--- a/balancer.go
+++ b/internal/engine/balancer.go
@@ -1,4 +1,4 @@
-package main
+package engine
import (
"context"
@@ -10,6 +10,8 @@ import (
"sync/atomic"
"syscall"
"time"
+
+ "net-merge/internal/nics"
)
// Balancer dials outbound flows through the Scheduler. Front-ends (SOCKS5 now, TUN later)
@@ -129,16 +131,16 @@ func classify(err error) dialClass {
// DialTCP connects to host:port over one NIC, failing over to the others on link-level errors.
// On success the caller owns the returned slot and must Relay or Release it.
-func (b *Balancer) DialTCP(ctx context.Context, host string, port int) (net.Conn, *Slot, family, error) {
+func (b *Balancer) DialTCP(ctx context.Context, host string, port int) (net.Conn, *Slot, Family, error) {
// The destination's family decides which NIC address is used; a host name stays IPv4.
- f, network := fam4, "tcp4"
+ f, network := Fam4, "tcp4"
if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
- f, network = fam6, "tcp6"
+ f, network = Fam6, "tcp6"
}
tried := map[string]struct{}{}
rep := byte(repFailure)
var lastErr error = errors.New("no usable network adapter")
- if f == fam6 {
+ if f == Fam6 {
rep, lastErr = repNetUnreachable, errors.New("no usable IPv6 adapter")
}
for {
@@ -148,8 +150,8 @@ func (b *Balancer) DialTCP(ctx context.Context, host string, port int) (net.Conn
}
tried[sl.key] = struct{}{}
d := net.Dialer{
- LocalAddr: &net.TCPAddr{IP: sl.ip(f)}, // binding the source IP pins the flow to this NIC
- Control: unicastIF(sl.Index, f == fam6), // and this forces egress even if the TUN's routes match
+ LocalAddr: &net.TCPAddr{IP: sl.ip(f)}, // binding the source IP pins the flow to this NIC
+ Control: nics.ForceEgress(sl.Index, f == Fam6), // and this forces egress even if the TUN's routes match
Timeout: b.ConnectTimeout,
KeepAlive: 30 * time.Second,
}
@@ -182,7 +184,7 @@ var bufPool = sync.Pool{New: func() any { b := make([]byte, 128<<10); return &b
// Relay copies both directions until both sides finish, counting bytes on the slot, then
// closes both conns and releases the slot. Half-close is honoured so request/response
// protocols that shut down their write side still receive the reply.
-func Relay(client, upstream net.Conn, sl *Slot, f family, s *Scheduler) {
+func Relay(client, upstream net.Conn, sl *Slot, f Family, s *Scheduler) {
var wg sync.WaitGroup
var once sync.Once
release := func() { once.Do(func() { s.ReleaseFor(sl, f) }) } // at the first half-close, see slotConn
diff --git a/flowconn.go b/internal/engine/flowconn.go
similarity index 92%
rename from flowconn.go
rename to internal/engine/flowconn.go
index b130d29..030fc20 100644
--- a/flowconn.go
+++ b/internal/engine/flowconn.go
@@ -1,10 +1,12 @@
-package main
+package engine
import (
"context"
"errors"
"net"
"sync"
+
+ "net-merge/internal/nics"
)
// slotConn counts a pinned TCP flow's bytes and releases its slot on Close. It exposes
@@ -12,7 +14,7 @@ import (
type slotConn struct {
*net.TCPConn
sl *Slot
- fam family
+ fam Family
s *Scheduler
once sync.Once
}
@@ -50,7 +52,7 @@ func (b *Balancer) DialPinned(ctx context.Context, host string, port int) (net.C
type slotPacketConn struct {
net.PacketConn
sl *Slot
- fam family
+ fam Family
}
func (c *slotPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {
@@ -68,9 +70,9 @@ func (c *slotPacketConn) WriteTo(p []byte, a net.Addr) (int, error) {
// ListenUDP opens a UDP socket pinned to one NIC (a UDP "flow" = the socket, so every datagram
// of that flow leaves the same way). UDP flows are short and numerous (DNS), so they don't hold
// a balancing slot: the pick still spreads them via the scheduler's tie-breaking.
-func (b *Balancer) ListenUDP(ctx context.Context, f family) (net.PacketConn, error) {
+func (b *Balancer) ListenUDP(ctx context.Context, f Family) (net.PacketConn, error) {
network := "udp4"
- if f == fam6 {
+ if f == Fam6 {
network = "udp6"
}
tried := map[string]struct{}{}
@@ -81,7 +83,7 @@ func (b *Balancer) ListenUDP(ctx context.Context, f family) (net.PacketConn, err
return nil, lastErr
}
tried[sl.key] = struct{}{}
- lc := net.ListenConfig{Control: unicastIF(sl.Index, f == fam6)}
+ lc := net.ListenConfig{Control: nics.ForceEgress(sl.Index, f == Fam6)}
pc, err := lc.ListenPacket(ctx, network, net.JoinHostPort(sl.ip(f).String(), "0"))
b.S.ReleaseFor(sl, f)
if err != nil {
diff --git a/probe.go b/internal/engine/probe.go
similarity index 83%
rename from probe.go
rename to internal/engine/probe.go
index 666f16e..c11a0c5 100644
--- a/probe.go
+++ b/internal/engine/probe.go
@@ -1,14 +1,16 @@
-package main
+package engine
import (
"net"
"time"
+
+ "net-merge/internal/nics"
)
// Internet reachability probes: a TCP connect to a well-known anycast IP, bound to the NIC.
var probeTargets = [2][]string{
- fam4: {"1.1.1.1:443", "8.8.8.8:443"},
- fam6: {"[2606:4700:4700::1111]:443", "[2001:4860:4860::8888]:443"},
+ Fam4: {"1.1.1.1:443", "8.8.8.8:443"},
+ Fam6: {"[2606:4700:4700::1111]:443", "[2001:4860:4860::8888]:443"},
}
const (
@@ -17,17 +19,17 @@ const (
probeEveryDown = 4 * time.Second
)
-func probe(sl *Slot, f family) bool {
+func probe(sl *Slot, f Family) bool {
ip := sl.ip(f)
if ip == nil {
return false
}
network := "tcp4"
- if f == fam6 {
+ if f == Fam6 {
network = "tcp6"
}
for _, t := range probeTargets[f] {
- d := net.Dialer{LocalAddr: &net.TCPAddr{IP: ip}, Control: unicastIF(sl.Index, f == fam6), Timeout: probeTimeout}
+ d := net.Dialer{LocalAddr: &net.TCPAddr{IP: ip}, Control: nics.ForceEgress(sl.Index, f == Fam6), Timeout: probeTimeout}
if c, err := d.Dial(network, t); err == nil {
c.Close()
return true
@@ -38,7 +40,7 @@ func probe(sl *Slot, f family) bool {
type probeJob struct {
sl *Slot
- f family
+ f Family
}
// RunProbes checks every adapter's internet access per address family: new ones immediately,
@@ -73,7 +75,7 @@ func (s *Scheduler) probeDue() []probeJob {
if !sl.present {
continue
}
- for _, f := range []family{fam4, fam6} {
+ for _, f := range []Family{Fam4, Fam6} {
if sl.ip(f) == nil || sl.probing[f].Load() {
continue
}
diff --git a/sched.go b/internal/engine/sched.go
similarity index 86%
rename from sched.go
rename to internal/engine/sched.go
index e6cfe50..94510c9 100644
--- a/sched.go
+++ b/internal/engine/sched.go
@@ -1,4 +1,4 @@
-package main
+package engine
import (
"math"
@@ -7,16 +7,18 @@ import (
"sync"
"sync/atomic"
"time"
+
+ "net-merge/internal/nics"
)
-// family selects which address of a NIC a flow is pinned to. Load, speed and health are tracked
+// Family selects which address of a NIC a flow is pinned to. Load, speed and health are tracked
// per family because one link can behave very differently over each (e.g. a carrier hotspot that
// is fast over native IPv6 and slow over translated IPv4).
-type family int
+type Family int
const (
- fam4 family = iota
- fam6
+ Fam4 Family = iota
+ Fam6
)
// linkState is the result of the internet probe: new adapters are "unknown" (still preferred
@@ -57,15 +59,15 @@ type Slot struct {
rateIn, rateOut [2]float64 // bytes/s over the last tick
peak [2]float64 // observed capacity: max recent rateIn+rateOut
- // The adapter's total traffic from Windows' counters (all apps, not only net-merge's flows).
+ // The adapter's total traffic from the OS's counters (all apps, not only net-merge's flows).
linkIn, linkOut uint64
linkRateIn, linkRateOut float64
linkPrimed bool
}
-func (sl *Slot) ip(f family) net.IP {
+func (sl *Slot) ip(f Family) net.IP {
a := sl.addr.Load()
- if f == fam6 {
+ if f == Fam6 {
return a.ip6
}
return a.ip4
@@ -83,7 +85,7 @@ type SlotStats struct {
Failed int64
BytesIn, BytesOut int64
RateIn, RateOut float64 // through net-merge, both families summed (bytes/s)
- LinkIn, LinkOut float64 // through the adapter by any app, from Windows' counters (bytes/s)
+ LinkIn, LinkOut float64 // through the adapter by any app, from the OS's counters (bytes/s)
Peak, Peak6 float64
}
@@ -97,7 +99,7 @@ type Scheduler struct {
now func() time.Time
}
-func NewScheduler(nics []Nic) *Scheduler {
+func NewScheduler(nics []nics.Nic) *Scheduler {
s := &Scheduler{now: time.Now}
s.Update(nics)
return s
@@ -110,7 +112,7 @@ func (s *Scheduler) SetAuto(on bool) {
s.mu.Unlock()
}
-func normAddr(n Nic) *slotAddr {
+func normAddr(n nics.Nic) *slotAddr {
a := &slotAddr{}
if n.IP != nil {
a.ip4 = n.IP.To4()
@@ -124,7 +126,7 @@ func normAddr(n Nic) *slotAddr {
// Update applies a re-scan: keeps counters of known NICs, picks up changed addresses (DHCP
// renewal, a new IPv6 prefix), adds new ones (a tether plugged in later), and drops vanished
// ones once their last flow ends. Adapters are keyed by name.
-func (s *Scheduler) Update(nics []Nic) {
+func (s *Scheduler) Update(nics []nics.Nic) {
s.mu.Lock()
defer s.mu.Unlock()
for _, sl := range s.slots {
@@ -151,10 +153,10 @@ func (s *Scheduler) Update(nics []Nic) {
}
old := found.addr.Load()
if !old.ip4.Equal(na.ip4) {
- found.state[fam4] = stateUnknown // new address: re-verify
+ found.state[Fam4] = stateUnknown // new address: re-verify
}
if !old.ip6.Equal(na.ip6) {
- found.state[fam6] = stateUnknown
+ found.state[Fam6] = stateUnknown
}
if !old.ip4.Equal(na.ip4) || !old.ip6.Equal(na.ip6) {
found.addr.Store(na)
@@ -182,7 +184,7 @@ func (s *Scheduler) Tick(dt time.Duration) {
defer s.mu.Unlock()
sec := dt.Seconds()
for _, sl := range s.slots {
- in, out, ok := ifOctets(sl.Index)
+ in, out, ok := nics.Octets(sl.Index)
if !sl.present || !ok {
sl.linkRateIn, sl.linkRateOut, sl.linkPrimed = 0, 0, false
continue
@@ -193,7 +195,7 @@ func (s *Scheduler) Tick(dt time.Duration) {
}
sl.linkIn, sl.linkOut, sl.linkPrimed = in, out, true
}
- for _, f := range []family{fam4, fam6} {
+ for _, f := range []Family{Fam4, Fam6} {
var maxPeak float64
live, measured := 0, true
idle := map[*Slot]bool{}
@@ -244,11 +246,11 @@ func (s *Scheduler) Tick(dt time.Duration) {
}
// Acquire picks an IPv4 NIC for a new flow, skipping the ones in skip. The caller must Release it.
-func (s *Scheduler) Acquire(skip map[string]struct{}) *Slot { return s.AcquireFor(fam4, skip) }
-func (s *Scheduler) Release(sl *Slot) { s.ReleaseFor(sl, fam4) }
+func (s *Scheduler) Acquire(skip map[string]struct{}) *Slot { return s.AcquireFor(Fam4, skip) }
+func (s *Scheduler) Release(sl *Slot) { s.ReleaseFor(sl, Fam4) }
// AcquireFor picks a NIC that has an address of the given family.
-func (s *Scheduler) AcquireFor(f family, skip map[string]struct{}) *Slot {
+func (s *Scheduler) AcquireFor(f Family, skip map[string]struct{}) *Slot {
s.mu.Lock()
defer s.mu.Unlock()
now := s.now()
@@ -304,7 +306,7 @@ func (s *Scheduler) V6Usable() bool {
s.mu.Lock()
defer s.mu.Unlock()
for _, sl := range s.slots {
- if sl.present && sl.ip(fam6) != nil && sl.state[fam6] != stateDown {
+ if sl.present && sl.ip(Fam6) != nil && sl.state[Fam6] != stateDown {
return true
}
}
@@ -322,24 +324,24 @@ func (s *Scheduler) V6CoversAll() bool {
if !sl.present {
continue
}
- has6 := sl.ip(fam6) != nil && sl.state[fam6] != stateDown
+ has6 := sl.ip(Fam6) != nil && sl.state[Fam6] != stateDown
if has6 {
any6 = true
}
- if sl.ip(fam4) != nil && sl.state[fam4] != stateDown && !has6 {
+ if sl.ip(Fam4) != nil && sl.state[Fam4] != stateDown && !has6 {
return false
}
}
return any6
}
-func (s *Scheduler) ReleaseFor(sl *Slot, f family) {
+func (s *Scheduler) ReleaseFor(sl *Slot, f Family) {
sl.active.Add(-1)
sl.actF[f].Add(-1)
}
// SetState records a probe result. A passing probe also clears any link-error cooldown.
-func (s *Scheduler) SetState(sl *Slot, f family, up bool) {
+func (s *Scheduler) SetState(sl *Slot, f Family, up bool) {
s.mu.Lock()
defer s.mu.Unlock()
if up {
@@ -351,7 +353,7 @@ func (s *Scheduler) SetState(sl *Slot, f family, up bool) {
}
// Fail sidelines a NIC whose link itself is broken (for one address family).
-func (s *Scheduler) Fail(sl *Slot, f family, cooldown time.Duration) {
+func (s *Scheduler) Fail(sl *Slot, f Family, cooldown time.Duration) {
s.mu.Lock()
sl.downUntil[f] = s.now().Add(cooldown)
s.mu.Unlock()
@@ -366,19 +368,19 @@ func (s *Scheduler) Snapshot() []SlotStats {
a := sl.addr.Load()
st := SlotStats{
Name: sl.Name, State: "-", State6: "-", Present: sl.present,
- Weight: sl.weight[fam4], Weight6: sl.weight[fam6],
+ Weight: sl.weight[Fam4], Weight6: sl.weight[Fam6],
Active: sl.active.Load(), Total: sl.total.Load(), Failed: sl.failed.Load(),
- BytesIn: sl.bytesIn[fam4].Load() + sl.bytesIn[fam6].Load(),
- BytesOut: sl.bytesOut[fam4].Load() + sl.bytesOut[fam6].Load(),
- RateIn: sl.rateIn[fam4] + sl.rateIn[fam6], RateOut: sl.rateOut[fam4] + sl.rateOut[fam6],
+ BytesIn: sl.bytesIn[Fam4].Load() + sl.bytesIn[Fam6].Load(),
+ BytesOut: sl.bytesOut[Fam4].Load() + sl.bytesOut[Fam6].Load(),
+ RateIn: sl.rateIn[Fam4] + sl.rateIn[Fam6], RateOut: sl.rateOut[Fam4] + sl.rateOut[Fam6],
LinkIn: sl.linkRateIn, LinkOut: sl.linkRateOut,
- Peak: sl.peak[fam4], Peak6: sl.peak[fam6],
+ Peak: sl.peak[Fam4], Peak6: sl.peak[Fam6],
}
if a.ip4 != nil {
- st.IP, st.State = a.ip4.String(), sl.state[fam4].String()
+ st.IP, st.State = a.ip4.String(), sl.state[Fam4].String()
}
if a.ip6 != nil {
- st.IP6, st.State6 = a.ip6.String(), sl.state[fam6].String()
+ st.IP6, st.State6 = a.ip6.String(), sl.state[Fam6].String()
}
out = append(out, st)
}
diff --git a/sched_test.go b/internal/engine/sched_test.go
similarity index 56%
rename from sched_test.go
rename to internal/engine/sched_test.go
index 378dd99..a89781a 100644
--- a/sched_test.go
+++ b/internal/engine/sched_test.go
@@ -1,15 +1,16 @@
-package main
+package engine
import (
"net"
- "strings"
"testing"
"time"
- "unicode/utf16"
- "unicode/utf8"
+
+ "net-merge/internal/nics"
)
-func nic(name, ip string, w float64) Nic { return Nic{Name: name, IP: net.ParseIP(ip), Weight: w} }
+func nic(name, ip string, w float64) nics.Nic {
+ return nics.Nic{Name: name, IP: net.ParseIP(ip), Weight: w}
+}
func countBy(picks []*Slot, name string) int {
n := 0
@@ -30,7 +31,7 @@ func acquireN(s *Scheduler, n int) []*Slot {
}
func TestEqualWeightsSpreadEvenly(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
p := acquireN(s, 6)
if countBy(p, "A") != 3 || countBy(p, "B") != 3 {
t.Fatalf("want 3/3, got A=%d B=%d", countBy(p, "A"), countBy(p, "B"))
@@ -38,7 +39,7 @@ func TestEqualWeightsSpreadEvenly(t *testing.T) {
}
func TestWeightsSkew(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 3), nic("B", "10.0.0.2", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 3), nic("B", "10.0.0.2", 1)})
p := acquireN(s, 8)
if countBy(p, "A") != 6 || countBy(p, "B") != 2 {
t.Fatalf("want 6/2, got A=%d B=%d", countBy(p, "A"), countBy(p, "B"))
@@ -46,7 +47,7 @@ func TestWeightsSkew(t *testing.T) {
}
func TestReleaseFreesNic(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
first := s.Acquire(nil)
s.Acquire(nil)
s.Release(first)
@@ -56,7 +57,7 @@ func TestReleaseFreesNic(t *testing.T) {
}
func TestFailCooldown(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
clock := time.Unix(1000, 0)
s.now = func() time.Time { return clock }
bad := s.Snapshot()[0]
@@ -66,7 +67,7 @@ func TestFailCooldown(t *testing.T) {
badSlot = sl
}
}
- s.Fail(badSlot, fam4, 5*time.Second)
+ s.Fail(badSlot, Fam4, 5*time.Second)
for i := 0; i < 4; i++ {
if s.Acquire(nil) == badSlot {
t.Fatal("cooling-down NIC was picked")
@@ -85,33 +86,33 @@ func TestFailCooldown(t *testing.T) {
}
func TestAllDownStillServes(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1)})
- s.Fail(s.slots[0], fam4, time.Hour)
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1)})
+ s.Fail(s.slots[0], Fam4, time.Hour)
if s.Acquire(nil) == nil {
t.Fatal("total outage: all-NICs-down must still hand one out")
}
}
func TestProbeStateTiers(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1), nic("C", "10.0.0.3", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1), nic("C", "10.0.0.3", 1)})
a, b, c := s.slots[0], s.slots[1], s.slots[2]
- s.SetState(a, fam4, true)
- s.SetState(c, fam4, false)
+ s.SetState(a, Fam4, true)
+ s.SetState(c, Fam4, false)
// A is up, B is unprobed, C is dead: only A gets flows while it is the best tier.
for i := 0; i < 5; i++ {
if got := s.Acquire(nil); got != a {
t.Fatalf("flow %d went to %s, want the probed-up NIC", i, got.Name)
}
}
- s.SetState(a, fam4, false) // now B (unknown) beats the two dead ones
+ s.SetState(a, Fam4, false) // now B (unknown) beats the two dead ones
if got := s.Acquire(nil); got != b {
t.Fatalf("want unprobed NIC over dead ones, got %s", got.Name)
}
- s.SetState(b, fam4, false) // everything dead: still serve, never an outage
+ s.SetState(b, Fam4, false) // everything dead: still serve, never an outage
if s.Acquire(nil) == nil {
t.Fatal("all-dead must still hand out a NIC")
}
- s.SetState(c, fam4, true) // a recovered NIC takes over immediately
+ s.SetState(c, Fam4, true) // a recovered NIC takes over immediately
if got := s.Acquire(nil); got != c {
t.Fatalf("recovered NIC should win, got %s", got.Name)
}
@@ -132,16 +133,16 @@ func TestProbeAgainstLocalListener(t *testing.T) {
c.Close()
}
}()
- old := probeTargets[fam4]
- defer func() { probeTargets[fam4] = old }()
- probeTargets[fam4] = []string{ln.Addr().String()}
+ old := probeTargets[Fam4]
+ defer func() { probeTargets[Fam4] = old }()
+ probeTargets[Fam4] = []string{ln.Addr().String()}
- s := NewScheduler([]Nic{nic("A", "127.0.0.2", 1)})
- if !probe(s.slots[0], fam4) {
+ s := NewScheduler([]nics.Nic{nic("A", "127.0.0.2", 1)})
+ if !probe(s.slots[0], Fam4) {
t.Fatal("probe should pass against a reachable target")
}
ln.Close()
- if probe(s.slots[0], fam4) {
+ if probe(s.slots[0], Fam4) {
t.Fatal("probe should fail once the target is gone")
}
}
@@ -149,17 +150,17 @@ func TestProbeAgainstLocalListener(t *testing.T) {
func TestIPv6OnlyGoesToNicsWithV6(t *testing.T) {
n6 := nic("B", "10.0.0.2", 1)
n6.IP6 = net.ParseIP("2001:db8::2")
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), n6})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), n6})
for i := 0; i < 4; i++ {
- if got := s.AcquireFor(fam6, nil); got == nil || got.Name != "B" {
+ if got := s.AcquireFor(Fam6, nil); got == nil || got.Name != "B" {
t.Fatalf("v6 flow %d went to %v, want the only v6-capable NIC B", i, got)
}
}
- if got := s.AcquireFor(fam4, nil); got == nil {
+ if got := s.AcquireFor(Fam4, nil); got == nil {
t.Fatal("v4 flows must still work")
}
- s2 := NewScheduler([]Nic{nic("A", "10.0.0.1", 1)})
- if s2.AcquireFor(fam6, nil) != nil {
+ s2 := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1)})
+ if s2.AcquireFor(Fam6, nil) != nil {
t.Fatal("no v6-capable NIC: v6 flows must be refused so apps fall back to IPv4")
}
}
@@ -169,22 +170,22 @@ func TestV6StateIsIndependentOfV4(t *testing.T) {
n.IP6 = net.ParseIP("2001:db8::1")
m := nic("B", "10.0.0.2", 1)
m.IP6 = net.ParseIP("2001:db8::2")
- s := NewScheduler([]Nic{n, m})
+ s := NewScheduler([]nics.Nic{n, m})
a, b := s.slots[0], s.slots[1]
- s.SetState(a, fam4, true)
- s.SetState(b, fam4, true)
- s.SetState(a, fam6, false) // A has working v4 but its v6 is dead
- s.SetState(b, fam6, true)
+ s.SetState(a, Fam4, true)
+ s.SetState(b, Fam4, true)
+ s.SetState(a, Fam6, false) // A has working v4 but its v6 is dead
+ s.SetState(b, Fam6, true)
for i := 0; i < 4; i++ {
- got := s.AcquireFor(fam6, nil)
+ got := s.AcquireFor(Fam6, nil)
if got != b {
t.Fatalf("v6 flow %d went to %s, want B", i, got.Name)
}
- s.ReleaseFor(got, fam6)
+ s.ReleaseFor(got, Fam6)
}
seen := map[string]bool{}
for i := 0; i < 4; i++ {
- seen[s.AcquireFor(fam4, nil).Name] = true
+ seen[s.AcquireFor(Fam4, nil).Name] = true
}
if !seen["A"] || !seen["B"] {
t.Fatalf("v4 should still use both NICs, got %v", seen)
@@ -198,52 +199,52 @@ func TestAutoWeightsArePerFamily(t *testing.T) {
a.IP6 = net.ParseIP("2001:db8::1")
b := nic("B", "10.0.0.2", 1)
b.IP6 = net.ParseIP("2001:db8::2")
- s := NewScheduler([]Nic{a, b})
+ s := NewScheduler([]nics.Nic{a, b})
s.SetAuto(true)
sa, sb := s.slots[0], s.slots[1]
const mbit = 125_000 // bytes/s
// v4: A 100 Mbit/s, B 5 Mbit/s. v6: both 100 Mbit/s.
for i := 0; i < 3; i++ {
- sa.bytesIn[fam4].Add(100 * mbit)
- sb.bytesIn[fam4].Add(5 * mbit)
- sa.bytesIn[fam6].Add(100 * mbit)
- sb.bytesIn[fam6].Add(100 * mbit)
+ sa.bytesIn[Fam4].Add(100 * mbit)
+ sb.bytesIn[Fam4].Add(5 * mbit)
+ sa.bytesIn[Fam6].Add(100 * mbit)
+ sb.bytesIn[Fam6].Add(100 * mbit)
s.Tick(time.Second)
}
- if got := sb.weight[fam4] / sa.weight[fam4]; got > 0.06 {
+ if got := sb.weight[Fam4] / sa.weight[Fam4]; got > 0.06 {
t.Fatalf("slow v4 path should be down-weighted to ~0.05, got ratio %.2f", got)
}
- if got := sb.weight[fam6] / sa.weight[fam6]; got < 0.95 {
+ if got := sb.weight[Fam6] / sa.weight[Fam6]; got < 0.95 {
t.Fatalf("fast v6 path must keep full weight, got ratio %.2f", got)
}
// And the peak is remembered while idle (no traffic for a while).
for i := 0; i < 20; i++ {
s.Tick(time.Second)
}
- if sb.peak[fam6] < 90*mbit {
- t.Fatalf("idle NIC forgot its capacity: peak %.0f", sb.peak[fam6])
+ if sb.peak[Fam6] < 90*mbit {
+ t.Fatalf("idle NIC forgot its capacity: peak %.0f", sb.peak[Fam6])
}
}
// A NIC whose estimate was poisoned by one bad moment must not stay starved forever.
func TestPessimisticEstimateRecoversWhileIdle(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
s.SetAuto(true)
sa, sb := s.slots[0], s.slots[1]
const mbit = 125_000
for i := 0; i < 3; i++ { // B looks 20x slower than A
- sa.bytesIn[fam4].Add(100 * mbit)
- sb.bytesIn[fam4].Add(5 * mbit)
+ sa.bytesIn[Fam4].Add(100 * mbit)
+ sb.bytesIn[Fam4].Add(5 * mbit)
s.Tick(time.Second)
}
- if w := sb.weight[fam4] / sa.weight[fam4]; w > 0.06 {
+ if w := sb.weight[Fam4] / sa.weight[Fam4]; w > 0.06 {
t.Fatalf("setup: B should be down-weighted, ratio %.2f", w)
}
for i := 0; i < 80; i++ { // then nobody uses B, and A keeps working
- sa.bytesIn[fam4].Add(100 * mbit)
+ sa.bytesIn[Fam4].Add(100 * mbit)
s.Tick(time.Second)
}
- if w := sb.weight[fam4] / sa.weight[fam4]; w < 0.45 {
+ if w := sb.weight[Fam4] / sa.weight[Fam4]; w < 0.45 {
t.Fatalf("idle NIC should drift back up to ~0.5 so it is re-measured, ratio %.2f", w)
}
}
@@ -252,7 +253,7 @@ func TestV6CoverageDecidesWhetherIPv6IsBalanced(t *testing.T) {
a := nic("A", "10.0.0.1", 1)
a.IP6 = net.ParseIP("2001:db8::1")
b := nic("B", "10.0.0.2", 1) // IPv4 only
- s := NewScheduler([]Nic{a, b})
+ s := NewScheduler([]nics.Nic{a, b})
if s.V6CoversAll() {
t.Fatal("B has no IPv6: IPv6 would funnel onto A, coverage must be partial")
}
@@ -260,74 +261,22 @@ func TestV6CoverageDecidesWhetherIPv6IsBalanced(t *testing.T) {
t.Fatal("A can carry IPv6")
}
b.IP6 = net.ParseIP("2001:db8::2")
- s.Update([]Nic{a, b})
+ s.Update([]nics.Nic{a, b})
if !s.V6CoversAll() {
t.Fatal("every adapter has IPv6 now")
}
- s.SetState(s.slots[1], fam6, false) // B's IPv6 probe fails
+ s.SetState(s.slots[1], Fam6, false) // B's IPv6 probe fails
if s.V6CoversAll() {
t.Fatal("a dead IPv6 path on B means partial coverage again")
}
- only4 := NewScheduler([]Nic{nic("A", "10.0.0.1", 1)})
+ only4 := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1)})
if only4.V6CoversAll() || only4.V6Usable() {
t.Fatal("no IPv6 anywhere: nothing to allow")
}
}
-func TestLinkCountersReadRealAdapter(t *testing.T) {
- ifaces, _ := net.Interfaces()
- for _, ifc := range ifaces {
- if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 {
- continue
- }
- if _, _, ok := ifOctets(ifc.Index); !ok {
- t.Fatalf("could not read Windows counters for %s (index %d)", ifc.Name, ifc.Index)
- }
- return
- }
- t.Skip("no up adapter")
-}
-
-func TestShortenCountsUTF16AndKeepsRunesWhole(t *testing.T) {
- s := "net-merge ON ↓12 ↑3.4 Mbit/s"
- if got := shorten(s, 127); got != s {
- t.Fatalf("short string changed: %q", got)
- }
- got := shorten(s, 16)
- if n := len(utf16.Encode([]rune(got))); n > 16 {
- t.Fatalf("%q is %d UTF-16 units, want <= 16", got, n)
- }
- if !utf8.ValidString(got) || !strings.HasSuffix(got, "…") {
- t.Fatalf("bad cut: %q", got)
- }
-}
-
-func TestTrayTooltipFitsWindowsLimit(t *testing.T) {
- const mbit = 125_000
- mk := func(name string, down, up float64) SlotStats {
- return SlotStats{Name: name, Present: true, State: "up", LinkIn: down * mbit, LinkOut: up * mbit}
- }
- two := []SlotStats{mk("Ethernet 3", 16, 0.2), mk("Ethernet 4", 79, 7)}
- tip := trayTooltip(stateWord(true), 95*mbit, 7.2*mbit, two)
- for _, want := range []string{"Merging", "Eth 3 ↓16 ↑0.2", "Eth 4 ↓79 ↑7.0", "Total ↓95 ↑7.2 Mbps"} {
- if utf16Len(tip) > tooltipMax || !strings.Contains(tip, want) {
- t.Fatalf("two adapters should fit with full detail (%q), got %d chars:\n%s", want, utf16Len(tip), tip)
- }
- }
- four := append(two, mk("Wi-Fi", 55, 3), mk("Ethernet 7", 12, 1))
- tip = trayTooltip(stateWord(false), 162*mbit, 11.2*mbit, four)
- if utf16Len(tip) > tooltipMax {
- t.Fatalf("tooltip is %d chars, Windows shows only %d:\n%s", utf16Len(tip), tooltipMax+1, tip)
- }
- for _, want := range []string{"Paused", "Eth 3 ↓", "Eth 4 ↓", "WiFi ↓", "Eth 7 ↓", "Total ↓162 ↑11"} {
- if !strings.Contains(tip, want) {
- t.Fatalf("every adapter keeps its download speed and the total is always shown; %q missing:\n%s", want, tip)
- }
- }
-}
-
func TestSkipSet(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
a, b := s.slots[0], s.slots[1]
if got := s.Acquire(map[string]struct{}{a.key: {}}); got != b {
t.Fatal("skip set not honoured")
@@ -338,9 +287,9 @@ func TestSkipSet(t *testing.T) {
}
func TestUpdateAddsAndKeepsCounters(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1)})
s.Acquire(nil)
- s.Update([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s.Update([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
snap := s.Snapshot()
if len(snap) != 2 || snap[0].Total != 1 {
t.Fatalf("unexpected snapshot: %+v", snap)
@@ -348,7 +297,7 @@ func TestUpdateAddsAndKeepsCounters(t *testing.T) {
}
func TestUpdateDropsVanishedWhenIdle(t *testing.T) {
- s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
busy := s.Acquire(nil)
s.Update(nil)
if len(s.Snapshot()) != 1 {
diff --git a/socks5.go b/internal/engine/socks5.go
similarity index 96%
rename from socks5.go
rename to internal/engine/socks5.go
index b34484d..0021fe8 100644
--- a/socks5.go
+++ b/internal/engine/socks5.go
@@ -1,4 +1,4 @@
-package main
+package engine
import (
"bytes"
@@ -10,7 +10,7 @@ import (
"time"
)
-func serveSocks5(ln net.Listener, b *Balancer) error {
+func ServeSocks5(ln net.Listener, b *Balancer) error {
for {
c, err := ln.Accept()
if err != nil {
diff --git a/socks5_test.go b/internal/engine/socks5_test.go
similarity index 90%
rename from socks5_test.go
rename to internal/engine/socks5_test.go
index e60caf8..b083b65 100644
--- a/socks5_test.go
+++ b/internal/engine/socks5_test.go
@@ -1,4 +1,4 @@
-package main
+package engine
import (
"bufio"
@@ -6,6 +6,8 @@ import (
"net"
"testing"
"time"
+
+ "net-merge/internal/nics"
)
// Loopback aliases (127.0.0.2, 127.0.0.3) stand in for physical NICs: the target server
@@ -34,7 +36,7 @@ func startTarget(t *testing.T) int {
return ln.Addr().(*net.TCPAddr).Port
}
-func startProxy(t *testing.T, nics []Nic) (*Scheduler, string) {
+func startProxy(t *testing.T, nics []nics.Nic) (*Scheduler, string) {
t.Helper()
s := NewScheduler(nics)
b := NewBalancer(s)
@@ -44,7 +46,7 @@ func startProxy(t *testing.T, nics []Nic) (*Scheduler, string) {
t.Fatal(err)
}
t.Cleanup(func() { ln.Close() })
- go serveSocks5(ln, b)
+ go ServeSocks5(ln, b)
return s, ln.Addr().String()
}
@@ -87,7 +89,7 @@ func (s *socksConn) line(t *testing.T) string {
func TestFlowsSplitAcrossNics(t *testing.T) {
port := startTarget(t)
- sched, proxy := startProxy(t, []Nic{nic("nic-a", "127.0.0.2", 1), nic("nic-b", "127.0.0.3", 1)})
+ sched, proxy := startProxy(t, []nics.Nic{nic("nic-a", "127.0.0.2", 1), nic("nic-b", "127.0.0.3", 1)})
seen := map[string]int{}
for i := 0; i < 6; i++ {
@@ -114,7 +116,7 @@ func TestFlowsSplitAcrossNics(t *testing.T) {
func TestBrokenNicFailsOver(t *testing.T) {
port := startTarget(t)
// 203.0.113.9 (TEST-NET-3) isn't owned by this machine: bind fails with WSAEADDRNOTAVAIL.
- sched, proxy := startProxy(t, []Nic{nic("bad", "203.0.113.9", 1), nic("good", "127.0.0.2", 1)})
+ sched, proxy := startProxy(t, []nics.Nic{nic("bad", "203.0.113.9", 1), nic("good", "127.0.0.2", 1)})
for i := 0; i < 4; i++ {
c := socksConnect(t, proxy, port)
if c.rep != 0 {
@@ -132,7 +134,7 @@ func TestBrokenNicFailsOver(t *testing.T) {
}
func TestRefusedIsReportedNotRetried(t *testing.T) {
- sched, proxy := startProxy(t, []Nic{nic("a", "127.0.0.2", 1), nic("b", "127.0.0.3", 1)})
+ sched, proxy := startProxy(t, []nics.Nic{nic("a", "127.0.0.2", 1), nic("b", "127.0.0.3", 1)})
ln, _ := net.Listen("tcp4", "127.0.0.1:0")
deadPort := ln.Addr().(*net.TCPAddr).Port
ln.Close()
@@ -168,7 +170,7 @@ func TestIPv6Destination(t *testing.T) {
// ::1 doubles as the NIC's IPv6 source address.
n := nic("v6nic", "127.0.0.2", 1)
n.IP6 = net.ParseIP("::1")
- _, proxy := startProxy(t, []Nic{n})
+ _, proxy := startProxy(t, []nics.Nic{n})
c, err := net.Dial("tcp4", proxy)
if err != nil {
@@ -192,7 +194,7 @@ func TestIPv6Destination(t *testing.T) {
}
func TestUDPAssociateRefusedCleanly(t *testing.T) {
- _, proxy := startProxy(t, []Nic{nic("a", "127.0.0.2", 1)})
+ _, proxy := startProxy(t, []nics.Nic{nic("a", "127.0.0.2", 1)})
c, _ := net.Dial("tcp4", proxy)
defer c.Close()
c.SetDeadline(time.Now().Add(3 * time.Second))
@@ -218,7 +220,7 @@ func TestHalfCloseStillDeliversReply(t *testing.T) {
c.Write(append([]byte("got:"), data...))
c.Close()
}()
- _, proxy := startProxy(t, []Nic{nic("a", "127.0.0.2", 1)})
+ _, proxy := startProxy(t, []nics.Nic{nic("a", "127.0.0.2", 1)})
// 127.0.0.2 -> 127.0.0.1 target; reuse socksConnect but don't read the greeting line.
c := socksConnect(t, proxy, ln.Addr().(*net.TCPAddr).Port)
c.Write([]byte("hello"))
@@ -250,10 +252,10 @@ func benchRelay(b *testing.B, streams int) {
}()
}
}()
- s := NewScheduler([]Nic{nic("a", "127.0.0.2", 1), nic("b", "127.0.0.3", 1)})
+ s := NewScheduler([]nics.Nic{nic("a", "127.0.0.2", 1), nic("b", "127.0.0.3", 1)})
pl, _ := net.Listen("tcp4", "127.0.0.1:0")
defer pl.Close()
- go serveSocks5(pl, NewBalancer(s))
+ go ServeSocks5(pl, NewBalancer(s))
port := ln.Addr().(*net.TCPAddr).Port
conns := make([]net.Conn, streams)
diff --git a/icon.go b/internal/icon/icon.go
similarity index 78%
rename from icon.go
rename to internal/icon/icon.go
index 32568c3..9f99beb 100644
--- a/icon.go
+++ b/internal/icon/icon.go
@@ -1,4 +1,5 @@
-package main
+// Package icon draws the tray icon.
+package icon
import (
"bytes"
@@ -9,10 +10,11 @@ import (
"math"
)
-// trayIcon draws a round badge with a "merge" glyph (two lines converging into one):
-// green when system-wide mode is on, grey when off. Returned as an .ico (PNG payload).
-func trayIcon(on bool) []byte {
- const size = 32
+const size = 32
+
+// PNG draws a round badge with a "merge" glyph (two lines converging into one): green when
+// system-wide mode is on, grey when off.
+func PNG(on bool) []byte {
bg := color.NRGBA{113, 113, 122, 255}
if on {
bg = color.NRGBA{34, 197, 94, 255}
@@ -40,14 +42,19 @@ func trayIcon(on bool) []byte {
}
var pngBuf bytes.Buffer
png.Encode(&pngBuf, img)
+ return pngBuf.Bytes()
+}
+// ICO wraps the PNG in an .ico container, which is what Windows wants.
+func ICO(on bool) []byte {
+ p := PNG(on)
var ico bytes.Buffer
binary.Write(&ico, binary.LittleEndian, [3]uint16{0, 1, 1}) // ICONDIR: reserved, type=icon, count=1
ico.Write([]byte{size, size, 0, 0}) // width, height, colors, reserved
binary.Write(&ico, binary.LittleEndian, [2]uint16{1, 32}) // planes, bit depth
- binary.Write(&ico, binary.LittleEndian, uint32(pngBuf.Len()))
+ binary.Write(&ico, binary.LittleEndian, uint32(len(p)))
binary.Write(&ico, binary.LittleEndian, uint32(22)) // image offset: 6 + 16
- ico.Write(pngBuf.Bytes())
+ ico.Write(p)
return ico.Bytes()
}
diff --git a/internal/icon/tray_other.go b/internal/icon/tray_other.go
new file mode 100644
index 0000000..862df9f
--- /dev/null
+++ b/internal/icon/tray_other.go
@@ -0,0 +1,7 @@
+//go:build !windows
+
+package icon
+
+// Tray is the icon in the format the tray library expects on this OS: its Linux backend decodes
+// PNG but not ICO.
+func Tray(on bool) []byte { return PNG(on) }
diff --git a/internal/icon/tray_windows.go b/internal/icon/tray_windows.go
new file mode 100644
index 0000000..65dca06
--- /dev/null
+++ b/internal/icon/tray_windows.go
@@ -0,0 +1,4 @@
+package icon
+
+// Tray is the icon in the format the tray library expects on this OS.
+func Tray(on bool) []byte { return ICO(on) }
diff --git a/internal/logx/logx.go b/internal/logx/logx.go
new file mode 100644
index 0000000..468a811
--- /dev/null
+++ b/internal/logx/logx.go
@@ -0,0 +1,15 @@
+// Package logx is net-merge's console/log-file output, shared by every package.
+package logx
+
+import (
+ "fmt"
+ "io"
+ "os"
+)
+
+var out io.Writer = os.Stdout
+
+// SetOutput sends all further output to w (the -log file).
+func SetOutput(w io.Writer) { out = w }
+
+func Printf(format string, a ...any) { fmt.Fprintf(out, format, a...) }
diff --git a/internal/nics/counters_linux.go b/internal/nics/counters_linux.go
new file mode 100644
index 0000000..df4705c
--- /dev/null
+++ b/internal/nics/counters_linux.go
@@ -0,0 +1,37 @@
+package nics
+
+import (
+ "net"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// Octets reads the kernel's byte counters for an adapter. They cover every app's traffic, not
+// just what net-merge relays: apps like qBittorrent bind to each adapter directly and bypass the
+// TUN, but still show up here.
+func Octets(idx int) (in, out uint64, ok bool) {
+ if idx <= 0 {
+ return 0, 0, false
+ }
+ ifc, err := net.InterfaceByIndex(idx)
+ if err != nil {
+ return 0, 0, false
+ }
+ stats := filepath.Join("/sys/class/net", ifc.Name, "statistics")
+ in, err1 := readUint(filepath.Join(stats, "rx_bytes"))
+ out, err2 := readUint(filepath.Join(stats, "tx_bytes"))
+ if err1 != nil || err2 != nil {
+ return 0, 0, false
+ }
+ return in, out, true
+}
+
+func readUint(path string) (uint64, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return 0, err
+ }
+ return strconv.ParseUint(strings.TrimSpace(string(b)), 10, 64)
+}
diff --git a/ifcounters_windows.go b/internal/nics/counters_windows.go
similarity index 71%
rename from ifcounters_windows.go
rename to internal/nics/counters_windows.go
index 3f4e404..7230a04 100644
--- a/ifcounters_windows.go
+++ b/internal/nics/counters_windows.go
@@ -1,11 +1,11 @@
-package main
+package nics
import "golang.org/x/sys/windows"
-// ifOctets reads Windows' own byte counters for an adapter. They cover every app's traffic, not
+// Octets reads Windows' own byte counters for an adapter. They cover every app's traffic, not
// just what net-merge relays: apps like qBittorrent bind to each adapter directly and bypass the
// TUN, but still show up here.
-func ifOctets(idx int) (in, out uint64, ok bool) {
+func Octets(idx int) (in, out uint64, ok bool) {
if idx <= 0 {
return 0, 0, false
}
diff --git a/internal/nics/egress_linux.go b/internal/nics/egress_linux.go
new file mode 100644
index 0000000..34ec5e8
--- /dev/null
+++ b/internal/nics/egress_linux.go
@@ -0,0 +1,33 @@
+package nics
+
+import (
+ "net"
+ "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 through the bound device.
+// Unprivileged since Linux 5.7; older kernels need CAP_NET_RAW. SO_BINDTOIFINDEX (5.0+) avoids
+// a name lookup per socket, with SO_BINDTODEVICE as the fallback for older kernels.
+func ForceEgress(idx int, v6 bool) func(network, address string, c syscall.RawConn) error {
+ if idx <= 0 {
+ return nil
+ }
+ return func(network, address string, c syscall.RawConn) error {
+ var serr error
+ if err := c.Control(func(fd uintptr) {
+ serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_BINDTOIFINDEX, idx)
+ if serr == unix.ENOPROTOOPT {
+ var ifc *net.Interface
+ if ifc, serr = net.InterfaceByIndex(idx); serr == nil {
+ serr = unix.BindToDevice(int(fd), ifc.Name)
+ }
+ }
+ }); err != nil {
+ return err
+ }
+ return serr
+ }
+}
diff --git a/sockopt_windows.go b/internal/nics/egress_windows.go
similarity index 77%
rename from sockopt_windows.go
rename to internal/nics/egress_windows.go
index 930a894..0264ac6 100644
--- a/sockopt_windows.go
+++ b/internal/nics/egress_windows.go
@@ -1,4 +1,4 @@
-package main
+package nics
import (
"math/bits"
@@ -7,10 +7,10 @@ import (
const ipUnicastIf = 31 // IP_UNICAST_IF and IPV6_UNICAST_IF share the value
-// unicastIF forces a socket's egress interface regardless of the routing table, so our own
+// ForceEgress forces a socket's egress interface regardless of the routing table, so our own
// outbound flows can never be captured by the TUN's routes (no routing loop). IPv4 takes the
// interface index in network byte order, IPv6 in host byte order.
-func unicastIF(idx int, v6 bool) func(network, address string, c syscall.RawConn) error {
+func ForceEgress(idx int, v6 bool) func(network, address string, c syscall.RawConn) error {
if idx <= 0 {
return nil
}
diff --git a/internal/nics/info_linux.go b/internal/nics/info_linux.go
new file mode 100644
index 0000000..4335454
--- /dev/null
+++ b/internal/nics/info_linux.go
@@ -0,0 +1,77 @@
+package nics
+
+import (
+ "fmt"
+ "net"
+ "os"
+ "path/filepath"
+ "strings"
+
+ "github.com/vishvananda/netlink"
+ "golang.org/x/sys/unix"
+)
+
+// adapterInfo is what Linux 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 // kernel driver, e.g. iwlwifi, r8169, rndis_host, ipheth
+}
+
+// adapterInfos returns, per interface index, the adapters with their default-route families,
+// whether they are backed by hardware, and their driver. Real NICs (PCI, USB tethers, WWAN
+// modems) have a device link in sysfs; tunnels, VPNs, bridges, veth pairs and other software
+// interfaces don't. Default routes are read from every routing table, so adapters whose gateway
+// lives in a per-interface policy table are picked up too.
+func adapterInfos() (map[int]adapterInfo, error) {
+ ifaces, err := net.Interfaces()
+ if err != nil {
+ return nil, err
+ }
+ m := map[int]adapterInfo{}
+ for _, ifc := range ifaces {
+ sys := filepath.Join("/sys/class/net", ifc.Name)
+ info := adapterInfo{}
+ if drv, err := os.Readlink(filepath.Join(sys, "device", "driver")); err == nil {
+ info.desc = filepath.Base(drv)
+ }
+ if _, err := os.Stat(filepath.Join(sys, "device")); err != nil {
+ kind := "software interface"
+ if t, err := os.ReadFile(filepath.Join(sys, "type")); err == nil {
+ kind += " type " + strings.TrimSpace(string(t))
+ }
+ info.virtual = fmt.Sprintf("tunnel/virtual interface (%s, no hardware device)", kind)
+ }
+ m[ifc.Index] = info
+ }
+ for _, fam := range []int{netlink.FAMILY_V4, netlink.FAMILY_V6} {
+ routes, err := netlink.RouteListFiltered(fam, &netlink.Route{Table: unix.RT_TABLE_UNSPEC}, netlink.RT_FILTER_TABLE)
+ if err != nil {
+ return nil, err
+ }
+ for _, r := range routes {
+ if r.Dst != nil {
+ if ones, _ := r.Dst.Mask.Size(); ones != 0 {
+ continue
+ }
+ }
+ links := []int{r.LinkIndex}
+ for _, nh := range r.MultiPath {
+ links = append(links, nh.LinkIndex)
+ }
+ for _, idx := range links {
+ cur, ok := m[idx]
+ if !ok {
+ continue
+ }
+ if fam == netlink.FAMILY_V4 {
+ cur.v4 = true
+ } else {
+ cur.v6 = true
+ }
+ m[idx] = cur
+ }
+ }
+ }
+ return m, nil
+}
diff --git a/nics_windows.go b/internal/nics/info_windows.go
similarity index 82%
rename from nics_windows.go
rename to internal/nics/info_windows.go
index 432d0cb..b598e01 100644
--- a/nics_windows.go
+++ b/internal/nics/info_windows.go
@@ -1,6 +1,7 @@
-package main
+package nics
import (
+ "fmt"
"unsafe"
"golang.org/x/sys/windows"
@@ -8,9 +9,9 @@ import (
// adapterInfo is what Windows knows about an adapter beyond what package net exposes.
type adapterInfo struct {
- v4, v6 bool // has an IPv4 / IPv6 default gateway (can reach the internet over that family)
- ifType uint32
- desc string
+ v4, v6 bool // has an IPv4 / IPv6 default gateway (can reach the internet over that family)
+ virtual string // why this is not real network hardware; empty if it is
+ desc string
}
// IANA ifType values for real network hardware. Tunnels (131), PPP (23), "proprietary virtual"
@@ -48,7 +49,10 @@ func adapterInfos() (map[int]adapterInfo, error) {
if a.OperStatus != windows.IfOperStatusUp {
continue
}
- info := adapterInfo{ifType: a.IfType, desc: windows.UTF16PtrToString(a.Description)}
+ info := adapterInfo{desc: windows.UTF16PtrToString(a.Description)}
+ if !physicalIfType(a.IfType) {
+ info.virtual = fmt.Sprintf("tunnel/virtual interface type %d (%s)", a.IfType, info.desc)
+ }
for g := a.FirstGatewayAddress; g != nil; g = g.Next {
if g.Address.Sockaddr == nil {
continue
@@ -67,7 +71,7 @@ func adapterInfos() (map[int]adapterInfo, error) {
}
cur := m[int(idx)]
cur.v4, cur.v6 = cur.v4 || info.v4, cur.v6 || info.v6
- cur.ifType, cur.desc = info.ifType, info.desc
+ cur.virtual, cur.desc = info.virtual, info.desc
m[int(idx)] = cur
}
}
diff --git a/nics.go b/internal/nics/nics.go
similarity index 90%
rename from nics.go
rename to internal/nics/nics.go
index a2285af..498e7b0 100644
--- a/nics.go
+++ b/internal/nics/nics.go
@@ -1,4 +1,4 @@
-package main
+package nics
import (
"fmt"
@@ -21,10 +21,10 @@ type Nic struct {
type Skip struct{ Name, Reason string }
// Second line of defence after the adapter type check: virtual adapters that report as plain
-// Ethernet (virtual switches, VPN TAP drivers, VM host-only adapters), matched by name or
-// driver description.
+// Ethernet (virtual switches, VPN TAP drivers, VM host-only adapters, container bridges), matched
+// by name or driver description. The anchored names are Linux interface naming conventions.
var (
- virtualName = regexp.MustCompile(`(?i)loopback|vethernet|wsl|tailscale|zerotier|wintun|net-merge`)
+ virtualName = regexp.MustCompile(`(?i)loopback|vethernet|wsl|tailscale|zerotier|wintun|net-merge|docker|podman|^veth|^virbr|^br-|^vboxnet|^vmnet|^vnet\d|^lxc|^lxdbr|^cni|^flannel|^wg\d|^tun\d|^tap\d|^zt`)
virtualDesc = regexp.MustCompile(`(?i)virtual|vpn|\btap\b|tap-|tunnel|wintun|wireguard|tailscale|zerotier|openvpn|anyconnect|fortinet|vmware|npcap|miniport|teredo|isatap|6to4|pseudo`)
)
@@ -61,8 +61,8 @@ func DiscoverNicsDetailed(include []string, weights map[string]float64) ([]Nic,
case virtualName.MatchString(ifc.Name):
skip("looks like a virtual/VPN adapter (name)")
continue
- case info != nil && haveInfo && !physicalIfType(ai.ifType):
- skip(fmt.Sprintf("tunnel/virtual interface type %d (%s)", ai.ifType, ai.desc))
+ case info != nil && haveInfo && ai.virtual != "":
+ skip(ai.virtual)
continue
case info != nil && haveInfo && virtualDesc.MatchString(ai.desc):
skip(fmt.Sprintf("virtual/VPN adapter (%s)", ai.desc))
diff --git a/internal/nics/nics_test.go b/internal/nics/nics_test.go
new file mode 100644
index 0000000..3fe5cd3
--- /dev/null
+++ b/internal/nics/nics_test.go
@@ -0,0 +1,20 @@
+package nics
+
+import (
+ "net"
+ "testing"
+)
+
+func TestLinkCountersReadRealAdapter(t *testing.T) {
+ ifaces, _ := net.Interfaces()
+ for _, ifc := range ifaces {
+ if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 {
+ continue
+ }
+ if _, _, ok := Octets(ifc.Index); !ok {
+ t.Fatalf("could not read OS counters for %s (index %d)", ifc.Name, ifc.Index)
+ }
+ return
+ }
+ t.Skip("no up adapter")
+}
diff --git a/internal/platform/autostart_linux.go b/internal/platform/autostart_linux.go
new file mode 100644
index 0000000..477a9de
--- /dev/null
+++ b/internal/platform/autostart_linux.go
@@ -0,0 +1,86 @@
+package platform
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+)
+
+// autostartFile is an XDG autostart entry, honoured by GNOME, KDE, XFCE, Cinnamon, LXQt and others
+// at sign-in. On NixOS the module's programs.net-merge.autostart (a systemd user service) is an
+// alternative that doesn't depend on the desktop.
+func autostartFile() (string, error) {
+ dir, err := os.UserConfigDir()
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(dir, "autostart", "net-merge.desktop"), nil
+}
+
+// trayExe prefers net-merge on PATH: on NixOS that is the capability wrapper in /run/wrappers/bin,
+// while os.Executable is the store path, which doesn't carry the capabilities.
+func trayExe() string {
+ if p, err := exec.LookPath("net-merge"); err == nil {
+ if abs, err := filepath.Abs(p); err == nil {
+ return abs
+ }
+ }
+ exe, _ := os.Executable()
+ return exe
+}
+
+// desktopQuote quotes an Exec argument as the Desktop Entry spec requires.
+func desktopQuote(s string) string {
+ if !strings.ContainsAny(s, " \t\"'\\$`") {
+ return s
+ }
+ return `"` + strings.NewReplacer(`\`, `\\\\`, `"`, `\"`, "`", "\\`", "$", `\$`).Replace(s) + `"`
+}
+
+// Autostart turns start-at-sign-in "on" or "off", or prints its "status".
+func Autostart(action string) error {
+ path, err := autostartFile()
+ if err != nil {
+ return err
+ }
+ _, 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":
+ 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 err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ entry := "[Desktop Entry]\n" +
+ "Type=Application\n" +
+ "Name=net-merge\n" +
+ "Comment=Use all your network adapters at once\n" +
+ "Exec=" + desktopQuote(trayExe()) + " tray\n" +
+ "Terminal=false\n" +
+ "X-GNOME-Autostart-enabled=true\n"
+ if err := os.WriteFile(path, []byte(entry), 0o644); err != nil {
+ return err
+ }
+ fmt.Println("autostart is ON: net-merge starts at sign-in (" + path + ").")
+ if !IsAdmin() {
+ fmt.Println("note: the tray needs CAP_NET_ADMIN to start merging; see `net-merge tray` or the README.")
+ }
+ return nil
+}
diff --git a/autostart_windows.go b/internal/platform/autostart_windows.go
similarity index 84%
rename from autostart_windows.go
rename to internal/platform/autostart_windows.go
index f0dfedb..9940d43 100644
--- a/autostart_windows.go
+++ b/internal/platform/autostart_windows.go
@@ -1,4 +1,4 @@
-package main
+package platform
import (
"encoding/binary"
@@ -60,35 +60,29 @@ func utf16le(s string) []byte {
return b
}
-func cmdAutostart(args []string) {
- if len(args) != 1 || (args[0] != "on" && args[0] != "off" && args[0] != "status") {
- fmt.Fprintln(os.Stderr, "usage: net-merge autostart on|off|status")
- os.Exit(2)
- }
- if args[0] == "status" {
+// Autostart turns start-at-sign-in "on" or "off", or prints its "status".
+func Autostart(action string) error {
+ if action == "status" {
if run("schtasks", "/Query", "/TN", taskName) == nil {
fmt.Println("autostart is ON (starts at sign-in, no UAC prompt).")
} else {
fmt.Println("autostart is OFF.")
}
- return
+ return nil
}
- if !isAdmin() {
- if err := relaunchElevated(append([]string{"autostart"}, args...), false); err != nil {
- die(err)
- }
- return
+ if !IsAdmin() {
+ return RelaunchElevated([]string{"autostart", action}, false)
}
- if args[0] == "off" {
+ if action == "off" {
if run("schtasks", "/Query", "/TN", taskName) != nil {
fmt.Println("autostart is already OFF.")
- return
+ return nil
}
if err := run("schtasks", "/Delete", "/F", "/TN", taskName); err != nil {
- die(err)
+ return err
}
fmt.Println("autostart is OFF.")
- return
+ return nil
}
user := os.Getenv("USERNAME")
if d := os.Getenv("USERDOMAIN"); d != "" {
@@ -96,23 +90,24 @@ func cmdAutostart(args []string) {
}
tmp := filepath.Join(os.TempDir(), "net-merge-task.xml")
if err := os.WriteFile(tmp, utf16le(taskXML(user, trayExe())), 0o600); err != nil {
- die(err)
+ return err
}
defer os.Remove(tmp)
if err := run("schtasks", "/Create", "/F", "/TN", taskName, "/XML", tmp); err != nil {
- die(err)
+ return err
}
fmt.Println("autostart is ON: net-merge starts at sign-in without a UAC prompt.")
+ return nil
}
-// hasConsole is false for the windowless tray build and for a double-clicked GUI launch.
-func hasConsole() bool {
+// HasConsole is false for the windowless tray build and for a double-clicked GUI launch.
+func HasConsole() bool {
r, _, _ := windows.NewLazySystemDLL("kernel32.dll").NewProc("GetConsoleWindow").Call()
return r != 0
}
-// showError is how the windowless build reports a fatal error: there is no console to print to.
-func showError(msg string) {
+// ShowError is how the windowless build reports a fatal error: there is no console to print to.
+func ShowError(msg string) {
t, _ := windows.UTF16PtrFromString(msg)
c, _ := windows.UTF16PtrFromString("net-merge")
windows.MessageBox(0, t, c, windows.MB_OK|windows.MB_ICONERROR)
diff --git a/internal/platform/desktop_windows.go b/internal/platform/desktop_windows.go
new file mode 100644
index 0000000..f7a6166
--- /dev/null
+++ b/internal/platform/desktop_windows.go
@@ -0,0 +1,54 @@
+package platform
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "syscall"
+ "time"
+ "unsafe"
+
+ "golang.org/x/sys/windows"
+)
+
+// CheckDriver reports whether the TUN driver can be loaded: wintun.dll must sit next to the exe.
+func CheckDriver() error {
+ exe, _ := os.Executable()
+ if _, err := os.Stat(filepath.Join(filepath.Dir(exe), "wintun.dll")); err != nil {
+ return fmt.Errorf("wintun.dll not found next to %s", exe)
+ }
+ return nil
+}
+
+// WaitForTray blocks until the shell's taskbar and notification area exist.
+func WaitForTray(max time.Duration) bool {
+ user32 := windows.NewLazySystemDLL("user32.dll")
+ findWindow, findWindowEx := user32.NewProc("FindWindowW"), user32.NewProc("FindWindowExW")
+ taskbar, _ := windows.UTF16PtrFromString("Shell_TrayWnd")
+ notify, _ := windows.UTF16PtrFromString("TrayNotifyWnd")
+ deadline := time.Now().Add(max)
+ for {
+ if h, _, _ := findWindow.Call(uintptr(unsafe.Pointer(taskbar)), 0); h != 0 {
+ if n, _, _ := findWindowEx.Call(h, 0, uintptr(unsafe.Pointer(notify)), 0); n != 0 {
+ time.Sleep(time.Second) // let the notification area finish initialising
+ return true
+ }
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(500 * time.Millisecond)
+ }
+}
+
+func run(name string, args ...string) error {
+ cmd := exec.Command(name, args...)
+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s %s: %v: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
diff --git a/internal/platform/doc.go b/internal/platform/doc.go
new file mode 100644
index 0000000..22ef9a2
--- /dev/null
+++ b/internal/platform/doc.go
@@ -0,0 +1,3 @@
+// Package platform holds what differs between operating systems outside the network code:
+// privileges, single-instance locking, autostart and how errors reach a user with no console.
+package platform
diff --git a/internal/platform/platform_linux.go b/internal/platform/platform_linux.go
new file mode 100644
index 0000000..e3d5f27
--- /dev/null
+++ b/internal/platform/platform_linux.go
@@ -0,0 +1,138 @@
+package platform
+
+import (
+ "bufio"
+ "errors"
+ "fmt"
+ "log"
+ "net"
+ "os"
+ "os/exec"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/unix"
+)
+
+// IsAdmin reports whether this process may create the TUN and its routes, i.e. holds
+// CAP_NET_ADMIN: as root, or through file capabilities (setcap, or NixOS's security.wrappers).
+func IsAdmin() bool {
+ f, err := os.Open("/proc/self/status")
+ if err != nil {
+ return os.Geteuid() == 0
+ }
+ defer f.Close()
+ sc := bufio.NewScanner(f)
+ for sc.Scan() {
+ if v, ok := strings.CutPrefix(sc.Text(), "CapEff:"); ok {
+ caps, err := strconv.ParseUint(strings.TrimSpace(v), 16, 64)
+ return err == nil && caps&(1<<unix.CAP_NET_ADMIN) != 0
+ }
+ }
+ return os.Geteuid() == 0
+}
+
+// The single-instance lock is an abstract unix socket: visible to every user, and released by the
+// kernel when the process dies, so a crash never leaves a stale lock behind.
+const lockAddr = "@net-merge"
+
+var lock net.Listener
+
+// SingleInstance is false if another net-merge (run or tray) already owns the TUN.
+// The socket is intentionally kept for the life of the process.
+func SingleInstance() bool {
+ ln, err := net.Listen("unix", lockAddr)
+ if err != nil {
+ return false
+ }
+ lock = ln
+ go func() { // InstanceRunning connects to check; answer by hanging up
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }()
+ return true
+}
+
+// InstanceRunning reports whether a net-merge holds the single-instance lock.
+func InstanceRunning() bool {
+ c, err := net.DialTimeout("unix", lockAddr, time.Second)
+ if err != nil {
+ return false
+ }
+ c.Close()
+ return true
+}
+
+// RedirectStd points stdout/stderr (including the runtime's panic output) at f, for a process
+// started with no terminal (autostart, systemd).
+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.Dup3(int(f.Fd()), 1, 0)
+ unix.Dup3(int(f.Fd()), 2, 0)
+}
+
+// RelaunchElevated replaces this process with itself run as root: sudo in a terminal, pkexec
+// (a graphical password prompt) otherwise. It only returns on failure.
+func RelaunchElevated(args []string, hidden bool) error {
+ exe, err := os.Executable()
+ if err != nil {
+ return err
+ }
+ tool := "pkexec"
+ if HasConsole() {
+ tool = "sudo"
+ }
+ path, err := exec.LookPath(tool)
+ if err != nil {
+ return fmt.Errorf("%s not found; run net-merge as root or give it CAP_NET_ADMIN (see README)", tool)
+ }
+ return syscall.Exec(path, append([]string{tool, exe}, args...), os.Environ())
+}
+
+// RelaunchTray is RelaunchElevated for the tray. On Linux the tray icon is a D-Bus service in the
+// user's desktop session, which a process restarted as root can't reach, so the tray has to run
+// as the user with CAP_NET_ADMIN granted to the binary instead.
+func RelaunchTray(args []string, hidden bool) error {
+ exe, _ := os.Executable()
+ if strings.HasPrefix(exe, "/nix/store/") { // read-only: capabilities come from a NixOS security wrapper
+ return errors.New("the tray needs CAP_NET_ADMIN: enable programs.net-merge in your NixOS configuration " +
+ "and run /run/wrappers/bin/net-merge (see README). `sudo net-merge run` works without it")
+ }
+ return errors.New("the tray needs CAP_NET_ADMIN. Grant it once with:\n" +
+ " sudo setcap cap_net_admin,cap_net_raw+ep " + exe + "\n" +
+ "`sudo net-merge run` works without it")
+}
+
+// HasConsole reports whether stderr is a terminal.
+func HasConsole() bool {
+ _, err := unix.IoctlGetTermios(2, unix.TCGETS)
+ return err == nil
+}
+
+// ShowError reports a fatal error to a user with no terminal, as a desktop notification if
+// notify-send is installed (the error is in the log file either way).
+func ShowError(msg string) {
+ if path, err := exec.LookPath("notify-send"); err == nil {
+ exec.Command(path, "--urgency=critical", "--app-name=net-merge", "net-merge", msg).Run()
+ }
+}
+
+// CheckDriver reports whether the kernel's TUN driver is available.
+func CheckDriver() error {
+ if _, err := os.Stat("/dev/net/tun"); err != nil {
+ return fmt.Errorf("/dev/net/tun not found (try: sudo modprobe tun): %w", err)
+ }
+ return nil
+}
+
+// WaitForTray is a no-op on Linux: the tray library registers with the desktop's
+// StatusNotifierWatcher over D-Bus whenever it is available.
+func WaitForTray(max time.Duration) bool { return true }
diff --git a/elevate_windows.go b/internal/platform/platform_windows.go
similarity index 74%
rename from elevate_windows.go
rename to internal/platform/platform_windows.go
index 3c1b140..dc1fa16 100644
--- a/elevate_windows.go
+++ b/internal/platform/platform_windows.go
@@ -1,4 +1,4 @@
-package main
+package platform
import (
"log"
@@ -9,19 +9,19 @@ import (
"golang.org/x/sys/windows"
)
-func isAdmin() bool { return windows.GetCurrentProcessToken().IsElevated() }
+func IsAdmin() bool { return windows.GetCurrentProcessToken().IsElevated() }
-// singleInstance is false if another net-merge (run or tray) already owns the TUN.
+// SingleInstance is false if another net-merge (run or tray) already owns the TUN.
// The mutex handle is intentionally kept for the life of the process.
-func singleInstance() bool {
+func SingleInstance() bool {
name, _ := windows.UTF16PtrFromString(`Global\net-merge`)
_, err := windows.CreateMutex(nil, false, name)
return err != windows.ERROR_ALREADY_EXISTS
}
-// instanceRunning reports whether an (elevated) net-merge holds the mutex. From a normal shell
+// InstanceRunning reports whether an (elevated) net-merge holds the mutex. From a normal shell
// OpenMutex is denied rather than succeeding, which also means it exists.
-func instanceRunning() bool {
+func InstanceRunning() bool {
name, _ := windows.UTF16PtrFromString(`Global\net-merge`)
h, err := windows.OpenMutex(windows.SYNCHRONIZE, false, name)
if err == nil {
@@ -31,17 +31,18 @@ func instanceRunning() bool {
return err == windows.ERROR_ACCESS_DENIED
}
-// redirectStd points stdout/stderr (including the runtime's panic output and the TUN library's
+// RedirectStd points stdout/stderr (including the runtime's panic output and the TUN library's
// logger) at f, for the hidden elevated process that has no console.
-func redirectStd(f *os.File) {
+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
windows.SetStdHandle(windows.STD_OUTPUT_HANDLE, windows.Handle(f.Fd()))
windows.SetStdHandle(windows.STD_ERROR_HANDLE, windows.Handle(f.Fd()))
}
-// relaunchElevated re-runs this exe with the given args behind a UAC prompt.
-func relaunchElevated(args []string, hidden bool) error {
+// RelaunchElevated re-runs this exe with the given args behind a UAC prompt and returns once it
+// has started.
+func RelaunchElevated(args []string, hidden bool) error {
exe, err := os.Executable()
if err != nil {
return err
diff --git a/internal/platform/tray_windows.go b/internal/platform/tray_windows.go
new file mode 100644
index 0000000..67d6b87
--- /dev/null
+++ b/internal/platform/tray_windows.go
@@ -0,0 +1,11 @@
+package platform
+
+import "fmt"
+
+// RelaunchTray is RelaunchElevated for the tray.
+func RelaunchTray(args []string, hidden bool) error {
+ if err := RelaunchElevated(args, hidden); err != nil {
+ return fmt.Errorf("could not start elevated (UAC declined?): %w", err)
+ }
+ return nil
+}
diff --git a/state.go b/internal/state/state.go
similarity index 69%
rename from state.go
rename to internal/state/state.go
index 322a22e..d63ccf4 100644
--- a/state.go
+++ b/internal/state/state.go
@@ -1,10 +1,12 @@
-package main
+package state
import (
"encoding/json"
"os"
"path/filepath"
"time"
+
+ "net-merge/internal/engine"
)
// The elevated process can't be signalled from a normal shell, so control goes through files in
@@ -17,10 +19,10 @@ type Status struct {
V6 string
Since time.Time
Updated time.Time
- NICs []SlotStats
+ NICs []engine.SlotStats
}
-func defaultStateDir() string {
+func DefaultDir() string {
base, err := os.UserCacheDir()
if err != nil {
base = os.TempDir()
@@ -28,7 +30,7 @@ func defaultStateDir() string {
return filepath.Join(base, "net-merge")
}
-func writeStatus(dir string, st Status) {
+func Write(dir string, st Status) {
b, err := json.Marshal(st)
if err != nil {
return
@@ -39,10 +41,10 @@ func writeStatus(dir string, st Status) {
}
}
-func clearStatus(dir string) { os.Remove(filepath.Join(dir, "status.json")) }
+func Clear(dir string) { os.Remove(filepath.Join(dir, "status.json")) }
-// readStatus returns the status only if it is fresh, i.e. a live process is writing it.
-func readStatus(dir string) (*Status, bool) {
+// Read returns the status only if it is fresh, i.e. a live process is writing it.
+func Read(dir string) (*Status, bool) {
b, err := os.ReadFile(filepath.Join(dir, "status.json"))
if err != nil {
return nil, false
@@ -54,12 +56,12 @@ func readStatus(dir string) (*Status, bool) {
return &st, true
}
-func sendMarker(dir, name string) error {
+func SendMarker(dir, name string) error {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
return os.WriteFile(filepath.Join(dir, name), nil, 0o644)
}
-// takeMarker consumes a marker, reporting whether it was there.
-func takeMarker(dir, name string) bool { return os.Remove(filepath.Join(dir, name)) == nil }
+// TakeMarker consumes a marker, reporting whether it was there.
+func TakeMarker(dir, name string) bool { return os.Remove(filepath.Join(dir, name)) == nil }
diff --git a/tray_windows.go b/internal/tray/tray.go
similarity index 62%
rename from tray_windows.go
rename to internal/tray/tray.go
index 91bd6be..87d5a2a 100644
--- a/tray_windows.go
+++ b/internal/tray/tray.go
@@ -1,122 +1,36 @@
-package main
+// Package tray is the notification-area icon: green/grey for on/off, live speeds on hover, and
+// a menu to pause, change the IPv6 mode or quit.
+package tray
import (
- "flag"
"fmt"
- "os"
- "path/filepath"
"strings"
"time"
"unicode/utf16"
- "unsafe"
"fyne.io/systray"
- "golang.org/x/sys/windows"
+
+ "net-merge/internal/engine"
+ "net-merge/internal/icon"
+ "net-merge/internal/logx"
+ "net-merge/internal/state"
+ "net-merge/internal/tun"
)
const trayRows = 4 // adapters shown in the menu; extra rows stay hidden
-func cmdTray(args []string) {
- fs := flag.NewFlagSet("tray", flag.ExitOnError)
- var c common
- c.register(fs)
- hidden := fs.Bool("hidden", true, "hide the console window of the elevated process")
- startOff := fs.Bool("off", false, "start with system-wide mode OFF (default: ON)")
- fs.Parse(args)
-
- if !isAdmin() {
- child := append([]string{"tray"}, args...)
- child = append(child, "-state-dir", c.stateDir)
- if err := relaunchElevated(child, *hidden); err != nil {
- die(fmt.Errorf("could not start elevated (UAC declined?): %w", err))
- }
- fmt.Println("Approve the UAC prompt. Look for the net-merge icon in the system tray (^ overflow arrow).")
- return
- }
- if !singleInstance() {
- fmt.Println("net-merge is already running.")
- return
- }
- if c.logFile == "" {
- c.stats = 0 // nobody is watching a hidden console
- if !hasConsole() {
- c.logFile = filepath.Join(c.stateDir, "net-merge.log") // windowless build: keep a log for diagnosis
- }
- }
- if err := c.setup(); err != nil {
- die(err)
- }
- if err := checkWintun(); err != nil {
- die(err)
- }
-
- tun := NewTun(nil)
- tun.mtu = c.mtu
- mode := func() string {
- if tun.IsOn() {
- return "system-wide (tray)"
- }
- return ""
- }
- sched, bal, err := c.boot(mode)
- if err != nil {
- die(err)
- }
- tun.b = bal
-
- // Started at sign-in this process can beat explorer.exe by a fraction of a second. With no
- // taskbar the tray library fails to create the icon and never becomes ready, so wait for it.
- if !waitForTaskbar(3 * time.Minute) {
- logf("warning: taskbar not found after 3 minutes, trying anyway\n")
- }
- ready := make(chan struct{})
- go func() { // safety net: if the icon still can't be created, exit so the scheduled task retries
- select {
- case <-ready:
- case <-time.After(30 * time.Second):
- logf("error: tray icon did not initialise within 30s; exiting so the scheduled task can restart it\n")
- os.Exit(4)
- }
- }()
-
- ui := &trayUI{tun: tun, sched: sched, bal: bal, stateDir: c.stateDir, startOn: !*startOff,
- iconOn: trayIcon(true), iconOff: trayIcon(false), toggleReq: make(chan struct{}, 1), ready: ready}
- systray.Run(ui.onReady, func() { tun.Off(); clearStatus(c.stateDir) })
-}
-
-// waitForTaskbar blocks until the shell's taskbar and notification area exist.
-func waitForTaskbar(max time.Duration) bool {
- user32 := windows.NewLazySystemDLL("user32.dll")
- findWindow, findWindowEx := user32.NewProc("FindWindowW"), user32.NewProc("FindWindowExW")
- taskbar, _ := windows.UTF16PtrFromString("Shell_TrayWnd")
- notify, _ := windows.UTF16PtrFromString("TrayNotifyWnd")
- deadline := time.Now().Add(max)
- for {
- if h, _, _ := findWindow.Call(uintptr(unsafe.Pointer(taskbar)), 0); h != 0 {
- if n, _, _ := findWindowEx.Call(h, 0, uintptr(unsafe.Pointer(notify)), 0); n != 0 {
- time.Sleep(time.Second) // let the notification area finish initialising
- return true
- }
- }
- if time.Now().After(deadline) {
- return false
- }
- time.Sleep(500 * time.Millisecond)
- }
-}
-
-func checkWintun() error {
- exe, _ := os.Executable()
- if _, err := os.Stat(filepath.Join(filepath.Dir(exe), "wintun.dll")); err != nil {
- return fmt.Errorf("wintun.dll not found next to %s", exe)
- }
- return nil
+// Run shows the tray icon and blocks until Quit. It turns merging on at once if startOn, and
+// 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) })
}
type trayUI struct {
- tun *Tun
- bal *Balancer
- sched *Scheduler
+ tun *tun.Tun
+ bal *engine.Balancer
+ sched *engine.Scheduler
stateDir string
startOn bool
iconOn []byte
@@ -150,7 +64,7 @@ func (u *trayUI) onReady() {
u.rows = append(u.rows, r)
}
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() == V6Auto)
+ 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")
quit := systray.AddMenuItem("Quit", "Turns system-wide mode off and exits")
systray.SetOnTapped(func() {
@@ -176,22 +90,22 @@ func (u *trayUI) onReady() {
case <-u.v6Item.ClickedCh:
if u.v6Item.Checked() {
u.v6Item.Uncheck()
- u.bal.SetV6Mode(V6On)
+ u.bal.SetV6Mode(engine.V6On)
} else {
u.v6Item.Check()
- u.bal.SetV6Mode(V6Auto)
+ u.bal.SetV6Mode(engine.V6Auto)
}
case <-quit.ClickedCh:
systray.Quit()
return
case <-tick.C:
switch { // `net-merge on|off|quit` from a terminal
- case takeMarker(u.stateDir, "quit"):
+ case state.TakeMarker(u.stateDir, "quit"):
systray.Quit()
return
- case takeMarker(u.stateDir, "off"):
+ case state.TakeMarker(u.stateDir, "off"):
u.turn(false)
- case takeMarker(u.stateDir, "on"):
+ case state.TakeMarker(u.stateDir, "on"):
u.turn(true)
}
}
@@ -203,13 +117,13 @@ func (u *trayUI) turn(on bool) {
u.lastErr = ""
if !on {
u.tun.Off()
- clearStatus(u.stateDir)
+ state.Clear(u.stateDir)
return
}
u.setHeader("Turning on...")
if err := u.tun.On(); err != nil {
u.lastErr = err.Error()
- logf("error: %v\n", err)
+ logx.Printf("error: %v\n", err)
}
}
@@ -233,9 +147,9 @@ func (u *trayUI) refresh() {
u.lastOn = &on
}
- // Speeds are each adapter's real traffic from Windows' counters, i.e. every app (qBittorrent binds
+ // Speeds are each adapter's real traffic from the OS's counters, i.e. every app (qBittorrent binds
// to adapters directly and never passes through net-merge), and they are shown even when paused.
- var live []SlotStats
+ var live []engine.SlotStats
var down, up float64
for _, s := range u.sched.Snapshot() {
if s.Present {
@@ -307,7 +221,7 @@ func stateWord(on bool) string {
//
// It drops detail (the app name, then per-adapter upload, then the unit) until it fits; every
// adapter keeps its download speed and the total is always shown.
-func trayTooltip(state string, down, up float64, live []SlotStats) string {
+func trayTooltip(state string, down, up float64, live []engine.SlotStats) string {
build := func(head string, withUp bool, unit string) string {
lines := []string{head}
for _, s := range live {
diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go
new file mode 100644
index 0000000..9631344
--- /dev/null
+++ b/internal/tray/tray_test.go
@@ -0,0 +1,48 @@
+package tray
+
+import (
+ "strings"
+ "testing"
+ "unicode/utf16"
+ "unicode/utf8"
+
+ "net-merge/internal/engine"
+)
+
+func TestShortenCountsUTF16AndKeepsRunesWhole(t *testing.T) {
+ s := "net-merge ON ↓12 ↑3.4 Mbit/s"
+ if got := shorten(s, 127); got != s {
+ t.Fatalf("short string changed: %q", got)
+ }
+ got := shorten(s, 16)
+ if n := len(utf16.Encode([]rune(got))); n > 16 {
+ t.Fatalf("%q is %d UTF-16 units, want <= 16", got, n)
+ }
+ if !utf8.ValidString(got) || !strings.HasSuffix(got, "…") {
+ t.Fatalf("bad cut: %q", got)
+ }
+}
+
+func TestTrayTooltipFitsWindowsLimit(t *testing.T) {
+ const mbit = 125_000
+ mk := func(name string, down, up float64) engine.SlotStats {
+ return engine.SlotStats{Name: name, Present: true, State: "up", LinkIn: down * mbit, LinkOut: up * mbit}
+ }
+ two := []engine.SlotStats{mk("Ethernet 3", 16, 0.2), mk("Ethernet 4", 79, 7)}
+ tip := trayTooltip(stateWord(true), 95*mbit, 7.2*mbit, two)
+ for _, want := range []string{"Merging", "Eth 3 ↓16 ↑0.2", "Eth 4 ↓79 ↑7.0", "Total ↓95 ↑7.2 Mbps"} {
+ if utf16Len(tip) > tooltipMax || !strings.Contains(tip, want) {
+ t.Fatalf("two adapters should fit with full detail (%q), got %d chars:\n%s", want, utf16Len(tip), tip)
+ }
+ }
+ four := append(two, mk("Wi-Fi", 55, 3), mk("Ethernet 7", 12, 1))
+ tip = trayTooltip(stateWord(false), 162*mbit, 11.2*mbit, four)
+ if utf16Len(tip) > tooltipMax {
+ t.Fatalf("tooltip is %d chars, Windows shows only %d:\n%s", utf16Len(tip), tooltipMax+1, tip)
+ }
+ for _, want := range []string{"Paused", "Eth 3 ↓", "Eth 4 ↓", "WiFi ↓", "Eth 7 ↓", "Total ↓162 ↑11"} {
+ if !strings.Contains(tip, want) {
+ t.Fatalf("every adapter keeps its download speed and the total is always shown; %q missing:\n%s", want, tip)
+ }
+ }
+}
diff --git a/forward.go b/internal/tun/forward.go
similarity index 99%
rename from forward.go
rename to internal/tun/forward.go
index fce58c7..96c2a28 100644
--- a/forward.go
+++ b/internal/tun/forward.go
@@ -1,4 +1,4 @@
-package main
+package tun
import (
"time"
diff --git a/internal/tun/tun.go b/internal/tun/tun.go
new file mode 100644
index 0000000..5f9fb1e
--- /dev/null
+++ b/internal/tun/tun.go
@@ -0,0 +1,167 @@
+// Package tun is the system-wide front-end: a virtual adapter whose routes capture every flow,
+// terminated in a userland TCP/IP stack and re-dialed through the Balancer.
+package tun
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "sync"
+ "time"
+
+ "gvisor.dev/gvisor/pkg/tcpip/stack"
+
+ "github.com/xjasonlyu/tun2socks/v2/core"
+ "github.com/xjasonlyu/tun2socks/v2/core/device"
+ "github.com/xjasonlyu/tun2socks/v2/core/device/tun"
+ "github.com/xjasonlyu/tun2socks/v2/core/option"
+ tlog "github.com/xjasonlyu/tun2socks/v2/log"
+ M "github.com/xjasonlyu/tun2socks/v2/metadata"
+ "github.com/xjasonlyu/tun2socks/v2/proxy/reject"
+ "github.com/xjasonlyu/tun2socks/v2/tunnel"
+
+ "net-merge/internal/engine"
+)
+
+const (
+ tunName = "net-merge"
+ tunIP = "198.18.0.1"
+ tunMask = "255.255.255.0"
+ // A ULA on purpose. The OS's source-address policy (RFC 6724, on Windows and in glibc) prefers
+ // IPv4 over IPv6 when the only IPv6 source on the route is a ULA, so dual-stack sites go over
+ // IPv4 and spread across every adapter, while IPv6-only sites (and explicit IPv6) still work
+ // through the IPv6 path. A global-scope address here makes the OS prefer IPv6 everywhere, which
+ // funnels all traffic onto whichever adapters happen to have IPv6. Nothing is ever sent from
+ // this address.
+ tunIP6 = "fd6e:6d65:7267::1"
+)
+
+// Two /1 routes per family beat any default route (/0) without touching it, so Off() is just
+// deleting these.
+var (
+ routes4 = []string{"0.0.0.0/1", "128.0.0.0/1"}
+ routes6 = []string{"::/1", "8000::/1"}
+)
+
+// tunProxy plugs the Balancer into tun2socks: every TCP/UDP flow that enters the TUN is dialed
+// out through a pinned NIC. There is no SOCKS hop in between.
+type tunProxy struct{ b *engine.Balancer }
+
+func (p tunProxy) DialContext(ctx context.Context, m *M.Metadata) (net.Conn, error) {
+ return p.b.DialPinned(ctx, m.DstIP.Unmap().String(), int(m.DstPort))
+}
+
+func (p tunProxy) DialUDP(m *M.Metadata) (net.PacketConn, error) {
+ f := engine.Fam4
+ if d := m.DstIP.Unmap(); d.Is6() {
+ f = engine.Fam6
+ }
+ return p.b.ListenUDP(context.Background(), f)
+}
+
+// Tun is the system-wide switch: On creates the adapter and routes, Off removes them. Both are
+// idempotent. If the process dies, the adapter and its routes die with it.
+type Tun struct {
+ mu sync.Mutex
+ B *engine.Balancer // set before On
+ MTU int // set before On; see DefaultMTU
+ dev device.Device
+ stk *stack.Stack
+ idx int
+ on bool
+}
+
+// DefaultMTU is the TUN's MTU, used both by the userland stack and by the OS. TUN traffic never
+// leaves the machine (flows are re-dialed with normal sockets), so it isn't bound by the links'
+// 1500. Bigger packets mean far fewer per-packet trips through the userland stack: about 6x fewer
+// for bulk TCP at 9000. Not 65535: the TUN library allocates a full-MTU buffer for every inbound
+// packet, even a 40-byte ACK.
+const DefaultMTU = 9000
+
+// udpSessionTimeout ends idle UDP sessions sooner than tun2socks' 60s. Torrent DHT opens a session
+// per peer queried, each holding a socket, two goroutines and two 64 KB buffers. 30s stays above the
+// ~25s keepalives common in VPN and NAT-traversal protocols.
+const udpSessionTimeout = 30 * time.Second
+
+func New(b *engine.Balancer) *Tun { return &Tun{B: b, MTU: DefaultMTU} }
+
+func (t *Tun) IsOn() bool {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ return t.on
+}
+
+func (t *Tun) On() (err error) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.on {
+ return nil
+ }
+ // "error", not "warn": tun2socks warns once per dropped UDP packet ("symmetric NAT ... drop
+ // packet"), which a torrent client triggers continuously.
+ if lvl, e := tlog.ParseLevel("error"); e == nil {
+ tlog.SetLogger(tlog.Must(tlog.NewLeveled(lvl)))
+ }
+ tunnel.T().SetUDPTimeout(udpSessionTimeout)
+ CleanupStale()
+
+ dev, err := tun.Open(tunName, uint32(t.MTU))
+ if err != nil {
+ return fmt.Errorf("open TUN (%s): %w", openHint, err)
+ }
+ stk, err := core.CreateStack(&core.Config{
+ LinkEndpoint: dev,
+ TransportHandler: tunnel.T(),
+ Options: []option.Option{option.WithTCPModerateReceiveBuffer(true)},
+ })
+ if err != nil {
+ dev.Close()
+ return err
+ }
+ installForwarders(stk, t.B.V6Allowed)
+ t.dev, t.stk = dev, stk
+ defer func() {
+ if err != nil {
+ t.teardown()
+ }
+ }()
+ tunnel.T().SetProxy(tunProxy{t.B})
+
+ if t.idx, err = configure(t.MTU); err != nil {
+ return err
+ }
+ t.on = true
+ return nil
+}
+
+func (t *Tun) Off() {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.teardown()
+}
+
+func (t *Tun) teardown() {
+ if t.idx != 0 {
+ delRoutes(t.idx) // traffic falls straight back to the normal default route
+ }
+ tunnel.T().SetProxy(&reject.Reject{})
+ if t.dev != nil {
+ t.dev.Close()
+ }
+ if t.stk != nil {
+ done := make(chan struct{})
+ go func() { t.stk.Close(); t.stk.Wait(); close(done) }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ }
+ }
+ t.dev, t.stk, t.idx, t.on = nil, nil, 0, false
+}
+
+// CleanupStale removes routes left on a surviving net-merge adapter (e.g. after a crash).
+func CleanupStale() {
+ if ifc, err := net.InterfaceByName(tunName); err == nil {
+ delRoutes(ifc.Index)
+ }
+}
diff --git a/internal/tun/tun_linux.go b/internal/tun/tun_linux.go
new file mode 100644
index 0000000..358fe26
--- /dev/null
+++ b/internal/tun/tun_linux.go
@@ -0,0 +1,77 @@
+package tun
+
+import (
+ "fmt"
+ "net"
+
+ "github.com/vishvananda/netlink"
+ "golang.org/x/sys/unix"
+
+ "net-merge/internal/logx"
+)
+
+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)
+ if err != nil {
+ return 0, fmt.Errorf("adapter %q did not appear: %w", tunName, err)
+ }
+ idx := link.Attrs().Index
+ if err := netlink.AddrReplace(link, &netlink.Addr{IPNet: hostCIDR(tunIP + "/24")}); err != nil {
+ return idx, fmt.Errorf("set address: %w", err)
+ }
+ if err := netlink.LinkSetUp(link); err != nil {
+ return idx, fmt.Errorf("bring up: %w", err)
+ }
+ for _, dst := range routes4 {
+ if err := netlink.RouteReplace(tunRoute(idx, dst)); err != nil {
+ return idx, fmt.Errorf("route %s: %w", dst, err)
+ }
+ }
+ // IPv6 is best-effort: if it can't be set up (IPv6 disabled), IPv4 still works and IPv6 stays on
+ // its normal path. No DAD: the address is ours alone, and it should be usable immediately.
+ if err := netlink.AddrReplace(link, &netlink.Addr{IPNet: hostCIDR(tunIP6 + "/64"), Flags: unix.IFA_F_NODAD}); err != nil {
+ logx.Printf("warning: IPv6 not captured: %v\n", err)
+ } else {
+ for _, dst := range routes6 {
+ if err := netlink.RouteReplace(tunRoute(idx, dst)); err != nil {
+ logx.Printf("warning: IPv6 route %s: %v\n", dst, err)
+ }
+ }
+ }
+ return idx, nil
+}
+
+// delRoutes removes the capturing routes. Closing the TUN also removes the adapter and everything
+// on it, but deleting the routes first stops capture before the stack goes away.
+func delRoutes(idx int) {
+ for _, dst := range append(append([]string{}, routes4...), routes6...) {
+ netlink.RouteDel(tunRoute(idx, dst)) // already gone is fine: IPv6 may never have been set up
+ }
+}
+
+func tunRoute(idx int, dst string) *netlink.Route {
+ return &netlink.Route{LinkIndex: idx, Dst: prefix(dst), Scope: netlink.SCOPE_LINK}
+}
+
+// hostCIDR is an address with its subnet, e.g. 198.18.0.1/24.
+func hostCIDR(s string) *net.IPNet {
+ ip, n, err := net.ParseCIDR(s)
+ if err != nil {
+ panic(err)
+ }
+ n.IP = ip
+ return n
+}
+
+func prefix(s string) *net.IPNet {
+ _, n, err := net.ParseCIDR(s)
+ if err != nil {
+ panic(err)
+ }
+ return n
+}
diff --git a/internal/tun/tun_windows.go b/internal/tun/tun_windows.go
new file mode 100644
index 0000000..ddc0977
--- /dev/null
+++ b/internal/tun/tun_windows.go
@@ -0,0 +1,100 @@
+package tun
+
+import (
+ "fmt"
+ "net"
+ "os/exec"
+ "strconv"
+ "strings"
+ "syscall"
+ "time"
+
+ "golang.org/x/sys/windows"
+ wun "golang.zx2c4.com/wireguard/tun"
+
+ "net-merge/internal/logx"
+)
+
+const openHint = "needs admin and wintun.dll next to net-merge.exe"
+
+// routes4 as `route` wants them: destination and mask.
+var routes4win = [][2]string{{"0.0.0.0", "128.0.0.0"}, {"128.0.0.0", "128.0.0.0"}}
+
+func init() {
+ wun.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 {
+ wun.WintunStaticRequestedGUID = &g
+ }
+}
+
+// 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",
+ "address="+tunIP, "mask="+tunMask, "store=active"); err != nil {
+ return 0, err
+ }
+ ifc, err := waitIface(tunName, 5*time.Second)
+ if err != nil {
+ return 0, err
+ }
+ // 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)
+ mtuArg := "mtu=" + strconv.Itoa(mtu)
+ if e := run("netsh", "interface", "ipv4", "set", "subinterface", "interface="+idx, mtuArg, "store=active"); e != nil {
+ logx.Printf("warning: could not set IPv4 MTU: %v\n", e)
+ }
+ for _, dst := range routes4win {
+ if err = run("route", "add", dst[0], "mask", dst[1], "0.0.0.0", "metric", "1", "if", idx); 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 e := run("netsh", "interface", "ipv6", "add", "address", "interface="+idx, "address="+tunIP6+"/64", "store=active"); e != nil {
+ logx.Printf("warning: IPv6 not captured: %v\n", e)
+ } else {
+ if e := run("netsh", "interface", "ipv6", "set", "subinterface", "interface="+idx, mtuArg, "store=active"); e != nil {
+ logx.Printf("warning: could not set IPv6 MTU: %v\n", e)
+ }
+ for _, p := range routes6 {
+ if e := run("netsh", "interface", "ipv6", "add", "route", "prefix="+p, "interface="+idx, "metric=1", "store=active"); e != nil {
+ logx.Printf("warning: IPv6 route %s: %v\n", p, e)
+ }
+ }
+ }
+ return ifc.Index, nil
+}
+
+func delRoutes(idx int) {
+ for _, dst := range routes4win {
+ run("route", "delete", dst[0], "mask", dst[1], "0.0.0.0", "if", strconv.Itoa(idx))
+ }
+ for _, p := range routes6 {
+ run("netsh", "interface", "ipv6", "delete", "route", "prefix="+p, "interface="+strconv.Itoa(idx), "store=active")
+ }
+}
+
+func run(name string, args ...string) error {
+ cmd := exec.Command(name, args...)
+ cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("%s %s: %v: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return nil
+}
+
+func waitIface(name string, d time.Duration) (*net.Interface, error) {
+ deadline := time.Now().Add(d)
+ for {
+ ifc, err := net.InterfaceByName(name)
+ if err == nil {
+ return ifc, nil
+ }
+ if time.Now().After(deadline) {
+ return nil, fmt.Errorf("adapter %q did not appear: %w", name, err)
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
diff --git a/listen.go b/listen.go
deleted file mode 100644
index 391deef..0000000
--- a/listen.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package main
-
-import "net"
-
-func listenTCP(addr string) (net.Listener, error) { return net.Listen("tcp4", addr) }
diff --git a/nix/module.nix b/nix/module.nix
new file mode 100644
index 0000000..3b1b0b6
--- /dev/null
+++ b/nix/module.nix
@@ -0,0 +1,80 @@
+self:
+{
+ config,
+ lib,
+ pkgs,
+ ...
+}:
+
+let
+ cfg = config.programs.net-merge;
+in
+{
+ options.programs.net-merge = {
+ enable = lib.mkEnableOption ''
+ net-merge, which balances connections across all network adapters. Installs a capability
+ wrapper (CAP_NET_ADMIN, CAP_NET_RAW) at /run/wrappers/bin/net-merge so the tray and
+ `net-merge run` work without root
+ '';
+
+ package = lib.mkOption {
+ type = lib.types.package;
+ default = self.packages.${pkgs.stdenv.hostPlatform.system}.default;
+ defaultText = lib.literalExpression "net-merge.packages.\${system}.default";
+ description = "The net-merge package to use.";
+ };
+
+ autostart = lib.mkOption {
+ type = lib.types.bool;
+ default = false;
+ description = ''
+ Start the net-merge tray in every graphical session, as a systemd user service bound to
+ graphical-session.target.
+ '';
+ };
+
+ extraArgs = lib.mkOption {
+ type = lib.types.listOf lib.types.str;
+ default = [ ];
+ example = [
+ "-ipv6"
+ "on"
+ "-include"
+ "wlp2s0,enp0s20f0u1"
+ ];
+ description = "Extra flags passed to `net-merge tray` by the autostart service.";
+ };
+ };
+
+ config = lib.mkIf cfg.enable {
+ security.wrappers.net-merge = {
+ source = lib.getExe cfg.package;
+ owner = "root";
+ group = "root";
+ # NET_ADMIN creates the TUN and its routes; NET_RAW lets SO_BINDTODEVICE pin flows to an
+ # adapter on kernels older than 5.7.
+ capabilities = "cap_net_admin,cap_net_raw+ep";
+ };
+
+ # Replies to captured flows arrive on the TUN; they belong to connections this machine opened.
+ networking.firewall.trustedInterfaces = [ "net-merge" ];
+
+ systemd.user.services.net-merge = lib.mkIf cfg.autostart {
+ description = "net-merge tray (use all network adapters at once)";
+ partOf = [ "graphical-session.target" ];
+ after = [ "graphical-session.target" ];
+ wantedBy = [ "graphical-session.target" ];
+ serviceConfig = {
+ ExecStart = lib.escapeShellArgs (
+ [
+ "${config.security.wrapperDir}/net-merge"
+ "tray"
+ ]
+ ++ cfg.extraArgs
+ );
+ Restart = "on-failure";
+ RestartSec = 5;
+ };
+ };
+ };
+}
diff --git a/nix/package.nix b/nix/package.nix
new file mode 100644
index 0000000..ad6062f
--- /dev/null
+++ b/nix/package.nix
@@ -0,0 +1,41 @@
+{
+ lib,
+ buildGoModule,
+ go_1_27,
+ version ? "dev",
+}:
+
+(buildGoModule.override { go = go_1_27; }) {
+ pname = "net-merge";
+ inherit version;
+
+ src = lib.fileset.toSource {
+ root = ./..;
+ fileset = lib.fileset.unions [
+ ../go.mod
+ ../go.sum
+ ../cmd
+ ../internal
+ ];
+ };
+
+ vendorHash = "sha256-rJelc2cmpkvc02bmMBVicoPDvuhzJsjaq7xI3JQBWRI=";
+ subPackages = [ "cmd/net-merge" ];
+ env.CGO_ENABLED = 0;
+ ldflags = [
+ "-s"
+ "-w"
+ "-X main.version=${version}"
+ ];
+
+ # The tests bind to loopback aliases and connect to local listeners; the sandbox allows that.
+ doCheck = true;
+
+ meta = {
+ description = "Use all your network adapters at once: balances connections across Wi-Fi, Ethernet and tethers";
+ homepage = "https://github.com/sidharthify/net-merge";
+ license = lib.licenses.mit;
+ mainProgram = "net-merge";
+ platforms = lib.platforms.linux ++ lib.platforms.windows;
+ };
+}
diff --git a/scripts/build.ps1 b/scripts/build.ps1
index f998628..df23b3f 100644
--- a/scripts/build.ps1
+++ b/scripts/build.ps1
@@ -23,8 +23,8 @@ Invoke-Native 'go vet' { go vet ./... }
Invoke-Native 'go test' { go test ./... }
# One source, two exes: a console CLI, and a windowless build that defaults to the tray.
-Invoke-Native 'build cli' { go build -trimpath -ldflags "-s -w -X main.version=$Version" -o dist\net-merge.exe . }
-Invoke-Native 'build tray' { go build -trimpath -ldflags "-s -w -H=windowsgui -X main.defaultCmd=tray -X main.version=$Version" -o dist\net-merge-tray.exe . }
+Invoke-Native 'build cli' { go build -trimpath -ldflags "-s -w -X main.version=$Version" -o dist\net-merge.exe .\cmd\net-merge }
+Invoke-Native 'build tray' { go build -trimpath -ldflags "-s -w -H=windowsgui -X main.defaultCmd=tray -X main.version=$Version" -o dist\net-merge-tray.exe .\cmd\net-merge }
Invoke-Native 'icon' { .\dist\net-merge.exe _icon dist\net-merge.ico }
& "$PSScriptRoot\fetch-wintun.ps1" -OutDir dist
diff --git a/tun_windows.go b/tun_windows.go
deleted file mode 100644
index 677c235..0000000
--- a/tun_windows.go
+++ /dev/null
@@ -1,234 +0,0 @@
-package main
-
-import (
- "context"
- "fmt"
- "net"
- "os/exec"
- "strconv"
- "strings"
- "sync"
- "syscall"
- "time"
-
- "golang.org/x/sys/windows"
- wun "golang.zx2c4.com/wireguard/tun"
- "gvisor.dev/gvisor/pkg/tcpip/stack"
-
- "github.com/xjasonlyu/tun2socks/v2/core"
- "github.com/xjasonlyu/tun2socks/v2/core/device"
- "github.com/xjasonlyu/tun2socks/v2/core/device/tun"
- "github.com/xjasonlyu/tun2socks/v2/core/option"
- tlog "github.com/xjasonlyu/tun2socks/v2/log"
- M "github.com/xjasonlyu/tun2socks/v2/metadata"
- "github.com/xjasonlyu/tun2socks/v2/proxy/reject"
- "github.com/xjasonlyu/tun2socks/v2/tunnel"
-)
-
-const (
- tunName = "net-merge"
- tunIP = "198.18.0.1"
- tunMask = "255.255.255.0"
- // A ULA on purpose. Windows' source-address policy prefers IPv4 over IPv6 when the only IPv6
- // source on the route is a ULA, so dual-stack sites go over IPv4 and spread across every
- // adapter, while IPv6-only sites (and explicit IPv6) still work through the IPv6 path. A
- // global-scope address here makes the OS prefer IPv6 everywhere, which funnels all traffic
- // onto whichever adapters happen to have IPv6. Nothing is ever sent from this address.
- tunIP6 = "fd6e:6d65:7267::1"
-)
-
-func init() {
- wun.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 {
- wun.WintunStaticRequestedGUID = &g
- }
-}
-
-// tunProxy plugs the Balancer into tun2socks: every TCP/UDP flow that enters the TUN is dialed
-// out through a pinned NIC. There is no SOCKS hop in between.
-type tunProxy struct{ b *Balancer }
-
-func (p tunProxy) DialContext(ctx context.Context, m *M.Metadata) (net.Conn, error) {
- return p.b.DialPinned(ctx, m.DstIP.Unmap().String(), int(m.DstPort))
-}
-
-func (p tunProxy) DialUDP(m *M.Metadata) (net.PacketConn, error) {
- f := fam4
- if d := m.DstIP.Unmap(); d.Is6() {
- f = fam6
- }
- return p.b.ListenUDP(context.Background(), f)
-}
-
-// Tun is the system-wide switch: On creates the adapter and routes, Off removes them. Both are
-// idempotent. If the process dies, the adapter and its routes die with it.
-type Tun struct {
- mu sync.Mutex
- b *Balancer
- mtu int // set before On; see defaultMTU
- dev device.Device
- stk *stack.Stack
- idx int
- on bool
-}
-
-// defaultMTU is the TUN's MTU, used both by the userland stack and by Windows. TUN traffic never
-// leaves the machine (flows are re-dialed with normal sockets), so it isn't bound by the links'
-// 1500. Bigger packets mean far fewer per-packet trips through the userland stack: about 6x fewer
-// for bulk TCP at 9000. Not 65535: the TUN library allocates a full-MTU buffer for every inbound
-// packet, even a 40-byte ACK.
-const defaultMTU = 9000
-
-// udpSessionTimeout ends idle UDP sessions sooner than tun2socks' 60s. Torrent DHT opens a session
-// per peer queried, each holding a socket, two goroutines and two 64 KB buffers. 30s stays above the
-// ~25s keepalives common in VPN and NAT-traversal protocols.
-const udpSessionTimeout = 30 * time.Second
-
-func NewTun(b *Balancer) *Tun { return &Tun{b: b, mtu: defaultMTU} }
-
-func (t *Tun) IsOn() bool {
- t.mu.Lock()
- defer t.mu.Unlock()
- return t.on
-}
-
-func (t *Tun) On() (err error) {
- t.mu.Lock()
- defer t.mu.Unlock()
- if t.on {
- return nil
- }
- // "error", not "warn": tun2socks warns once per dropped UDP packet ("symmetric NAT ... drop
- // packet"), which a torrent client triggers continuously.
- if lvl, e := tlog.ParseLevel("error"); e == nil {
- tlog.SetLogger(tlog.Must(tlog.NewLeveled(lvl)))
- }
- tunnel.T().SetUDPTimeout(udpSessionTimeout)
- cleanupStale()
-
- dev, err := tun.Open(tunName, uint32(t.mtu))
- if err != nil {
- return fmt.Errorf("open TUN (needs admin and wintun.dll next to net-merge.exe): %w", err)
- }
- stk, err := core.CreateStack(&core.Config{
- LinkEndpoint: dev,
- TransportHandler: tunnel.T(),
- Options: []option.Option{option.WithTCPModerateReceiveBuffer(true)},
- })
- if err != nil {
- dev.Close()
- return err
- }
- installForwarders(stk, t.b.V6Allowed)
- t.dev, t.stk = dev, stk
- defer func() {
- if err != nil {
- t.teardown()
- }
- }()
- tunnel.T().SetProxy(tunProxy{t.b})
-
- if err = run("netsh", "interface", "ipv4", "set", "address", "name="+tunName, "source=static",
- "address="+tunIP, "mask="+tunMask, "store=active"); err != nil {
- return err
- }
- ifc, err := waitIface(tunName, 5*time.Second)
- if err != nil {
- return err
- }
- t.idx = 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(t.idx)
- mtu := "mtu=" + strconv.Itoa(t.mtu)
- if e := run("netsh", "interface", "ipv4", "set", "subinterface", "interface="+idx, mtu, "store=active"); e != nil {
- logf("warning: could not set IPv4 MTU: %v\n", e)
- }
- // Two /1 routes beat any default route (/0) without touching it, so Off() is just deleting these.
- for _, dst := range [][2]string{{"0.0.0.0", "128.0.0.0"}, {"128.0.0.0", "128.0.0.0"}} {
- if err = run("route", "add", dst[0], "mask", dst[1], "0.0.0.0", "metric", "1", "if", strconv.Itoa(t.idx)); err != nil {
- return err
- }
- }
- // IPv6 is best-effort: if it can't be set up, IPv4 still works and IPv6 stays on its normal path.
- if e := run("netsh", "interface", "ipv6", "add", "address", "interface="+idx, "address="+tunIP6+"/64", "store=active"); e != nil {
- logf("warning: IPv6 not captured: %v\n", e)
- } else {
- if e := run("netsh", "interface", "ipv6", "set", "subinterface", "interface="+idx, mtu, "store=active"); e != nil {
- logf("warning: could not set IPv6 MTU: %v\n", e)
- }
- for _, p := range []string{"::/1", "8000::/1"} {
- if e := run("netsh", "interface", "ipv6", "add", "route", "prefix="+p, "interface="+idx, "metric=1", "store=active"); e != nil {
- logf("warning: IPv6 route %s: %v\n", p, e)
- }
- }
- }
- t.on = true
- return nil
-}
-
-func (t *Tun) Off() {
- t.mu.Lock()
- defer t.mu.Unlock()
- t.teardown()
-}
-
-func (t *Tun) teardown() {
- if t.idx != 0 {
- delRoutes(t.idx) // traffic falls straight back to the normal default route
- }
- tunnel.T().SetProxy(&reject.Reject{})
- if t.dev != nil {
- t.dev.Close()
- }
- if t.stk != nil {
- done := make(chan struct{})
- go func() { t.stk.Close(); t.stk.Wait(); close(done) }()
- select {
- case <-done:
- case <-time.After(5 * time.Second):
- }
- }
- t.dev, t.stk, t.idx, t.on = nil, nil, 0, false
-}
-
-// cleanupStale removes routes left on a surviving net-merge adapter (e.g. after a crash).
-func cleanupStale() {
- if ifc, err := net.InterfaceByName(tunName); err == nil {
- delRoutes(ifc.Index)
- }
-}
-
-func delRoutes(idx int) {
- for _, dst := range [][2]string{{"0.0.0.0", "128.0.0.0"}, {"128.0.0.0", "128.0.0.0"}} {
- run("route", "delete", dst[0], "mask", dst[1], "0.0.0.0", "if", strconv.Itoa(idx))
- }
- for _, p := range []string{"::/1", "8000::/1"} {
- run("netsh", "interface", "ipv6", "delete", "route", "prefix="+p, "interface="+strconv.Itoa(idx), "store=active")
- }
-}
-
-func waitIface(name string, d time.Duration) (*net.Interface, error) {
- deadline := time.Now().Add(d)
- for {
- ifc, err := net.InterfaceByName(name)
- if err == nil {
- return ifc, nil
- }
- if time.Now().After(deadline) {
- return nil, fmt.Errorf("adapter %q did not appear: %w", name, err)
- }
- time.Sleep(50 * time.Millisecond)
- }
-}
-
-func run(name string, args ...string) error {
- cmd := exec.Command(name, args...)
- cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
- out, err := cmd.CombinedOutput()
- if err != nil {
- return fmt.Errorf("%s %s: %v: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out)))
- }
- return nil
-}