diff --git a/build-desktop-joiner.sh b/build-desktop-joiner.sh index 2282394..83de95a 100755 --- a/build-desktop-joiner.sh +++ b/build-desktop-joiner.sh @@ -49,11 +49,24 @@ build_linux() { ls -lh "$JOINER_GO_DIR/desktop-joiner-linux-$OUT_TAG" } +build_darwin_universal() { + echo "" + echo "=== Building desktop-joiner darwin (universal) ===" + cd "$JOINER_GO_DIR" + GOOS=darwin GOARCH=amd64 go build -trimpath -ldflags="-s -w" -o desktop-joiner-darwin-amd64 . + GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags="-s -w" -o desktop-joiner-darwin-arm64 . + lipo -create -output desktop-joiner-darwin desktop-joiner-darwin-amd64 desktop-joiner-darwin-arm64 + rm desktop-joiner-darwin-amd64 desktop-joiner-darwin-arm64 + ls -lh "$JOINER_GO_DIR/desktop-joiner-darwin" +} + build_windows amd64 x64 amd64 build_windows 386 ia32 x86 build_linux amd64 x64 +build_darwin_universal + rm -f "$JOINER_GO_DIR/wintun.zip" echo "" diff --git a/build-joiner-app.sh b/build-joiner-app.sh index 687d1de..1a5af7e 100755 --- a/build-joiner-app.sh +++ b/build-joiner-app.sh @@ -23,6 +23,7 @@ npx tsc cleanup_artifacts() { rm -f "$JOINER_GO_DIR"/desktop-joiner-windows-*.exe \ "$JOINER_GO_DIR"/desktop-joiner-linux-* \ + "$JOINER_GO_DIR"/desktop-joiner-darwin \ "$JOINER_GO_DIR"/desktop-joiner-bundle \ "$JOINER_GO_DIR"/desktop-joiner-bundle.exe \ "$JOINER_GO_DIR"/wintun-*.dll @@ -47,6 +48,12 @@ cp "$JOINER_GO_DIR/desktop-joiner-linux-x64" "$JOINER_GO_DIR/desktop-joiner-bund chmod +x "$JOINER_GO_DIR/desktop-joiner-bundle" npx electron-builder --linux --x64 --publish never +if [ "$(uname)" = "Darwin" ]; then + echo "" + echo "--- macOS (universal) ---" + npx electron-builder --mac --publish never || true +fi + "$ROOT/clean-prebuilts.sh" echo "" diff --git a/joiner-desktop-app/desktop-joiner/.gitignore b/joiner-desktop-app/desktop-joiner/.gitignore index 9a8e0e2..ea2534e 100644 --- a/joiner-desktop-app/desktop-joiner/.gitignore +++ b/joiner-desktop-app/desktop-joiner/.gitignore @@ -1,5 +1,7 @@ desktop-joiner-windows-*.exe desktop-joiner-linux-* +desktop-joiner-darwin +desktop-joiner-darwin-* desktop-joiner-bundle desktop-joiner-bundle.exe wintun-*.dll diff --git a/joiner-desktop-app/desktop-joiner/main.go b/joiner-desktop-app/desktop-joiner/main.go index 0cb2a43..9fbebba 100644 --- a/joiner-desktop-app/desktop-joiner/main.go +++ b/joiner-desktop-app/desktop-joiner/main.go @@ -29,7 +29,7 @@ import ( "whitelist-bypass/relay/pion" "whitelist-bypass/relay/tunnel" "whitelist-bypass/relay/wbstream" - "whitelist-bypass/relay/wintunnel" + "whitelist-bypass/relay/desktoptun" ) type statusEmitter struct{} @@ -108,12 +108,12 @@ func main() { } common.MaskingEnabled = true - // One wintunnel.Tunnel covers both platforms. Created up-front so + // One desktoptun.Tunnel covers both platforms. Created up-front so // signaling-host bypass routes can be installed before any platform // code touches the network. - var tun *wintunnel.Tunnel + var tun *desktoptun.Tunnel if !*noTun { - cfg := wintunnel.Config{ + cfg := desktoptun.Config{ AdapterName: tunAdapter, TunnelIP: tunIP, TunnelMask: tunMask, @@ -127,9 +127,9 @@ func main() { LogFn: log.Printf, } var err error - tun, err = wintunnel.New(cfg) + tun, err = desktoptun.New(cfg) if err != nil { - log.Fatalf("[wintunnel] init: %v", err) + log.Fatalf("[desktoptun] init: %v", err) } } @@ -151,6 +151,7 @@ func main() { sig := make(chan os.Signal, 1) signal.Notify(sig, os.Interrupt, syscall.SIGTERM) + watchStdinQuit(sig) tunReady := make(chan struct{}) var tunOnce sync.Once @@ -161,7 +162,7 @@ func main() { return } if err := tun.Start(); err != nil { - log.Fatalf("[wintunnel] start: %v", err) + log.Fatalf("[desktoptun] start: %v", err) } // Now that the tunnel knows the original gateway, // pin /32 bypass routes for the signaling hosts. diff --git a/joiner-desktop-app/desktop-joiner/quit_linux.go b/joiner-desktop-app/desktop-joiner/quit_linux.go new file mode 100644 index 0000000..177c837 --- /dev/null +++ b/joiner-desktop-app/desktop-joiner/quit_linux.go @@ -0,0 +1,23 @@ +//go:build linux + +package main + +import ( + "bufio" + "os" + "strings" + "syscall" +) + +func watchStdinQuit(sig chan<- os.Signal) { + go func() { + scanner := bufio.NewScanner(os.Stdin) + for scanner.Scan() { + if strings.TrimSpace(scanner.Text()) == "QUIT" { + sig <- syscall.SIGTERM + return + } + } + sig <- syscall.SIGTERM + }() +} diff --git a/joiner-desktop-app/desktop-joiner/quit_other.go b/joiner-desktop-app/desktop-joiner/quit_other.go new file mode 100644 index 0000000..84b7dfc --- /dev/null +++ b/joiner-desktop-app/desktop-joiner/quit_other.go @@ -0,0 +1,7 @@ +//go:build !linux + +package main + +import "os" + +func watchStdinQuit(_ chan<- os.Signal) {} diff --git a/joiner-desktop-app/package.json b/joiner-desktop-app/package.json index b747a95..2f854e1 100644 --- a/joiner-desktop-app/package.json +++ b/joiner-desktop-app/package.json @@ -52,6 +52,18 @@ "to": "desktop-joiner" } ] + }, + "mac": { + "target": "dmg", + "artifactName": "${productName}-${version}-${arch}.${ext}", + "icon": "resources/icon.icns", + "category": "public.app-category.utilities", + "extraResources": [ + { + "from": "desktop-joiner/desktop-joiner-darwin", + "to": "desktop-joiner" + } + ] } } } diff --git a/joiner-desktop-app/src/main/index.ts b/joiner-desktop-app/src/main/index.ts index 1381119..0f1c22d 100644 --- a/joiner-desktop-app/src/main/index.ts +++ b/joiner-desktop-app/src/main/index.ts @@ -43,12 +43,15 @@ function resolveJoinerExe(): string { const packaged = join(process.resourcesPath || '', exeName); if (existsSync(packaged)) return packaged; + const baseDir = join(__dirname, '..', '..', 'desktop-joiner'); + if (process.platform === 'darwin') { + return join(baseDir, 'desktop-joiner-darwin'); + } const archMap: Record = { x64: 'x64', arm64: 'arm64', ia32: 'ia32' }; const archTag = archMap[process.arch] ?? 'x64'; - const platTag = process.platform === 'win32' ? 'windows' : 'linux'; const suffix = process.platform === 'win32' ? '.exe' : ''; - return join(__dirname, '..', '..', 'desktop-joiner', - `desktop-joiner-${platTag}-${archTag}${suffix}`); + const platTag = process.platform === 'win32' ? 'windows' : 'linux'; + return join(baseDir, `desktop-joiner-${platTag}-${archTag}${suffix}`); } function send(channel: string, payload: unknown) { @@ -94,9 +97,12 @@ ipcMain.handle(IPC.START, async (_e, settings: JoinerSettings) => { if (!existsSync(exe)) { return { ok: false, error: `desktop-joiner binary not found at ${exe}` }; } - // wintun is Windows-only; on Linux always run in SOCKS5-only mode - // regardless of the noTun checkbox. - const noTun = process.platform !== 'win32' ? true : settings.noTun; + const tunSupported = + process.platform === 'win32' || process.platform === 'linux' || process.platform === 'darwin'; + const noTun = tunSupported ? settings.noTun : true; + if (process.platform !== 'win32' && !noTun && process.getuid && process.getuid() !== 0) { + send(IPC.LOG, `[main] WARNING: ${process.platform} TUN routing needs root; relaunch with sudo or untick the TUN option\n`); + } const args = [ '--platform', settings.platform, '--link', settings.link, @@ -112,10 +118,15 @@ ipcMain.handle(IPC.START, async (_e, settings: JoinerSettings) => { if (settings.socksPass) args.push('--socks-pass', settings.socksPass); if (noTun) args.push('--no-tun'); - const commandLine = [exe, ...args].map((s) => (/\s/.test(s) ? `"${s}"` : s)).join(' '); + const elevateOnLinux = + process.platform === 'linux' && !noTun && + process.getuid && process.getuid() !== 0; + const spawnCmd = elevateOnLinux ? 'pkexec' : exe; + const spawnArgs = elevateOnLinux ? [exe, ...args] : args; + const commandLine = [spawnCmd, ...spawnArgs].map((s) => (/\s/.test(s) ? `"${s}"` : s)).join(' '); send(IPC.LOG, `[main] spawning: ${commandLine}\n`); try { - joinerProcess = spawn(exe, args, { windowsHide: true }); + joinerProcess = spawn(spawnCmd, spawnArgs, { windowsHide: true }); } catch (err) { return { ok: false, error: `spawn failed: ${(err as Error).message}` }; } @@ -159,10 +170,13 @@ ipcMain.handle(IPC.STOP, async () => { function stopJoiner() { closeCaptchaWindow(); if (!joinerProcess) return; + // On Linux when the Go binary was spawned via pkexec, it runs as + // root and we (the user) cannot SIGTERM it. The binary watches + // stdin: writing "QUIT\n" and closing the pipe triggers the same + // shutdown path as SIGTERM. + try { joinerProcess.stdin?.write('QUIT\n'); } catch {} + try { joinerProcess.stdin?.end(); } catch {} try { - // SIGTERM on Windows ends up as TerminateProcess for the child. - // The Go binary registers a signal handler for SIGTERM which - // triggers Tunnel.Stop and tears down routes cleanly. joinerProcess.kill('SIGTERM'); } catch {} } diff --git a/relay/wintunnel/bypass_windows.go b/relay/desktoptun/bypass.go similarity index 97% rename from relay/wintunnel/bypass_windows.go rename to relay/desktoptun/bypass.go index d44f423..09dbcb0 100644 --- a/relay/wintunnel/bypass_windows.go +++ b/relay/desktoptun/bypass.go @@ -1,6 +1,4 @@ -//go:build windows - -package wintunnel +package desktoptun import ( "net" diff --git a/relay/desktoptun/desktoptun_darwin.go b/relay/desktoptun/desktoptun_darwin.go new file mode 100644 index 0000000..c1e36a7 --- /dev/null +++ b/relay/desktoptun/desktoptun_darwin.go @@ -0,0 +1,287 @@ +//go:build darwin + +package desktoptun + +import ( + "bufio" + "errors" + "fmt" + "log" + "net" + "os/exec" + "strconv" + "strings" + "sync" + + "github.com/xjasonlyu/tun2socks/v2/engine" +) + +type Config struct { + AdapterName string + TunnelIP string + TunnelMask string + TunnelPeer string + MTU int + DNSServers []string + SocksHost string + SocksPort int + SocksUser string + SocksPass string + LogFn func(format string, args ...any) +} + +type Tunnel struct { + cfg Config + log func(string, ...any) + + mu sync.Mutex + started bool + stopped bool + bypass map[string]struct{} + origGateway string + origIface string + tunDev string +} + +func New(cfg Config) (*Tunnel, error) { + if cfg.AdapterName == "" { + return nil, errors.New("desktoptun: AdapterName required") + } + if cfg.TunnelIP == "" || cfg.TunnelMask == "" || cfg.TunnelPeer == "" { + return nil, errors.New("desktoptun: TunnelIP, TunnelMask and TunnelPeer required") + } + if cfg.MTU <= 0 { + cfg.MTU = 1500 + } + if cfg.SocksHost == "" { + cfg.SocksHost = "127.0.0.1" + } + if cfg.SocksPort <= 0 { + return nil, errors.New("desktoptun: SocksPort required") + } + if cfg.LogFn == nil { + cfg.LogFn = log.Printf + } + if len(cfg.DNSServers) == 0 { + cfg.DNSServers = []string{"1.1.1.1", "8.8.8.8"} + } + return &Tunnel{ + cfg: cfg, + log: cfg.LogFn, + bypass: make(map[string]struct{}), + }, nil +} + +func (t *Tunnel) Start() error { + t.mu.Lock() + defer t.mu.Unlock() + if t.started { + return errors.New("desktoptun: already started") + } + + gw, iface, err := defaultIPv4GatewayDarwin() + if err != nil { + return fmt.Errorf("desktoptun: read default gateway: %w", err) + } + t.origGateway = gw + t.origIface = iface + t.log("[desktoptun] original default gateway %s via %q", gw, iface) + + proxy := fmt.Sprintf("socks5://%s:%d", t.cfg.SocksHost, t.cfg.SocksPort) + if t.cfg.SocksUser != "" { + proxy = fmt.Sprintf("socks5://%s:%s@%s:%d", + t.cfg.SocksUser, t.cfg.SocksPass, t.cfg.SocksHost, t.cfg.SocksPort) + } + dev := t.cfg.AdapterName + if !strings.HasPrefix(dev, "utun") { + dev = "utun" + } + key := &engine.Key{ + Proxy: proxy, + Device: "tun://" + dev, + MTU: t.cfg.MTU, + } + t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=%s", dev, t.cfg.MTU, proxy) + engine.Insert(key) + engine.Start() + + actual, err := findUtunByMTU(t.cfg.MTU) + if err != nil { + engine.Stop() + return fmt.Errorf("desktoptun: locate utun: %w", err) + } + t.tunDev = actual + t.log("[desktoptun] kernel assigned %s", actual) + + if out, err := runCmd("ifconfig", actual, "inet", t.cfg.TunnelIP, t.cfg.TunnelPeer, "up"); err != nil { + engine.Stop() + return fmt.Errorf("desktoptun: ifconfig %s: %w (%s)", actual, err, out) + } + if out, err := runCmd("ifconfig", actual, "mtu", strconv.Itoa(t.cfg.MTU)); err != nil { + t.log("[desktoptun] set mtu failed (continuing): %v (%s)", err, out) + } + + for _, p := range []string{"0.0.0.0/1", "128.0.0.0/1"} { + if out, err := runCmd("route", "-n", "add", "-net", p, "-interface", actual); err != nil { + t.log("[desktoptun] add default-half %s failed: %v (%s)", p, err, out) + } + } + + t.started = true + t.log("[desktoptun] up: adapter=%s ip=%s peer=%s", + actual, t.cfg.TunnelIP, t.cfg.TunnelPeer) + return nil +} + +func (t *Tunnel) Stop() { + t.mu.Lock() + defer t.mu.Unlock() + if !t.started || t.stopped { + return + } + t.stopped = true + + for ip := range t.bypass { + if _, err := runCmd("route", "-n", "delete", "-host", ip); err != nil { + t.log("[desktoptun] remove bypass route %s: %v", ip, err) + } + } + t.bypass = nil + + for _, p := range []string{"0.0.0.0/1", "128.0.0.0/1"} { + if _, err := runCmd("route", "-n", "delete", "-net", p); err != nil { + t.log("[desktoptun] remove default-half %s: %v", p, err) + } + } + + engine.Stop() + t.log("[desktoptun] down") +} + +func (t *Tunnel) AddBypassIP(ip net.IP) error { + if ip == nil { + return errors.New("desktoptun: nil IP") + } + v4 := ip.To4() + if v4 == nil { + return nil + } + addr := v4.String() + t.mu.Lock() + if _, dup := t.bypass[addr]; dup { + t.mu.Unlock() + return nil + } + gw := t.origGateway + t.mu.Unlock() + if gw == "" { + return errors.New("desktoptun: original gateway unknown, start the tunnel first") + } + if _, err := runCmd("route", "-n", "add", "-host", addr, gw); err != nil { + return fmt.Errorf("desktoptun: add bypass %s via %s: %w", addr, gw, err) + } + t.mu.Lock() + t.bypass[addr] = struct{}{} + t.mu.Unlock() + t.log("[desktoptun] bypass %s -> %s", addr, gw) + return nil +} + +func (t *Tunnel) AddBypassHost(hostname string) ([]net.IP, error) { + if ip := net.ParseIP(hostname); ip != nil { + return []net.IP{ip}, t.AddBypassIP(ip) + } + ips, err := net.LookupIP(hostname) + if err != nil { + return nil, fmt.Errorf("desktoptun: resolve %s: %w", hostname, err) + } + out := make([]net.IP, 0, len(ips)) + for _, ip := range ips { + if v4 := ip.To4(); v4 != nil { + if addErr := t.AddBypassIP(v4); addErr != nil { + t.log("[desktoptun] bypass host %s ip %s: %v", hostname, v4, addErr) + continue + } + out = append(out, v4) + } + } + if len(out) == 0 { + return nil, fmt.Errorf("desktoptun: no v4 addresses for %s", hostname) + } + return out, nil +} + +func (t *Tunnel) AddBypassFromCandidate(candidate string) error { + ips := extractCandidateIPs(candidate) + if len(ips) == 0 { + return nil + } + var firstErr error + for _, ip := range ips { + if err := t.AddBypassIP(ip); err != nil && firstErr == nil { + firstErr = err + } + } + return firstErr +} + +func runCmd(name string, args ...string) ([]byte, error) { + return exec.Command(name, args...).CombinedOutput() +} + +func defaultIPv4GatewayDarwin() (gateway, iface string, err error) { + out, nerr := exec.Command("netstat", "-rn", "-f", "inet").Output() + if nerr != nil { + return "", "", fmt.Errorf("netstat: %w", nerr) + } + scanner := bufio.NewScanner(strings.NewReader(string(out))) + for scanner.Scan() { + fields := strings.Fields(scanner.Text()) + if len(fields) < 4 || fields[0] != "default" { + continue + } + candidateGw := fields[1] + candidateIf := fields[len(fields)-1] + if net.ParseIP(candidateGw) == nil || net.ParseIP(candidateGw).To4() == nil { + continue + } + return candidateGw, candidateIf, nil + } + return "", "", fmt.Errorf("no IPv4 default route found in netstat output:\n%s", string(out)) +} + +func findUtunByMTU(mtu int) (string, error) { + out, err := exec.Command("ifconfig").Output() + if err != nil { + return "", err + } + var bestName string + var bestNum = -1 + scanner := bufio.NewScanner(strings.NewReader(string(out))) + var current string + var currentMTU int + for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "utun") { + if idx := strings.Index(line, ":"); idx > 0 { + name := line[:idx] + mtuPos := strings.Index(line, "mtu ") + if mtuPos > 0 { + currentMTU, _ = strconv.Atoi(strings.TrimSpace(line[mtuPos+4:])) + } + current = name + if currentMTU == mtu { + n, _ := strconv.Atoi(strings.TrimPrefix(name, "utun")) + if n > bestNum { + bestNum = n + bestName = current + } + } + } + } + } + if bestName == "" { + return "", errors.New("no utun with matching mtu") + } + return bestName, nil +} diff --git a/relay/desktoptun/desktoptun_linux.go b/relay/desktoptun/desktoptun_linux.go new file mode 100644 index 0000000..3f0ddef --- /dev/null +++ b/relay/desktoptun/desktoptun_linux.go @@ -0,0 +1,274 @@ +//go:build linux + +package desktoptun + +import ( + "bufio" + "errors" + "fmt" + "log" + "net" + "os/exec" + "strconv" + "strings" + "sync" + + "github.com/xjasonlyu/tun2socks/v2/engine" +) + +type Config struct { + AdapterName string + TunnelIP string + TunnelMask string + TunnelPeer string + MTU int + DNSServers []string + SocksHost string + SocksPort int + SocksUser string + SocksPass string + LogFn func(format string, args ...any) +} + +type Tunnel struct { + cfg Config + log func(string, ...any) + + mu sync.Mutex + started bool + stopped bool + bypass map[string]struct{} + origGateway string + origIface string +} + +func New(cfg Config) (*Tunnel, error) { + if cfg.AdapterName == "" { + return nil, errors.New("desktoptun: AdapterName required") + } + if cfg.TunnelIP == "" || cfg.TunnelMask == "" || cfg.TunnelPeer == "" { + return nil, errors.New("desktoptun: TunnelIP, TunnelMask and TunnelPeer required") + } + if cfg.MTU <= 0 { + cfg.MTU = 1500 + } + if cfg.SocksHost == "" { + cfg.SocksHost = "127.0.0.1" + } + if cfg.SocksPort <= 0 { + return nil, errors.New("desktoptun: SocksPort required") + } + if cfg.LogFn == nil { + cfg.LogFn = log.Printf + } + if len(cfg.DNSServers) == 0 { + cfg.DNSServers = []string{"1.1.1.1", "8.8.8.8"} + } + return &Tunnel{ + cfg: cfg, + log: cfg.LogFn, + bypass: make(map[string]struct{}), + }, nil +} + +func (t *Tunnel) Start() error { + t.mu.Lock() + defer t.mu.Unlock() + if t.started { + return errors.New("desktoptun: already started") + } + + gw, iface, err := defaultIPv4GatewayLinux() + if err != nil { + return fmt.Errorf("desktoptun: read default gateway: %w", err) + } + t.origGateway = gw + t.origIface = iface + t.log("[desktoptun] original default gateway %s via %q", gw, iface) + + proxy := fmt.Sprintf("socks5://%s:%d", t.cfg.SocksHost, t.cfg.SocksPort) + if t.cfg.SocksUser != "" { + proxy = fmt.Sprintf("socks5://%s:%s@%s:%d", + t.cfg.SocksUser, t.cfg.SocksPass, t.cfg.SocksHost, t.cfg.SocksPort) + } + key := &engine.Key{ + Proxy: proxy, + Device: "tun://" + t.cfg.AdapterName, + MTU: t.cfg.MTU, + } + t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=%s", + t.cfg.AdapterName, t.cfg.MTU, proxy) + engine.Insert(key) + engine.Start() + + prefix, err := maskToCIDR(t.cfg.TunnelMask) + if err != nil { + engine.Stop() + return fmt.Errorf("desktoptun: bad mask: %w", err) + } + addr := fmt.Sprintf("%s/%d", t.cfg.TunnelIP, prefix) + if out, err := runCmd("ip", "addr", "add", addr, "dev", t.cfg.AdapterName); err != nil { + engine.Stop() + return fmt.Errorf("desktoptun: ip addr add %s: %w (%s)", addr, err, out) + } + if out, err := runCmd("ip", "link", "set", t.cfg.AdapterName, "mtu", strconv.Itoa(t.cfg.MTU)); err != nil { + t.log("[desktoptun] set mtu failed (continuing): %v (%s)", err, out) + } + if out, err := runCmd("ip", "link", "set", t.cfg.AdapterName, "up"); err != nil { + engine.Stop() + return fmt.Errorf("desktoptun: ip link set up: %w (%s)", err, out) + } + + for _, p := range []string{"0.0.0.0/1", "128.0.0.0/1"} { + if out, err := runCmd("ip", "route", "add", p, "dev", t.cfg.AdapterName); err != nil { + t.log("[desktoptun] add default-half %s failed: %v (%s)", p, err, out) + } + } + + t.started = true + t.log("[desktoptun] up: adapter=%s ip=%s peer=%s", + t.cfg.AdapterName, addr, t.cfg.TunnelPeer) + return nil +} + +func (t *Tunnel) Stop() { + t.mu.Lock() + defer t.mu.Unlock() + if !t.started || t.stopped { + return + } + t.stopped = true + + for ip := range t.bypass { + if _, err := runCmd("ip", "route", "del", ip+"/32"); err != nil { + t.log("[desktoptun] remove bypass route %s: %v", ip, err) + } + } + t.bypass = nil + + for _, p := range []string{"0.0.0.0/1", "128.0.0.0/1"} { + if _, err := runCmd("ip", "route", "del", p, "dev", t.cfg.AdapterName); err != nil { + t.log("[desktoptun] remove default-half %s: %v", p, err) + } + } + + engine.Stop() + t.log("[desktoptun] down") +} + +func (t *Tunnel) AddBypassIP(ip net.IP) error { + if ip == nil { + return errors.New("desktoptun: nil IP") + } + v4 := ip.To4() + if v4 == nil { + return nil + } + addr := v4.String() + t.mu.Lock() + if _, dup := t.bypass[addr]; dup { + t.mu.Unlock() + return nil + } + gw := t.origGateway + iface := t.origIface + t.mu.Unlock() + if gw == "" { + return errors.New("desktoptun: original gateway unknown, start the tunnel first") + } + if _, err := runCmd("ip", "route", "add", addr+"/32", "via", gw, "dev", iface); err != nil { + return fmt.Errorf("desktoptun: add bypass %s via %s: %w", addr, gw, err) + } + t.mu.Lock() + t.bypass[addr] = struct{}{} + t.mu.Unlock() + t.log("[desktoptun] bypass %s -> %s", addr, gw) + return nil +} + +func (t *Tunnel) AddBypassHost(hostname string) ([]net.IP, error) { + if ip := net.ParseIP(hostname); ip != nil { + return []net.IP{ip}, t.AddBypassIP(ip) + } + ips, err := net.LookupIP(hostname) + if err != nil { + return nil, fmt.Errorf("desktoptun: resolve %s: %w", hostname, err) + } + out := make([]net.IP, 0, len(ips)) + for _, ip := range ips { + if v4 := ip.To4(); v4 != nil { + if addErr := t.AddBypassIP(v4); addErr != nil { + t.log("[desktoptun] bypass host %s ip %s: %v", hostname, v4, addErr) + continue + } + out = append(out, v4) + } + } + if len(out) == 0 { + return nil, fmt.Errorf("desktoptun: no v4 addresses for %s", hostname) + } + return out, nil +} + +func (t *Tunnel) AddBypassFromCandidate(candidate string) error { + ips := extractCandidateIPs(candidate) + if len(ips) == 0 { + return nil + } + var firstErr error + for _, ip := range ips { + if err := t.AddBypassIP(ip); err != nil && firstErr == nil { + firstErr = err + } + } + return firstErr +} + +func runCmd(name string, args ...string) ([]byte, error) { + cmd := exec.Command(name, args...) + return cmd.CombinedOutput() +} + +func defaultIPv4GatewayLinux() (gateway, iface string, err error) { + out, err := exec.Command("ip", "-4", "route", "show", "default").Output() + if err != nil { + return "", "", fmt.Errorf("ip route show default: %w", err) + } + scanner := bufio.NewScanner(strings.NewReader(string(out))) + for scanner.Scan() { + fields := strings.Fields(scanner.Text()) + var gw, dev string + for i := 0; i < len(fields)-1; i++ { + switch fields[i] { + case "via": + gw = fields[i+1] + case "dev": + dev = fields[i+1] + } + } + if gw != "" && dev != "" { + return gw, dev, nil + } + } + return "", "", errors.New("no IPv4 default route found") +} + +func maskToCIDR(mask string) (int, error) { + parts := strings.Split(mask, ".") + if len(parts) != 4 { + return 0, fmt.Errorf("bad mask %q", mask) + } + var bits int + for _, p := range parts { + n, err := strconv.Atoi(p) + if err != nil || n < 0 || n > 255 { + return 0, fmt.Errorf("bad mask octet %q", p) + } + for i := 7; i >= 0; i-- { + if n&(1< %s", addr, gw) + t.log("[desktoptun] bypass %s -> %s", addr, gw) return nil } @@ -219,20 +219,20 @@ func (t *Tunnel) AddBypassHost(hostname string) ([]net.IP, error) { } ips, err := net.LookupIP(hostname) if err != nil { - return nil, fmt.Errorf("wintunnel: resolve %s: %w", hostname, err) + return nil, fmt.Errorf("desktoptun: resolve %s: %w", hostname, err) } out := make([]net.IP, 0, len(ips)) for _, ip := range ips { if v4 := ip.To4(); v4 != nil { if addErr := t.AddBypassIP(v4); addErr != nil { - t.log("[wintunnel] bypass host %s ip %s: %v", hostname, v4, addErr) + t.log("[desktoptun] bypass host %s ip %s: %v", hostname, v4, addErr) continue } out = append(out, v4) } } if len(out) == 0 { - return nil, fmt.Errorf("wintunnel: no v4 addresses for %s", hostname) + return nil, fmt.Errorf("desktoptun: no v4 addresses for %s", hostname) } return out, nil } diff --git a/relay/desktoptun/doc.go b/relay/desktoptun/doc.go new file mode 100644 index 0000000..607d95f --- /dev/null +++ b/relay/desktoptun/doc.go @@ -0,0 +1,15 @@ +// Package desktoptun brings up a TUN adapter, configures system-wide +// routing through it, and runs xjasonlyu/tun2socks as the engine that +// forwards every IP packet to a local SOCKS5 proxy. +// +// The package is the desktop counterpart to relay/androidbind. Android +// uses a VpnService fd plus addDisallowedApplication for the joiner's +// own traffic; on desktop OSes there is no per-process exclusion, so +// the joiner's signaling and SFU media flows are kept off the tunnel +// by installing /32 bypass routes through the original default gateway. +// +// Implementations live in desktoptun_windows.go (wintun), in +// desktoptun_linux.go (/dev/net/tun + iproute2), and in +// desktoptun_darwin.go (utun + route(8) + ifconfig). stub_other.go is +// a build stub for any platform that none of those cover. +package desktoptun diff --git a/relay/wintunnel/exec_windows.go b/relay/desktoptun/exec_windows.go similarity index 94% rename from relay/wintunnel/exec_windows.go rename to relay/desktoptun/exec_windows.go index d38fefa..024358c 100644 --- a/relay/wintunnel/exec_windows.go +++ b/relay/desktoptun/exec_windows.go @@ -1,6 +1,6 @@ //go:build windows -package wintunnel +package desktoptun import ( "os/exec" diff --git a/relay/wintunnel/routes_windows.go b/relay/desktoptun/routes_windows.go similarity index 98% rename from relay/wintunnel/routes_windows.go rename to relay/desktoptun/routes_windows.go index b82a375..7a3bc33 100644 --- a/relay/wintunnel/routes_windows.go +++ b/relay/desktoptun/routes_windows.go @@ -1,6 +1,6 @@ //go:build windows -package wintunnel +package desktoptun import ( "bytes" @@ -12,7 +12,7 @@ import ( "strings" ) -// runHidden invokes a command with no console window. All wintunnel +// runHidden invokes a command with no console window. All desktoptun // helpers use netsh / route / powershell here; subprocess parsing // avoids pulling in winipcfg-style cgo or large Go bindings. func runHidden(name string, args ...string) ([]byte, error) { diff --git a/relay/wintunnel/stub_other.go b/relay/desktoptun/stub_other.go similarity index 83% rename from relay/wintunnel/stub_other.go rename to relay/desktoptun/stub_other.go index 0287908..64a869f 100644 --- a/relay/wintunnel/stub_other.go +++ b/relay/desktoptun/stub_other.go @@ -1,13 +1,13 @@ -//go:build !windows +//go:build !windows && !linux && !darwin -package wintunnel +package desktoptun import ( "errors" "net" ) -var errUnsupported = errors.New("wintunnel: only supported on windows") +var errUnsupported = errors.New("desktoptun: only supported on windows, linux and darwin") type Config struct { AdapterName string diff --git a/relay/pion/headless-joiner-common/util.go b/relay/pion/headless-joiner-common/util.go index 85adc9b..0569c09 100644 --- a/relay/pion/headless-joiner-common/util.go +++ b/relay/pion/headless-joiner-common/util.go @@ -1,6 +1,21 @@ package joiner -import "strings" +import ( + "strings" + + "github.com/pion/logging" +) + +// QuietPionLoggerFactory returns a Pion LoggerFactory that silences the +// "turnc" scope. Pion's TURN client logs CreatePermission refresh +// failures at Error level every few minutes during a normal call when +// the SFU advertises peer addresses the TURN server rejects on +// refresh (often IPv6). The call itself is unaffected. +func QuietPionLoggerFactory() *logging.DefaultLoggerFactory { + factory := logging.NewDefaultLoggerFactory() + factory.ScopeLevels["turnc"] = logging.LogLevelDisabled + return factory +} func TmParseMids(sdp string) (audioMid, videoMid string) { var media string diff --git a/relay/wintunnel/doc.go b/relay/wintunnel/doc.go deleted file mode 100644 index bb74e0a..0000000 --- a/relay/wintunnel/doc.go +++ /dev/null @@ -1,13 +0,0 @@ -// Package wintunnel brings up a wintun adapter on Windows, configures -// system-wide routing through it, and runs xjasonlyu/tun2socks as the -// engine that forwards every IP packet to a local SOCKS5 proxy. -// -// The package is the Windows counterpart to relay/androidbind. Android -// uses a VpnService fd plus addDisallowedApplication for the joiner's -// own traffic; on Windows there is no per-process exclusion, so the -// joiner's signaling and SFU media flows are kept off the tunnel by -// installing /32 bypass routes through the original default gateway. -// -// All real work is in wintunnel_windows.go; the !windows build is a -// stub so the relay module still compiles on macOS and Linux. -package wintunnel