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

Pause by itself with one connection, resume with two (#12)

Rohit Mahto09906fd39f0f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aca947d..c66073d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,17 @@ entry here before pushing a version tag.
## [Unreleased]
+### Added
+- **Pauses by itself when only one connection works, and resumes when two do.** With fewer than two
+ connections that reach the internet there is nothing to merge, so the tray pauses merging ("Paused: one
+ connection") and starts it again when a second connection works. Pausing or starting by hand always wins,
+ and it waits for things to settle first: 10 seconds with nothing moving (2 minutes if a download or
+ upload is still going) before pausing, 3 seconds before resuming, and at least 30 seconds between automatic switches.
+ Untick *Pause when there is only one connection* in the tray menu, or run `net-merge tray -auto-pause=false`.
+
### Changed
+- On macOS, pausing and resuming no longer removes and recreates the virtual adapter, so it no longer
+ drops a TetherKit (Android) link. Starting and quitting still do.
- New connections no longer wait while the once-a-second adapter speed reading runs (thanks @b0r1ssh).
## [0.2.0] - 2026-10-16
diff --git a/README.md b/README.md
index 96f77c6..b6fac94 100644
--- a/README.md
+++ b/README.md
@@ -141,8 +141,8 @@ macOS cannot use Android USB tethering by itself. The app **TetherKit** adds tha
3. Click **Apply** in TetherKit. net-merge adds the new network in a few seconds.
> **Start net-merge first, then connect the Android phone.** macOS drops the TetherKit connection each
-> time net-merge starts, quits, or is paused and resumed. If the phone link disappears, click **Apply**
-> in TetherKit again. The iPhone is not affected.
+> time net-merge starts or quits. Pausing and resuming is safe: net-merge keeps its virtual adapter while
+> paused. If the phone link disappears, click **Apply** in TetherKit again. The iPhone is not affected.
A phone uses its mobile data, so part of your traffic goes through it while net-merge runs. Quit
net-merge when you do not want that.
@@ -151,10 +151,15 @@ net-merge when you do not want that.
1. Start net-merge. A tray icon appears (menu bar on Mac).
2. The icon is **green** when it is merging and **grey** when it is paused.
-3. **Hover** the icon to see the speed of each connection and the total.
-4. **Right-click** the icon (on Mac, click it) to open the menu. It shows each connection's speed, how
+3. **It pauses by itself** when fewer than two connections have internet, because there is nothing to
+ merge, and the menu says *Paused: one connection*. It **starts again by itself** when a second
+ connection works. If you pause or start it yourself, that choice wins: it will not start again after
+ you paused it. Untick *Pause when there is only one connection* in the menu to switch this off, or run
+ `net-merge tray -auto-pause=false`.
+4. **Hover** the icon to see the speed of each connection and the total.
+5. **Right-click** the icon (on Mac, click it) to open the menu. It shows each connection's speed, how
many connections net-merge gave it, and the buttons *Pause merging* / *Start merging* and *Quit*.
-5. To start it at sign-in: tick the box in the Windows installer, or run `net-merge autostart on`.
+6. To start it at sign-in: tick the box in the Windows installer, or run `net-merge autostart on`.
Tips:
- Torrent clients already use every connection. Leave qBittorrent's network interface on *Any interface*.
@@ -196,8 +201,8 @@ Run `net-merge list`. It shows which connections are used and why the others are
<summary><strong>The Android connection disappears on a Mac</strong></summary>
<br>
-macOS drops the TetherKit connection each time net-merge starts, quits, or is paused and resumed. Start
-net-merge first, then connect the phone. If it vanishes, click **Apply** in TetherKit again.
+macOS drops the TetherKit connection each time net-merge starts or quits (pausing and resuming is safe).
+Start net-merge first, then connect the phone. If it vanishes, click **Apply** in TetherKit again.
</details>
<details>
@@ -217,6 +222,21 @@ The apps are not code-signed yet. On macOS run `xattr -d com.apple.quarantine ne
*More info*, then *Run anyway*.
</details>
+<details>
+<summary><strong>The menu says "Paused: one connection"</strong></summary>
+<br>
+
+net-merge only has something to do with two or more connections that have internet, so it waits. Plug
+in or connect the second one (see *Add a second connection*) and it starts by itself after a few seconds.
+To merge anyway, choose *Start merging* (it then stays on until a second connection has come and gone), or
+untick *Pause when there is only one connection*.
+
+Switching merging on or off cuts the connections that are open at that moment, which is why it waits 10
+seconds with nothing moving before pausing (2 minutes if a download or upload is still going) and
+3 seconds before resuming,
+and never switches by itself more than once every 30 seconds.
+</details>
+
<details>
<summary><strong>I cannot find the tray icon</strong></summary>
<br>
diff --git a/cmd/net-merge/main.go b/cmd/net-merge/main.go
index 75bc698..477ba8a 100644
--- a/cmd/net-merge/main.go
+++ b/cmd/net-merge/main.go
@@ -382,7 +382,7 @@ func cmdRun(args []string) {
}
break
}
- t.Off()
+ t.Close()
state.Clear(c.stateDir)
logx.Printf("net-merge is OFF.\n")
}
diff --git a/cmd/net-merge/tray.go b/cmd/net-merge/tray.go
index dcbd426..3a3c56e 100644
--- a/cmd/net-merge/tray.go
+++ b/cmd/net-merge/tray.go
@@ -22,6 +22,7 @@ func cmdTray(args []string) {
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)")
+ autoPause := fs.Bool("auto-pause", true, "pause by itself when fewer than two connections work, and resume when two do (pausing by hand always wins)")
fs.Parse(args)
if !platform.IsAdmin() {
@@ -84,9 +85,9 @@ func cmdTray(args []string) {
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
go func() { // logout, `launchctl bootout`, kill: turn off cleanly instead of leaving routes behind
<-sig
- t.Off()
+ t.Close()
state.Clear(c.stateDir)
os.Exit(0)
}()
- tray.Run(t, sched, bal, c.stateDir, !*startOff, ready)
+ tray.Run(t, sched, bal, c.stateDir, !*startOff, *autoPause, ready)
}
diff --git a/internal/tray/autopause.go b/internal/tray/autopause.go
new file mode 100644
index 0000000..79f44f4
--- /dev/null
+++ b/internal/tray/autopause.go
@@ -0,0 +1,105 @@
+package tray
+
+import "time"
+
+// Pausing by itself: with fewer than two usable connections there is nothing to merge, so merging
+// pauses, and it resumes once a second connection works. A switch cuts the connections that are
+// open at that moment, so both directions wait for things to settle, and automatic switches are
+// spaced apart so a flapping link can't toggle it all the time.
+const (
+ pauseAfterIdle = 10 * time.Second // one connection and nothing moving through net-merge
+ pauseAfterBusy = 2 * time.Minute // one connection but data is still moving: give it time to end
+ resumeAfter = 3 * time.Second // two or more connections
+ autoGap = 30 * time.Second // least time between two automatic switches
+ quietRate = 50_000 // bytes/s through net-merge under which it counts as quiet (about 0.4 Mbit/s)
+)
+
+type autoAction int
+
+const (
+ autoNone autoAction = iota
+ autoPause
+ autoResume
+)
+
+type autoPauser struct {
+ enabled bool
+ manualOff bool // the user paused it: it never starts by itself
+ held bool // the user started it with one connection: no auto-pause until two have been seen
+ waiting bool // paused by us, or not started yet: resumes when two connections are usable
+ low, high time.Duration
+ quiet time.Duration // how long nothing has been moving
+ lastTick time.Time
+ lastSwitch time.Time
+}
+
+// start sets the first state: startOn false means the user asked for it to stay off.
+func (a *autoPauser) start(startOn bool) {
+ if !startOn {
+ a.manualOff = true
+ } else if a.enabled {
+ a.waiting = true
+ }
+}
+
+// tick runs about once a second. on is whether merging is on, usable how many connections reach
+// the internet, active how many flows are moving data through net-merge (0 when it is quiet).
+func (a *autoPauser) tick(now time.Time, on bool, usable int, active int64) autoAction {
+ dt := time.Second
+ if d := now.Sub(a.lastTick); !a.lastTick.IsZero() && d > 0 && d < 2*time.Second {
+ dt = d // after a sleep one second counts, not the whole gap
+ }
+ a.lastTick = now
+ if active == 0 {
+ a.quiet += dt
+ } else {
+ a.quiet = 0
+ }
+ if !a.enabled {
+ a.low, a.high = 0, 0
+ return autoNone
+ }
+ if usable >= 2 {
+ a.held = false
+ }
+ cooling := !a.lastSwitch.IsZero() && now.Sub(a.lastSwitch) < autoGap
+ switch {
+ case on && usable < 2 && !a.held:
+ a.low, a.high = a.low+dt, 0
+ settled := a.low >= pauseAfterIdle && a.quiet >= pauseAfterIdle
+ if (settled || a.low >= pauseAfterBusy) && !cooling {
+ a.low, a.waiting, a.lastSwitch = 0, true, now
+ return autoPause
+ }
+ case !on && a.waiting && !a.manualOff && usable >= 2:
+ a.high, a.low = a.high+dt, 0
+ if a.high >= resumeAfter && !cooling {
+ a.high, a.waiting, a.lastSwitch = 0, false, now
+ return autoResume
+ }
+ default:
+ a.low, a.high = 0, 0
+ }
+ return autoNone
+}
+
+// userSet records that the user switched merging on or off (menu or `net-merge on|off`).
+func (a *autoPauser) userSet(on bool, usable int) {
+ a.low, a.high = 0, 0
+ a.waiting = false
+ a.manualOff = !on
+ a.held = on && usable < 2
+}
+
+// setEnabled is the menu checkbox.
+func (a *autoPauser) setEnabled(enabled, on bool) {
+ a.enabled = enabled
+ a.low, a.high = 0, 0
+ if enabled && !on && !a.manualOff {
+ a.waiting = true
+ }
+}
+
+// resumeFailed puts back the wait after an automatic switch-on that did not work; it tries again
+// after the gap.
+func (a *autoPauser) resumeFailed() { a.waiting = true }
diff --git a/internal/tray/autopause_test.go b/internal/tray/autopause_test.go
new file mode 100644
index 0000000..ebfec99
--- /dev/null
+++ b/internal/tray/autopause_test.go
@@ -0,0 +1,156 @@
+package tray
+
+import (
+ "testing"
+ "time"
+)
+
+// run feeds the machine one tick per second for d, returning the first action and when it came.
+func run(a *autoPauser, now *time.Time, d time.Duration, on bool, usable int, active int64) (autoAction, time.Duration) {
+ for el := time.Duration(0); el < d; el += time.Second {
+ *now = now.Add(time.Second)
+ if act := a.tick(*now, on, usable, active); act != autoNone {
+ return act, el + time.Second
+ }
+ }
+ return autoNone, 0
+}
+
+func newPauser(startOn bool) (*autoPauser, *time.Time) {
+ a := &autoPauser{enabled: true}
+ a.start(startOn)
+ now := time.Unix(1_000_000, 0)
+ return a, &now
+}
+
+func TestPausesAfterTenIdleSecondsWithOneConnection(t *testing.T) {
+ a, now := newPauser(false)
+ a.manualOff, a.waiting = false, false // running, as if started by hand earlier and released
+ if act, _ := run(a, now, 9*time.Second, true, 1, 0); act != autoNone {
+ t.Fatal("paused too early")
+ }
+ if act, at := run(a, now, 3*time.Second, true, 1, 0); act != autoPause || at != time.Second {
+ t.Fatalf("want a pause on the 10th second, got %v after %v", act, at)
+ }
+}
+
+func TestBusyFlowsDelayThePause(t *testing.T) {
+ a, now := newPauser(true)
+ a.waiting = false
+ if act, _ := run(a, now, 100*time.Second, true, 1, 5); act != autoNone {
+ t.Fatal("paused while flows were open")
+ }
+ if act, _ := run(a, now, 30*time.Second, true, 1, 5); act != autoPause {
+ t.Fatal("should pause after two minutes even with open flows")
+ }
+}
+
+func TestAShortStallDoesNotPause(t *testing.T) {
+ a, now := newPauser(true)
+ a.waiting = false
+ run(a, now, 30*time.Second, true, 1, 5) // a transfer is going
+ if act, _ := run(a, now, 9*time.Second, true, 1, 0); act != autoNone {
+ t.Fatal("paused during a short stall")
+ }
+ if act, at := run(a, now, 3*time.Second, true, 1, 0); act != autoPause || at != time.Second {
+ t.Fatalf("want a pause after 10 quiet seconds, got %v after %v", act, at)
+ }
+}
+
+func TestSecondConnectionResetsThePauseTimer(t *testing.T) {
+ a, now := newPauser(true)
+ a.waiting = false
+ run(a, now, 8*time.Second, true, 1, 0)
+ run(a, now, 1*time.Second, true, 2, 0) // a second link appeared for a moment
+ if act, _ := run(a, now, 8*time.Second, true, 1, 0); act != autoNone {
+ t.Fatal("the timer should have restarted")
+ }
+}
+
+func TestStartsPausedAndResumesWithTwoConnections(t *testing.T) {
+ a, now := newPauser(true) // tray started, auto on: waits for two connections
+ if act, _ := run(a, now, 60*time.Second, false, 1, 0); act != autoNone {
+ t.Fatal("must stay paused with one connection")
+ }
+ if act, at := run(a, now, 10*time.Second, false, 2, 0); act != autoResume || at != 3*time.Second {
+ t.Fatalf("want a resume after 3s of two connections, got %v after %v", act, at)
+ }
+}
+
+func TestManualOffIsNeverUndone(t *testing.T) {
+ a, now := newPauser(true)
+ a.userSet(false, 2) // the user pauses it
+ if act, _ := run(a, now, 120*time.Second, false, 3, 0); act != autoNone {
+ t.Fatal("resumed something the user paused")
+ }
+ a.userSet(true, 3) // and starts it again
+ if a.manualOff {
+ t.Fatal("starting it clears the manual pause")
+ }
+}
+
+func TestStartedWithOffFlagStaysOff(t *testing.T) {
+ a, now := newPauser(false)
+ if act, _ := run(a, now, 60*time.Second, false, 2, 0); act != autoNone {
+ t.Fatal("-off means off until the user says otherwise")
+ }
+}
+
+func TestManualStartWithOneConnectionIsHeldUntilTwoAreSeen(t *testing.T) {
+ a, now := newPauser(true)
+ a.userSet(true, 1) // the user starts it on purpose with one connection
+ if act, _ := run(a, now, 300*time.Second, true, 1, 0); act != autoNone {
+ t.Fatal("paused something the user started on purpose")
+ }
+ run(a, now, 2*time.Second, true, 2, 0) // two connections seen: normal rules again
+ if act, _ := run(a, now, 15*time.Second, true, 1, 0); act != autoPause {
+ t.Fatal("should pause once the second connection is gone again")
+ }
+}
+
+func TestSwitchesAreSpacedApart(t *testing.T) {
+ a, now := newPauser(true)
+ a.waiting = false
+ if act, _ := run(a, now, 15*time.Second, true, 1, 0); act != autoPause {
+ t.Fatal("expected the first pause")
+ }
+ // the second link comes back at once: resume has to wait out the 30 s gap
+ act, at := run(a, now, 60*time.Second, false, 2, 0)
+ if act != autoResume || at < autoGap-10*time.Second {
+ t.Fatalf("resume came too soon (%v after %v)", act, at)
+ }
+}
+
+func TestSleepGapCountsAsOneSecond(t *testing.T) {
+ a, now := newPauser(true)
+ a.waiting = false
+ a.tick(*now, true, 1, 0)
+ *now = now.Add(8 * time.Hour) // laptop slept
+ if act := a.tick(*now, true, 1, 0); act != autoNone {
+ t.Fatal("a long gap must not count as a long time with one connection")
+ }
+}
+
+func TestDisabledDoesNothing(t *testing.T) {
+ a, now := newPauser(true)
+ a.enabled, a.waiting = false, false
+ if act, _ := run(a, now, 600*time.Second, true, 0, 0); act != autoNone {
+ t.Fatal("acted while disabled")
+ }
+ a.setEnabled(true, false) // ticking the box while paused: it will resume when two links are up
+ if !a.waiting {
+ t.Fatal("enabling while paused should wait for two connections")
+ }
+}
+
+func TestFailedResumeIsRetriedAfterTheGap(t *testing.T) {
+ a, now := newPauser(true)
+ if act, _ := run(a, now, 10*time.Second, false, 2, 0); act != autoResume {
+ t.Fatal("expected a resume")
+ }
+ a.resumeFailed()
+ act, at := run(a, now, 90*time.Second, false, 2, 0)
+ if act != autoResume || at < autoGap-10*time.Second {
+ t.Fatalf("retry should wait for the gap, got %v after %v", act, at)
+ }
+}
diff --git a/internal/tray/tray.go b/internal/tray/tray.go
index 6848995..95d7886 100644
--- a/internal/tray/tray.go
+++ b/internal/tray/tray.go
@@ -19,12 +19,13 @@ import (
const trayRows = 4 // adapters shown in the menu; extra rows stay hidden
-// Run shows the tray icon and blocks until Quit. It turns merging on at once if startOn, and
-// closes ready once the icon exists.
-func Run(t *tun.Tun, sched *engine.Scheduler, bal *engine.Balancer, stateDir string, startOn bool, ready chan struct{}) {
+// Run shows the tray icon and blocks until Quit, and closes ready once the icon exists. With
+// startOn it merges as soon as it can (at once, or, with autoPause, once two connections work).
+func Run(t *tun.Tun, sched *engine.Scheduler, bal *engine.Balancer, stateDir string, startOn, autoPause bool, ready chan struct{}) {
ui := &trayUI{tun: t, sched: sched, bal: bal, stateDir: stateDir, startOn: startOn,
iconOn: icon.Tray(true), iconOff: icon.Tray(false), ready: ready}
- exit := func() { t.Off(); state.Clear(stateDir) }
+ ui.ap.enabled = autoPause
+ exit := func() { t.Close(); state.Clear(stateDir) }
systray.Run(ui.onReady, exit)
exit() // macOS's Run returns on Quit without calling onExit; both are idempotent
}
@@ -39,14 +40,16 @@ type trayUI struct {
iconOff []byte
ready chan struct{} // closed once the tray icon exists
- header, toggleItem, v6Item *systray.MenuItem
- rows []*systray.MenuItem
- lastOn *bool
- lastHeader string
- lastTip string
- lastRows [trayRows]string
- lastErr string
- busyUntil time.Time
+ ap autoPauser
+
+ header, toggleItem, v6Item, autoItem *systray.MenuItem
+ rows []*systray.MenuItem
+ lastOn *bool
+ lastHeader string
+ lastTip string
+ lastRows [trayRows]string
+ lastErr string
+ busyUntil time.Time
}
func (u *trayUI) onReady() {
@@ -66,11 +69,21 @@ func (u *trayUI) onReady() {
}
systray.AddSeparator()
u.v6Item = systray.AddMenuItemCheckbox("Use all adapters (IPv6 only if every adapter has it)", "Ticked: apps are pushed to IPv4 so every adapter is used. Unticked: IPv6 is allowed and funnels onto the adapters that have it.", u.bal.V6Mode() == engine.V6Auto)
+ u.autoItem = systray.AddMenuItemCheckbox("Pause when there is only one connection", "Pauses merging by itself when fewer than two connections have internet, and starts it again when a second one works. Pausing or starting by hand always wins.", u.ap.enabled)
u.toggleItem = systray.AddMenuItem("Start merging", "")
quit := systray.AddMenuItem("Quit", "Turns system-wide mode off and exits")
go func() {
- if u.startOn {
+ u.ap.start(u.startOn)
+ switch {
+ case !u.startOn:
+ case u.ap.enabled:
+ // Merging starts when two connections work. The adapter is made now, before a phone is
+ // plugged in, because on macOS making it later would drop that phone's link.
+ if err := u.tun.Warm(); err != nil {
+ logx.Printf("warning: %v\n", err)
+ }
+ default:
u.turn(true)
}
tick := time.NewTicker(time.Second)
@@ -79,7 +92,14 @@ func (u *trayUI) onReady() {
u.refresh()
select {
case <-u.toggleItem.ClickedCh:
- u.turn(!u.tun.IsOn())
+ u.manual(!u.tun.IsOn())
+ case <-u.autoItem.ClickedCh:
+ if u.autoItem.Checked() {
+ u.autoItem.Uncheck()
+ } else {
+ u.autoItem.Check()
+ }
+ u.ap.setEnabled(u.autoItem.Checked(), u.tun.IsOn())
case <-u.v6Item.ClickedCh:
if u.v6Item.Checked() {
u.v6Item.Uncheck()
@@ -97,15 +117,55 @@ func (u *trayUI) onReady() {
systray.Quit()
return
case state.TakeMarker(u.stateDir, "off"):
- u.turn(false)
+ u.manual(false)
case state.TakeMarker(u.stateDir, "on"):
- u.turn(true)
+ u.manual(true)
+ }
+ switch u.ap.tick(time.Now(), u.tun.IsOn(), u.usable(), u.movingFlows()) {
+ case autoPause:
+ u.turn(false)
+ case autoResume:
+ if u.turn(true); !u.tun.IsOn() {
+ u.ap.resumeFailed()
+ }
}
}
}
}()
}
+// manual is a switch by the user (menu or `net-merge on|off`), which pausing by itself must respect.
+func (u *trayUI) manual(on bool) {
+ u.ap.userSet(on, u.usable())
+ u.turn(on)
+}
+
+// usable is how many connections reach the internet right now.
+func (u *trayUI) usable() (n int) {
+ for _, s := range u.sched.Snapshot() {
+ if s.Present && (s.State == "up" || s.State6 == "up") {
+ n++
+ }
+ }
+ return n
+}
+
+// movingFlows is how many connections net-merge is relaying while data is really moving. Idle
+// keep-alive connections are always open, so they don't count and don't hold back a pause.
+func (u *trayUI) movingFlows() (n int64) {
+ var rate float64
+ for _, s := range u.sched.Snapshot() {
+ if s.Present {
+ n += s.Active
+ rate += s.RateIn + s.RateOut
+ }
+ }
+ if rate < quietRate {
+ return 0
+ }
+ return n
+}
+
func (u *trayUI) turn(on bool) {
u.lastErr = ""
if !on {
@@ -152,6 +212,9 @@ func (u *trayUI) refresh() {
}
}
state := stateWord(on)
+ if !on && u.ap.enabled && u.ap.waiting && !u.ap.manualOff {
+ state = "Paused: one connection"
+ }
if u.lastErr != "" {
u.setHeader("Error: " + shorten(u.lastErr, 70))
diff --git a/internal/tun/tun.go b/internal/tun/tun.go
index 7e60d1f..d858fc6 100644
--- a/internal/tun/tun.go
+++ b/internal/tun/tun.go
@@ -97,12 +97,13 @@ func (t *Tun) IsOn() bool {
return t.on
}
-func (t *Tun) On() (err error) {
- t.mu.Lock()
- defer t.mu.Unlock()
- if t.on {
- return nil
- }
+// keepDevice makes Off pause instead of tear down: only the capture routes go, the adapter stays.
+// macOS sets it, because there taking a utun away or adding one makes the system drop other
+// virtual links such as a TetherKit phone, so pausing and resuming must never touch the adapter.
+var keepDevice bool
+
+// open creates the adapter and the userland stack, without capturing anything yet.
+func (t *Tun) open() error {
// "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 {
@@ -126,6 +127,31 @@ func (t *Tun) On() (err error) {
}
installForwarders(stk, t.B.V6Allowed)
t.dev, t.stk = dev, stk
+ return nil
+}
+
+// Warm creates the adapter ahead of time, so a later On only adds routes. Only platforms with
+// keepDevice need it; elsewhere it does nothing.
+func (t *Tun) Warm() error {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if !keepDevice || t.dev != nil {
+ return nil
+ }
+ return t.open()
+}
+
+func (t *Tun) On() (err error) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.on {
+ return nil
+ }
+ if t.dev == nil {
+ if err = t.open(); err != nil {
+ return err
+ }
+ }
defer func() {
if err != nil {
t.teardown()
@@ -133,14 +159,30 @@ func (t *Tun) On() (err error) {
}()
tunnel.T().SetProxy(tunProxy{t.B})
- if t.idx, err = configure(dev.Name(), t.MTU); err != nil {
+ if t.idx, err = configure(t.dev.Name(), t.MTU); err != nil {
return err
}
t.on = true
return nil
}
+// Off stops capturing: with keepDevice it only removes the routes, otherwise it removes the adapter.
func (t *Tun) Off() {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if keepDevice && t.dev != nil {
+ if t.idx != 0 {
+ delRoutes(t.idx) // traffic falls straight back to the normal default route
+ }
+ tunnel.T().SetProxy(&reject.Reject{})
+ t.on = false
+ return
+ }
+ t.teardown()
+}
+
+// Close removes everything, including a kept adapter. Call it when the program exits.
+func (t *Tun) Close() {
t.mu.Lock()
defer t.mu.Unlock()
t.teardown()
diff --git a/internal/tun/tun_darwin.go b/internal/tun/tun_darwin.go
index 03865d7..9d3d7fa 100644
--- a/internal/tun/tun_darwin.go
+++ b/internal/tun/tun_darwin.go
@@ -19,6 +19,7 @@ const openHint = "needs root"
func init() {
openName = "utun"
staleHook = cleanupScoped
+ keepDevice = true
}
// configure gives the new utun its addresses and capture routes, and returns its index.