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

Per-adapter speed limits in the tray, in Mbit/s (#47)

E4crypt3df5ee0e85d29f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68a79a2..447d944 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,15 @@ entry here before pushing a version tag.
## [Unreleased]
+### Added
+- **Speed limits per connection** from the tray menu: click a connection and pick 1, 2, 5, 10, 20, 50 or
+ 100 Mbit/s (or *Unlimited*). The cap covers that connection's downloads and uploads across all of its
+ flows and takes effect immediately; the choice is saved and applied again after a restart (on macOS
+ it is kept under `/Library/Application Support`, so it survives a reboot too). From a
+ terminal, `net-merge limit <adapter> <Mbit/s>` sets any other speed, and `net-merge limit` lists the
+ saved caps. Only traffic net-merge relays is capped, so an app bound directly to an adapter is not
+ affected.
+
## [0.3.5] - 2026-10-24
### Changed
diff --git a/README.md b/README.md
index 4aba206..95b6e99 100644
--- a/README.md
+++ b/README.md
@@ -350,7 +350,11 @@ net-merge when you do not want that.
many connections net-merge gave it, and the buttons *Pause merging* / *Start merging* and *Quit*. The
line above *Quit* is the version you are running, like `v0.3.3`. It reads the newest release number
from GitHub (at start, and again every 6 hours) and turns into *Update to v0.3.4* if there is one;
- click it to open the release page.
+ click it to open the release page. Click a connection to cap it at 1, 2, 5, 10, 20, 50 or 100 Mbit/s
+ (or *Unlimited*). For any other speed, from a terminal: `net-merge limit "Ethernet 2" 25` (Mbit/s; 0 or
+ `unlimited` removes the cap), and `net-merge limit` lists what is set. The cap covers its downloads and
+ uploads and is remembered after a restart. Only traffic net-merge relays is capped: an app bound directly
+ to an adapter (for example qBittorrent on a fixed interface) ignores it.
6. To start it at sign-in: tick *Start at sign-in* in the menu (or the box in the Windows installer, or run
`net-merge autostart on`). On a Mac this needs `sudo net-merge install` once.
diff --git a/cmd/net-merge/main.go b/cmd/net-merge/main.go
index 477ba8a..1286c00 100644
--- a/cmd/net-merge/main.go
+++ b/cmd/net-merge/main.go
@@ -6,6 +6,7 @@ import (
"net"
"os"
"os/signal"
+ "sort"
"strconv"
"strings"
"syscall"
@@ -27,6 +28,8 @@ const usage = `net-merge: use all your network adapters at once.
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 limit <adapter> <Mbit/s> cap an adapter (0 or unlimited removes the cap)
+ net-merge limit list the saved speed limits
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 (Windows: no UAC prompt)
@@ -132,6 +135,11 @@ func (c *common) boot(mode func() string) (*engine.Scheduler, *engine.Balancer,
}
sched := engine.NewScheduler(nics)
sched.SetAuto(c.auto && len(c.weights) == 0)
+ if limits, err := state.LoadLimits(c.stateDir); err != nil {
+ logx.Printf("warning: %v (ignored)\n", err) // a bad limits file must not stop merging
+ } else {
+ sched.SetLimits(limits)
+ }
for _, n := range nics {
logx.Printf(" + %s\n", describeNic(n))
}
@@ -197,8 +205,12 @@ func formatNICs(snap []engine.SlotStats) string {
}
// "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)
+ lim := ""
+ if s.LimitMbps > 0 {
+ lim = " limit " + limitPhrase(s.LimitMbps)
+ }
+ 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%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, lim, gone)
}
return sb.String()
}
@@ -251,6 +263,8 @@ func main() {
cmdControl(cmd, args)
case "status":
cmdStatus(args)
+ case "limit":
+ cmdLimit(args)
case "socks":
cmdSocks(args)
case "list":
@@ -345,7 +359,7 @@ func cmdRun(args []string) {
}
state.TakeMarker(c.stateDir, "off") // drop a stale marker
- _, bal, err := c.boot(func() string { return "system-wide" })
+ sched, bal, err := c.boot(func() string { return "system-wide" })
if err != nil {
logx.Printf("error: %v\n", err)
os.Exit(1)
@@ -376,6 +390,12 @@ func cmdRun(args []string) {
case <-crash:
os.Exit(3) // simulates a crash: no teardown runs
case <-poll.C:
+ if req, ok := state.TakeLimit(c.stateDir); ok {
+ sched.SetLimit(req.Adapter, req.Mbps)
+ if err := state.SaveLimits(c.stateDir, sched.Limits()); err != nil {
+ logx.Printf("warning: saving speed limits: %v\n", err)
+ }
+ }
if !state.TakeMarker(c.stateDir, "off") && !state.TakeMarker(c.stateDir, "quit") {
continue
}
@@ -432,6 +452,99 @@ func cmdStatus(args []string) {
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))
}
+// cmdLimit lists the saved caps, or sets one. A running instance gets the change through a marker
+// file and saves it; with nothing running, limits.json is updated directly so the next start picks
+// it up.
+func cmdLimit(args []string) {
+ fs := flag.NewFlagSet("limit", flag.ExitOnError)
+ dir := fs.String("state-dir", state.DefaultDir(), "state directory")
+ fs.Parse(args)
+ rest := fs.Args()
+
+ if len(rest) == 0 {
+ limits, err := state.LoadLimits(*dir)
+ if err != nil {
+ die(err)
+ }
+ if len(limits) == 0 {
+ fmt.Println("No speed limits set.")
+ return
+ }
+ names := make([]string, 0, len(limits))
+ for name := range limits {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ for _, name := range names {
+ fmt.Printf("%-14s %s\n", name, limitPhrase(limits[name]))
+ }
+ return
+ }
+ if len(rest) != 2 {
+ fmt.Fprintln(os.Stderr, "usage: net-merge limit <adapter> <Mbit/s> (0, off or unlimited removes the cap)")
+ os.Exit(2)
+ }
+ name := strings.TrimSpace(rest[0])
+ mbitPerSec, err := engine.ParseLimit(rest[1])
+ if err != nil {
+ die(err)
+ }
+ live, err := limitApply(*dir, name, mbitPerSec, platform.InstanceRunning(), limitWait)
+ if err != nil {
+ die(err)
+ }
+ if live {
+ fmt.Printf("%s: %s.\n", name, limitPhrase(mbitPerSec))
+ } else {
+ fmt.Printf("%s: %s. It takes effect the next time net-merge starts.\n", name, limitPhrase(mbitPerSec))
+ }
+}
+
+// limitWait is how long `net-merge limit` waits for a running instance to apply and save the cap.
+var limitWait = 4 * time.Second
+
+// limitApply saves a cap. With a running instance the request goes through ctl/ and the instance
+// applies it and saves limits.json; with nothing running this writes limits.json itself, so the
+// next start picks it up. It reports whether a running instance applied it.
+func limitApply(dir, name string, mbitPerSec float64, running bool, wait time.Duration) (live bool, err error) {
+ if !running {
+ limits, err := state.LoadLimits(dir)
+ if err != nil {
+ return false, err
+ }
+ if mbitPerSec <= 0 {
+ delete(limits, name)
+ } else {
+ limits[name] = mbitPerSec
+ }
+ return false, state.SaveLimits(dir, limits)
+ }
+ if err := state.SendLimit(dir, state.LimitRequest{Adapter: name, Mbps: mbitPerSec}); err != nil {
+ return true, err
+ }
+ // The instance applies it within a second and saves limits.json; wait for that as proof.
+ deadline := time.Now().Add(wait)
+ for {
+ if limits, err := state.LoadLimits(dir); err == nil {
+ got, set := limits[name]
+ if (mbitPerSec <= 0 && !set) || (set && got == mbitPerSec) {
+ return true, nil
+ }
+ }
+ if time.Now().After(deadline) {
+ return true, fmt.Errorf("sent the limit, but the running instance did not apply it")
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+}
+
+func limitPhrase(mbitPerSec float64) string {
+ if mbitPerSec <= 0 {
+ return "unlimited"
+ }
+ return strconv.FormatFloat(mbitPerSec, 'f', -1, 64) + " Mbit/s"
+}
+
func cmdCleanup() {
if !platform.IsAdmin() {
if err := platform.RelaunchElevated([]string{"cleanup"}, false); err != nil {
diff --git a/cmd/net-merge/main_test.go b/cmd/net-merge/main_test.go
new file mode 100644
index 0000000..0d2b3c6
--- /dev/null
+++ b/cmd/net-merge/main_test.go
@@ -0,0 +1,100 @@
+package main
+
+import (
+ "strings"
+ "testing"
+ "time"
+
+ "net-merge/internal/engine"
+ "net-merge/internal/state"
+)
+
+func TestLimitApplyWithoutInstanceWritesLimitsFile(t *testing.T) {
+ dir := t.TempDir()
+ if err := state.SaveLimits(dir, map[string]float64{"Ethernet": 10}); err != nil {
+ t.Fatal(err)
+ }
+
+ live, err := limitApply(dir, "Wi-Fi", 50, false, time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if live {
+ t.Fatal("nothing was running, so it must not report a live change")
+ }
+ limits, err := state.LoadLimits(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if limits["Wi-Fi"] != 50 || limits["Ethernet"] != 10 {
+ t.Fatalf("limits = %v, want Wi-Fi=50 and Ethernet kept at 10", limits)
+ }
+
+ if _, err := limitApply(dir, "Ethernet", 0, false, time.Second); err != nil {
+ t.Fatal(err)
+ }
+ limits, err = state.LoadLimits(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, set := limits["Ethernet"]; set {
+ t.Fatalf("Ethernet still capped: %v", limits)
+ }
+}
+
+func TestLimitApplyThroughRunningInstance(t *testing.T) {
+ dir := t.TempDir()
+ sched := engine.NewScheduler(nil)
+ stop := make(chan struct{})
+ defer close(stop)
+
+ // Stand-in for the tray's once-a-second poll: take the request, apply it, save it.
+ go func() {
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ if req, ok := state.TakeLimit(dir); ok {
+ sched.SetLimit(req.Adapter, req.Mbps)
+ state.SaveLimits(dir, sched.Limits())
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ }()
+
+ live, err := limitApply(dir, "Ethernet 2", 35, true, 2*time.Second)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !live {
+ t.Fatal("a running instance should report a live change")
+ }
+ limits, err := state.LoadLimits(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if limits["Ethernet 2"] != 35 {
+ t.Fatalf("limits = %v, want Ethernet 2 = 35", limits)
+ }
+ if got := sched.Limits()["Ethernet 2"]; got != 35 {
+ t.Fatalf("the instance applied %v, want 35", got)
+ }
+ if _, ok := state.TakeLimit(dir); ok {
+ t.Fatal("the request must be consumed")
+ }
+}
+
+func TestFormatNICsShowsTheCapInMbit(t *testing.T) {
+ out := formatNICs([]engine.SlotStats{{
+ Name: "Ethernet", State: "up", State6: "-", Present: true, LimitMbps: 12.5, Weight: 1, Weight6: 1,
+ }})
+ if !strings.Contains(out, "limit 12.5 Mbit/s") {
+ t.Fatalf("want the cap in Mbit/s, got:\n%s", out)
+ }
+ if strings.Contains(out, "MB/s") {
+ t.Fatalf("status must not mix megabytes into a Mbit/s line:\n%s", out)
+ }
+}
diff --git a/install.sh b/install.sh
index 1fb5c01..86a148f 100755
--- a/install.sh
+++ b/install.sh
@@ -131,7 +131,7 @@ uninstall() {
brew uninstall net-merge
brew untap rohit267/tap >/dev/null 2>&1 || true
fi
- $SUDO rm -rf /var/run/net-merge "$HOME/Library/Logs/net-merge.log"
+ $SUDO rm -rf /var/run/net-merge "/Library/Application Support/net-merge" "$HOME/Library/Logs/net-merge.log"
else
if have dpkg && dpkg -s net-merge >/dev/null 2>&1; then
say "Removing with apt"
diff --git a/internal/engine/balancer.go b/internal/engine/balancer.go
index 83cdfee..a8846c9 100644
--- a/internal/engine/balancer.go
+++ b/internal/engine/balancer.go
@@ -197,17 +197,17 @@ func Relay(client, upstream net.Conn, sl *Slot, f Family, s *Scheduler) {
wg.Add(1)
go func() {
defer wg.Done()
- pump(upstream, client, &sl.bytesOut[f], activity)
+ pump(upstream, client, &sl.bytesOut[f], sl, false, activity)
release()
}()
- pump(client, upstream, &sl.bytesIn[f], activity)
+ pump(client, upstream, &sl.bytesIn[f], sl, true, activity)
release()
wg.Wait()
client.Close()
upstream.Close()
}
-func pump(dst, src net.Conn, counter interface{ Add(int64) int64 }, activity *flowActivity) {
+func pump(dst, src net.Conn, counter *atomic.Int64, sl *Slot, down bool, activity *flowActivity) {
bp := bufPool.Get().(*[]byte)
defer bufPool.Put(bp)
buf := *bp
@@ -216,7 +216,7 @@ func pump(dst, src net.Conn, counter interface{ Add(int64) int64 }, activity *fl
if n > 0 {
activity.bytes.Add(int64(n))
counter.Add(int64(n))
- if _, werr := dst.Write(buf[:n]); werr != nil {
+ if _, werr := sl.writePaced(dst, buf[:n], down); werr != nil {
dst.Close()
src.Close()
return
diff --git a/internal/engine/flowconn.go b/internal/engine/flowconn.go
index 450630f..59797e0 100644
--- a/internal/engine/flowconn.go
+++ b/internal/engine/flowconn.go
@@ -21,16 +21,22 @@ type slotConn struct {
}
func (c *slotConn) Read(p []byte) (int, error) {
+ if pair := c.sl.limit.Load(); pair != nil && len(p) > pair.chunk {
+ p = p[:pair.chunk] // hand out a chunk at a time, so a limited flow stays smooth
+ }
n, err := c.TCPConn.Read(p)
- c.sl.bytesIn[c.fam].Add(int64(n))
- if c.activity != nil {
- c.activity.bytes.Add(int64(n))
+ if n > 0 {
+ c.sl.bytesIn[c.fam].Add(int64(n))
+ if c.activity != nil {
+ c.activity.bytes.Add(int64(n))
+ }
+ c.sl.throttle(true, n)
}
return n, err
}
func (c *slotConn) Write(p []byte) (int, error) {
- n, err := c.TCPConn.Write(p)
+ n, err := c.sl.writePaced(c.TCPConn, p, false)
c.sl.bytesOut[c.fam].Add(int64(n))
if c.activity != nil {
c.activity.bytes.Add(int64(n))
@@ -69,11 +75,15 @@ type slotPacketConn struct {
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))
+ if n > 0 {
+ c.sl.bytesIn[c.fam].Add(int64(n))
+ c.sl.throttlePacket(true, n)
+ }
return n, a, err
}
func (c *slotPacketConn) WriteTo(p []byte, a net.Addr) (int, error) {
+ c.sl.throttlePacket(false, len(p))
n, err := c.PacketConn.WriteTo(p, a)
c.sl.bytesOut[c.fam].Add(int64(n))
return n, err
diff --git a/internal/engine/limit.go b/internal/engine/limit.go
new file mode 100644
index 0000000..489c284
--- /dev/null
+++ b/internal/engine/limit.go
@@ -0,0 +1,184 @@
+package engine
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+)
+
+// A speed limit is two token buckets per adapter, one per direction, shared by every flow and both
+// address families: the cap is for the adapter as a whole, not per connection or per address. Caps
+// are in Mbit/s everywhere (the same unit the tray shows for live speeds).
+const (
+ // limitChunkMin and limitChunkMax bound how many bytes one wait covers. The chunk is normally
+ // rate × 5 ms, so each wait is long enough that the timer's own delay does not cap the speed;
+ // at low rates the minimum keeps wake-ups rare, and at very high rates the maximum keeps a
+ // single write from being split too many times.
+ limitChunkMin = 16 << 10
+ limitChunkMax = 1 << 20
+ limitChunkTime = 5 * time.Millisecond
+ // limitBurstMin and limitBurstTime size the bucket: rate × 50 ms (minimum 16 KB) may pass at
+ // once after an idle moment, and a fresh bucket starts full so the first request on a quiet
+ // link does not stall.
+ limitBurstMin = 16 << 10
+ limitBurstTime = 50 * time.Millisecond
+ // udpFree lets small datagrams through untouched: DNS, mDNS and calls stay responsive even
+ // while a bulk QUIC download is being paced on the same adapter.
+ udpFree = 512
+
+ bytesPerMbit = 1_000_000 / 8
+)
+
+// limitPair is the installed cap: nil means unlimited. It is swapped as a whole so the data path
+// reads it without a lock, and changing a limit never blocks a flow.
+type limitPair struct {
+ in, out *bucket
+ mbitPerSec float64
+ chunk int
+}
+
+type bucket struct {
+ mu sync.Mutex
+ rate float64 // bytes/s
+ burst float64
+ tokens float64
+ last time.Time
+}
+
+func newBucket(bytesPerSec float64) *bucket {
+ burst := math.Max(limitBurstMin, bytesPerSec*limitBurstTime.Seconds())
+ return &bucket{rate: bytesPerSec, burst: burst, tokens: burst, last: time.Now()}
+}
+
+// take reserves n bytes and sleeps until they may pass. The reservation happens under the lock,
+// so concurrent flows queue fairly instead of all waking at once; the sleep itself is outside it.
+func (b *bucket) take(n int) {
+ b.mu.Lock()
+ now := time.Now()
+ b.tokens = math.Min(b.burst, b.tokens+now.Sub(b.last).Seconds()*b.rate)
+ b.last = now
+ var wait time.Duration
+ if need := float64(n); need > b.tokens {
+ seconds := (need - b.tokens) / b.rate
+ b.tokens = 0
+ b.last = now.Add(time.Duration(seconds * float64(time.Second)))
+ wait = time.Duration(seconds * float64(time.Second))
+ } else {
+ b.tokens -= need
+ }
+ b.mu.Unlock()
+ if wait > 0 {
+ time.Sleep(wait)
+ }
+}
+
+// LimitMaxMbps is the largest cap accepted, in Mbit/s. It is the same ceiling limits.json accepts.
+const LimitMaxMbps = 1e6
+
+// ParseLimit reads a cap written by a person: "10", "7.5", "0", "off" or "unlimited". It returns
+// 0 for no cap. Both the tray and `net-merge limit` use it, so both accept the same spellings and
+// reject the same nonsense.
+func ParseLimit(s string) (float64, error) {
+ t := strings.TrimSpace(s)
+ switch strings.ToLower(t) {
+ case "unlimited", "off", "none":
+ return 0, nil
+ }
+ mbitPerSec, err := strconv.ParseFloat(t, 64)
+ if err != nil || math.IsNaN(mbitPerSec) || math.IsInf(mbitPerSec, 0) {
+ return 0, fmt.Errorf("enter a speed in Mbit/s, like 50 or 7.5 (0 for unlimited)")
+ }
+ if mbitPerSec < 0 || mbitPerSec > LimitMaxMbps {
+ return 0, fmt.Errorf("the speed must be between 0 and %.0f Mbit/s", float64(LimitMaxMbps))
+ }
+ return mbitPerSec, nil
+}
+
+// limitChunkFor is how many bytes one wait covers at this rate.
+func limitChunkFor(bytesPerSec float64) int {
+ n := bytesPerSec * limitChunkTime.Seconds()
+ switch {
+ case n < limitChunkMin:
+ return limitChunkMin
+ case n > limitChunkMax:
+ return limitChunkMax
+ default:
+ return int(n)
+ }
+}
+
+// setLimit installs the adapter's cap in Mbit/s, or clears it with 0.
+func (sl *Slot) setLimit(mbitPerSec float64) {
+ if mbitPerSec <= 0 {
+ sl.limit.Store(nil)
+ return
+ }
+ rate := mbitPerSec * bytesPerMbit // Mbit/s to bytes/s
+ sl.limit.Store(&limitPair{
+ in: newBucket(rate),
+ out: newBucket(rate),
+ mbitPerSec: mbitPerSec,
+ chunk: limitChunkFor(rate),
+ })
+}
+
+func (sl *Slot) limitMbps() float64 {
+ if p := sl.limit.Load(); p != nil {
+ return p.mbitPerSec
+ }
+ return 0
+}
+
+// throttle paces n bytes in one direction (down = from the internet) on this adapter.
+func (sl *Slot) throttle(down bool, n int) {
+ p := sl.limit.Load()
+ if p == nil || n <= 0 {
+ return
+ }
+ b := p.out
+ if down {
+ b = p.in
+ }
+ for n > 0 {
+ k := min(n, p.chunk)
+ b.take(k)
+ n -= k
+ }
+}
+
+// throttlePacket is throttle for datagrams: small ones skip the bucket so latency-sensitive
+// traffic (DNS, calls) is not stuck behind a bulk download.
+func (sl *Slot) throttlePacket(down bool, n int) {
+ if n <= udpFree {
+ return
+ }
+ sl.throttle(down, n)
+}
+
+// writePaced waits for the adapter's tokens and writes p in chunks while doing so, so a large
+// buffer is delivered smoothly instead of in one burst at the end of the wait.
+func (sl *Slot) writePaced(dst io.Writer, p []byte, down bool) (int, error) {
+ pair := sl.limit.Load()
+ if pair == nil {
+ return dst.Write(p)
+ }
+ written := 0
+ for len(p) > 0 {
+ k := min(len(p), pair.chunk)
+ sl.throttle(down, k)
+ n, err := dst.Write(p[:k])
+ written += n
+ if err != nil {
+ return written, err
+ }
+ if n < k {
+ return written, io.ErrShortWrite
+ }
+ p = p[k:]
+ }
+ return written, nil
+}
diff --git a/internal/engine/limit_test.go b/internal/engine/limit_test.go
new file mode 100644
index 0000000..1bc23e4
--- /dev/null
+++ b/internal/engine/limit_test.go
@@ -0,0 +1,288 @@
+package engine
+
+import (
+ "io"
+ "net"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "net-merge/internal/nics"
+)
+
+func TestParseLimit(t *testing.T) {
+ for _, c := range []struct {
+ in string
+ want float64
+ ok bool
+ }{
+ {"10", 10, true},
+ {" 7.5 ", 7.5, true},
+ {"0", 0, true},
+ {"unlimited", 0, true},
+ {"Off", 0, true},
+ {"none", 0, true},
+ {"", 0, false},
+ {"fast", 0, false},
+ {"-1", 0, false},
+ {"NaN", 0, false},
+ {"+Inf", 0, false},
+ {"1e7", 0, false}, // over LimitMaxMbps
+ } {
+ got, err := ParseLimit(c.in)
+ if c.ok && err != nil {
+ t.Errorf("ParseLimit(%q): %v", c.in, err)
+ }
+ if !c.ok && err == nil {
+ t.Errorf("ParseLimit(%q) = %v, want an error", c.in, got)
+ }
+ if c.ok && got != c.want {
+ t.Errorf("ParseLimit(%q) = %v, want %v", c.in, got, c.want)
+ }
+ }
+}
+
+func TestBucketPacesAfterTheBurst(t *testing.T) {
+ b := newBucket(100_000) // 100 KB/s, below the minimum burst
+ start := time.Now()
+ b.take(limitBurstMin) // a quiet bucket starts full, so the first chunk is free
+ if d := time.Since(start); d > 50*time.Millisecond {
+ t.Fatalf("the initial burst waited %s", d)
+ }
+ start = time.Now()
+ b.take(limitChunkMin)
+ if d := time.Since(start); d < 100*time.Millisecond {
+ t.Fatalf("16 KB at 100 KB/s took %s, want about 164 ms", d)
+ }
+}
+
+func TestThrottleWithoutLimitIsFree(t *testing.T) {
+ sl := &Slot{}
+ start := time.Now()
+ for i := 0; i < 100; i++ {
+ sl.throttle(true, 64<<10)
+ }
+ if d := time.Since(start); d > 50*time.Millisecond {
+ t.Fatalf("throttling an unlimited adapter took %s", d)
+ }
+}
+
+func TestThrottleKeepsDirectionsSeparate(t *testing.T) {
+ sl := &Slot{}
+ sl.setLimit(4) // 4 Mbit/s = 500 KB/s
+ sl.throttle(false, 64<<10)
+ start := time.Now()
+ sl.throttle(true, limitChunkMin) // the download bucket is untouched
+ if d := time.Since(start); d > 50*time.Millisecond {
+ t.Fatalf("download waited %s behind upload traffic", d)
+ }
+}
+
+func TestSmallDatagramsAreNotPaced(t *testing.T) {
+ sl := &Slot{}
+ sl.setLimit(4)
+ sl.throttle(false, 64<<10)
+ start := time.Now()
+ sl.throttlePacket(false, 40) // a DNS query
+ if d := time.Since(start); d > 50*time.Millisecond {
+ t.Fatalf("a 40-byte datagram waited %s behind a bulk flow", d)
+ }
+}
+
+func TestPumpHonoursLimit(t *testing.T) {
+ sl := &Slot{}
+ sl.setLimit(0.8) // 0.8 Mbit/s = 100 KB/s
+ srcR, srcW := net.Pipe()
+ dstR, dstW := net.Pipe()
+ defer srcR.Close()
+ defer srcW.Close()
+ defer dstR.Close()
+ defer dstW.Close()
+
+ var counted atomic.Int64
+ go pump(dstW, srcR, &counted, sl, false, &flowActivity{})
+ go func() {
+ srcW.Write(make([]byte, 32<<10))
+ srcW.Close()
+ }()
+
+ start := time.Now()
+ got := make([]byte, 32<<10)
+ if _, err := io.ReadFull(dstR, got); err != nil {
+ t.Fatal(err)
+ }
+ if d := time.Since(start); d < 100*time.Millisecond {
+ t.Fatalf("32 KB at 100 KB/s took %s, want at least ~164 ms", d)
+ }
+ if n := counted.Load(); n != int64(len(got)) {
+ t.Fatalf("counted %d bytes, want %d", n, len(got))
+ }
+}
+
+func TestLimitUnits(t *testing.T) {
+ sl := &Slot{}
+ sl.setLimit(400) // 400 Mbit/s = 50 MB/s
+ p := sl.limit.Load()
+ if p == nil {
+ t.Fatal("no cap installed")
+ }
+ const wantRate = 400 * bytesPerMbit
+ if p.in.rate != wantRate || p.out.rate != wantRate {
+ t.Fatalf("rate = %v/%v B/s, want %v", p.in.rate, p.out.rate, float64(wantRate))
+ }
+ if p.chunk != 250_000 {
+ t.Fatalf("chunk = %d, want 250000 (rate x 5 ms)", p.chunk)
+ }
+ if p.in.burst != 2_500_000 {
+ t.Fatalf("burst = %v, want 2500000 (rate x 50 ms)", p.in.burst)
+ }
+ if got := sl.limitMbps(); got != 400 {
+ t.Fatalf("limitMbps = %v, want 400", got)
+ }
+
+ sl.setLimit(1) // 125 KB/s: the minimum chunk and burst apply
+ p = sl.limit.Load()
+ if p.chunk != limitChunkMin || p.in.burst != limitBurstMin {
+ t.Fatalf("chunk/burst = %d/%v at 1 Mbit/s, want %d/%d", p.chunk, p.in.burst, limitChunkMin, limitBurstMin)
+ }
+
+ sl.setLimit(0)
+ if sl.limit.Load() != nil || sl.limitMbps() != 0 {
+ t.Fatal("0 did not clear the cap")
+ }
+}
+
+func TestHighCapIsReached(t *testing.T) {
+ sl := &Slot{}
+ sl.setLimit(400) // 50 MB/s
+ const size = 8 << 20
+ start := time.Now()
+ if _, err := sl.writePaced(io.Discard, make([]byte, size), false); err != nil {
+ t.Fatal(err)
+ }
+ d := time.Since(start)
+ // 8 MB at 50 MB/s is 160 ms; the first 2.5 MB (50 ms worth) passes as burst, so ~110 ms is right.
+ // 16 KB chunks would spend most of their time in timer overshoot and land far below the cap.
+ if d < 70*time.Millisecond {
+ t.Fatalf("8 MB at 400 Mbit/s took only %s: the cap was not applied", d)
+ }
+ if d > 400*time.Millisecond {
+ t.Fatalf("8 MB at 400 Mbit/s took %s, want about 110-200 ms", d)
+ }
+}
+
+func TestSlotConnPacesWrites(t *testing.T) {
+ sl := &Slot{}
+ sl.setLimit(80) // 10 MB/s
+ ln, err := net.Listen("tcp4", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ go func() {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ io.Copy(io.Discard, c)
+ c.Close()
+ }()
+
+ raw, err := net.Dial("tcp4", ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := &slotConn{TCPConn: raw.(*net.TCPConn), sl: sl, fam: Fam4, s: NewScheduler(nil)}
+ defer c.Close()
+
+ const size = 2 << 20 // 2 MB at 10 MB/s is 200 ms, minus the 500 KB burst
+ start := time.Now()
+ if _, err := c.Write(make([]byte, size)); err != nil {
+ t.Fatal(err)
+ }
+ if d := time.Since(start); d < 60*time.Millisecond || d > 2*time.Second {
+ t.Fatalf("2 MB through a limited slotConn took %s, want about 150-300 ms", d)
+ }
+}
+
+func TestSlotConnPacesReads(t *testing.T) {
+ sl := &Slot{}
+ sl.setLimit(80) // 10 MB/s
+ ln, err := net.Listen("tcp4", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer ln.Close()
+ go func() {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Write(make([]byte, 2<<20))
+ c.Close()
+ }()
+
+ raw, err := net.Dial("tcp4", ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := raw.(*net.TCPConn).SetReadBuffer(32 << 10); err != nil {
+ t.Fatal(err)
+ }
+ c := &slotConn{TCPConn: raw.(*net.TCPConn), sl: sl, fam: Fam4, s: NewScheduler(nil)}
+ defer c.Close()
+
+ const size = 2 << 20
+ buf := make([]byte, 64<<10)
+ start := time.Now()
+ read := 0
+ for read < size {
+ n, err := c.Read(buf)
+ read += n
+ if err != nil {
+ t.Fatalf("after %d bytes: %v", read, err)
+ }
+ }
+ if d := time.Since(start); d < 60*time.Millisecond || d > 2*time.Second {
+ t.Fatalf("2 MB through a limited slotConn.Read took %s, want about 150-300 ms", d)
+ }
+}
+
+func TestLimitsFollowAdapters(t *testing.T) {
+ s := NewScheduler([]nics.Nic{nic("A", "10.0.0.1", 1)})
+ s.SetLimit("A", 5)
+ s.SetLimit("B", 10) // not seen yet: saved for when it appears
+
+ limitOf := func(name string) float64 {
+ for _, st := range s.Snapshot() {
+ if st.Name == name {
+ return st.LimitMbps
+ }
+ }
+ t.Fatalf("adapter %q not in the snapshot", name)
+ return 0
+ }
+ if got := limitOf("A"); got != 5 {
+ t.Fatalf("A has limit %v, want 5", got)
+ }
+
+ s.Update([]nics.Nic{nic("A", "10.0.0.1", 1), nic("B", "10.0.0.2", 1)})
+ if got := limitOf("B"); got != 10 {
+ t.Fatalf("B came back with limit %v, want 10", got)
+ }
+ if limits := s.Limits(); len(limits) != 2 || limits["A"] != 5 || limits["B"] != 10 {
+ t.Fatalf("Limits() = %v, want A=5 B=10", limits)
+ }
+
+ s.SetLimits(map[string]float64{"C": 20})
+ if got := limitOf("A"); got != 0 {
+ t.Fatalf("A still has limit %v after SetLimits replaced the map", got)
+ }
+ if limits := s.Limits(); len(limits) != 1 || limits["C"] != 20 {
+ t.Fatalf("Limits() = %v, want only C=20", limits)
+ }
+ s.SetLimit("C", 0)
+ if limits := s.Limits(); len(limits) != 0 {
+ t.Fatalf("Limits() = %v after clearing C, want empty", limits)
+ }
+}
diff --git a/internal/engine/sched.go b/internal/engine/sched.go
index 5b927ff..182dfbc 100644
--- a/internal/engine/sched.go
+++ b/internal/engine/sched.go
@@ -48,6 +48,7 @@ type Slot struct {
actF [2]atomic.Int64
bytesIn, bytesOut [2]atomic.Int64
probing [2]atomic.Bool
+ limit atomic.Pointer[limitPair] // nil = unlimited; see limit.go
// guarded by Scheduler.mu
weight [2]float64
@@ -126,16 +127,18 @@ type SlotStats struct {
RateIn, RateOut float64 // through net-merge, both families summed (bytes/s)
LinkIn, LinkOut float64 // through the adapter by any app, from the OS's counters (bytes/s)
Peak, Peak6 float64
+ LimitMbps float64 // cap in Mbit/s, 0 = unlimited
}
// Scheduler uses weighted least-busy-flows per address family. Automatic mode
// discounts idle TCP sockets; static mode
// retains weighted least-open-flows. Data transfer accounting stays lock-free.
type Scheduler struct {
- mu sync.Mutex
- slots []*Slot
- auto bool
- now func() time.Time
+ mu sync.Mutex
+ slots []*Slot
+ auto bool
+ limits map[string]float64 // adapter name -> Mbit/s, 0 or absent = unlimited
+ now func() time.Time
}
func NewScheduler(nics []nics.Nic) *Scheduler {
@@ -151,6 +154,52 @@ func (s *Scheduler) SetAuto(on bool) {
s.mu.Unlock()
}
+// SetLimit caps an adapter at mbitPerSec Mbit/s across all of its flows and both address families;
+// 0 removes the cap. Saved in the scheduler, so an adapter that is unplugged and comes back keeps it.
+func (s *Scheduler) SetLimit(name string, mbitPerSec float64) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.limits == nil {
+ s.limits = map[string]float64{}
+ }
+ if mbitPerSec <= 0 {
+ delete(s.limits, name)
+ } else {
+ s.limits[name] = mbitPerSec
+ }
+ for _, sl := range s.slots {
+ if sl.key == name {
+ sl.setLimit(mbitPerSec)
+ }
+ }
+}
+
+// SetLimits replaces every cap, e.g. with what was saved on disk at startup.
+func (s *Scheduler) SetLimits(limits map[string]float64) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.limits = make(map[string]float64, len(limits))
+ for name, mbitPerSec := range limits {
+ if name != "" && mbitPerSec > 0 {
+ s.limits[name] = mbitPerSec
+ }
+ }
+ for _, sl := range s.slots {
+ sl.setLimit(s.limits[sl.key])
+ }
+}
+
+// Limits returns the caps by adapter name in Mbit/s, for saving and for `net-merge status`.
+func (s *Scheduler) Limits() map[string]float64 {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ out := make(map[string]float64, len(s.limits))
+ for name, mbitPerSec := range s.limits {
+ out[name] = mbitPerSec
+ }
+ return out
+}
+
func normAddr(n nics.Nic) *slotAddr {
a := &slotAddr{}
if n.IP != nil {
@@ -183,6 +232,7 @@ func (s *Scheduler) Update(nics []nics.Nic) {
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)
+ sl.setLimit(s.limits[n.Name])
s.slots = append(s.slots, sl)
continue
}
@@ -463,6 +513,7 @@ func (s *Scheduler) Snapshot() []SlotStats {
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],
+ LimitMbps: sl.limitMbps(),
}
if a.ip4 != nil {
st.IP, st.State = a.ip4.String(), sl.state[Fam4].String()
diff --git a/internal/state/limitfile_other.go b/internal/state/limitfile_other.go
new file mode 100644
index 0000000..d4f883e
--- /dev/null
+++ b/internal/state/limitfile_other.go
@@ -0,0 +1,9 @@
+//go:build !unix
+
+package state
+
+import "os"
+
+// openLimitFile opens a request for reading. Windows has no O_NOFOLLOW/O_NONBLOCK in syscall, so
+// there the regular-file check in readLimitRequest is the guard; ctl/ is not world-writable there.
+func openLimitFile(path string) (*os.File, error) { return os.Open(path) }
diff --git a/internal/state/limitfile_unix.go b/internal/state/limitfile_unix.go
new file mode 100644
index 0000000..2f0d960
--- /dev/null
+++ b/internal/state/limitfile_unix.go
@@ -0,0 +1,16 @@
+//go:build unix
+
+package state
+
+import (
+ "os"
+ "syscall"
+)
+
+// openLimitFile opens a request for reading without following a final symlink and without blocking
+// on a FIFO. Both matter because ctl/ is writable by every user: a symlink to /dev/zero would read
+// forever, and a FIFO would hold the tray's menu loop until someone wrote to it. With these flags
+// the open fails or returns at once, and readLimitRequest rejects whatever is not a regular file.
+func openLimitFile(path string) (*os.File, error) {
+ return os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW|syscall.O_NONBLOCK, 0)
+}
diff --git a/internal/state/limitrequest.go b/internal/state/limitrequest.go
new file mode 100644
index 0000000..b29d410
--- /dev/null
+++ b/internal/state/limitrequest.go
@@ -0,0 +1,85 @@
+package state
+
+import (
+ "encoding/json"
+ "io"
+ "os"
+ "path/filepath"
+)
+
+// A running tray or `run` may be elevated and cannot be signalled from a normal shell, so a limit
+// change travels through a file in ctl/, like the on/off markers. The instance applies it to its
+// scheduler and saves limits.json itself.
+//
+// ctl/ is world-writable (that is the point: a normal user has to be able to drop a request there),
+// so the elevated instance must treat what it finds as hostile. TakeLimit only trusts a small
+// regular file that it opened itself, never a symlink, a FIFO or anything that could grow.
+
+// LimitRequest is one adapter's new cap, in Mbit/s; 0 removes the cap.
+type LimitRequest struct {
+ Adapter string `json:"adapter"`
+ Mbps float64 `json:"mbps"`
+}
+
+// limitRequestMax is the most of ctl/limit that is read. A real request is well under 200 bytes;
+// the cap means a planted endless file cannot fill memory.
+const limitRequestMax = 4 << 10
+
+func limitRequestPath(dir string) string { return filepath.Join(dir, "ctl", "limit") }
+
+// SendLimit hands a cap to a running instance.
+func SendLimit(dir string, req LimitRequest) error {
+ if err := os.MkdirAll(filepath.Join(dir, "ctl"), 0o755); err != nil {
+ return err
+ }
+ b, err := json.Marshal(req)
+ if err != nil {
+ return err
+ }
+ tmp := limitRequestPath(dir) + ".tmp"
+ if err := os.WriteFile(tmp, b, 0o666); err != nil {
+ return err
+ }
+ return os.Rename(tmp, limitRequestPath(dir))
+}
+
+// TakeLimit consumes a pending request. The file is renamed aside before it is read, so a request
+// that arrives at the same moment cannot be deleted unread.
+func TakeLimit(dir string) (LimitRequest, bool) {
+ p := limitRequestPath(dir)
+ taken := p + ".taken"
+ os.Remove(taken) // left over if an earlier read failed
+ if err := os.Rename(p, taken); err != nil {
+ return LimitRequest{}, false
+ }
+ b, ok := readLimitRequest(taken)
+ os.Remove(taken)
+ if !ok {
+ return LimitRequest{}, false
+ }
+ var req LimitRequest
+ if json.Unmarshal(b, &req) != nil || req.Adapter == "" {
+ return LimitRequest{}, false
+ }
+ return req, true
+}
+
+// readLimitRequest reads a request file if it is a small regular file. Opening it must not follow a
+// symlink (which could point at /dev/zero) and must not block on a FIFO, hence openLimitFile.
+func readLimitRequest(path string) ([]byte, bool) {
+ f, err := openLimitFile(path)
+ if err != nil {
+ return nil, false
+ }
+ defer f.Close()
+ // Stat the open file, not the name: the file that was opened is the one that gets read.
+ st, err := f.Stat()
+ if err != nil || !st.Mode().IsRegular() {
+ return nil, false
+ }
+ b, err := io.ReadAll(io.LimitReader(f, limitRequestMax))
+ if err != nil {
+ return nil, false
+ }
+ return b, true
+}
diff --git a/internal/state/limitrequest_test.go b/internal/state/limitrequest_test.go
new file mode 100644
index 0000000..a5b7eea
--- /dev/null
+++ b/internal/state/limitrequest_test.go
@@ -0,0 +1,57 @@
+package state
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestLimitRequestRoundTrip(t *testing.T) {
+ dir := t.TempDir()
+ if req, ok := TakeLimit(dir); ok {
+ t.Fatalf("want no request, got %+v", req)
+ }
+ if err := SendLimit(dir, LimitRequest{Adapter: "Ethernet 2", Mbps: 7.5}); err != nil {
+ t.Fatal(err)
+ }
+ req, ok := TakeLimit(dir)
+ if !ok {
+ t.Fatal("want the request back")
+ }
+ if req.Adapter != "Ethernet 2" || req.Mbps != 7.5 {
+ t.Fatalf("got %+v", req)
+ }
+ if _, ok := TakeLimit(dir); ok {
+ t.Fatal("a request must be consumed exactly once")
+ }
+}
+
+func TestTakeLimitIgnoresGarbage(t *testing.T) {
+ dir := t.TempDir()
+ if err := SendLimit(dir, LimitRequest{Adapter: "Wi-Fi", Mbps: 2}); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(limitRequestPath(dir), []byte("not json"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if req, ok := TakeLimit(dir); ok {
+ t.Fatalf("want garbage ignored, got %+v", req)
+ }
+}
+
+// Only the first limitRequestMax bytes are read, so a valid-looking request that is too long is
+// refused rather than used (and a planted endless file cannot exhaust memory).
+func TestTakeLimitRefusesAnOversizedRequest(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(dir, "ctl"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ body := `{"adapter":"` + strings.Repeat("a", limitRequestMax) + `","mbps":5}`
+ if err := os.WriteFile(limitRequestPath(dir), []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if req, ok := TakeLimit(dir); ok {
+ t.Fatalf("accepted a %d-byte request: %+v", len(body), req)
+ }
+}
diff --git a/internal/state/limitrequest_unix_test.go b/internal/state/limitrequest_unix_test.go
new file mode 100644
index 0000000..671ffd6
--- /dev/null
+++ b/internal/state/limitrequest_unix_test.go
@@ -0,0 +1,61 @@
+//go:build unix
+
+package state
+
+import (
+ "os"
+ "path/filepath"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// ctl/ is writable by every user on the machine, and on macOS the tray that reads it runs as root.
+// A FIFO planted there must not be able to freeze the tray's menu loop.
+func TestTakeLimitDoesNotBlockOnAFifo(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(dir, "ctl"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := syscall.Mkfifo(limitRequestPath(dir), 0o666); err != nil {
+ t.Fatalf("mkfifo: %v", err)
+ }
+
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ if req, ok := TakeLimit(dir); ok {
+ t.Errorf("took a request from a FIFO: %+v", req)
+ }
+ }()
+ select {
+ case <-done:
+ case <-time.After(5 * time.Second):
+ t.Fatal("TakeLimit blocked on a FIFO")
+ }
+ if _, err := os.Stat(limitRequestPath(dir)); !os.IsNotExist(err) {
+ t.Fatalf("the FIFO should have been consumed, Stat: %v", err)
+ }
+}
+
+// A symlink to something endless (/dev/zero, a huge file) must be refused, not followed.
+func TestTakeLimitRefusesASymlink(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(dir, "ctl"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ target := filepath.Join(dir, "planted.json")
+ if err := os.WriteFile(target, []byte(`{"adapter":"Ethernet","mbps":1}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(target, limitRequestPath(dir)); err != nil {
+ t.Fatal(err)
+ }
+
+ if req, ok := TakeLimit(dir); ok {
+ t.Fatalf("followed a symlink and took %+v", req)
+ }
+ if _, err := os.Stat(target); err != nil {
+ t.Fatalf("the link's target was touched: %v", err)
+ }
+}
diff --git a/internal/state/limits.go b/internal/state/limits.go
new file mode 100644
index 0000000..5bc3857
--- /dev/null
+++ b/internal/state/limits.go
@@ -0,0 +1,73 @@
+package state
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "runtime"
+)
+
+const limitsVersion = 1
+
+type limitsFile struct {
+ Version int `json:"version"`
+ Limits map[string]float64 `json:"limits"`
+}
+
+// LimitsPath is where the per-adapter speed limits live: next to the status file, except on macOS,
+// where the status file is in /var/run and is gone after a reboot, so the caps go to Application
+// Support instead. A custom -state-dir keeps them in that directory, which is what someone passing
+// that flag expects.
+func LimitsPath(dir string) string {
+ return filepath.Join(limitsDir(dir), "limits.json")
+}
+
+func limitsDir(stateDir string) string { return limitsDirFor(runtime.GOOS, stateDir) }
+
+// limitsDirFor is limitsDir with the OS passed in, so the macOS rule can be tested anywhere.
+func limitsDirFor(goos, stateDir string) string {
+ if goos == "darwin" && stateDir == macStateDir {
+ return macLimitsDir
+ }
+ return stateDir
+}
+
+// LoadLimits reads the saved caps in Mbit/s. A missing file means no caps, not an error.
+func LoadLimits(dir string) (map[string]float64, error) {
+ b, err := os.ReadFile(LimitsPath(dir))
+ if errors.Is(err, os.ErrNotExist) {
+ return map[string]float64{}, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ var f limitsFile
+ if err := json.Unmarshal(b, &f); err != nil {
+ return nil, fmt.Errorf("%s: %w", LimitsPath(dir), err)
+ }
+ limits := make(map[string]float64, len(f.Limits))
+ for name, mbitPerSec := range f.Limits {
+ if name != "" && mbitPerSec > 0 && mbitPerSec <= 1e6 {
+ limits[name] = mbitPerSec
+ }
+ }
+ return limits, nil
+}
+
+// SaveLimits writes the caps atomically, so a crash mid-write cannot leave a broken file.
+func SaveLimits(dir string, limits map[string]float64) error {
+ if err := os.MkdirAll(limitsDir(dir), 0o755); err != nil {
+ return err
+ }
+ b, err := json.MarshalIndent(limitsFile{Version: limitsVersion, Limits: limits}, "", " ")
+ if err != nil {
+ return err
+ }
+ tmp := LimitsPath(dir) + ".tmp"
+ if err := os.WriteFile(tmp, append(b, '\n'), 0o644); err != nil {
+ return err
+ }
+ return os.Rename(tmp, LimitsPath(dir))
+}
diff --git a/internal/state/limits_test.go b/internal/state/limits_test.go
new file mode 100644
index 0000000..e550823
--- /dev/null
+++ b/internal/state/limits_test.go
@@ -0,0 +1,79 @@
+package state
+
+import (
+ "os"
+ "path/filepath"
+ "reflect"
+ "testing"
+)
+
+func TestLimitsRoundTrip(t *testing.T) {
+ dir := t.TempDir()
+ want := map[string]float64{"Ethernet 3": 10, "Wi-Fi": 2.5}
+ if err := SaveLimits(dir, want); err != nil {
+ t.Fatal(err)
+ }
+ got, err := LoadLimits(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("LoadLimits = %v, want %v", got, want)
+ }
+}
+
+func TestLoadLimitsWithoutAFile(t *testing.T) {
+ got, err := LoadLimits(t.TempDir())
+ if err != nil {
+ t.Fatalf("a missing limits file must not be an error: %v", err)
+ }
+ if len(got) != 0 {
+ t.Fatalf("want no limits, got %v", got)
+ }
+}
+
+func TestLoadLimitsSanitises(t *testing.T) {
+ dir := t.TempDir()
+ raw := `{"version":1,"limits":{"neg":-1,"zero":0,"huge":1e9,"ok":5,"":7}}`
+ if err := os.WriteFile(LimitsPath(dir), []byte(raw), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ got, err := LoadLimits(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[string]float64{"ok": 5}
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("LoadLimits = %v, want %v", got, want)
+ }
+}
+
+func TestLoadLimitsBrokenFile(t *testing.T) {
+ dir := t.TempDir()
+ if err := os.WriteFile(LimitsPath(dir), []byte("not json"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := LoadLimits(dir); err == nil {
+ t.Fatal("want an error for a broken limits file")
+ }
+}
+
+// macOS empties /var/run at boot, so caps kept there would be forgotten by the next morning.
+func TestLimitsSurviveARebootOnMacOS(t *testing.T) {
+ for _, c := range []struct {
+ goos, stateDir, want string
+ }{
+ {"darwin", macStateDir, macLimitsDir},
+ {"linux", macStateDir, macStateDir},
+ {"windows", `C:\Users\me\AppData\Local\net-merge`, `C:\Users\me\AppData\Local\net-merge`},
+ {"darwin", "/tmp/somewhere-else", "/tmp/somewhere-else"}, // a custom -state-dir is left alone
+ } {
+ got := limitsDirFor(c.goos, c.stateDir)
+ if got != c.want {
+ t.Errorf("limitsDirFor(%s, %q) = %q, want %q", c.goos, c.stateDir, got, c.want)
+ }
+ }
+ if got, want := LimitsPath(macStateDir), filepath.Join(limitsDir(macStateDir), "limits.json"); got != want {
+ t.Errorf("LimitsPath(%q) = %q, want %q", macStateDir, got, want)
+ }
+}
diff --git a/internal/state/state.go b/internal/state/state.go
index 8823118..eda02a2 100644
--- a/internal/state/state.go
+++ b/internal/state/state.go
@@ -14,6 +14,15 @@ import (
// a per-user directory: status.json (written once a second while on) and marker files
// ("on", "off", "quit") that the running instance consumes.
+// macStateDir is where the macOS tray keeps its status and markers. It is under /var/run because
+// the tray runs as root but is driven by a normal user, so the directory has to be root-owned.
+const macStateDir = "/var/run/net-merge"
+
+// macLimitsDir is where the caps live on macOS: /var/run is emptied at boot, and a metered-tether
+// cap that forgets itself after a reboot is worse than no cap at all. Application Support is the
+// usual place for a setting that has to stay.
+const macLimitsDir = "/Library/Application Support/net-merge"
+
type Status struct {
PID int
Mode string
@@ -27,7 +36,7 @@ func DefaultDir() string {
// The macOS tray runs as root but is commanded by the user, so its state can't live in a
// user-owned directory (root would follow a planted symlink): a fixed root-owned path.
if runtime.GOOS == "darwin" {
- return "/var/run/net-merge"
+ return macStateDir
}
base, err := os.UserCacheDir()
if err != nil {
diff --git a/internal/tray/tray.go b/internal/tray/tray.go
index b029cfb..fe9e4e4 100644
--- a/internal/tray/tray.go
+++ b/internal/tray/tray.go
@@ -4,6 +4,7 @@ package tray
import (
"fmt"
+ "math"
"strings"
"time"
"unicode/utf16"
@@ -45,6 +46,11 @@ type trayUI struct {
ap autoPauser
+ limitClicks chan limitClick
+ rowNames [trayRows]string
+ limitUnlim [trayRows]*systray.MenuItem
+ limitPreset [trayRows][]*systray.MenuItem
+
header, toggleItem, v6Item, autoItem, signInItem *systray.MenuItem
versionItem *systray.MenuItem
rows []*systray.MenuItem
@@ -65,11 +71,27 @@ func (u *trayUI) onReady() {
u.header = systray.AddMenuItem("net-merge", "")
u.header.Disable()
systray.AddSeparator()
+ u.limitClicks = make(chan limitClick, trayRows)
for i := 0; i < trayRows; i++ {
- r := systray.AddMenuItem("", "")
- r.Disable()
- r.Hide()
+ r := systray.AddMenuItem("", "Click to cap this adapter's speed (download and upload)")
u.rows = append(u.rows, r)
+ addLimit := func(mbitPerSec float64, title string) *systray.MenuItem {
+ it := r.AddSubMenuItemCheckbox(title, limitTip(mbitPerSec), false)
+ go func() {
+ for range it.ClickedCh {
+ u.limitClicks <- limitClick{row: i, mbitPerSec: mbitPerSec}
+ }
+ }()
+ return it
+ }
+ u.limitUnlim[i] = addLimit(0, "Unlimited")
+ for _, mbitPerSec := range limitPresets {
+ u.limitPreset[i] = append(u.limitPreset[i], addLimit(mbitPerSec, limitText(mbitPerSec)))
+ }
+ // Add the children while the row is still in the menu: on Windows a hidden item is
+ // removed from the menu, so converting it to a submenu afterwards fails and only the
+ // entries added later (when they are first checked) would appear.
+ r.Hide()
}
systray.AddSeparator()
u.v6Item = systray.AddMenuItemCheckbox("Use all adapters (IPv6 only if every adapter has it)", "Ticked: apps are pushed to IPv4 so every adapter is used. Unticked: IPv6 is allowed and funnels onto the adapters that have it.", u.bal.V6Mode() == engine.V6Auto)
@@ -130,10 +152,19 @@ func (u *trayUI) onReady() {
if err := platform.OpenURL(update.ReleasesURL); err != nil {
logx.Printf("error: opening the release page: %v\n", err)
}
+ case c := <-u.limitClicks:
+ if c.name != "" {
+ u.applyLimit(c.name, c.mbitPerSec)
+ } else {
+ u.applyLimit(u.rowNames[c.row], c.mbitPerSec)
+ }
case <-quit.ClickedCh:
systray.Quit()
return
case <-tick.C:
+ if req, ok := state.TakeLimit(u.stateDir); ok { // `net-merge limit ...` from a terminal
+ u.applyLimit(req.Adapter, req.Mbps)
+ }
switch { // `net-merge on|off|quit` from a terminal
case state.TakeMarker(u.stateDir, "quit"):
systray.Quit()
@@ -249,11 +280,16 @@ func (u *trayUI) refresh() {
if u.lastRows[i] != "" {
r.Hide()
u.lastRows[i] = ""
+ u.rowNames[i] = ""
}
continue
}
s := live[i]
+ u.rowNames[i] = s.Name
txt := fmt.Sprintf("%s: ↓%s ↑%s Mbps", s.Name, mbps(s.LinkIn), mbps(s.LinkOut))
+ if s.LimitMbps > 0 {
+ txt += " limit " + limitText(s.LimitMbps)
+ }
if on {
txt += fmt.Sprintf(" (%d flows via net-merge)", s.Active)
}
@@ -268,6 +304,7 @@ func (u *trayUI) refresh() {
r.Show()
u.lastRows[i] = txt
}
+ u.showLimit(i, s.LimitMbps)
}
// Hover tooltip: one line per adapter, so speeds are visible without opening the menu.
@@ -386,3 +423,67 @@ func shorten(s string, n int) string {
}
return s
}
+
+// limitPresets are the caps offered in each adapter's submenu, in Mbit/s.
+var limitPresets = []float64{1, 2, 5, 10, 20, 50, 100}
+
+type limitClick struct {
+ row int
+ name string // set by `net-merge limit`, which knows the adapter by name, not row
+ mbitPerSec float64
+}
+
+func limitLabel(mbitPerSec float64) string {
+ if mbitPerSec == math.Trunc(mbitPerSec) {
+ return fmt.Sprintf("%.0f", mbitPerSec)
+ }
+ return fmt.Sprintf("%.1f", mbitPerSec)
+}
+
+// limitText is a cap as the menu and status line show it, e.g. "12.5 Mbit/s".
+func limitText(mbitPerSec float64) string {
+ return limitLabel(mbitPerSec) + " Mbit/s"
+}
+
+func limitTip(mbitPerSec float64) string {
+ if mbitPerSec <= 0 {
+ return "No cap: the adapter may use its full speed."
+ }
+ return "Cap this adapter at " + limitText(mbitPerSec) +
+ " for downloads and uploads, across all of its flows. Takes effect immediately."
+}
+
+// showLimit ticks the cap the adapter shown in row is using.
+func (u *trayUI) showLimit(row int, mbitPerSec float64) {
+ tick := func(it *systray.MenuItem, want bool) {
+ if it != nil && it.Checked() != want {
+ if want {
+ it.Check()
+ } else {
+ it.Uncheck()
+ }
+ }
+ }
+ tick(u.limitUnlim[row], mbitPerSec <= 0)
+ for i, it := range u.limitPreset[row] {
+ tick(it, math.Abs(limitPresets[i]-mbitPerSec) < 0.01)
+ }
+}
+
+// applyLimit caps the adapter with this name; 0 removes the cap. It runs on the menu goroutine,
+// so the checkmarks can be updated right away instead of on the next refresh.
+func (u *trayUI) applyLimit(name string, mbitPerSec float64) {
+ if name == "" {
+ return
+ }
+ u.sched.SetLimit(name, mbitPerSec)
+ if err := state.SaveLimits(u.stateDir, u.sched.Limits()); err != nil {
+ u.lastErr = "speed limit: " + err.Error()
+ logx.Printf("error: %v\n", err)
+ }
+ for i, n := range u.rowNames {
+ if n == name {
+ u.showLimit(i, mbitPerSec)
+ }
+ }
+}
diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go
index b2832c0..b4b4235 100644
--- a/internal/tray/tray_test.go
+++ b/internal/tray/tray_test.go
@@ -70,3 +70,25 @@ func TestTrayTooltipFitsWindowsLimit(t *testing.T) {
}
}
}
+
+func TestLimitLabel(t *testing.T) {
+ for in, want := range map[float64]string{1: "1", 2.5: "2.5", 100: "100"} {
+ if got := limitLabel(in); got != want {
+ t.Errorf("limitLabel(%v) = %q, want %q", in, got, want)
+ }
+ }
+}
+
+func TestLimitTextUsesMbit(t *testing.T) {
+ for in, want := range map[float64]string{1: "1 Mbit/s", 12.5: "12.5 Mbit/s", 1000: "1000 Mbit/s"} {
+ if got := limitText(in); got != want {
+ t.Errorf("limitText(%v) = %q, want %q", in, got, want)
+ }
+ }
+ if tip := limitTip(20); !strings.Contains(tip, "20 Mbit/s") {
+ t.Errorf("limitTip(20) = %q, want it to say 20 Mbit/s", tip)
+ }
+ if tip := limitTip(0); !strings.Contains(tip, "full speed") {
+ t.Errorf("limitTip(0) = %q, want it to describe no cap", tip)
+ }
+}