Joiner desktop windows (#89)

* base classes/logic from a playground

* fix sandbox

* add vk support
This commit is contained in:
kulikov0 authored and GitHub committed 2026-05-11 17:01:32 +02:00
1 parent 1308361eb6
commit 30ed29a161
34 files changed
+7056

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
//go:build windows
package wintunnel
import (
"net"
"strings"
)
// extractCandidateIPs pulls every IPv4 literal out of one SDP candidate
// line. ICE candidates look like
//
// candidate:1 1 udp 2122260223 18.197.224.5 49555 typ host
// candidate:2 1 udp 1686052607 203.0.113.5 49555 typ srflx raddr 192.168.1.2 rport 50000
//
// We bypass every IP on the line because, at this point, we don't know
// which one Pion will end up using. A handful of extra /32 host routes
// is cheap.
func extractCandidateIPs(line string) []net.IP {
if line == "" {
return nil
}
if strings.HasPrefix(line, "a=") {
line = line[2:]
}
if !strings.HasPrefix(line, "candidate:") {
return nil
}
parts := strings.Fields(line)
var out []net.IP
for i := 0; i < len(parts); i++ {
ip := net.ParseIP(parts[i])
if ip == nil {
continue
}
v4 := ip.To4()
if v4 == nil {
continue
}
if v4.IsLoopback() || v4.IsLinkLocalUnicast() {
continue
}
out = append(out, v4)
}
return dedupIPs(out)
}
func dedupIPs(ips []net.IP) []net.IP {
if len(ips) <= 1 {
return ips
}
seen := make(map[string]struct{}, len(ips))
out := ips[:0]
for _, ip := range ips {
k := ip.String()
if _, ok := seen[k]; ok {
continue
}
seen[k] = struct{}{}
out = append(out, ip)
}
return out
}
+13
View File
@@ -0,0 +1,13 @@
// 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
+17
View File
@@ -0,0 +1,17 @@
//go:build windows
package wintunnel
import (
"os/exec"
"syscall"
)
// hideConsole sets CREATE_NO_WINDOW so netsh/route/powershell helpers
// do not flash a cmd window when the joiner runs under Electron.
func hideConsole(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{
HideWindow: true,
CreationFlags: 0x08000000, // CREATE_NO_WINDOW
}
}
+158
View File
@@ -0,0 +1,158 @@
//go:build windows
package wintunnel
import (
"bytes"
"encoding/json"
"fmt"
"net"
"os/exec"
"strconv"
"strings"
)
// runHidden invokes a command with no console window. All wintunnel
// 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) {
cmd := exec.Command(name, args...)
hideConsole(cmd)
var out, errBuf bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &errBuf
if err := cmd.Run(); err != nil {
return out.Bytes(), fmt.Errorf("%s %s: %w (%s)",
name, strings.Join(args, " "), err, strings.TrimSpace(errBuf.String()))
}
return out.Bytes(), nil
}
// setAdapterIP gives the wintun adapter its tunnel IP.
func setAdapterIP(adapter, ipStr, mask string) error {
_, err := runHidden("netsh", "interface", "ipv4", "set", "address",
"name="+adapter, "static", ipStr, mask)
return err
}
// setAdapterMTU sets the wintun adapter's MTU. netsh accepts this on
// any IPv4-capable interface, including wintun.
func setAdapterMTU(adapter string, mtu int) error {
_, err := runHidden("netsh", "interface", "ipv4", "set", "subinterface",
adapter, "mtu="+strconv.Itoa(mtu), "store=active")
return err
}
// setAdapterDNS pins resolvers onto the wintun adapter. Windows picks
// resolvers per interface based on the routing decision, so this is
// what makes DNS lookups from non-bypassed apps go through the tunnel.
func setAdapterDNS(adapter string, servers []string) error {
if len(servers) == 0 {
return nil
}
if _, err := runHidden("netsh", "interface", "ipv4", "set", "dnsservers",
"name="+adapter, "static", servers[0], "primary", "validate=no"); err != nil {
return err
}
for _, s := range servers[1:] {
if _, err := runHidden("netsh", "interface", "ipv4", "add", "dnsservers",
"name="+adapter, s, "validate=no"); err != nil {
return err
}
}
return nil
}
// addRouteViaAdapter installs a prefix route bound to the wintun
// adapter. The nexthop must be on-link (typically TunnelPeer).
func addRouteViaAdapter(prefix, adapter, nexthop string, metric int) error {
_, err := runHidden("netsh", "interface", "ipv4", "add", "route",
"prefix="+prefix, "interface="+adapter,
"nexthop="+nexthop, "metric="+strconv.Itoa(metric),
"store=active")
return err
}
func deleteRouteByPrefix(prefix, adapter string) error {
_, err := runHidden("netsh", "interface", "ipv4", "delete", "route",
"prefix="+prefix, "interface="+adapter)
return err
}
// addHostRoute installs a /32 route for ip via the given gateway. Used
// for the joiner's signaling + SFU bypasses.
func addHostRoute(ip, gateway string, metric int) error {
_, err := runHidden("route", "-p", "ADD", ip,
"MASK", "255.255.255.255", gateway,
"METRIC", strconv.Itoa(metric))
if err == nil {
return nil
}
// retry without persistence in case -p is rejected on this host
_, err = runHidden("route", "ADD", ip,
"MASK", "255.255.255.255", gateway,
"METRIC", strconv.Itoa(metric))
return err
}
func deleteHostRoute(ip string) error {
_, err := runHidden("route", "DELETE", ip)
return err
}
// adapterIPv4Index returns the InterfaceIndex of the wintun adapter
// once netsh has assigned an IP to it. Best-effort; used only for logs.
func adapterIPv4Index(adapter string) (uint32, error) {
out, err := runHidden("powershell", "-NoProfile", "-Command",
"(Get-NetAdapter -Name '"+adapter+"' -ErrorAction Stop).ifIndex")
if err != nil {
return 0, err
}
v, err := strconv.ParseUint(strings.TrimSpace(string(out)), 10, 32)
if err != nil {
return 0, err
}
return uint32(v), nil
}
// defaultIPv4Gateway picks the active default route, excluding any
// route that already points through our future wintun adapter. The
// returned alias is the InterfaceAlias of that route's interface,
// useful for logging.
type psRoute struct {
NextHop string `json:"NextHop"`
InterfaceAlias string `json:"InterfaceAlias"`
RouteMetric int `json:"RouteMetric"`
}
func defaultIPv4Gateway() (gateway, alias string, err error) {
out, err := runHidden("powershell", "-NoProfile", "-Command",
"Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 -ErrorAction Stop "+
"| Sort-Object -Property RouteMetric "+
"| Select-Object NextHop,InterfaceAlias,RouteMetric "+
"| ConvertTo-Json -Compress")
if err != nil {
return "", "", err
}
body := bytes.TrimSpace(out)
if len(body) == 0 {
return "", "", fmt.Errorf("no default route on this host")
}
if body[0] == '{' {
body = append([]byte{'['}, append(body, ']')...)
}
var rows []psRoute
if err := json.Unmarshal(body, &rows); err != nil {
return "", "", fmt.Errorf("parse Get-NetRoute output: %w", err)
}
for _, r := range rows {
if r.NextHop == "" || r.NextHop == "0.0.0.0" {
continue
}
if ip := net.ParseIP(r.NextHop); ip == nil {
continue
}
return r.NextHop, r.InterfaceAlias, nil
}
return "", "", fmt.Errorf("no usable default route (out=%s)", string(out))
}
+35
View File
@@ -0,0 +1,35 @@
//go:build !windows
package wintunnel
import (
"errors"
"net"
)
var errUnsupported = errors.New("wintunnel: only supported on windows")
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{}
func New(_ Config) (*Tunnel, error) { return nil, errUnsupported }
func (*Tunnel) Start() error { return errUnsupported }
func (*Tunnel) Stop() {}
func (*Tunnel) AddBypassIP(_ net.IP) error { return errUnsupported }
func (*Tunnel) AddBypassHost(_ string) ([]net.IP, error) {
return nil, errUnsupported
}
func (*Tunnel) AddBypassFromCandidate(_ string) error { return errUnsupported }
+255
View File
@@ -0,0 +1,255 @@
//go:build windows
package wintunnel
import (
"errors"
"fmt"
"log"
"net"
"sync"
"github.com/xjasonlyu/tun2socks/v2/engine"
)
// Config describes one wintun adapter and the SOCKS5 endpoint that
// tun2socks should forward traffic to.
type Config struct {
// AdapterName is the wintun adapter name shown in Windows. Must be unique.
AdapterName string
// TunnelIP is the local address assigned to the adapter (e.g. 10.99.0.2).
TunnelIP string
// TunnelMask is the subnet mask as dotted-quad (e.g. 255.255.255.0).
TunnelMask string
// TunnelPeer is the on-link next-hop used by the default routes
// installed on the wintun adapter (e.g. 10.99.0.1). It does not need
// to answer; wintun is point-to-point so Windows does not ARP for it.
TunnelPeer string
// MTU for the wintun adapter. 1500 is fine for most networks.
MTU int
// DNSServers is the list of resolvers to assign to the adapter.
DNSServers []string
// SocksHost / SocksPort / SocksUser / SocksPass: the local SOCKS5
// proxy that the headless joiner is running. tun2socks dials this
// for every captured TCP/UDP flow.
SocksHost string
SocksPort int
SocksUser string
SocksPass string
LogFn func(format string, args ...any)
}
// Tunnel owns one wintun adapter and the tun2socks engine instance
// driving it. Call New + Start to bring it up, Stop to tear it down.
type Tunnel struct {
cfg Config
log func(string, ...any)
mu sync.Mutex
started bool
stopped bool
bypass map[string]struct{} // /32 routes we installed for bypass
origGateway string
origIfAlias string
tunIfIndex uint32
}
// 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")
}
if cfg.TunnelIP == "" || cfg.TunnelMask == "" || cfg.TunnelPeer == "" {
return nil, errors.New("wintunnel: 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("wintunnel: 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
}
// Start brings up the wintun adapter, captures the original default
// gateway so subsequent AddBypass* calls can pin /32 routes to it,
// configures the adapter, installs the split default route through
// the tunnel, and starts the tun2socks engine. After Start returns,
// every packet leaving the OS that does not match a bypass route
// will be steered through SOCKS5.
func (t *Tunnel) Start() error {
t.mu.Lock()
defer t.mu.Unlock()
if t.started {
return errors.New("wintunnel: already started")
}
gw, alias, err := defaultIPv4Gateway()
if err != nil {
return fmt.Errorf("wintunnel: read default gateway: %w", err)
}
t.origGateway = gw
t.origIfAlias = alias
t.log("[wintunnel] original default gateway %s via %q", gw, alias)
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("[wintunnel] starting tun2socks engine adapter=%s mtu=%d proxy=%s",
t.cfg.AdapterName, t.cfg.MTU, proxy)
engine.Insert(key)
engine.Start()
// 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)
}
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)
}
if err := setAdapterDNS(t.cfg.AdapterName, t.cfg.DNSServers); err != nil {
t.log("[wintunnel] set dns failed (continuing): %v", err)
}
idx, err := adapterIPv4Index(t.cfg.AdapterName)
if err == nil {
t.tunIfIndex = idx
}
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.started = true
t.log("[wintunnel] up: adapter=%s ip=%s/%s peer=%s",
t.cfg.AdapterName, t.cfg.TunnelIP, t.cfg.TunnelMask, t.cfg.TunnelPeer)
return nil
}
// Stop removes every route we installed and shuts the wintun adapter
// down. Safe to call from multiple goroutines and idempotent.
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 := deleteHostRoute(ip); err != nil {
t.log("[wintunnel] 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)
}
}
engine.Stop()
t.log("[wintunnel] down")
}
// AddBypassIP installs a /32 route for ip via the original default
// gateway. Used so the joiner's own connections to signaling and SFU
// 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")
}
v4 := ip.To4()
if v4 == nil {
// IPv6 bypass is out of scope: the joiner negotiates v4 hosts
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("wintunnel: 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)
}
t.mu.Lock()
t.bypass[addr] = struct{}{}
t.mu.Unlock()
t.log("[wintunnel] bypass %s -> %s", addr, gw)
return nil
}
// AddBypassHost resolves hostname (system resolver, no tunnel) and
// installs a /32 bypass route for every returned A record. The
// resolved IPs are returned so callers can wire them into other
// settings, e.g. a Pion ResolveICEHost callback.
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("wintunnel: 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)
continue
}
out = append(out, v4)
}
}
if len(out) == 0 {
return nil, fmt.Errorf("wintunnel: no v4 addresses for %s", hostname)
}
return out, nil
}
// AddBypassFromCandidate parses an SDP candidate line ("candidate:..."
// or "a=candidate:...") and bypasses every IPv4 address found in it.
// Both the relay address and the rel-addr (TURN reflexive) are honored.
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
}