macos build, linux tun hack
This commit is contained in:
1 parent
9639defdd4
commit
76ab72db2e
18 files changed
+719
-64
No files matched your search
@@ -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 ""
|
||||
|
||||
@@ -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 ""
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import "os"
|
||||
|
||||
func watchStdinQuit(_ chan<- os.Signal) {}
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<string, string> = { 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 {}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
//go:build windows
|
||||
|
||||
package wintunnel
|
||||
package desktoptun
|
||||
|
||||
import (
|
||||
"net"
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<<i) != 0 {
|
||||
bits++
|
||||
}
|
||||
}
|
||||
}
|
||||
return bits, nil
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package wintunnel
|
||||
package desktoptun
|
||||
|
||||
import (
|
||||
"errors"
|
||||
@@ -57,10 +57,10 @@ type Tunnel struct {
|
||||
// New validates a Config and returns a Tunnel ready to Start.
|
||||
func New(cfg Config) (*Tunnel, error) {
|
||||
if cfg.AdapterName == "" {
|
||||
return nil, errors.New("wintunnel: AdapterName required")
|
||||
return nil, errors.New("desktoptun: AdapterName required")
|
||||
}
|
||||
if cfg.TunnelIP == "" || cfg.TunnelMask == "" || cfg.TunnelPeer == "" {
|
||||
return nil, errors.New("wintunnel: TunnelIP, TunnelMask and TunnelPeer required")
|
||||
return nil, errors.New("desktoptun: TunnelIP, TunnelMask and TunnelPeer required")
|
||||
}
|
||||
if cfg.MTU <= 0 {
|
||||
cfg.MTU = 1500
|
||||
@@ -69,7 +69,7 @@ func New(cfg Config) (*Tunnel, error) {
|
||||
cfg.SocksHost = "127.0.0.1"
|
||||
}
|
||||
if cfg.SocksPort <= 0 {
|
||||
return nil, errors.New("wintunnel: SocksPort required")
|
||||
return nil, errors.New("desktoptun: SocksPort required")
|
||||
}
|
||||
if cfg.LogFn == nil {
|
||||
cfg.LogFn = log.Printf
|
||||
@@ -94,16 +94,16 @@ func (t *Tunnel) Start() error {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if t.started {
|
||||
return errors.New("wintunnel: already started")
|
||||
return errors.New("desktoptun: already started")
|
||||
}
|
||||
|
||||
gw, alias, err := defaultIPv4Gateway()
|
||||
if err != nil {
|
||||
return fmt.Errorf("wintunnel: read default gateway: %w", err)
|
||||
return fmt.Errorf("desktoptun: read default gateway: %w", err)
|
||||
}
|
||||
t.origGateway = gw
|
||||
t.origIfAlias = alias
|
||||
t.log("[wintunnel] original default gateway %s via %q", gw, alias)
|
||||
t.log("[desktoptun] original default gateway %s via %q", gw, alias)
|
||||
|
||||
proxy := fmt.Sprintf("socks5://%s:%d", t.cfg.SocksHost, t.cfg.SocksPort)
|
||||
if t.cfg.SocksUser != "" {
|
||||
@@ -115,7 +115,7 @@ func (t *Tunnel) Start() error {
|
||||
Device: "tun://" + t.cfg.AdapterName,
|
||||
MTU: t.cfg.MTU,
|
||||
}
|
||||
t.log("[wintunnel] starting tun2socks engine adapter=%s mtu=%d proxy=%s",
|
||||
t.log("[desktoptun] starting tun2socks engine adapter=%s mtu=%d proxy=%s",
|
||||
t.cfg.AdapterName, t.cfg.MTU, proxy)
|
||||
engine.Insert(key)
|
||||
engine.Start()
|
||||
@@ -123,14 +123,14 @@ func (t *Tunnel) Start() error {
|
||||
// adapter exists now; configure IP/MTU/DNS, install default routes
|
||||
if err := setAdapterIP(t.cfg.AdapterName, t.cfg.TunnelIP, t.cfg.TunnelMask); err != nil {
|
||||
engine.Stop()
|
||||
return fmt.Errorf("wintunnel: set adapter ip: %w", err)
|
||||
return fmt.Errorf("desktoptun: set adapter ip: %w", err)
|
||||
}
|
||||
if err := setAdapterMTU(t.cfg.AdapterName, t.cfg.MTU); err != nil {
|
||||
// non-fatal: log and continue
|
||||
t.log("[wintunnel] set mtu failed (continuing): %v", err)
|
||||
t.log("[desktoptun] set mtu failed (continuing): %v", err)
|
||||
}
|
||||
if err := setAdapterDNS(t.cfg.AdapterName, t.cfg.DNSServers); err != nil {
|
||||
t.log("[wintunnel] set dns failed (continuing): %v", err)
|
||||
t.log("[desktoptun] set dns failed (continuing): %v", err)
|
||||
}
|
||||
idx, err := adapterIPv4Index(t.cfg.AdapterName)
|
||||
if err == nil {
|
||||
@@ -139,12 +139,12 @@ func (t *Tunnel) Start() error {
|
||||
|
||||
for _, prefix := range []string{"0.0.0.0/1", "128.0.0.0/1"} {
|
||||
if err := addRouteViaAdapter(prefix, t.cfg.AdapterName, t.cfg.TunnelPeer, 2); err != nil {
|
||||
t.log("[wintunnel] add default-half %s failed: %v", prefix, err)
|
||||
t.log("[desktoptun] add default-half %s failed: %v", prefix, err)
|
||||
}
|
||||
}
|
||||
|
||||
t.started = true
|
||||
t.log("[wintunnel] up: adapter=%s ip=%s/%s peer=%s",
|
||||
t.log("[desktoptun] up: adapter=%s ip=%s/%s peer=%s",
|
||||
t.cfg.AdapterName, t.cfg.TunnelIP, t.cfg.TunnelMask, t.cfg.TunnelPeer)
|
||||
return nil
|
||||
}
|
||||
@@ -161,19 +161,19 @@ func (t *Tunnel) Stop() {
|
||||
|
||||
for ip := range t.bypass {
|
||||
if err := deleteHostRoute(ip); err != nil {
|
||||
t.log("[wintunnel] remove bypass route %s: %v", ip, err)
|
||||
t.log("[desktoptun] remove bypass route %s: %v", ip, err)
|
||||
}
|
||||
}
|
||||
t.bypass = nil
|
||||
|
||||
for _, prefix := range []string{"0.0.0.0/1", "128.0.0.0/1"} {
|
||||
if err := deleteRouteByPrefix(prefix, t.cfg.AdapterName); err != nil {
|
||||
t.log("[wintunnel] remove default-half %s: %v", prefix, err)
|
||||
t.log("[desktoptun] remove default-half %s: %v", prefix, err)
|
||||
}
|
||||
}
|
||||
|
||||
engine.Stop()
|
||||
t.log("[wintunnel] down")
|
||||
t.log("[desktoptun] down")
|
||||
}
|
||||
|
||||
// AddBypassIP installs a /32 route for ip via the original default
|
||||
@@ -181,7 +181,7 @@ func (t *Tunnel) Stop() {
|
||||
// hosts skip the tunnel and reach the real network directly.
|
||||
func (t *Tunnel) AddBypassIP(ip net.IP) error {
|
||||
if ip == nil {
|
||||
return errors.New("wintunnel: nil IP")
|
||||
return errors.New("desktoptun: nil IP")
|
||||
}
|
||||
v4 := ip.To4()
|
||||
if v4 == nil {
|
||||
@@ -197,15 +197,15 @@ func (t *Tunnel) AddBypassIP(ip net.IP) error {
|
||||
gw := t.origGateway
|
||||
t.mu.Unlock()
|
||||
if gw == "" {
|
||||
return errors.New("wintunnel: original gateway unknown, start the tunnel first")
|
||||
return errors.New("desktoptun: original gateway unknown, start the tunnel first")
|
||||
}
|
||||
if err := addHostRoute(addr, gw, 1); err != nil {
|
||||
return fmt.Errorf("wintunnel: add bypass %s via %s: %w", addr, gw, err)
|
||||
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("[wintunnel] bypass %s -> %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
|
||||
}
|
||||
@@ -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
|
||||
@@ -1,6 +1,6 @@
|
||||
//go:build windows
|
||||
|
||||
package wintunnel
|
||||
package desktoptun
|
||||
|
||||
import (
|
||||
"os/exec"
|
||||
@@ -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) {
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user