Use all your internet connections at once on Windows, macOS, Linux and Android: per-connection load balancing over Wi-Fi, Ethernet, mobile data and phone tethers
Go androidbandwidth-aggregationdownloadergolanglinuxload-balancingmacosnet-mergenetworkingtetheringtunwifiwindowswintun
Initial release: system-wide multi-adapter connection balancer for Windows
Rohit Mahtoc7f12d77cd21
diff --git a/.gitattributes b/.gitattributesnew file mode 100644index 0000000..dcad03c--- /dev/null+++ b/.gitattributes@@ -0,0 +1,3 @@+* text=auto eol=lf+*.ps1 text eol=lf+*.iss text eol=lfdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlnew file mode 100644index 0000000..8359a17--- /dev/null+++ b/.github/workflows/ci.yml@@ -0,0 +1,16 @@+name: ci+on:+ push:+ branches: [main]+ pull_request:++jobs:+ test:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: go.mod+ - run: go vet ./...+ - run: go test ./...diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..afe4b4d--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,34 @@+name: release+# Push a tag like v0.2.0 to build the installer and portable zip and publish a GitHub release.+on:+ push:+ tags: ['v*']++permissions:+ contents: write++jobs:+ release:+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@v4+ - uses: actions/setup-go@v5+ with:+ go-version-file: go.mod+ - name: Install Inno Setup+ run: choco install innosetup --no-progress -y+ - name: Build installer+ shell: pwsh+ run: |+ $version = '${{ github.ref_name }}'.TrimStart('v')+ scripts/build.ps1 -Version $version -RepoUrl "${{ github.server_url }}/${{ github.repository }}"+ - name: Publish release+ shell: pwsh+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ $tag = '${{ github.ref_name }}'+ $files = Get-ChildItem dist/net-merge-setup-*.exe, dist/net-merge-*-portable.zip+ gh release view $tag *> $null+ if ($LASTEXITCODE -eq 0) { gh release upload $tag $files --clobber } # release already created by hand+ else { gh release create $tag $files --generate-notes }diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..c9f82ce--- /dev/null+++ b/.gitignore@@ -0,0 +1,3 @@+*.exe+wintun.dll+dist/diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..1c255dc--- /dev/null+++ b/LICENSE@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2026 Rohit Mahto++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..fecafa9--- /dev/null+++ b/README.md@@ -0,0 +1,94 @@+# net-merge++Use all your network adapters at once on Windows. 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.++Measured with Wi-Fi + an Android USB tether + an iPhone hotspot, 9 parallel downloads:+**232-303 Mbit/s** vs about 121 Mbit/s for the fastest single link.++No server, VPN or account is involved: connections go straight out of the adapter they are assigned to.++## Install++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.++Then start **net-merge** from the Start menu. A tray icon appears:++- **left-click** toggles ON / OFF+- **right-click** shows live speed per adapter, "Turn on/off", and Quit++Tick *Start net-merge when I sign in* in the installer (or run `net-merge autostart on`) to start it at+sign-in without a UAC prompt.++## Command line++```+net-merge on | off | quit | status | list | autostart on|off|status | version+net-merge tray tray app (asks for admin once)+net-merge run system-wide in a console window+net-merge socks plain SOCKS5 proxy on 127.0.0.1:1080 (no admin, per-app)+net-merge cleanup remove leftover routes after a crash+```++Flags for `tray`/`run`/`socks`: `-include "WiFi,Ethernet"` (only these adapters), `-weight "Name=3"`+(fixed weight instead of measured), `-ipv6 auto|on|off`, `-log file`.++## How it works++- ON creates a Wintun adapter `net-merge` 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.+- 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+ (`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.+- Flows go to the adapter with the lowest (active flows + 1) / weight. Weights follow measured+ throughput, separately for IPv4 and IPv6 (a link can be fast over native IPv6 and slow over translated+ IPv4).+- IPv6 (`-ipv6 auto|on|off`, tray checkbox): IPv6 flows can only leave through adapters that have IPv6, and+ apps that prefer IPv6 (browsers, OBS, curl) would funnel everything onto them. In `auto` mode IPv6 is+ balanced only when every adapter has working IPv6; otherwise new IPv6 connections are refused at the SYN+ (UDP gets ICMP unreachable), apps fall back to IPv4 instantly, and IPv4 spreads over all adapters.+ Cost: IPv6-only hosts are unreachable while the adapters differ (untick the tray box or use `-ipv6 on`).++## Limits++- 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.++## Build++Needs Go (see `go.mod`) and, for the installer, [Inno Setup 6](https://jrsoftware.org/isinfo.php).++```+go test ./... # uses loopback aliases as fake adapters; no second link needed+scripts\build.ps1 -Version 0.1.0 # dist\: net-merge.exe, net-merge-tray.exe, installer, portable zip+```++`wintun.dll` is not in the repo: `scripts\fetch-wintun.ps1` downloads it and verifies its SHA-256 and its+WireGuard LLC signature. To run from source, put it next to the exe:++```+go build -o net-merge.exe .+scripts\fetch-wintun.ps1 -OutDir .+```++Releases are built by GitHub Actions when a `vX.Y.Z` tag is pushed (`.github/workflows/release.yml`).+`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+large downloads and the numbers become meaningless.++## License++MIT, see `LICENSE`. Third-party components are listed in `THIRD-PARTY-NOTICES.md`.diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.mdnew file mode 100644index 0000000..36fe8cb--- /dev/null+++ b/THIRD-PARTY-NOTICES.md@@ -0,0 +1,21 @@+# Third-party notices++net-merge is MIT licensed (see `LICENSE`). It links the following libraries, all under permissive+licenses (license texts are in each project's repository and in the Go module cache):++| Component | License | Use |+|---|---|---|+| [tun2socks](https://github.com/xjasonlyu/tun2socks) | MIT | TUN device + userland TCP/IP stack glue |+| [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 |+| Other transitive modules (see `go.mod` / `go.sum`) | MIT / Apache-2.0 / BSD | |++## Wintun++The installer and portable zip include `wintun.dll`, the prebuilt, signed driver from+<https://www.wintun.net/>, unmodified, under the Prebuilt Binaries License. Copyright (C) 2018-2021+WireGuard LLC. The license text is shipped next to it as `wintun-LICENSE.txt`. The DLL is not stored+in this repository: `scripts/fetch-wintun.ps1` downloads it and verifies its SHA-256 and its+WireGuard LLC code signature.diff --git a/autostart_windows.go b/autostart_windows.gonew file mode 100644index 0000000..ba1feda--- /dev/null+++ b/autostart_windows.go@@ -0,0 +1,118 @@+package main++import (+ "encoding/binary"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "unicode/utf16"++ "golang.org/x/sys/windows"+)++const taskName = "net-merge"++// trayExe prefers the windowless tray build installed next to this exe.+func trayExe() string {+ exe, _ := os.Executable()+ gui := filepath.Join(filepath.Dir(exe), "net-merge-tray.exe")+ if _, err := os.Stat(gui); err == nil {+ return gui+ }+ return exe+}++func xmlEscape(s string) string {+ return strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """).Replace(s)+}++// A scheduled task (not a Run-key entry) is what lets an admin-only app start at sign-in without+// a UAC prompt. It's defined by XML because the schtasks command line can't turn off the defaults+// that would break a tray app: "stop after 3 days" and "don't run on battery".+func taskXML(user, exe string) string {+ return `<?xml version="1.0" encoding="UTF-16"?>+<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">+ <RegistrationInfo><Description>Starts net-merge (multi-adapter connection balancer) at sign-in.</Description></RegistrationInfo>+ <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>` + xmlEscape(user) + `</UserId></LogonTrigger></Triggers>+ <Principals><Principal id="Author"><UserId>` + xmlEscape(user) + `</UserId><LogonType>InteractiveToken</LogonType><RunLevel>HighestAvailable</RunLevel></Principal></Principals>+ <Settings>+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>+ <AllowHardTerminate>true</AllowHardTerminate>+ <StartWhenAvailable>true</StartWhenAvailable>+ <Enabled>true</Enabled>+ </Settings>+ <Actions Context="Author"><Exec><Command>` + xmlEscape(exe) + `</Command><Arguments>tray</Arguments></Exec></Actions>+</Task>`+}++func utf16le(s string) []byte {+ u := utf16.Encode([]rune(s))+ b := make([]byte, 2+2*len(u))+ b[0], b[1] = 0xFF, 0xFE // BOM+ for i, c := range u {+ binary.LittleEndian.PutUint16(b[2+2*i:], c)+ }+ 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" {+ 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+ }+ if !isAdmin() {+ if err := relaunchElevated(append([]string{"autostart"}, args...), false); err != nil {+ die(err)+ }+ return+ }+ if args[0] == "off" {+ if run("schtasks", "/Query", "/TN", taskName) != nil {+ fmt.Println("autostart is already OFF.")+ return+ }+ if err := run("schtasks", "/Delete", "/F", "/TN", taskName); err != nil {+ die(err)+ }+ fmt.Println("autostart is OFF.")+ return+ }+ user := os.Getenv("USERNAME")+ if d := os.Getenv("USERDOMAIN"); d != "" {+ user = d + `\` + user+ }+ tmp := filepath.Join(os.TempDir(), "net-merge-task.xml")+ if err := os.WriteFile(tmp, utf16le(taskXML(user, trayExe())), 0o600); err != nil {+ die(err)+ }+ defer os.Remove(tmp)+ if err := run("schtasks", "/Create", "/F", "/TN", taskName, "/XML", tmp); err != nil {+ die(err)+ }+ fmt.Println("autostart is ON: net-merge starts at sign-in without a UAC prompt.")+}++// 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) {+ t, _ := windows.UTF16PtrFromString(msg)+ c, _ := windows.UTF16PtrFromString("net-merge")+ windows.MessageBox(0, t, c, windows.MB_OK|windows.MB_ICONERROR)+}diff --git a/balancer.go b/balancer.gonew file mode 100644index 0000000..0778305--- /dev/null+++ b/balancer.go@@ -0,0 +1,230 @@+package main++import (+ "context"+ "errors"+ "io"+ "net"+ "strconv"+ "sync"+ "sync/atomic"+ "syscall"+ "time"+)++// Balancer dials outbound flows through the Scheduler. Front-ends (SOCKS5 now, TUN later)+// only call DialTCP and Relay, so the balancing logic lives in one place.+type Balancer struct {+ S *Scheduler+ ConnectTimeout time.Duration+ FailCooldown time.Duration+ v6mode atomic.Int32+}++// V6Mode decides what happens to IPv6 flows entering the TUN.+type V6Mode int32++const (+ // V6Auto balances IPv6 only when every adapter has it. When adapters differ, IPv6 flows are+ // refused so apps fall back to IPv4, which spreads over all adapters. (Apps that prefer IPv6+ // would otherwise funnel onto the few adapters that have it.)+ V6Auto V6Mode = iota+ // V6On always allows IPv6, balanced across the adapters that have it.+ V6On+ // V6Off refuses IPv6 entirely.+ V6Off+)++func ParseV6Mode(s string) (V6Mode, bool) {+ switch s {+ case "auto":+ return V6Auto, true+ case "on":+ return V6On, true+ case "off":+ return V6Off, true+ }+ return V6Auto, false+}++func (b *Balancer) SetV6Mode(m V6Mode) { b.v6mode.Store(int32(m)) }+func (b *Balancer) V6Mode() V6Mode { return V6Mode(b.v6mode.Load()) }++// V6Allowed is consulted for every new IPv6 flow.+func (b *Balancer) V6Allowed() bool {+ switch b.V6Mode() {+ case V6Off:+ return false+ case V6On:+ return b.S.V6Usable()+ }+ return b.S.V6CoversAll()+}++// V6State describes the current IPv6 behaviour for `status` and the tray.+func (b *Balancer) V6State() string {+ switch b.V6Mode() {+ case V6Off:+ return "off (refused, apps use IPv4)"+ case V6On:+ return "on (balanced over the adapters that have IPv6)"+ }+ if b.S.V6CoversAll() {+ return "auto: balanced (every adapter has IPv6)"+ }+ return "auto: refused, apps fall back to IPv4 so every adapter is used (not every adapter has IPv6)"+}++func NewBalancer(s *Scheduler) *Balancer {+ return &Balancer{S: s, ConnectTimeout: 8 * time.Second, FailCooldown: 15 * time.Second}+}++// Windows socket error codes; the portable syscall.E* constants don't match them on Windows.+const (+ wsaeAddrNotAvail syscall.Errno = 10049+ wsaeNetDown syscall.Errno = 10050+ wsaeNetUnreach syscall.Errno = 10051+ wsaeTimedOut syscall.Errno = 10060+ wsaeConnRefused syscall.Errno = 10061+ wsaeHostUnreach syscall.Errno = 10065+)++// SOCKS5 reply codes (also used as the generic failure reason).+const (+ repOK = 0x00+ repFailure = 0x01+ repNetUnreachable = 0x03+ repHostUnreachable = 0x04+ repRefused = 0x05+ repCmdUnsupported = 0x07+ repAtypUnsupported = 0x08+)++type dialClass struct {+ rep byte+ retry bool // worth trying another NIC+ linkDown bool // this NIC itself is broken: sideline it+}++func classify(err error) dialClass {+ is := func(wsa, std syscall.Errno) bool { return errors.Is(err, wsa) || errors.Is(err, std) }+ var dns *net.DNSError+ var ne net.Error+ switch {+ case errors.As(err, &dns):+ return dialClass{rep: repHostUnreachable}+ case is(wsaeAddrNotAvail, syscall.EADDRNOTAVAIL), is(wsaeNetDown, syscall.ENETDOWN):+ return dialClass{rep: repNetUnreachable, retry: true, linkDown: true}+ case is(wsaeNetUnreach, syscall.ENETUNREACH):+ return dialClass{rep: repNetUnreachable, retry: true, linkDown: true}+ case is(wsaeHostUnreach, syscall.EHOSTUNREACH), is(wsaeTimedOut, syscall.ETIMEDOUT):+ return dialClass{rep: repHostUnreachable, retry: true}+ case is(wsaeConnRefused, syscall.ECONNREFUSED):+ return dialClass{rep: repRefused}+ case errors.Is(err, context.DeadlineExceeded), errors.As(err, &ne) && ne.Timeout():+ return dialClass{rep: repHostUnreachable, retry: true}+ }+ return dialClass{rep: repFailure}+}++// 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) {+ // The destination's family decides which NIC address is used; a host name stays IPv4.+ f, network := fam4, "tcp4"+ if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {+ f, network = fam6, "tcp6"+ }+ tried := map[string]struct{}{}+ rep := byte(repFailure)+ var lastErr error = errors.New("no usable network adapter")+ if f == fam6 {+ rep, lastErr = repNetUnreachable, errors.New("no usable IPv6 adapter")+ }+ for {+ sl := b.S.AcquireFor(f, tried)+ if sl == nil {+ return nil, nil, f, &dialError{rep: rep, err: lastErr}+ }+ 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+ Timeout: b.ConnectTimeout,+ KeepAlive: 30 * time.Second,+ }+ conn, err := d.DialContext(ctx, network, net.JoinHostPort(host, strconv.Itoa(port)))+ if err == nil {+ return conn, sl, f, nil+ }+ b.S.ReleaseFor(sl, f)+ c := classify(err)+ if c.linkDown {+ b.S.Fail(sl, f, b.FailCooldown)+ }+ rep, lastErr = c.rep, err+ if !c.retry || ctx.Err() != nil {+ return nil, nil, f, &dialError{rep: rep, err: err}+ }+ }+}++type dialError struct {+ rep byte+ err error+}++func (e *dialError) Error() string { return e.err.Error() }+func (e *dialError) Unwrap() error { return e.err }++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) {+ var wg sync.WaitGroup+ var once sync.Once+ release := func() { once.Do(func() { s.ReleaseFor(sl, f) }) } // at the first half-close, see slotConn+ wg.Add(1)+ go func() {+ defer wg.Done()+ pump(upstream, client, &sl.bytesOut[f])+ release()+ }()+ pump(client, upstream, &sl.bytesIn[f])+ release()+ wg.Wait()+ client.Close()+ upstream.Close()+}++func pump(dst, src net.Conn, counter interface{ Add(int64) int64 }) {+ bp := bufPool.Get().(*[]byte)+ defer bufPool.Put(bp)+ buf := *bp+ for {+ n, err := src.Read(buf)+ if n > 0 {+ counter.Add(int64(n))+ if _, werr := dst.Write(buf[:n]); werr != nil {+ dst.Close()+ src.Close()+ return+ }+ }+ if err != nil {+ if err == io.EOF {+ if cw, ok := dst.(interface{ CloseWrite() error }); ok {+ cw.CloseWrite()+ } else {+ dst.Close()+ }+ } else {+ dst.Close()+ src.Close()+ }+ return+ }+ }+}diff --git a/elevate_windows.go b/elevate_windows.gonew file mode 100644index 0000000..8921f5f--- /dev/null+++ b/elevate_windows.go@@ -0,0 +1,60 @@+package main++import (+ "os"+ "path/filepath"+ "strings"++ "golang.org/x/sys/windows"+)++func isAdmin() bool { return windows.GetCurrentProcessToken().IsElevated() }++// 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 {+ 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+// OpenMutex is denied rather than succeeding, which also means it exists.+func instanceRunning() bool {+ name, _ := windows.UTF16PtrFromString(`Global\net-merge`)+ h, err := windows.OpenMutex(windows.SYNCHRONIZE, false, name)+ if err == nil {+ windows.CloseHandle(h)+ return true+ }+ return err == windows.ERROR_ACCESS_DENIED+}++// 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) {+ os.Stdout, os.Stderr = f, f+ 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 {+ exe, err := os.Executable()+ if err != nil {+ return err+ }+ quoted := make([]string, len(args))+ for i, a := range args {+ quoted[i] = windows.EscapeArg(a)+ }+ verb, _ := windows.UTF16PtrFromString("runas")+ file, _ := windows.UTF16PtrFromString(exe)+ params, _ := windows.UTF16PtrFromString(strings.Join(quoted, " "))+ dir, _ := windows.UTF16PtrFromString(filepath.Dir(exe))+ show := int32(windows.SW_SHOWNORMAL)+ if hidden {+ show = windows.SW_HIDE+ }+ return windows.ShellExecute(0, verb, file, params, dir, show)+}diff --git a/flowconn.go b/flowconn.gonew file mode 100644index 0000000..b130d29--- /dev/null+++ b/flowconn.go@@ -0,0 +1,96 @@+package main++import (+ "context"+ "errors"+ "net"+ "sync"+)++// slotConn counts a pinned TCP flow's bytes and releases its slot on Close. It exposes+// CloseRead/CloseWrite because the TUN relay half-closes each direction separately.+type slotConn struct {+ *net.TCPConn+ sl *Slot+ fam family+ s *Scheduler+ once sync.Once+}++func (c *slotConn) Read(p []byte) (int, error) {+ n, err := c.TCPConn.Read(p)+ c.sl.bytesIn[c.fam].Add(int64(n))+ return n, err+}++func (c *slotConn) Write(p []byte) (int, error) {+ n, err := c.TCPConn.Write(p)+ c.sl.bytesOut[c.fam].Add(int64(n))+ return n, err+}++// release frees the slot's balancing count. It happens at the first half-close, not at the final+// Close: the relay can keep a finished flow open for up to a minute waiting for the peer's FIN,+// and counting those as active would steer new flows away from the NIC that just finished.+func (c *slotConn) release() { c.once.Do(func() { c.s.ReleaseFor(c.sl, c.fam) }) }++func (c *slotConn) CloseRead() error { c.release(); return c.TCPConn.CloseRead() }+func (c *slotConn) CloseWrite() error { c.release(); return c.TCPConn.CloseWrite() }+func (c *slotConn) Close() error { c.release(); return c.TCPConn.Close() }++// DialPinned is DialTCP for front-ends that hand the conn to someone else to pump.+func (b *Balancer) DialPinned(ctx context.Context, host string, port int) (net.Conn, error) {+ c, sl, f, err := b.DialTCP(ctx, host, port)+ if err != nil {+ return nil, err+ }+ return &slotConn{TCPConn: c.(*net.TCPConn), sl: sl, fam: f, s: b.S}, nil+}++type slotPacketConn struct {+ net.PacketConn+ sl *Slot+ fam family+}++func (c *slotPacketConn) ReadFrom(p []byte) (int, net.Addr, error) {+ n, a, err := c.PacketConn.ReadFrom(p)+ c.sl.bytesIn[c.fam].Add(int64(n))+ return n, a, err+}++func (c *slotPacketConn) WriteTo(p []byte, a net.Addr) (int, error) {+ n, err := c.PacketConn.WriteTo(p, a)+ c.sl.bytesOut[c.fam].Add(int64(n))+ return n, err+}++// 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) {+ network := "udp4"+ if f == fam6 {+ network = "udp6"+ }+ tried := map[string]struct{}{}+ lastErr := errors.New("no usable network adapter")+ for {+ sl := b.S.AcquireFor(f, tried)+ if sl == nil {+ return nil, lastErr+ }+ tried[sl.key] = struct{}{}+ lc := net.ListenConfig{Control: unicastIF(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 {+ if classify(err).linkDown {+ b.S.Fail(sl, f, b.FailCooldown)+ }+ lastErr = err+ continue+ }+ return &slotPacketConn{PacketConn: pc, sl: sl, fam: f}, nil+ }+}diff --git a/forward.go b/forward.gonew file mode 100644index 0000000..fce58c7--- /dev/null+++ b/forward.go@@ -0,0 +1,89 @@+package main++import (+ "time"++ "gvisor.dev/gvisor/pkg/tcpip"+ "gvisor.dev/gvisor/pkg/tcpip/adapters/gonet"+ "gvisor.dev/gvisor/pkg/tcpip/header"+ "gvisor.dev/gvisor/pkg/tcpip/stack"+ "gvisor.dev/gvisor/pkg/tcpip/transport/tcp"+ "gvisor.dev/gvisor/pkg/tcpip/transport/udp"+ "gvisor.dev/gvisor/pkg/waiter"++ "github.com/xjasonlyu/tun2socks/v2/tunnel"+)++// installForwarders replaces tun2socks' TCP/UDP handlers with equivalents that can refuse IPv6+// flows. The refusal has to happen at the SYN (RST before the handshake completes): once the+// userland stack has accepted the connection the app believes it is connected, and a browser+// that "won" the race on IPv6 will not fall back to IPv4 after a later reset.+func installForwarders(s *stack.Stack, allowV6 func() bool) {+ isV6 := func(id stack.TransportEndpointID) bool { return id.LocalAddress.Len() == header.IPv6AddressSize }++ tf := tcp.NewForwarder(s, 0, 2<<10, func(r *tcp.ForwarderRequest) {+ id := r.ID()+ if isV6(id) && !allowV6() {+ r.Complete(true) // RST: connect fails instantly, Happy Eyeballs moves on to IPv4+ return+ }+ var wq waiter.Queue+ ep, err := r.CreateEndpoint(&wq)+ if err != nil {+ r.Complete(true) // prevent a half-open connection leak+ return+ }+ defer r.Complete(false)+ setTCPOptions(s, ep)+ tunnel.T().HandleTCP(&tcpConn{TCPConn: gonet.NewTCPConn(&wq, ep), id: id})+ })+ s.SetTransportProtocolHandler(tcp.ProtocolNumber, tf.HandlePacket)++ uf := udp.NewForwarder(s, func(r *udp.ForwarderRequest) bool {+ id := r.ID()+ if isV6(id) && !allowV6() {+ return false // unhandled: the stack answers ICMP port unreachable, so QUIC falls back fast+ }+ var wq waiter.Queue+ ep, err := r.CreateEndpoint(&wq)+ if err != nil {+ return false+ }+ tunnel.T().HandleUDP(&udpConn{UDPConn: gonet.NewUDPConn(&wq, ep), id: id})+ return true+ })+ s.SetTransportProtocolHandler(udp.ProtocolNumber, uf.HandlePacket)+}++type tcpConn struct {+ *gonet.TCPConn+ id stack.TransportEndpointID+}++func (c *tcpConn) ID() stack.TransportEndpointID { return c.id }++type udpConn struct {+ *gonet.UDPConn+ id stack.TransportEndpointID+}++func (c *udpConn) ID() stack.TransportEndpointID { return c.id }++// setTCPOptions mirrors tun2socks' defaults: keepalive plus the stack's default buffer sizes.+func setTCPOptions(s *stack.Stack, ep tcpip.Endpoint) {+ ep.SocketOptions().SetKeepAlive(true)+ idle := tcpip.KeepaliveIdleOption(60 * time.Second)+ ep.SetSockOpt(&idle)+ interval := tcpip.KeepaliveIntervalOption(30 * time.Second)+ ep.SetSockOpt(&interval)+ ep.SetSockOptInt(tcpip.KeepaliveCountOption, 9)++ var ss tcpip.TCPSendBufferSizeRangeOption+ if err := s.TransportProtocolOption(header.TCPProtocolNumber, &ss); err == nil {+ ep.SocketOptions().SetSendBufferSize(int64(ss.Default), false)+ }+ var rs tcpip.TCPReceiveBufferSizeRangeOption+ if err := s.TransportProtocolOption(header.TCPProtocolNumber, &rs); err == nil {+ ep.SocketOptions().SetReceiveBufferSize(int64(rs.Default), false)+ }+}diff --git a/go.mod b/go.modnew file mode 100644index 0000000..df9c586--- /dev/null+++ b/go.mod@@ -0,0 +1,24 @@+module net-merge++go 1.27++require (+ fyne.io/systray v1.12.2+ github.com/xjasonlyu/tun2socks/v2 v2.7.0+ golang.org/x/sys v0.46.0+ golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446+ gvisor.dev/gvisor v0.0.0-20260701204157-69c2d17aea96+)++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+ go.uber.org/atomic v1.11.0 // indirect+ go.uber.org/multierr v1.11.0 // indirect+ go.uber.org/zap v1.28.0 // indirect+ golang.org/x/exp v0.0.0-20260611194520-c48552f49976 // indirect+ golang.org/x/net v0.56.0 // indirect+ golang.org/x/time v0.15.0 // indirect+ golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect+)diff --git a/go.sum b/go.sumnew file mode 100644index 0000000..279a99e--- /dev/null+++ b/go.sum@@ -0,0 +1,42 @@+fyne.io/systray v1.12.2 h1:Y8DZxgLHsVQt6rY9Zrkkg+j67S7vv/1F2viOWKPpVeA=+fyne.io/systray v1.12.2/go.mod h1:RVwqP9nYMo7h5zViCBHri2FgjXF7H2cub7MAq4NSoLs=+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=+github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=+github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=+github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=+github.com/google/btree v1.1.3 h1:CVpQJjYgC4VbzxeGVHfvZrv1ctoYCAI8vbl07Fcxlyg=+github.com/google/btree v1.1.3/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=+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/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=+go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=+go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=+go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=+go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=+go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=+go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=+go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=+golang.org/x/exp v0.0.0-20260611194520-c48552f49976 h1:X8Hz2ImujgbmetVuW+w2YkyZChE3cBpZi2P158rTG9M=+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.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=+golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=+golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg=+golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI=+golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446 h1:cqHQ3AycTHvM2R7ikgyX57D+XvtcSnGylsLkOVhta/w=+golang.zx2c4.com/wireguard v0.0.0-20260522210424-ecfc5a8d5446/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw=+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=+gvisor.dev/gvisor v0.0.0-20260701204157-69c2d17aea96 h1:LZXOf4NwvAwUy/eI8P+Y3DUdYLyaCEDNPEjsL2OP2ro=+gvisor.dev/gvisor v0.0.0-20260701204157-69c2d17aea96/go.mod h1:8aLQqUBHDH8fY5y60lzmwDpMMbQCcT3EBfoSwhfaGCY=diff --git a/icon.go b/icon.gonew file mode 100644index 0000000..32568c3--- /dev/null+++ b/icon.go@@ -0,0 +1,60 @@+package main++import (+ "bytes"+ "encoding/binary"+ "image"+ "image/color"+ "image/png"+ "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+ bg := color.NRGBA{113, 113, 122, 255}+ if on {+ bg = color.NRGBA{34, 197, 94, 255}+ }+ segs := [][4]float64{{9, 8, 16, 16}, {23, 8, 16, 16}, {16, 16, 16, 25}}+ img := image.NewNRGBA(image.Rect(0, 0, size, size))+ for y := 0; y < size; y++ {+ for x := 0; x < size; x++ {+ px, py := float64(x)+0.5, float64(y)+0.5+ disc := clamp01(15.5 - math.Hypot(px-16, py-16) + 0.5)+ if disc == 0 {+ continue+ }+ glyph := 0.0+ for _, s := range segs {+ glyph = math.Max(glyph, clamp01(1.4-distToSeg(px, py, s[0], s[1], s[2], s[3])+0.5))+ }+ img.SetNRGBA(x, y, color.NRGBA{+ R: uint8(float64(bg.R)*(1-glyph) + 255*glyph),+ G: uint8(float64(bg.G)*(1-glyph) + 255*glyph),+ B: uint8(float64(bg.B)*(1-glyph) + 255*glyph),+ A: uint8(disc * 255),+ })+ }+ }+ var pngBuf bytes.Buffer+ png.Encode(&pngBuf, img)++ 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(22)) // image offset: 6 + 16+ ico.Write(pngBuf.Bytes())+ return ico.Bytes()+}++func clamp01(v float64) float64 { return math.Max(0, math.Min(1, v)) }++func distToSeg(px, py, ax, ay, bx, by float64) float64 {+ dx, dy := bx-ax, by-ay+ t := clamp01(((px-ax)*dx + (py-ay)*dy) / (dx*dx + dy*dy))+ return math.Hypot(px-(ax+t*dx), py-(ay+t*dy))+}diff --git a/installer/net-merge.iss b/installer/net-merge.issnew file mode 100644index 0000000..d49ca4a--- /dev/null+++ b/installer/net-merge.iss@@ -0,0 +1,94 @@+; Inno Setup script. Built by scripts/build.ps1 (needs dist/ filled first):+; ISCC /DVersion=0.1.0 installer\net-merge.iss+#ifndef Version+ #define Version "0.0.0"+#endif++[Setup]+AppId={{8F2A6C1E-5B3D-4E7A-9C41-2D6B8E0F7A13}+AppName=net-merge+AppVersion={#Version}+AppVerName=net-merge {#Version}+AppPublisher=net-merge contributors+#ifdef RepoUrl+AppPublisherURL={#RepoUrl}+AppSupportURL={#RepoUrl}/issues+AppUpdatesURL={#RepoUrl}/releases+#endif+VersionInfoVersion={#Version}+DefaultDirName={autopf}\net-merge+DefaultGroupName=net-merge+DisableProgramGroupPage=yes+; The TUN adapter and routes need admin, and so does writing to Program Files.+PrivilegesRequired=admin+ArchitecturesAllowed=x64compatible+ArchitecturesInstallIn64BitMode=x64compatible+MinVersion=10.0.17763+Compression=lzma2+SolidCompression=yes+WizardStyle=modern+LicenseFile=LICENSE+SourceDir=..+OutputDir=dist+OutputBaseFilename=net-merge-setup-{#Version}+UninstallDisplayIcon={app}\net-merge.ico+CloseApplications=no+; Uninstall removes %LOCALAPPDATA%\net-merge (status/log files) of the user who installed.+UsedUserAreasWarning=no++[Languages]+Name: "english"; MessagesFile: "compiler:Default.isl"++[Tasks]+Name: "autostart"; Description: "Start net-merge when I sign in (no UAC prompt)"; GroupDescription: "Startup:"; Flags: unchecked+Name: "desktopicon"; Description: "Create a &desktop shortcut"; GroupDescription: "Shortcuts:"; Flags: unchecked++[Files]+Source: "dist\net-merge.exe"; DestDir: "{app}"; Flags: ignoreversion+Source: "dist\net-merge-tray.exe"; DestDir: "{app}"; Flags: ignoreversion+Source: "dist\wintun.dll"; DestDir: "{app}"; Flags: ignoreversion+Source: "dist\wintun-LICENSE.txt"; DestDir: "{app}"; Flags: ignoreversion+Source: "dist\net-merge.ico"; DestDir: "{app}"; Flags: ignoreversion+Source: "LICENSE"; DestDir: "{app}"; Flags: ignoreversion+Source: "THIRD-PARTY-NOTICES.md"; DestDir: "{app}"; Flags: ignoreversion+Source: "README.md"; DestDir: "{app}"; Flags: ignoreversion isreadme++[Icons]+Name: "{autoprograms}\net-merge"; Filename: "{app}\net-merge-tray.exe"; IconFilename: "{app}\net-merge.ico"; Comment: "Use all your network adapters at once"+Name: "{autodesktop}\net-merge"; Filename: "{app}\net-merge-tray.exe"; IconFilename: "{app}\net-merge.ico"; Tasks: desktopicon++[Run]+Filename: "{app}\net-merge.exe"; Parameters: "autostart on"; Flags: runhidden; Tasks: autostart; StatusMsg: "Enabling start at sign-in..."+; The installer is already elevated, so the tray starts without a second UAC prompt.+Filename: "{app}\net-merge-tray.exe"; Description: "Start net-merge now"; Flags: nowait postinstall skipifsilent++[UninstallRun]+Filename: "{app}\net-merge.exe"; Parameters: "autostart off"; Flags: runhidden; RunOnceId: "AutostartOff"++[UninstallDelete]+Type: filesandordirs; Name: "{localappdata}\net-merge"++[Code]+// Turn net-merge off and make sure no copy is running before files are replaced or removed.+// Killing it is safe: the TUN adapter and its routes disappear with the process.+procedure StopNetMerge;+var+ rc: Integer;+begin+ if FileExists(ExpandConstant('{app}\net-merge.exe')) then+ Exec(ExpandConstant('{app}\net-merge.exe'), 'quit', '', SW_HIDE, ewWaitUntilTerminated, rc);+ Exec(ExpandConstant('{sys}\taskkill.exe'), '/F /IM net-merge-tray.exe', '', SW_HIDE, ewWaitUntilTerminated, rc);+ Exec(ExpandConstant('{sys}\taskkill.exe'), '/F /IM net-merge.exe', '', SW_HIDE, ewWaitUntilTerminated, rc);+end;++function PrepareToInstall(var NeedsRestart: Boolean): String;+begin+ StopNetMerge;+ Result := '';+end;++procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);+begin+ if CurUninstallStep = usUninstall then+ StopNetMerge;+end;diff --git a/listen.go b/listen.gonew file mode 100644index 0000000..391deef--- /dev/null+++ b/listen.go@@ -0,0 +1,5 @@+package main++import "net"++func listenTCP(addr string) (net.Listener, error) { return net.Listen("tcp4", addr) }diff --git a/main.go b/main.gonew file mode 100644index 0000000..3aa3e23--- /dev/null+++ b/main.go@@ -0,0 +1,412 @@+package main++import (+ "flag"+ "fmt"+ "io"+ "os"+ "os/signal"+ "strconv"+ "strings"+ "syscall"+ "time"+)++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 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 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 "" }+func (w weightFlags) Set(v string) error {+ i := strings.LastIndex(v, "=")+ if i < 1 {+ return fmt.Errorf(`want "Name=3", got %q`, v)+ }+ n, err := strconv.ParseFloat(v[i+1:], 64)+ if err != nil || n <= 0 {+ return fmt.Errorf("weight must be > 0 in %q", v)+ }+ w[v[:i]] = n+ return nil+}++type common struct {+ include string+ weights weightFlags+ rescan time.Duration+ stats time.Duration+ auto bool+ logFile string+ stateDir string+ ipv6 string+}++func (c *common) register(fs *flag.FlagSet) {+ c.weights = weightFlags{}+ fs.StringVar(&c.include, "include", "", "comma-separated adapter names to use (default: all non-virtual)")+ fs.Var(c.weights, "weight", `fixed adapter weight, repeatable: -weight "Wi-Fi=3"`)+ fs.DurationVar(&c.rescan, "rescan", 3*time.Second, "adapter re-scan interval")+ 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.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")+}++func (c *common) nicsDetailed() ([]Nic, []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)+}++func (c *common) nics() ([]Nic, error) {+ nics, _, err := c.nicsDetailed()+ return nics, err+}++// setup opens the log file (if any) and the state dir.+func (c *common) setup() error {+ if err := os.MkdirAll(c.stateDir, 0o755); err != nil {+ return err+ }+ if c.logFile != "" {+ f, err := os.OpenFile(c.logFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644)+ if err != nil {+ return err+ }+ out = f+ 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) {+ nics, err := c.nics()+ if err != nil {+ return nil, nil, err+ }+ if len(nics) == 0 {+ return nil, nil, fmt.Errorf("no usable IPv4 adapters found (try: net-merge list)")+ }+ sched := NewScheduler(nics)+ sched.SetAuto(c.auto && len(c.weights) == 0)+ for _, n := range nics {+ logf(" + %s\n", describeNic(n))+ }+ if len(nics) == 1 {+ logf(" note: only one adapter found, nothing to aggregate yet\n")+ }++ bal := NewBalancer(sched)+ v6, ok := ParseV6Mode(c.ipv6)+ if !ok {+ return nil, nil, fmt.Errorf(`-ipv6 must be auto, on or off, got %q`, c.ipv6)+ }+ bal.SetV6Mode(v6)++ since := time.Now()+ go sched.RunProbes(nil)+ go func() {+ for range time.Tick(c.rescan) {+ if ns, err := c.nics(); err == nil {+ sched.Update(ns)+ }+ }+ }()+ go func() {+ last := time.Now()+ for now := range time.Tick(time.Second) {+ sched.Tick(now.Sub(last))+ 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()})+ }+ }+ }+ }()+ 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()))+ }+ }()+ }+ return sched, bal, nil+}++func describeNic(n Nic) string {+ s := n.Name+ if n.IP != nil {+ s += " v4 " + n.IP.String()+ }+ if n.IP6 != nil {+ s += " v6 " + n.IP6.String()+ }+ return s+}++func formatNICs(snap []SlotStats) string {+ var sb strings.Builder+ for _, s := range snap {+ gone := ""+ if !s.Present {+ gone = " (gone)"+ }+ fmt.Fprintf(&sb, "%-14s v4 %-11s v6 %-11s now %6.1f Mbit/s active %3d total %5d w %.2f/%.2f peak %5.0f/%5.0f Mbit/s down %8.1f MB up %7.1f MB failed %d%s\n",+ s.Name, s.State, s.State6, (s.RateIn+s.RateOut)*8/1e6, s.Active, s.Total, s.Weight, s.Weight6, s.Peak*8/1e6, s.Peak6*8/1e6, float64(s.BytesIn)/1e6, float64(s.BytesOut)/1e6, s.Failed, gone)+ }+ return sb.String()+}++// Set at build time: -X main.version=... and, for the windowless tray build, -X main.defaultCmd=tray.+var (+ version = "dev"+ defaultCmd = ""+)++func main() {+ var cmd string+ var args []string+ switch {+ case len(os.Args) >= 2:+ cmd, args = os.Args[1], os.Args[2:]+ case defaultCmd != "":+ cmd = defaultCmd+ default:+ fmt.Fprint(os.Stderr, usage)+ os.Exit(2)+ }+ switch cmd {+ case "version":+ fmt.Println("net-merge", version)+ case "autostart":+ cmdAutostart(args)+ 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 {+ die(err)+ }+ case "tray":+ cmdTray(args)+ case "run":+ cmdRun(args)+ case "on", "off", "quit":+ cmdControl(cmd, args)+ case "status":+ cmdStatus(args)+ case "socks":+ cmdSocks(args)+ case "list":+ cmdList(args)+ case "cleanup":+ cmdCleanup()+ default:+ fmt.Fprint(os.Stderr, usage)+ os.Exit(2)+ }+}++func die(err error) {+ fmt.Fprintln(os.Stderr, "error:", err)+ if !hasConsole() {+ showError(err.Error())+ }+ os.Exit(1)+}++func cmdList(args []string) {+ fs := flag.NewFlagSet("list", flag.ExitOnError)+ var c common+ c.register(fs)+ fs.Parse(args)+ nics, skipped, err := c.nicsDetailed()+ if err != nil {+ die(err)+ }+ if len(nics) == 0 {+ fmt.Println("No usable adapters found.")+ }+ for _, n := range nics {+ fmt.Printf("USE %s (index %d)\n", describeNic(n), n.Index)+ }+ for _, s := range skipped {+ fmt.Printf("skip %s: %s\n", s.Name, s.Reason)+ }+}++func cmdSocks(args []string) {+ fs := flag.NewFlagSet("socks", flag.ExitOnError)+ var c common+ c.register(fs)+ listen := fs.String("listen", "127.0.0.1:1080", "SOCKS5 listen address")+ fs.Parse(args)+ if err := c.setup(); err != nil {+ die(err)+ }+ _, bal, err := c.boot(nil)+ if err != nil {+ die(err)+ }+ ln, err := listenTCP(*listen)+ if err != nil {+ die(err)+ }+ logf("net-merge SOCKS5 listening on %s\n", *listen)+ die(serveSocks5(ln, bal))+}++func cmdRun(args []string) {+ fs := flag.NewFlagSet("run", flag.ExitOnError)+ var c common+ c.register(fs)+ hidden := fs.Bool("hidden", false, "when elevating, hide the new console window")+ crashAfter := fs.Duration("crash-after", 0, "test only: exit abruptly (no cleanup) after this long")+ runFor := fs.Duration("for", 0, "turn off automatically after this long (0 = until stopped)")+ fs.Parse(args)++ if !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))+ }+ fmt.Println("Approve the UAC prompt. System-wide mode runs in the new window; `net-merge off` turns it off.")+ return+ }+ if !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)+ os.Exit(1)+ }+ 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)+ os.Exit(1)+ }+ tun := NewTun(bal)+ if err := tun.On(); err != nil {+ logf("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")++ sig := make(chan os.Signal, 1)+ signal.Notify(sig, os.Interrupt, syscall.SIGTERM)+ var crash, timeUp <-chan time.Time+ if *crashAfter > 0 {+ crash = time.After(*crashAfter)+ }+ if *runFor > 0 {+ timeUp = time.After(*runFor)+ }+ poll := time.NewTicker(300 * time.Millisecond)+ defer poll.Stop()+ for {+ select {+ case <-sig:+ case <-timeUp:+ case <-crash:+ os.Exit(3) // simulates a crash: no teardown runs+ case <-poll.C:+ if !takeMarker(c.stateDir, "off") && !takeMarker(c.stateDir, "quit") {+ continue+ }+ }+ break+ }+ tun.Off()+ clearStatus(c.stateDir)+ logf("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")+ fs.Parse(args)+ if !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 {+ die(err)+ }+ want := name == "on"+ for i := 0; i < 60; i++ {+ time.Sleep(150 * time.Millisecond)+ _, on := readStatus(*dir)+ switch {+ case name == "on" && on == want:+ fmt.Println("net-merge is ON.")+ return+ case name != "on" && !on:+ fmt.Println("net-merge is OFF.")+ return+ }+ }+ _ = wasOn+ die(fmt.Errorf("sent %q but it did not take effect (does this instance support it? run: net-merge tray)", name))+}++func cmdStatus(args []string) {+ fs := flag.NewFlagSet("status", flag.ExitOnError)+ dir := fs.String("state-dir", defaultStateDir(), "state directory")+ fs.Parse(args)+ st, on := readStatus(*dir)+ if !on {+ fmt.Println("net-merge is OFF.")+ return+ }+ fmt.Printf("net-merge is ON (%s, pid %d, up %s)\nIPv6: %s\n%s", st.Mode, st.PID, time.Since(st.Since).Truncate(time.Second), st.V6, formatNICs(st.NICs))+}++func cmdCleanup() {+ if !isAdmin() {+ if err := relaunchElevated([]string{"cleanup"}, false); err != nil {+ die(err)+ }+ return+ }+ cleanupStale()+ fmt.Println("done.")+}diff --git a/nics.go b/nics.gonew file mode 100644index 0000000..a2285af--- /dev/null+++ b/nics.go@@ -0,0 +1,122 @@+package main++import (+ "fmt"+ "net"+ "regexp"+ "strings"+)++// Nic is one physical adapter with the source addresses flows are pinned to: its IPv4 address+// and/or its global IPv6 address (either may be nil).+type Nic struct {+ Name string+ Index int // interface index, used to force egress (IP_UNICAST_IF); 0 = don't force+ IP net.IP+ IP6 net.IP+ Weight float64+}++// Skip is an adapter that was seen but not used, with the reason (shown by `net-merge list`).+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.+var (+ virtualName = regexp.MustCompile(`(?i)loopback|vethernet|wsl|tailscale|zerotier|wintun|net-merge`)+ virtualDesc = regexp.MustCompile(`(?i)virtual|vpn|\btap\b|tap-|tunnel|wintun|wireguard|tailscale|zerotier|openvpn|anyconnect|fortinet|vmware|npcap|miniport|teredo|isatap|6to4|pseudo`)+)++func DiscoverNics(include []string, weights map[string]float64) ([]Nic, error) {+ nics, _, err := DiscoverNicsDetailed(include, weights)+ return nics, err+}++func DiscoverNicsDetailed(include []string, weights map[string]float64) ([]Nic, []Skip, error) {+ ifaces, err := net.Interfaces()+ if err != nil {+ return nil, nil, err+ }+ // Auto mode only takes real hardware adapters that have a default gateway (can reach the+ // internet), per family. An explicit -include list overrides all of these checks.+ var info map[int]adapterInfo+ if len(include) == 0 {+ info, _ = adapterInfos() // nil on error: fall back to name filtering only+ }+ var out []Nic+ var skipped []Skip+ for _, ifc := range ifaces {+ if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 {+ continue+ }+ skip := func(reason string) { skipped = append(skipped, Skip{ifc.Name, reason}) }+ ai, haveInfo := info[ifc.Index]+ if len(include) > 0 {+ if !containsFold(include, ifc.Name) {+ continue+ }+ } else {+ switch {+ 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))+ continue+ case info != nil && haveInfo && virtualDesc.MatchString(ai.desc):+ skip(fmt.Sprintf("virtual/VPN adapter (%s)", ai.desc))+ continue+ }+ }+ addrs, err := ifc.Addrs()+ if err != nil {+ continue+ }+ var ip4, ip6 net.IP+ for _, a := range addrs {+ ipn, ok := a.(*net.IPNet)+ if !ok {+ continue+ }+ if v4 := ipn.IP.To4(); v4 != nil {+ if ip4 == nil && !v4.IsLinkLocalUnicast() { // 169.254/16: no DHCP lease, no internet+ ip4 = v4+ }+ } else if ip6 == nil && ipn.IP.IsGlobalUnicast() && !ipn.IP.IsPrivate() { // skips fe80:: and ULA+ ip6 = ipn.IP+ }+ }+ if info != nil {+ if !ai.v4 {+ ip4 = nil+ }+ if !ai.v6 {+ ip6 = nil+ }+ }+ if ip4 == nil && ip6 == nil {+ if info != nil && !ai.v4 && !ai.v6 {+ skip("no default gateway (no internet route)")+ } else {+ skip("no usable IP address")+ }+ continue+ }+ w := 1.0+ if v, ok := weights[ifc.Name]; ok {+ w = v+ }+ out = append(out, Nic{Name: ifc.Name, Index: ifc.Index, IP: ip4, IP6: ip6, Weight: w})+ }+ return out, skipped, nil+}++func containsFold(list []string, s string) bool {+ for _, x := range list {+ if strings.EqualFold(x, s) {+ return true+ }+ }+ return false+}diff --git a/nics_windows.go b/nics_windows.gonew file mode 100644index 0000000..432d0cb--- /dev/null+++ b/nics_windows.go@@ -0,0 +1,77 @@+package main++import (+ "unsafe"++ "golang.org/x/sys/windows"+)++// 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+}++// IANA ifType values for real network hardware. Tunnels (131), PPP (23), "proprietary virtual"+// (53, used by most VPN drivers) and software loopback (24) are not in this set.+func physicalIfType(t uint32) bool {+ switch t {+ case 6, 62, 69, 117, // ethernet (incl. fast / gigabit variants)+ 71, // IEEE 802.11 Wi-Fi+ 243, 244: // mobile broadband (WWAN)+ return true+ }+ return false+}++// adapterInfos returns, per interface index, the up adapters with their gateway families, type+// and description. This is what lets any adapter (Wi-Fi, Ethernet, USB tether, phone hotspot)+// be picked up automatically while VPNs, tunnels, virtual switches and LAN-only adapters are+// skipped, without maintaining a list of product names.+func adapterInfos() (map[int]adapterInfo, error) {+ const flags = windows.GAA_FLAG_INCLUDE_GATEWAYS | windows.GAA_FLAG_SKIP_ANYCAST |+ windows.GAA_FLAG_SKIP_MULTICAST | windows.GAA_FLAG_SKIP_DNS_SERVER+ size := uint32(32 << 10)+ for try := 0; try < 4; try++ {+ buf := make([]byte, size)+ aa := (*windows.IpAdapterAddresses)(unsafe.Pointer(&buf[0]))+ err := windows.GetAdaptersAddresses(windows.AF_UNSPEC, flags, 0, aa, &size)+ if err == windows.ERROR_BUFFER_OVERFLOW {+ continue+ }+ if err != nil {+ return nil, err+ }+ m := map[int]adapterInfo{}+ for a := aa; a != nil; a = a.Next {+ if a.OperStatus != windows.IfOperStatusUp {+ continue+ }+ info := adapterInfo{ifType: a.IfType, desc: windows.UTF16PtrToString(a.Description)}+ for g := a.FirstGatewayAddress; g != nil; g = g.Next {+ if g.Address.Sockaddr == nil {+ continue+ }+ switch g.Address.Sockaddr.Addr.Family {+ case windows.AF_INET:+ info.v4 = true+ case windows.AF_INET6:+ info.v6 = true+ }+ }+ // One adapter can appear per family; merge by index.+ for _, idx := range []uint32{a.IfIndex, a.Ipv6IfIndex} {+ if idx == 0 {+ continue+ }+ cur := m[int(idx)]+ cur.v4, cur.v6 = cur.v4 || info.v4, cur.v6 || info.v6+ cur.ifType, cur.desc = info.ifType, info.desc+ m[int(idx)] = cur+ }+ }+ return m, nil+ }+ return nil, windows.ERROR_BUFFER_OVERFLOW+}diff --git a/probe.go b/probe.gonew file mode 100644index 0000000..666f16e--- /dev/null+++ b/probe.go@@ -0,0 +1,95 @@+package main++import (+ "net"+ "time"+)++// 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"},+}++const (+ probeTimeout = 2 * time.Second+ probeEveryUp = 15 * time.Second+ probeEveryDown = 4 * time.Second+)++func probe(sl *Slot, f family) bool {+ ip := sl.ip(f)+ if ip == nil {+ return false+ }+ network := "tcp4"+ 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}+ if c, err := d.Dial(network, t); err == nil {+ c.Close()+ return true+ }+ }+ return false+}++type probeJob struct {+ sl *Slot+ f family+}++// RunProbes checks every adapter's internet access per address family: new ones immediately,+// healthy ones occasionally, dead ones more often so they rejoin quickly. A tether with no data+// or a captive-portal Wi-Fi therefore never receives flows, and a recovered link is used again+// within seconds. Runs until stop is closed (nil = forever).+func (s *Scheduler) RunProbes(stop <-chan struct{}) {+ t := time.NewTicker(time.Second)+ defer t.Stop()+ for {+ select {+ case <-stop:+ return+ case <-t.C:+ }+ for _, j := range s.probeDue() {+ go func() {+ defer j.sl.probing[j.f].Store(false)+ s.SetState(j.sl, j.f, probe(j.sl, j.f))+ }()+ }+ }+}++// probeDue returns the (slot, family) pairs that need a probe now and marks them in flight.+func (s *Scheduler) probeDue() []probeJob {+ s.mu.Lock()+ defer s.mu.Unlock()+ now := s.now()+ var due []probeJob+ for _, sl := range s.slots {+ if !sl.present {+ continue+ }+ for _, f := range []family{fam4, fam6} {+ if sl.ip(f) == nil || sl.probing[f].Load() {+ continue+ }+ every := probeEveryUp+ switch sl.state[f] {+ case stateUnknown:+ every = 0+ case stateDown:+ every = probeEveryDown+ }+ if now.Sub(sl.lastProbe[f]) >= every {+ sl.lastProbe[f] = now+ sl.probing[f].Store(true)+ due = append(due, probeJob{sl, f})+ }+ }+ }+ return due+}diff --git a/sched.go b/sched.gonew file mode 100644index 0000000..ed649cc--- /dev/null+++ b/sched.go@@ -0,0 +1,367 @@+package main++import (+ "math"+ "math/rand/v2"+ "net"+ "sync"+ "sync/atomic"+ "time"+)++// 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++const (+ fam4 family = iota+ fam6+)++// linkState is the result of the internet probe: new adapters are "unknown" (still preferred+// over dead ones, so a probe that can't run never causes an outage) until the first probe lands.+type linkState int++const (+ stateUnknown linkState = iota+ stateUp+ stateDown+)++func (l linkState) String() string {+ return [...]string{"checking", "up", "no internet"}[l]+}++type slotAddr struct{ ip4, ip6 net.IP }++// Slot is a NIC plus its live counters. Counters are atomic so the data path never takes a lock.+type Slot struct {+ Name string+ Index int+ key string+ addr atomic.Pointer[slotAddr]++ active, total, failed atomic.Int64 // active is across families (idle check on removal)+ actF [2]atomic.Int64+ bytesIn, bytesOut [2]atomic.Int64+ probing [2]atomic.Bool++ // guarded by Scheduler.mu+ weight [2]float64+ present bool+ state [2]linkState+ lastProbe [2]time.Time+ downUntil [2]time.Time+ lastIn, lastOut [2]int64+ rateIn, rateOut [2]float64 // bytes/s over the last tick+ peak [2]float64 // observed capacity: max recent rateIn+rateOut+}++func (sl *Slot) ip(f family) net.IP {+ a := sl.addr.Load()+ if f == fam6 {+ return a.ip6+ }+ return a.ip4+}++type SlotStats struct {+ Name string+ IP string+ IP6 string+ State string // IPv4 probe state, "-" if the adapter has no IPv4+ State6 string+ Weight, Weight6 float64+ Present bool+ Active, Total int64+ Failed int64+ BytesIn, BytesOut int64+ RateIn, RateOut float64 // both families summed+ Peak, Peak6 float64+}++// Scheduler is weighted least-active-flows, per address family: each new flow goes to the NIC+// with the lowest (active + 1) / weight among those that have an address of that family. Only+// new flows take the lock.+type Scheduler struct {+ mu sync.Mutex+ slots []*Slot+ auto bool+ now func() time.Time+}++func NewScheduler(nics []Nic) *Scheduler {+ s := &Scheduler{now: time.Now}+ s.Update(nics)+ return s+}++// SetAuto makes Tick derive weights from observed throughput instead of the static ones.+func (s *Scheduler) SetAuto(on bool) {+ s.mu.Lock()+ s.auto = on+ s.mu.Unlock()+}++func normAddr(n Nic) *slotAddr {+ a := &slotAddr{}+ if n.IP != nil {+ a.ip4 = n.IP.To4()+ }+ if n.IP6 != nil && n.IP6.To4() == nil {+ a.ip6 = n.IP6+ }+ return a+}++// 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) {+ s.mu.Lock()+ defer s.mu.Unlock()+ for _, sl := range s.slots {+ sl.present = false+ }+ for _, n := range nics {+ na := normAddr(n)+ var found *Slot+ for _, sl := range s.slots {+ if sl.key == n.Name {+ found = sl+ break+ }+ }+ if found == nil {+ sl := &Slot{Name: n.Name, Index: n.Index, key: n.Name, weight: [2]float64{n.Weight, n.Weight}, present: true}+ sl.addr.Store(na)+ s.slots = append(s.slots, sl)+ continue+ }+ found.present = true+ if !s.auto {+ found.weight = [2]float64{n.Weight, n.Weight}+ }+ old := found.addr.Load()+ if !old.ip4.Equal(na.ip4) {+ found.state[fam4] = stateUnknown // new address: re-verify+ }+ if !old.ip6.Equal(na.ip6) {+ found.state[fam6] = stateUnknown+ }+ if !old.ip4.Equal(na.ip4) || !old.ip6.Equal(na.ip6) {+ found.addr.Store(na)+ }+ }+ kept := s.slots[:0]+ for _, sl := range s.slots {+ if sl.present || sl.active.Load() > 0 {+ kept = append(kept, sl)+ }+ }+ s.slots = kept+}++// A NIC counts as measured once it has carried this much (bytes/s, about 0.4 Mbit/s).+const minMeasuredPeak = 50_000++// Tick samples throughput per family. With auto on, a family's weights follow each NIC's+// observed peak for that family (floored at 0.05, so a slow path still sees an occasional flow+// and is re-measured). Until every NIC with that family has been measured the weights stay+// equal, which spreads load so each one gets measured. The peak holds while a NIC is idle and+// only decays when it is in use but underperforming, so capacity is remembered across pauses.+func (s *Scheduler) Tick(dt time.Duration) {+ s.mu.Lock()+ defer s.mu.Unlock()+ sec := dt.Seconds()+ for _, f := range []family{fam4, fam6} {+ var maxPeak float64+ live, measured := 0, true+ idle := map[*Slot]bool{}+ for _, sl := range s.slots {+ in, out := sl.bytesIn[f].Load(), sl.bytesOut[f].Load()+ sl.rateIn[f] = float64(in-sl.lastIn[f]) / sec+ sl.rateOut[f] = float64(out-sl.lastOut[f]) / sec+ sl.lastIn[f], sl.lastOut[f] = in, out+ r := sl.rateIn[f] + sl.rateOut[f]+ if r >= 0.05*sl.peak[f] {+ sl.peak[f] = math.Max(r, sl.peak[f]*0.97)+ } else {+ idle[sl] = true+ }+ if !sl.present || sl.ip(f) == nil {+ continue+ }+ live+++ maxPeak = math.Max(maxPeak, sl.peak[f])+ }+ // An idle NIC's old estimate may be stale or pessimistic (it was measured during a bad+ // moment and then starved of flows, so it could never correct itself). Let it drift back+ // up, capped at half of the best NIC, so it keeps getting a fair chance to be re-measured.+ for sl := range idle {+ if sl.present && sl.ip(f) != nil && sl.peak[f] > 0 {+ sl.peak[f] = math.Min(sl.peak[f]*1.03, math.Max(sl.peak[f], 0.5*maxPeak))+ }+ }+ for _, sl := range s.slots {+ if sl.present && sl.ip(f) != nil && sl.peak[f] < minMeasuredPeak {+ measured = false+ }+ }+ if !s.auto {+ continue+ }+ for _, sl := range s.slots {+ if !sl.present || sl.ip(f) == nil {+ continue+ }+ if live < 2 || !measured {+ sl.weight[f] = 1+ } else {+ sl.weight[f] = math.Max(0.05, sl.peak[f]/maxPeak)+ }+ }+ }+}++// 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) }++// AcquireFor picks a NIC that has an address of the given family.+func (s *Scheduler) AcquireFor(f family, skip map[string]struct{}) *Slot {+ s.mu.Lock()+ defer s.mu.Unlock()+ now := s.now()+ // Tiers: 0 = probed up, 1 = not probed yet, 2 = probe failed or link error cooldown.+ // Only the best non-empty tier is used, so a dead tether gets no flows but, if every NIC+ // looks dead, flows still go somewhere rather than nowhere.+ var tiers [3][]*Slot+ for _, sl := range s.slots {+ if !sl.present || sl.ip(f) == nil {+ continue+ }+ if _, no := skip[sl.key]; no {+ continue+ }+ t := 1+ switch {+ case now.Before(sl.downUntil[f]) || sl.state[f] == stateDown:+ t = 2+ case sl.state[f] == stateUp:+ t = 0+ }+ tiers[t] = append(tiers[t], sl)+ }+ var pool []*Slot+ for _, tier := range tiers {+ if len(tier) > 0 {+ pool = tier+ break+ }+ }+ if len(pool) == 0 {+ return nil+ }+ // Random start so ties don't resonate with the arrival pattern (a rotating counter can+ // lock onto e.g. "every third flow is a short DNS-like one" and starve an adapter).+ start := rand.IntN(len(pool))+ var best *Slot+ bestScore := math.Inf(1)+ for i := range pool {+ sl := pool[(start+i)%len(pool)]+ if score := float64(sl.actF[f].Load()+1) / sl.weight[f]; score < bestScore {+ best, bestScore = sl, score+ }+ }+ best.active.Add(1)+ best.actF[f].Add(1)+ best.total.Add(1)+ return best+}++// V6Usable reports whether any adapter can currently carry IPv6.+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 {+ return true+ }+ }+ return false+}++// V6CoversAll reports whether every adapter that can carry IPv4 can also carry IPv6, i.e. whether+// balancing IPv6 flows would use the same set of adapters as IPv4 does. If not, IPv6 would funnel+// everything onto the adapters that have it.+func (s *Scheduler) V6CoversAll() bool {+ s.mu.Lock()+ defer s.mu.Unlock()+ any6 := false+ for _, sl := range s.slots {+ if !sl.present {+ continue+ }+ has6 := sl.ip(fam6) != nil && sl.state[fam6] != stateDown+ if has6 {+ any6 = true+ }+ if sl.ip(fam4) != nil && sl.state[fam4] != stateDown && !has6 {+ return false+ }+ }+ return any6+}++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) {+ s.mu.Lock()+ defer s.mu.Unlock()+ if up {+ sl.state[f] = stateUp+ sl.downUntil[f] = time.Time{}+ } else {+ sl.state[f] = stateDown+ }+}++// Fail sidelines a NIC whose link itself is broken (for one address family).+func (s *Scheduler) Fail(sl *Slot, f family, cooldown time.Duration) {+ s.mu.Lock()+ sl.downUntil[f] = s.now().Add(cooldown)+ s.mu.Unlock()+ sl.failed.Add(1)+}++func (s *Scheduler) Snapshot() []SlotStats {+ s.mu.Lock()+ defer s.mu.Unlock()+ out := make([]SlotStats, 0, len(s.slots))+ for _, sl := range s.slots {+ a := sl.addr.Load()+ st := SlotStats{+ Name: sl.Name, State: "-", State6: "-", Present: sl.present,+ 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],+ Peak: sl.peak[fam4], Peak6: sl.peak[fam6],+ }+ if a.ip4 != nil {+ 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()+ }+ out = append(out, st)+ }+ return out+}diff --git a/sched_test.go b/sched_test.gonew file mode 100644index 0000000..7bf6958--- /dev/null+++ b/sched_test.go@@ -0,0 +1,310 @@+package main++import (+ "net"+ "testing"+ "time"+)++func nic(name, ip string, w float64) Nic { return Nic{Name: name, IP: net.ParseIP(ip), Weight: w} }++func countBy(picks []*Slot, name string) int {+ n := 0+ for _, p := range picks {+ if p.Name == name {+ n+++ }+ }+ return n+}++func acquireN(s *Scheduler, n int) []*Slot {+ out := make([]*Slot, n)+ for i := range out {+ out[i] = s.Acquire(nil)+ }+ return out+}++func TestEqualWeightsSpreadEvenly(t *testing.T) {+ s := NewScheduler([]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"))+ }+}++func TestWeightsSkew(t *testing.T) {+ s := NewScheduler([]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"))+ }+}++func TestReleaseFreesNic(t *testing.T) {+ s := NewScheduler([]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)+ if got := s.Acquire(nil); got != first {+ t.Fatalf("want the released NIC %s, got %s", first.Name, got.Name)+ }+}++func TestFailCooldown(t *testing.T) {+ s := NewScheduler([]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]+ var badSlot *Slot+ for _, sl := range s.slots {+ if sl.Name == bad.Name {+ badSlot = sl+ }+ }+ 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")+ }+ }+ clock = clock.Add(6 * time.Second)+ seen := false+ for i := 0; i < 6; i++ {+ if s.Acquire(nil) == badSlot {+ seen = true+ }+ }+ if !seen {+ t.Fatal("NIC never came back after cooldown")+ }+}++func TestAllDownStillServes(t *testing.T) {+ s := NewScheduler([]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)})+ a, b, c := s.slots[0], s.slots[1], s.slots[2]+ 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+ 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+ 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+ if got := s.Acquire(nil); got != c {+ t.Fatalf("recovered NIC should win, got %s", got.Name)+ }+}++func TestProbeAgainstLocalListener(t *testing.T) {+ ln, err := net.Listen("tcp4", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ defer ln.Close()+ go func() {+ for {+ c, err := ln.Accept()+ if err != nil {+ return+ }+ c.Close()+ }+ }()+ 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) {+ t.Fatal("probe should pass against a reachable target")+ }+ ln.Close()+ if probe(s.slots[0], fam4) {+ t.Fatal("probe should fail once the target is gone")+ }+}++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})+ for i := 0; i < 4; i++ {+ 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 {+ t.Fatal("v4 flows must still work")+ }+ s2 := NewScheduler([]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")+ }+}++func TestV6StateIsIndependentOfV4(t *testing.T) {+ n := nic("A", "10.0.0.1", 1)+ 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})+ 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)+ for i := 0; i < 4; i++ {+ 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)+ }+ seen := map[string]bool{}+ for i := 0; i < 4; i++ {+ seen[s.AcquireFor(fam4, nil).Name] = true+ }+ if !seen["A"] || !seen["B"] {+ t.Fatalf("v4 should still use both NICs, got %v", seen)+ }+}++// A hotspot that is fast over native IPv6 but slow over translated IPv4 must be weighted per+// family: nearly starved for v4 flows, fully used for v6 flows.+func TestAutoWeightsArePerFamily(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)+ b.IP6 = net.ParseIP("2001:db8::2")+ s := NewScheduler([]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)+ s.Tick(time.Second)+ }+ 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 {+ 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])+ }+}++// 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.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)+ s.Tick(time.Second)+ }+ 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)+ s.Tick(time.Second)+ }+ 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)+ }+}++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})+ if s.V6CoversAll() {+ t.Fatal("B has no IPv6: IPv6 would funnel onto A, coverage must be partial")+ }+ if !s.V6Usable() {+ t.Fatal("A can carry IPv6")+ }+ b.IP6 = net.ParseIP("2001:db8::2")+ s.Update([]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+ 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)})+ if only4.V6CoversAll() || only4.V6Usable() {+ t.Fatal("no IPv6 anywhere: nothing to allow")+ }+}++func TestSkipSet(t *testing.T) {+ s := NewScheduler([]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")+ }+ if got := s.Acquire(map[string]struct{}{a.key: {}, b.key: {}}); got != nil {+ t.Fatal("want nil when everything is skipped")+ }+}++func TestUpdateAddsAndKeepsCounters(t *testing.T) {+ s := NewScheduler([]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)})+ snap := s.Snapshot()+ if len(snap) != 2 || snap[0].Total != 1 {+ t.Fatalf("unexpected snapshot: %+v", snap)+ }+}++func TestUpdateDropsVanishedWhenIdle(t *testing.T) {+ s := NewScheduler([]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 {+ t.Fatalf("idle NIC should be dropped, busy one kept: %+v", s.Snapshot())+ }+ if s.Acquire(nil) != nil {+ t.Fatal("vanished NIC must not get new flows")+ }+ s.Release(busy)+ s.Update(nil)+ if len(s.Snapshot()) != 0 {+ t.Fatal("NIC should be dropped once idle")+ }+}diff --git a/scripts/build.ps1 b/scripts/build.ps1new file mode 100644index 0000000..f998628--- /dev/null+++ b/scripts/build.ps1@@ -0,0 +1,45 @@+# Builds everything into dist\: the two exes, wintun.dll, the installer, and a portable zip.+# scripts\build.ps1 -Version 0.1.0+# Needs Go and Inno Setup 6 (ISCC.exe on PATH, in a default install dir, or in $env:ISCC).+param(+ [string]$Version = '0.0.0',+ [string]$RepoUrl = ''+)+$ErrorActionPreference = 'Stop'+Set-Location (Split-Path $PSScriptRoot -Parent)++function Invoke-Native {+ param([string]$What, [scriptblock]$Cmd)+ & $Cmd+ if ($LASTEXITCODE -ne 0) { throw "$What failed (exit $LASTEXITCODE)" }+}++if ($Version -notmatch '^\d+\.\d+\.\d+$') { throw "Version must look like 1.2.3, got '$Version'" }++if (Test-Path dist) { Remove-Item dist -Recurse -Force }+New-Item -ItemType Directory dist | Out-Null++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 'icon' { .\dist\net-merge.exe _icon dist\net-merge.ico }++& "$PSScriptRoot\fetch-wintun.ps1" -OutDir dist++$iscc = $env:ISCC+if (-not $iscc) { $iscc = (Get-Command ISCC.exe -ErrorAction SilentlyContinue).Source }+if (-not $iscc) {+ $iscc = Get-ChildItem 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe', 'C:\Program Files\Inno Setup 6\ISCC.exe' -ErrorAction SilentlyContinue | Select-Object -First 1 -ExpandProperty FullName+}+if (-not $iscc) { throw 'ISCC.exe not found. Install Inno Setup 6 or set $env:ISCC.' }++$isccArgs = @("/DVersion=$Version")+if ($RepoUrl) { $isccArgs += "/DRepoUrl=$RepoUrl" }+Invoke-Native 'inno setup' { & $iscc @isccArgs installer\net-merge.iss }++$portable = "dist\net-merge-$Version-portable.zip"+Compress-Archive -Path dist\net-merge.exe, dist\net-merge-tray.exe, dist\wintun.dll, dist\wintun-LICENSE.txt, LICENSE, THIRD-PARTY-NOTICES.md, README.md -DestinationPath $portable+Get-ChildItem dist\net-merge-setup-$Version.exe, $portable | ForEach-Object { '{0} {1:N1} MB' -f $_.Name, ($_.Length / 1MB) }diff --git a/scripts/fetch-wintun.ps1 b/scripts/fetch-wintun.ps1new file mode 100644index 0000000..05c78ff--- /dev/null+++ b/scripts/fetch-wintun.ps1@@ -0,0 +1,26 @@+# Downloads the Wintun driver DLL, verifies it, and copies it (plus its license) to -OutDir.+# Wintun is distributed as a prebuilt, signed binary; it is not kept in this repository.+param([string]$OutDir = 'dist')+$ErrorActionPreference = 'Stop'++$version = '0.14.1'+$sha256 = '07c256185d6ee3652e09fa55c0b673e2624b565e02c4b9091c79ca7d2f24ef51'++$tmp = Join-Path ([IO.Path]::GetTempPath()) "wintun-$version"+New-Item -ItemType Directory -Force $tmp, $OutDir | Out-Null+$zip = Join-Path $tmp 'wintun.zip'+Invoke-WebRequest "https://www.wintun.net/builds/wintun-$version.zip" -OutFile $zip -TimeoutSec 120++$actual = (Get-FileHash $zip -Algorithm SHA256).Hash.ToLower()+if ($actual -ne $sha256) { throw "wintun-$version.zip checksum mismatch: got $actual" }++$x = Join-Path $tmp 'x'+Expand-Archive $zip -DestinationPath $x -Force+$dll = Join-Path $x 'wintun\bin\amd64\wintun.dll'+$sig = Get-AuthenticodeSignature $dll+if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Subject -notmatch 'WireGuard LLC') {+ throw "wintun.dll is not validly signed by WireGuard LLC (status: $($sig.Status))"+}+Copy-Item $dll (Join-Path $OutDir 'wintun.dll') -Force+Copy-Item (Join-Path $x 'wintun\LICENSE.txt') (Join-Path $OutDir 'wintun-LICENSE.txt') -Force+Write-Host "wintun $version OK (sha256 and WireGuard LLC signature verified)"diff --git a/sockopt_windows.go b/sockopt_windows.gonew file mode 100644index 0000000..930a894--- /dev/null+++ b/sockopt_windows.go@@ -0,0 +1,30 @@+package main++import (+ "math/bits"+ "syscall"+)++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+// 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 {+ if idx <= 0 {+ return nil+ }+ level, val := syscall.IPPROTO_IP, int(int32(bits.ReverseBytes32(uint32(idx))))+ if v6 {+ level, val = syscall.IPPROTO_IPV6, idx+ }+ return func(network, address string, c syscall.RawConn) error {+ var serr error+ if err := c.Control(func(fd uintptr) {+ serr = syscall.SetsockoptInt(syscall.Handle(fd), level, ipUnicastIf, val)+ }); err != nil {+ return err+ }+ return serr+ }+}diff --git a/socks5.go b/socks5.gonew file mode 100644index 0000000..b34484d--- /dev/null+++ b/socks5.go@@ -0,0 +1,113 @@+package main++import (+ "bytes"+ "context"+ "encoding/binary"+ "errors"+ "io"+ "net"+ "time"+)++func serveSocks5(ln net.Listener, b *Balancer) error {+ for {+ c, err := ln.Accept()+ if err != nil {+ return err+ }+ go b.handleSocks5(c)+ }+}++func socksReply(c net.Conn, rep byte) {+ c.Write([]byte{0x05, rep, 0x00, 0x01, 0, 0, 0, 0, 0, 0})+}++func (b *Balancer) handleSocks5(c net.Conn) {+ c.SetDeadline(time.Now().Add(15 * time.Second))++ var hdr [2]byte+ if _, err := io.ReadFull(c, hdr[:]); err != nil || hdr[0] != 0x05 || hdr[1] == 0 {+ c.Close()+ return+ }+ methods := make([]byte, hdr[1])+ if _, err := io.ReadFull(c, methods); err != nil {+ c.Close()+ return+ }+ if !bytes.Contains(methods, []byte{0x00}) {+ c.Write([]byte{0x05, 0xff})+ c.Close()+ return+ }+ c.Write([]byte{0x05, 0x00})++ var req [4]byte+ if _, err := io.ReadFull(c, req[:]); err != nil || req[0] != 0x05 {+ c.Close()+ return+ }+ var host string+ switch req[3] {+ case 0x01:+ var a [4]byte+ if _, err := io.ReadFull(c, a[:]); err != nil {+ c.Close()+ return+ }+ host = net.IP(a[:]).String()+ case 0x03:+ var l [1]byte+ if _, err := io.ReadFull(c, l[:]); err != nil || l[0] == 0 {+ c.Close()+ return+ }+ name := make([]byte, l[0])+ if _, err := io.ReadFull(c, name); err != nil {+ c.Close()+ return+ }+ host = string(name)+ case 0x04:+ var a [16]byte+ if _, err := io.ReadFull(c, a[:]); err != nil {+ c.Close()+ return+ }+ host = net.IP(a[:]).String()+ default:+ socksReply(c, repAtypUnsupported)+ c.Close()+ return+ }+ var p [2]byte+ if _, err := io.ReadFull(c, p[:]); err != nil {+ c.Close()+ return+ }+ port := int(binary.BigEndian.Uint16(p[:]))+ if req[1] != 0x01 { // CONNECT only; UDP ASSOCIATE comes with the TUN front-end+ socksReply(c, repCmdUnsupported)+ c.Close()+ return+ }++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ up, sl, fam, err := b.DialTCP(ctx, host, port)+ if err != nil {+ rep := byte(repFailure)+ var de *dialError+ if errors.As(err, &de) {+ rep = de.rep+ }+ socksReply(c, rep)+ c.Close()+ return+ }+ c.SetDeadline(time.Time{})+ socksReply(c, repOK)+ Relay(c, up, sl, fam, b.S)+}diff --git a/socks5_test.go b/socks5_test.gonew file mode 100644index 0000000..e60caf8--- /dev/null+++ b/socks5_test.go@@ -0,0 +1,288 @@+package main++import (+ "bufio"+ "io"+ "net"+ "testing"+ "time"+)++// Loopback aliases (127.0.0.2, 127.0.0.3) stand in for physical NICs: the target server+// reports which source address each flow arrived from.+func startTarget(t *testing.T) int {+ t.Helper()+ ln, err := net.Listen("tcp4", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { ln.Close() })+ go func() {+ for {+ c, err := ln.Accept()+ if err != nil {+ return+ }+ go func() {+ defer c.Close()+ host, _, _ := net.SplitHostPort(c.RemoteAddr().String())+ c.Write([]byte(host + "\n"))+ io.Copy(c, c) // echo+ }()+ }+ }()+ return ln.Addr().(*net.TCPAddr).Port+}++func startProxy(t *testing.T, nics []Nic) (*Scheduler, string) {+ t.Helper()+ s := NewScheduler(nics)+ b := NewBalancer(s)+ b.ConnectTimeout = 2 * time.Second+ ln, err := net.Listen("tcp4", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { ln.Close() })+ go serveSocks5(ln, b)+ return s, ln.Addr().String()+}++type socksConn struct {+ net.Conn+ r *bufio.Reader+ rep byte+}++func socksConnect(t *testing.T, proxy string, port int) *socksConn {+ t.Helper()+ c, err := net.Dial("tcp4", proxy)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { c.Close() })+ c.SetDeadline(time.Now().Add(5 * time.Second))+ c.Write([]byte{5, 1, 0})+ r := bufio.NewReader(c)+ greet := make([]byte, 2)+ if _, err := io.ReadFull(r, greet); err != nil || greet[0] != 5 || greet[1] != 0 {+ t.Fatalf("bad greeting reply %v %v", greet, err)+ }+ c.Write([]byte{5, 1, 0, 1, 127, 0, 0, 1, byte(port >> 8), byte(port)})+ resp := make([]byte, 10)+ if _, err := io.ReadFull(r, resp); err != nil {+ t.Fatal(err)+ }+ return &socksConn{Conn: c, r: r, rep: resp[1]}+}++func (s *socksConn) line(t *testing.T) string {+ t.Helper()+ l, err := s.r.ReadString('\n')+ if err != nil {+ t.Fatal(err)+ }+ return l[:len(l)-1]+}++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)})++ seen := map[string]int{}+ for i := 0; i < 6; i++ {+ c := socksConnect(t, proxy, port)+ if c.rep != 0 {+ t.Fatalf("connect failed rep=%d", c.rep)+ }+ seen[c.line(t)]+++ c.Write([]byte("ping\n"))+ if got := c.line(t); got != "ping" {+ t.Fatalf("echo mismatch: %q", got)+ }+ }+ if seen["127.0.0.2"] != 3 || seen["127.0.0.3"] != 3 {+ t.Fatalf("want 3/3 split, got %v", seen)+ }+ for _, s := range sched.Snapshot() {+ if s.Active != 3 {+ t.Fatalf("want 3 active on %s, got %d", s.Name, s.Active)+ }+ }+}++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)})+ for i := 0; i < 4; i++ {+ c := socksConnect(t, proxy, port)+ if c.rep != 0 {+ t.Fatalf("flow %d failed rep=%d", i, c.rep)+ }+ if got := c.line(t); got != "127.0.0.2" {+ t.Fatalf("flow %d came from %s", i, got)+ }+ }+ for _, s := range sched.Snapshot() {+ if s.Name == "bad" && s.Failed != 1 {+ t.Fatalf("bad NIC should be sidelined after one failure, failed=%d", s.Failed)+ }+ }+}++func TestRefusedIsReportedNotRetried(t *testing.T) {+ sched, proxy := startProxy(t, []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()++ c := socksConnect(t, proxy, deadPort)+ if c.rep != repRefused {+ t.Fatalf("want rep=5 (refused), got %d", c.rep)+ }+ var total int64+ for _, s := range sched.Snapshot() {+ total += s.Total+ }+ if total != 1 {+ t.Fatalf("refusal must not be retried on other NICs, attempts=%d", total)+ }+}++func TestIPv6Destination(t *testing.T) {+ ln, err := net.Listen("tcp6", "[::1]:0")+ if err != nil {+ t.Skip("no IPv6 loopback on this machine")+ }+ defer ln.Close()+ go func() {+ c, err := ln.Accept()+ if err != nil {+ return+ }+ host, _, _ := net.SplitHostPort(c.RemoteAddr().String())+ c.Write([]byte(host + "\n"))+ c.Close()+ }()+ // ::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})++ c, err := net.Dial("tcp4", proxy)+ if err != nil {+ t.Fatal(err)+ }+ defer c.Close()+ c.SetDeadline(time.Now().Add(5 * time.Second))+ c.Write([]byte{5, 1, 0})+ io.ReadFull(c, make([]byte, 2))+ port := ln.Addr().(*net.TCPAddr).Port+ req := append([]byte{5, 1, 0, 4}, net.ParseIP("::1").To16()...) // ATYP 4 = IPv6+ c.Write(append(req, byte(port>>8), byte(port)))+ resp := make([]byte, 10)+ if _, err := io.ReadFull(c, resp); err != nil || resp[1] != repOK {+ t.Fatalf("connect to IPv6 destination failed: %v err=%v", resp, err)+ }+ line, _ := bufio.NewReader(c).ReadString('\n')+ if line != "::1\n" {+ t.Fatalf("server saw source %q, want ::1", line)+ }+}++func TestUDPAssociateRefusedCleanly(t *testing.T) {+ _, proxy := startProxy(t, []Nic{nic("a", "127.0.0.2", 1)})+ c, _ := net.Dial("tcp4", proxy)+ defer c.Close()+ c.SetDeadline(time.Now().Add(3 * time.Second))+ c.Write([]byte{5, 1, 0})+ io.ReadFull(c, make([]byte, 2))+ c.Write([]byte{5, 3, 0, 1, 0, 0, 0, 0, 0, 0})+ resp := make([]byte, 10)+ if _, err := io.ReadFull(c, resp); err != nil || resp[1] != repCmdUnsupported {+ t.Fatalf("want rep=7, got %v err=%v", resp, err)+ }+}++func TestHalfCloseStillDeliversReply(t *testing.T) {+ // Target reads until EOF, then answers: breaks if the proxy tears down on first FIN.+ ln, _ := net.Listen("tcp4", "127.0.0.1:0")+ defer ln.Close()+ go func() {+ c, err := ln.Accept()+ if err != nil {+ return+ }+ data, _ := io.ReadAll(c)+ c.Write(append([]byte("got:"), data...))+ c.Close()+ }()+ _, proxy := startProxy(t, []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"))+ c.Conn.(*net.TCPConn).CloseWrite()+ got, err := io.ReadAll(c.r)+ if err != nil || string(got) != "got:hello" {+ t.Fatalf("got %q err=%v", got, err)+ }+}++// Raw relay throughput through the proxy over loopback (the CPU ceiling of the data path).+func benchRelay(b *testing.B, streams int) {+ ln, _ := net.Listen("tcp4", "127.0.0.1:0")+ defer ln.Close()+ chunk := make([]byte, 256<<10)+ go func() {+ for {+ c, err := ln.Accept()+ if err != nil {+ return+ }+ go func() { // source: writes until the client hangs up+ defer c.Close()+ for {+ if _, err := c.Write(chunk); err != nil {+ return+ }+ }+ }()+ }+ }()+ s := NewScheduler([]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))++ port := ln.Addr().(*net.TCPAddr).Port+ conns := make([]net.Conn, streams)+ for i := range conns {+ c, _ := net.Dial("tcp4", pl.Addr().String())+ c.Write([]byte{5, 1, 0})+ io.ReadFull(c, make([]byte, 2))+ c.Write([]byte{5, 1, 0, 1, 127, 0, 0, 1, byte(port >> 8), byte(port)})+ io.ReadFull(c, make([]byte, 10))+ conns[i] = c+ }+ per := int64(b.N) / int64(streams)+ b.SetBytes(int64(len(chunk)))+ b.ResetTimer()+ done := make(chan struct{}, streams)+ for _, c := range conns {+ go func() {+ io.CopyN(io.Discard, c, per*int64(len(chunk)))+ done <- struct{}{}+ }()+ }+ for range conns {+ <-done+ }+ b.StopTimer()+ for _, c := range conns {+ c.Close()+ }+}++func BenchmarkRelay1Stream(b *testing.B) { benchRelay(b, 1) }+func BenchmarkRelay8Streams(b *testing.B) { benchRelay(b, 8) }diff --git a/state.go b/state.gonew file mode 100644index 0000000..322a22e--- /dev/null+++ b/state.go@@ -0,0 +1,65 @@+package main++import (+ "encoding/json"+ "os"+ "path/filepath"+ "time"+)++// The elevated process can't be signalled from a normal shell, so control goes through files in+// a per-user directory: status.json (written once a second while on) and marker files+// ("on", "off", "quit") that the running instance consumes.++type Status struct {+ PID int+ Mode string+ V6 string+ Since time.Time+ Updated time.Time+ NICs []SlotStats+}++func defaultStateDir() string {+ base, err := os.UserCacheDir()+ if err != nil {+ base = os.TempDir()+ }+ return filepath.Join(base, "net-merge")+}++func writeStatus(dir string, st Status) {+ b, err := json.Marshal(st)+ if err != nil {+ return+ }+ tmp := filepath.Join(dir, "status.json.tmp")+ if os.WriteFile(tmp, b, 0o644) == nil {+ os.Rename(tmp, filepath.Join(dir, "status.json"))+ }+}++func clearStatus(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) {+ b, err := os.ReadFile(filepath.Join(dir, "status.json"))+ if err != nil {+ return nil, false+ }+ var st Status+ if json.Unmarshal(b, &st) != nil || time.Since(st.Updated) > 3*time.Second {+ return nil, false+ }+ return &st, true+}++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 }diff --git a/tray_windows.go b/tray_windows.gonew file mode 100644index 0000000..17e5da3--- /dev/null+++ b/tray_windows.go@@ -0,0 +1,251 @@+package main++import (+ "flag"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "time"++ "fyne.io/systray"+)++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)+ 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++ ui := &trayUI{tun: tun, sched: sched, bal: bal, stateDir: c.stateDir, startOn: !*startOff,+ iconOn: trayIcon(true), iconOff: trayIcon(false), toggleReq: make(chan struct{}, 1)}+ systray.Run(ui.onReady, func() { tun.Off(); clearStatus(c.stateDir) })+}++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+}++type trayUI struct {+ tun *Tun+ bal *Balancer+ sched *Scheduler+ stateDir string+ startOn bool+ iconOn []byte+ iconOff []byte+ toggleReq chan struct{}++ header, toggleItem, v6Item *systray.MenuItem+ rows []*systray.MenuItem+ lastOn *bool+ lastHeader string+ lastTip string+ lastRows [trayRows]string+ lastErr string+ busyUntil time.Time+}++func (u *trayUI) onReady() {+ systray.SetIcon(u.iconOff)+ systray.SetTooltip("net-merge")+ u.header = systray.AddMenuItem("net-merge", "")+ u.header.Disable()+ systray.AddSeparator()+ for i := 0; i < trayRows; i++ {+ r := systray.AddMenuItem("", "")+ r.Disable()+ r.Hide()+ 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.toggleItem = systray.AddMenuItem("Turn on", "Left-click the tray icon does the same")+ quit := systray.AddMenuItem("Quit", "Turns system-wide mode off and exits")+ systray.SetOnTapped(func() {+ select {+ case u.toggleReq <- struct{}{}:+ default:+ }+ })++ go func() {+ if u.startOn {+ u.turn(true)+ }+ tick := time.NewTicker(time.Second)+ defer tick.Stop()+ for {+ u.refresh()+ select {+ case <-u.toggleItem.ClickedCh:+ u.turn(!u.tun.IsOn())+ case <-u.toggleReq:+ u.turn(!u.tun.IsOn())+ case <-u.v6Item.ClickedCh:+ if u.v6Item.Checked() {+ u.v6Item.Uncheck()+ u.bal.SetV6Mode(V6On)+ } else {+ u.v6Item.Check()+ u.bal.SetV6Mode(V6Auto)+ }+ case <-quit.ClickedCh:+ systray.Quit()+ return+ case <-tick.C:+ switch { // `net-merge on|off|quit` from a terminal+ case takeMarker(u.stateDir, "quit"):+ systray.Quit()+ return+ case takeMarker(u.stateDir, "off"):+ u.turn(false)+ case takeMarker(u.stateDir, "on"):+ u.turn(true)+ }+ }+ }+ }()+}++func (u *trayUI) turn(on bool) {+ u.lastErr = ""+ if !on {+ u.tun.Off()+ clearStatus(u.stateDir)+ return+ }+ u.setHeader("Turning on...")+ if err := u.tun.On(); err != nil {+ u.lastErr = err.Error()+ logf("error: %v\n", err)+ }+}++func (u *trayUI) setHeader(s string) {+ if s != u.lastHeader {+ u.header.SetTitle(s)+ u.lastHeader = s+ }+}++func (u *trayUI) refresh() {+ on := u.tun.IsOn()+ if u.lastOn == nil || *u.lastOn != on {+ if on {+ systray.SetIcon(u.iconOn)+ u.toggleItem.SetTitle("Turn off")+ } else {+ systray.SetIcon(u.iconOff)+ u.toggleItem.SetTitle("Turn on")+ }+ u.lastOn = &on+ }++ var live []SlotStats+ total := 0.0+ for _, s := range u.sched.Snapshot() {+ if s.Present {+ live = append(live, s)+ total += (s.RateIn + s.RateOut) * 8 / 1e6+ }+ }++ switch {+ case u.lastErr != "":+ u.setHeader("Error: " + shorten(u.lastErr, 70))+ case on:+ u.setHeader(fmt.Sprintf("ON - %.0f Mbit/s total", total))+ default:+ u.setHeader("OFF")+ }++ var parts []string+ for i, r := range u.rows {+ if i >= len(live) {+ if u.lastRows[i] != "" {+ r.Hide()+ u.lastRows[i] = ""+ }+ continue+ }+ s := live[i]+ mbit := (s.RateIn + s.RateOut) * 8 / 1e6+ txt := fmt.Sprintf("%s: %.0f Mbit/s (%d flows)", s.Name, mbit, s.Active)+ if s.State != "up" && s.State6 != "up" { // neither family verified yet, or no internet+ txt = fmt.Sprintf("%s: %s", s.Name, s.State)+ }+ if s.State6 == "up" {+ txt += " +IPv6"+ }+ if txt != u.lastRows[i] {+ r.SetTitle(txt)+ r.Show()+ u.lastRows[i] = txt+ }+ parts = append(parts, fmt.Sprintf("%s %.0f", s.Name, mbit))+ }++ tip := "net-merge OFF"+ if on {+ tip = shorten(fmt.Sprintf("net-merge ON - %.0f Mbit/s\n%s", total, strings.Join(parts, " | ")), 120)+ }+ if tip != u.lastTip {+ systray.SetTooltip(tip)+ u.lastTip = tip+ }+}++func shorten(s string, n int) string {+ if len(s) <= n {+ return s+ }+ return s[:n-1] + "…"+}diff --git a/tun_windows.go b/tun_windows.gonew file mode 100644index 0000000..8c8b126--- /dev/null+++ b/tun_windows.go@@ -0,0 +1,209 @@+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+ dev device.Device+ stk *stack.Stack+ idx int+ on bool+}++func NewTun(b *Balancer) *Tun { return &Tun{b: b} }++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+ }+ if lvl, e := tlog.ParseLevel("warn"); e == nil {+ tlog.SetLogger(tlog.Must(tlog.NewLeveled(lvl)))+ }+ cleanupStale()++ dev, err := tun.Open(tunName, 1500)+ 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+ // 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.+ idx := strconv.Itoa(t.idx)+ 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 {+ 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+}