Skip to content

Use all your internet connections at once on Windows, macOS, Linux and Android: per-connection load balancing over Wi-Fi, Ethernet, mobile data and phone tethers

Cut CPU ~3x and show real per-adapter speeds in the tray

Rohit Mahto241343e6f419
diff --git a/README.md b/README.md
index 9edf320..7bfe3fb 100644
--- a/README.md
+++ b/README.md
@@ -10,6 +10,28 @@ Measured with Wi-Fi + an Android USB tether + an iPhone hotspot, 9 parallel down
No server, VPN or account is involved: connections go straight out of the adapter they are assigned to.
+## Screenshots
+
+| Hover the tray icon | Right-click the tray icon |
+|---|---|
+| ![Tooltip: Merging, speed of each adapter and the total](docs/tray-tooltip.png) | ![Menu: total, each adapter's speed and flows, IPv6 option, Pause merging, Quit](docs/tray-menu.png) |
+
+## Features
+
+- **Combines any adapters**: Wi-Fi, Ethernet, USB tethering, phone hotspots. Plug one in and it is used
+ within seconds; unplug it and its connections move to the others. VPN and virtual adapters (Tailscale,
+ WireGuard, Hyper-V, WSL) are ignored.
+- **System-wide**: every app, TCP and UDP, IPv4 and IPv6. No proxy settings, nothing to configure per app.
+- **Balances by real speed**: each link gets new connections in proportion to its measured throughput,
+ tracked separately for IPv4 and IPv6. A link with no internet (tether without data, captive-portal
+ Wi-Fi) gets nothing until it recovers.
+- **Live speeds on hover**: each adapter's download/upload and the total. These are the adapters' real
+ traffic from Windows, so apps that bypass net-merge (qBittorrent binds to adapters itself) still count.
+- **One click on and off**, and optional start at sign-in without a UAC prompt.
+- **Safe to crash**: the virtual adapter and its routes disappear with the process, so a crash or a kill
+ never leaves the PC without internet.
+- **Light on CPU**: about 0.18 cores per 100 Mbit/s.
+
## Uses and Tested on
- Steam downloads
- Torrent Downloads
@@ -22,26 +44,48 @@ Download `net-merge-setup-x.y.z.exe` from the [releases page](../../releases) an
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.
+## How to use
+
+1. Start **net-merge** from the Start menu and approve the admin prompt. A tray icon appears (if you
+ don't see it, it is behind the `^` arrow next to the clock; drag it onto the taskbar).
+2. Connect more links: plug in your phone with USB tethering on, join a second Wi-Fi, plug in Ethernet.
+ They are picked up automatically.
+3. Use the tray icon:
+ - **green** = merging, **grey** = paused
+ - **left-click** pauses or starts merging
+ - **hover** shows each adapter's speed and the total
+ - **right-click** shows the same with full adapter names, how many connections net-merge has put
+ on each adapter, the IPv6 option, *Pause merging* / *Start merging*, and *Quit*
+4. To start it at sign-in, tick *Start net-merge when I sign in* in the installer, or run
+ `net-merge autostart on`.
+
+Tips:
+- It helps most when an app opens many connections at once: Steam, browsers, cloud uploads, download
+ managers that split files (IDM). One single connection always stays on one adapter.
+- Torrent clients already use every adapter on their own. Leave qBittorrent's network interface on
+ *Any interface*; its speed still shows in the tray.
+- *Use all adapters (IPv6 only if every adapter has it)*: leave it ticked. If only some links have IPv6,
+ apps that prefer IPv6 would otherwise pile onto those links. Untick it only if you need an IPv6-only site.
+- `net-merge list` shows which adapters are used and why others are skipped; `net-merge status` shows
+ live per-adapter numbers.
## Command line
```
-net-merge on | off | quit | status | list | autostart on|off|status | version
+net-merge on | off start / pause merging in the running tray
+net-merge quit pause and exit the tray
+net-merge status | list live numbers / which adapters are used and why
+net-merge autostart on|off|status
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
+net-merge version
```
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`.
+(fixed weight instead of measured), `-ipv6 auto|on|off`, `-mtu 9000` (virtual adapter MTU, see below),
+`-pprof 127.0.0.1:6060` (Go profiler, loopback only), `-log file`.
## How it works
@@ -51,6 +95,9 @@ Flags for `tray`/`run`/`socks`: `-include "WiFi,Ethernet"` (only these adapters)
- Flows entering the TUN are terminated in a userland TCP/IP stack (tun2socks/gVisor) and re-dialed from
a chosen adapter: the socket is bound to that adapter's source IP and forced out of it with
`IP_UNICAST_IF`, so it can never loop back into the TUN.
+- The virtual adapter runs at MTU 9000 (both Windows and the userland stack). Its traffic never leaves
+ the machine, so the links' 1500 doesn't apply, and bigger packets cost far less CPU: measured about
+ 3x less CPU per Mbit/s than at 1500 (0.18 vs 0.54 cores per 100 Mbit/s). `-mtu` changes it.
- Adapters are detected automatically and re-scanned every 3 s. Only real hardware with a default gateway
is used: tunnels, VPNs (Tailscale, WireGuard, ...), virtual switches and LAN-only adapters are skipped
(`net-merge list` shows why).
diff --git a/docs/tray-menu.png b/docs/tray-menu.png
new file mode 100644
index 0000000..7d6b986
Binary files /dev/null and b/docs/tray-menu.png differ
diff --git a/docs/tray-tooltip.png b/docs/tray-tooltip.png
new file mode 100644
index 0000000..8f977f1
Binary files /dev/null and b/docs/tray-tooltip.png differ
diff --git a/ifcounters_windows.go b/ifcounters_windows.go
new file mode 100644
index 0000000..3f4e404
--- /dev/null
+++ b/ifcounters_windows.go
@@ -0,0 +1,17 @@
+package main
+
+import "golang.org/x/sys/windows"
+
+// ifOctets reads Windows' own byte counters for an adapter. They cover every app's traffic, not
+// just what net-merge relays: apps like qBittorrent bind to each adapter directly and bypass the
+// TUN, but still show up here.
+func ifOctets(idx int) (in, out uint64, ok bool) {
+ if idx <= 0 {
+ return 0, 0, false
+ }
+ row := windows.MibIfRow2{InterfaceIndex: uint32(idx)}
+ if windows.GetIfEntry2Ex(windows.MibIfEntryNormal, &row) != nil {
+ return 0, 0, false
+ }
+ return row.InOctets, row.OutOctets, true
+}
diff --git a/main.go b/main.go
index 3aa3e23..c5aeb6e 100644
--- a/main.go
+++ b/main.go
@@ -57,6 +57,8 @@ type common struct {
logFile string
stateDir string
ipv6 string
+ mtu int
+ pprof string
}
func (c *common) register(fs *flag.FlagSet) {
@@ -67,6 +69,8 @@ func (c *common) register(fs *flag.FlagSet) {
fs.DurationVar(&c.stats, "stats", 5*time.Second, "stats print interval (0 = off)")
fs.BoolVar(&c.auto, "auto-weight", true, "weight adapters by measured throughput (off when -weight is given)")
fs.StringVar(&c.ipv6, "ipv6", "auto", "auto: IPv6 only if every adapter has it (else apps use IPv4 on all adapters); on: always; off: never")
+ fs.IntVar(&c.mtu, "mtu", defaultMTU, "MTU of the virtual adapter (1280-65535); larger means fewer packets and less CPU")
+ fs.StringVar(&c.pprof, "pprof", "", "serve Go's profiler on this loopback address, e.g. 127.0.0.1:6060")
fs.StringVar(&c.logFile, "log", "", "write output to this file instead of the console")
fs.StringVar(&c.stateDir, "state-dir", defaultStateDir(), "where status/off marker files live")
}
@@ -105,6 +109,14 @@ func (c *common) setup() error {
// 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) {
+ if c.mtu < 1280 || c.mtu > 65535 {
+ return nil, nil, fmt.Errorf("-mtu must be between 1280 and 65535, got %d", c.mtu)
+ }
+ if c.pprof != "" {
+ if err := startPprof(c.pprof); err != nil {
+ return nil, nil, err
+ }
+ }
nics, err := c.nics()
if err != nil {
return nil, nil, err
@@ -177,8 +189,10 @@ func formatNICs(snap []SlotStats) string {
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)
+ // "link" is the adapter's total traffic by any app (Windows' counters); "via net-merge" is the
+ // part net-merge relayed. Apps that bind to adapters directly (qBittorrent) only show in "link".
+ fmt.Fprintf(&sb, "%-14s v4 %-11s v6 %-11s link down %6.1f up %5.1f Mbit/s via net-merge %6.1f active %3d total %5d w %.2f/%.2f failed %d%s\n",
+ s.Name, s.State, s.State6, s.LinkIn*8/1e6, s.LinkOut*8/1e6, (s.RateIn+s.RateOut)*8/1e6, s.Active, s.Total, s.Weight, s.Weight6, s.Failed, gone)
}
return sb.String()
}
@@ -320,6 +334,7 @@ func cmdRun(args []string) {
os.Exit(1)
}
tun := NewTun(bal)
+ tun.mtu = c.mtu
if err := tun.On(); err != nil {
logf("error: %v\n", err)
os.Exit(1)
diff --git a/pprof.go b/pprof.go
new file mode 100644
index 0000000..92ad8da
--- /dev/null
+++ b/pprof.go
@@ -0,0 +1,30 @@
+package main
+
+import (
+ "fmt"
+ "net"
+ "net/http"
+ _ "net/http/pprof" // registers /debug/pprof/ on the default mux
+)
+
+// startPprof serves Go's profiler for diagnosing CPU use, e.g.
+//
+// go tool pprof -top http://127.0.0.1:6060/debug/pprof/profile?seconds=20
+//
+// Loopback only: profiles reveal internals and the endpoint has no authentication.
+func startPprof(addr string) error {
+ host, _, err := net.SplitHostPort(addr)
+ if err != nil {
+ return fmt.Errorf("-pprof %q: %w", addr, err)
+ }
+ if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() {
+ return fmt.Errorf("-pprof must be a loopback address like 127.0.0.1:6060, got %q", addr)
+ }
+ ln, err := net.Listen("tcp", addr)
+ if err != nil {
+ return err
+ }
+ go http.Serve(ln, nil)
+ logf("pprof on http://%s/debug/pprof/\n", addr)
+ return nil
+}
diff --git a/sched.go b/sched.go
index ed649cc..e6cfe50 100644
--- a/sched.go
+++ b/sched.go
@@ -56,6 +56,11 @@ type Slot struct {
lastIn, lastOut [2]int64
rateIn, rateOut [2]float64 // bytes/s over the last tick
peak [2]float64 // observed capacity: max recent rateIn+rateOut
+
+ // The adapter's total traffic from Windows' counters (all apps, not only net-merge's flows).
+ linkIn, linkOut uint64
+ linkRateIn, linkRateOut float64
+ linkPrimed bool
}
func (sl *Slot) ip(f family) net.IP {
@@ -77,7 +82,8 @@ type SlotStats struct {
Active, Total int64
Failed int64
BytesIn, BytesOut int64
- RateIn, RateOut float64 // both families summed
+ RateIn, RateOut float64 // through net-merge, both families summed (bytes/s)
+ LinkIn, LinkOut float64 // through the adapter by any app, from Windows' counters (bytes/s)
Peak, Peak6 float64
}
@@ -175,6 +181,18 @@ func (s *Scheduler) Tick(dt time.Duration) {
s.mu.Lock()
defer s.mu.Unlock()
sec := dt.Seconds()
+ for _, sl := range s.slots {
+ in, out, ok := ifOctets(sl.Index)
+ if !sl.present || !ok {
+ sl.linkRateIn, sl.linkRateOut, sl.linkPrimed = 0, 0, false
+ continue
+ }
+ if sl.linkPrimed && in >= sl.linkIn && out >= sl.linkOut { // counters can reset when an adapter reconnects
+ sl.linkRateIn = float64(in-sl.linkIn) / sec
+ sl.linkRateOut = float64(out-sl.linkOut) / sec
+ }
+ sl.linkIn, sl.linkOut, sl.linkPrimed = in, out, true
+ }
for _, f := range []family{fam4, fam6} {
var maxPeak float64
live, measured := 0, true
@@ -353,6 +371,7 @@ func (s *Scheduler) Snapshot() []SlotStats {
BytesIn: sl.bytesIn[fam4].Load() + sl.bytesIn[fam6].Load(),
BytesOut: sl.bytesOut[fam4].Load() + sl.bytesOut[fam6].Load(),
RateIn: sl.rateIn[fam4] + sl.rateIn[fam6], RateOut: sl.rateOut[fam4] + sl.rateOut[fam6],
+ LinkIn: sl.linkRateIn, LinkOut: sl.linkRateOut,
Peak: sl.peak[fam4], Peak6: sl.peak[fam6],
}
if a.ip4 != nil {
diff --git a/sched_test.go b/sched_test.go
index 7bf6958..378dd99 100644
--- a/sched_test.go
+++ b/sched_test.go
@@ -2,8 +2,11 @@ package main
import (
"net"
+ "strings"
"testing"
"time"
+ "unicode/utf16"
+ "unicode/utf8"
)
func nic(name, ip string, w float64) Nic { return Nic{Name: name, IP: net.ParseIP(ip), Weight: w} }
@@ -271,6 +274,58 @@ func TestV6CoverageDecidesWhetherIPv6IsBalanced(t *testing.T) {
}
}
+func TestLinkCountersReadRealAdapter(t *testing.T) {
+ ifaces, _ := net.Interfaces()
+ for _, ifc := range ifaces {
+ if ifc.Flags&net.FlagUp == 0 || ifc.Flags&net.FlagLoopback != 0 {
+ continue
+ }
+ if _, _, ok := ifOctets(ifc.Index); !ok {
+ t.Fatalf("could not read Windows counters for %s (index %d)", ifc.Name, ifc.Index)
+ }
+ return
+ }
+ t.Skip("no up adapter")
+}
+
+func TestShortenCountsUTF16AndKeepsRunesWhole(t *testing.T) {
+ s := "net-merge ON ↓12 ↑3.4 Mbit/s"
+ if got := shorten(s, 127); got != s {
+ t.Fatalf("short string changed: %q", got)
+ }
+ got := shorten(s, 16)
+ if n := len(utf16.Encode([]rune(got))); n > 16 {
+ t.Fatalf("%q is %d UTF-16 units, want <= 16", got, n)
+ }
+ if !utf8.ValidString(got) || !strings.HasSuffix(got, "…") {
+ t.Fatalf("bad cut: %q", got)
+ }
+}
+
+func TestTrayTooltipFitsWindowsLimit(t *testing.T) {
+ const mbit = 125_000
+ mk := func(name string, down, up float64) SlotStats {
+ return SlotStats{Name: name, Present: true, State: "up", LinkIn: down * mbit, LinkOut: up * mbit}
+ }
+ two := []SlotStats{mk("Ethernet 3", 16, 0.2), mk("Ethernet 4", 79, 7)}
+ tip := trayTooltip(stateWord(true), 95*mbit, 7.2*mbit, two)
+ for _, want := range []string{"Merging", "Eth 3 ↓16 ↑0.2", "Eth 4 ↓79 ↑7.0", "Total ↓95 ↑7.2 Mbps"} {
+ if utf16Len(tip) > tooltipMax || !strings.Contains(tip, want) {
+ t.Fatalf("two adapters should fit with full detail (%q), got %d chars:\n%s", want, utf16Len(tip), tip)
+ }
+ }
+ four := append(two, mk("Wi-Fi", 55, 3), mk("Ethernet 7", 12, 1))
+ tip = trayTooltip(stateWord(false), 162*mbit, 11.2*mbit, four)
+ if utf16Len(tip) > tooltipMax {
+ t.Fatalf("tooltip is %d chars, Windows shows only %d:\n%s", utf16Len(tip), tooltipMax+1, tip)
+ }
+ for _, want := range []string{"Paused", "Eth 3 ↓", "Eth 4 ↓", "WiFi ↓", "Eth 7 ↓", "Total ↓162 ↑11"} {
+ if !strings.Contains(tip, want) {
+ t.Fatalf("every adapter keeps its download speed and the total is always shown; %q missing:\n%s", want, tip)
+ }
+ }
+}
+
func TestSkipSet(t *testing.T) {
s := NewScheduler([]Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
a, b := s.slots[0], s.slots[1]
diff --git a/tray_windows.go b/tray_windows.go
index a83be6c..91bd6be 100644
--- a/tray_windows.go
+++ b/tray_windows.go
@@ -7,6 +7,7 @@ import (
"path/filepath"
"strings"
"time"
+ "unicode/utf16"
"unsafe"
"fyne.io/systray"
@@ -50,6 +51,7 @@ func cmdTray(args []string) {
}
tun := NewTun(nil)
+ tun.mtu = c.mtu
mode := func() string {
if tun.IsOn() {
return "system-wide (tray)"
@@ -149,7 +151,7 @@ func (u *trayUI) onReady() {
}
systray.AddSeparator()
u.v6Item = systray.AddMenuItemCheckbox("Use all adapters (IPv6 only if every adapter has it)", "Ticked: apps are pushed to IPv4 so every adapter is used. Unticked: IPv6 is allowed and funnels onto the adapters that have it.", u.bal.V6Mode() == V6Auto)
- u.toggleItem = systray.AddMenuItem("Turn on", "Left-click the tray icon does the same")
+ u.toggleItem = systray.AddMenuItem("Start merging", "Left-click the tray icon does the same")
quit := systray.AddMenuItem("Quit", "Turns system-wide mode off and exits")
systray.SetOnTapped(func() {
select {
@@ -223,33 +225,33 @@ func (u *trayUI) refresh() {
if u.lastOn == nil || *u.lastOn != on {
if on {
systray.SetIcon(u.iconOn)
- u.toggleItem.SetTitle("Turn off")
+ u.toggleItem.SetTitle("Pause merging")
} else {
systray.SetIcon(u.iconOff)
- u.toggleItem.SetTitle("Turn on")
+ u.toggleItem.SetTitle("Start merging")
}
u.lastOn = &on
}
+ // Speeds are each adapter's real traffic from Windows' counters, i.e. every app (qBittorrent binds
+ // to adapters directly and never passes through net-merge), and they are shown even when paused.
var live []SlotStats
- total := 0.0
+ var down, up float64
for _, s := range u.sched.Snapshot() {
if s.Present {
live = append(live, s)
- total += (s.RateIn + s.RateOut) * 8 / 1e6
+ down += s.LinkIn
+ up += s.LinkOut
}
}
+ state := stateWord(on)
- switch {
- case u.lastErr != "":
+ if 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")
+ } else {
+ u.setHeader(fmt.Sprintf("%s · Total ↓%s ↑%s Mbps", state, mbps(down), mbps(up)))
}
- var parts []string
for i, r := range u.rows {
if i >= len(live) {
if u.lastRows[i] != "" {
@@ -259,10 +261,12 @@ func (u *trayUI) refresh() {
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)
+ txt := fmt.Sprintf("%s: ↓%s ↑%s Mbps", s.Name, mbps(s.LinkIn), mbps(s.LinkOut))
+ if on {
+ txt += fmt.Sprintf(" (%d flows via net-merge)", 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)
+ txt += " - " + s.State
}
if s.State6 == "up" {
txt += " +IPv6"
@@ -272,22 +276,101 @@ func (u *trayUI) refresh() {
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)
- }
+ // Hover tooltip: one line per adapter, so speeds are visible without opening the menu.
+ tip := trayTooltip(state, down, up, live)
if tip != u.lastTip {
systray.SetTooltip(tip)
u.lastTip = tip
}
}
+// Windows 11 shows only the first 64 characters of a tray tooltip (measured: the text stopped mid-
+// line at exactly 64), although the API accepts 128. So the hover text drops detail until it fits.
+const tooltipMax = 63
+
+// stateWord is how the tray names the two states.
+func stateWord(on bool) string {
+ if on {
+ return "Merging"
+ }
+ return "Paused"
+}
+
+// trayTooltip lists each adapter's speed and a Total line, e.g.
+//
+// Merging
+// Eth 3 ↓16 ↑0.2
+// Eth 4 ↓79 ↑7.0
+// Total ↓95 ↑7.2 Mbps
+//
+// It drops detail (the app name, then per-adapter upload, then the unit) until it fits; every
+// adapter keeps its download speed and the total is always shown.
+func trayTooltip(state string, down, up float64, live []SlotStats) string {
+ build := func(head string, withUp bool, unit string) string {
+ lines := []string{head}
+ for _, s := range live {
+ l := shortName(s.Name) + " ↓" + mbps(s.LinkIn)
+ if withUp {
+ l += " ↑" + mbps(s.LinkOut)
+ }
+ if s.State == "no internet" && s.State6 != "up" {
+ l += " (no net)"
+ }
+ lines = append(lines, l)
+ }
+ lines = append(lines, "Total ↓"+mbps(down)+" ↑"+mbps(up)+unit)
+ return strings.Join(lines, "\n")
+ }
+ leanest := build(state, false, "")
+ for _, t := range []string{
+ build("net-merge · "+state, true, " Mbps"),
+ build(state, true, " Mbps"),
+ build(state, false, " Mbps"),
+ leanest,
+ } {
+ if utf16Len(t) <= tooltipMax {
+ return t
+ }
+ }
+ return shorten(leanest, tooltipMax)
+}
+
+// shortName keeps adapter names short enough for the tooltip ("Ethernet 3" -> "Eth 3").
+var shortNamer = strings.NewReplacer("Ethernet", "Eth", "Wi-Fi", "WiFi", "Local Area Connection", "LAN", "Cellular", "Cell")
+
+func shortName(n string) string { return shortNamer.Replace(n) }
+
+func utf16Len(s string) int {
+ n := 0
+ for _, r := range s {
+ n += utf16.RuneLen(r)
+ }
+ return n
+}
+
+// mbps formats bytes/s as Mbit/s compactly: one decimal below 10, whole numbers above.
+func mbps(bytesPerSec float64) string {
+ m := bytesPerSec * 8 / 1e6
+ if m < 9.95 {
+ return fmt.Sprintf("%.1f", m)
+ }
+ return fmt.Sprintf("%.0f", m)
+}
+
+// shorten cuts s to at most n UTF-16 units (what Windows counts), ending in an ellipsis.
func shorten(s string, n int) string {
- if len(s) <= n {
+ if utf16Len(s) <= n {
return s
}
- return s[:n-1] + "…"
+ units := 0
+ for i, r := range s {
+ w := utf16.RuneLen(r)
+ if units+w > n-1 {
+ return s[:i] + "…"
+ }
+ units += w
+ }
+ return s
}
diff --git a/tun_windows.go b/tun_windows.go
index 8c8b126..677c235 100644
--- a/tun_windows.go
+++ b/tun_windows.go
@@ -66,13 +66,26 @@ func (p tunProxy) DialUDP(m *M.Metadata) (net.PacketConn, error) {
type Tun struct {
mu sync.Mutex
b *Balancer
+ mtu int // set before On; see defaultMTU
dev device.Device
stk *stack.Stack
idx int
on bool
}
-func NewTun(b *Balancer) *Tun { return &Tun{b: b} }
+// defaultMTU is the TUN's MTU, used both by the userland stack and by Windows. TUN traffic never
+// leaves the machine (flows are re-dialed with normal sockets), so it isn't bound by the links'
+// 1500. Bigger packets mean far fewer per-packet trips through the userland stack: about 6x fewer
+// for bulk TCP at 9000. Not 65535: the TUN library allocates a full-MTU buffer for every inbound
+// packet, even a 40-byte ACK.
+const defaultMTU = 9000
+
+// udpSessionTimeout ends idle UDP sessions sooner than tun2socks' 60s. Torrent DHT opens a session
+// per peer queried, each holding a socket, two goroutines and two 64 KB buffers. 30s stays above the
+// ~25s keepalives common in VPN and NAT-traversal protocols.
+const udpSessionTimeout = 30 * time.Second
+
+func NewTun(b *Balancer) *Tun { return &Tun{b: b, mtu: defaultMTU} }
func (t *Tun) IsOn() bool {
t.mu.Lock()
@@ -86,12 +99,15 @@ func (t *Tun) On() (err error) {
if t.on {
return nil
}
- if lvl, e := tlog.ParseLevel("warn"); e == nil {
+ // "error", not "warn": tun2socks warns once per dropped UDP packet ("symmetric NAT ... drop
+ // packet"), which a torrent client triggers continuously.
+ if lvl, e := tlog.ParseLevel("error"); e == nil {
tlog.SetLogger(tlog.Must(tlog.NewLeveled(lvl)))
}
+ tunnel.T().SetUDPTimeout(udpSessionTimeout)
cleanupStale()
- dev, err := tun.Open(tunName, 1500)
+ dev, err := tun.Open(tunName, uint32(t.mtu))
if err != nil {
return fmt.Errorf("open TUN (needs admin and wintun.dll next to net-merge.exe): %w", err)
}
@@ -122,6 +138,13 @@ func (t *Tun) On() (err error) {
return err
}
t.idx = ifc.Index
+ // Windows gives Wintun adapters an MTU of 65535. Match the stack's MTU, so Windows sizes TCP
+ // segments to it and fragments bigger UDP datagrams instead of sending packets the stack drops.
+ idx := strconv.Itoa(t.idx)
+ mtu := "mtu=" + strconv.Itoa(t.mtu)
+ if e := run("netsh", "interface", "ipv4", "set", "subinterface", "interface="+idx, mtu, "store=active"); e != nil {
+ logf("warning: could not set IPv4 MTU: %v\n", e)
+ }
// Two /1 routes beat any default route (/0) without touching it, so Off() is just deleting these.
for _, dst := range [][2]string{{"0.0.0.0", "128.0.0.0"}, {"128.0.0.0", "128.0.0.0"}} {
if err = run("route", "add", dst[0], "mask", dst[1], "0.0.0.0", "metric", "1", "if", strconv.Itoa(t.idx)); err != nil {
@@ -129,10 +152,12 @@ func (t *Tun) On() (err error) {
}
}
// 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 {
+ if e := run("netsh", "interface", "ipv6", "set", "subinterface", "interface="+idx, mtu, "store=active"); e != nil {
+ logf("warning: could not set IPv6 MTU: %v\n", e)
+ }
for _, p := range []string{"::/1", "8000::/1"} {
if e := run("netsh", "interface", "ipv6", "add", "route", "prefix="+p, "interface="+idx, "metric=1", "store=active"); e != nil {
logf("warning: IPv6 route %s: %v\n", p, e)