wsl: a bridged distro reaches Windows on the bridge's adapter, not the LAN router

ecalpal_ on Discord (magpie 0.1.2689, Windows 11, WSL 3.0.3.0, Ubuntu
22.04.5; .wslconfig vmSwitch=WSL_Bridge_Switch, networkingMode=Bridged,
dhcp=false). In bridged networking the distro is a peer on the LAN and its
default route is the router, 192.168.9.1. magpie took that next hop for
Windows: wsl.json got {"net":"bridged","gateway":"192.168.9.1"} and Pi's
models.json a baseUrl on 192.168.9.1:3425, where nothing listens, with the
gateway token rather than the WSL key. serveWSL already listened on
192.168.9.147, Windows' address on vEthernet (WSL_Bridge_Switch).

wslrun.HostAt now picks the address: "" where the distro's 127.0.0.1 is
Windows' (mirrored, consomme, virtioproxy, as before); the next hop as it
is when it is Windows' own address on a WSL adapter (NAT, unchanged);
otherwise Windows' address on the one WSL adapter whose network holds
that next hop (bridged: 192.168.9.1 in 192.168.9.147/24 -> .147). A next
hop on no WSL network is kept as it was. The adapter list moved from
gateway.wslNets to wslrun.Nets (gateway.WSLNets still wraps it), so both
probes use it: agent's parseProbe (distro.Gateway, what place writes into
agents) and wslrun's (Tool.Host, a 127.0.0.1 proxy handed to a WSL CLI),
which had the same bug.

The key follows the address: keyAt(http://192.168.9.147:3425) is on a WSL
net (OnWSLNet), so agents there get the WSL key.

Existing users: on the next start, the first probe of the running distro
writes the new gateway into wsl.json and keeps 192.168.9.1 in Was. The
startup SyncCatalog then rewrites Pi's provider block (baseUrl and apiKey)
at the new address; keptaway treats the old router address as magpie's
because it is in Was. A distro that isn't running at start is fixed at its
first probe after it runs, and its agents' files at the next sync after
that. Codex in WSL, which keeps its own base_url, gets the existing
"unreachable" drift with "Use 192.168.9.147:3425" (wslMovedFrom), not an
automatic rewrite.

Tests (fixtures are the reporter's values):
- wslrun TestHostAt: bridged/nat/mirrored/consomme each with its own route
  and adapters; TestParseProbeBridged (Tool.Host and proxy).
- agent TestWSLBridgedReachesWindowsOnTheBridge (bridged .147, nat
  172.20.0.1 unchanged, mirrored 127.0.0.1) and
  TestWSLBridgedOldRouterWrittenOver: wsl.json and Pi's models.json as
  0.1.2689 wrote them, then a probe and a sync: baseUrl .147, apiKey the
  WSL key, wsl.json rewritten.

Run:
- Broken by hand: probe code put back to HostLoopback only. Both new agent
  tests and TestParseProbeBridged FAIL (Gateway/Host 192.168.9.1).
- mote: gofmt -l empty; go vet, GOOS=windows go vet, GOOS=linux go vet
  -tags nogui for wslrun, gateway, agent; GOOS=windows go build: ok.
- mote: go test -timeout 45m ./internal/wslrun ./internal/agent
  ./internal/gateway: ok (wslrun 1.3s, agent 231s, gateway 855s)
- xiaomi-gpu (win-run): go test ./internal/wslrun ./internal/gateway
  -run 'HostAt|ParseProbe|WSL' ok; ./internal/agent -run
  'WSL|ParseProbe|Omp' ok. A first try with a fallback (bridged + one WSL
  adapter -> that adapter) went red there on TestParseProbe and
  TestWSLNetworkingFromWslinfo, because the box's real NAT adapter
  (vEthernet (WSL (Hyper-V firewall)) 172.17.32.1/20) was taken for the
  bridge; the fallback was dropped.
- xiaomi-gpu, real adapters: HostAt("nat", "172.17.32.1", Nets()) =
  172.17.32.1; magpie-desktop is NAT (wslinfo nat, default via
  172.17.32.1), so its value is unchanged.

Not tried: a real bridged WSL (none on the LAN; magpie-desktop's
networking was not changed), a real magpie start against an existing
wrong config, and the full go test ./... before the push (run after).
This commit is contained in:
yetone
2026-11-06 10:49:35 +08:00
parent 26a6461b14
commit cff530079f
6 changed files with 250 additions and 34 deletions
File diff suppressed because one or more lines are too long
+5 -4
View File
@@ -1788,10 +1788,11 @@ func parseProbe(name, out string) *distro {
// the default route of a distro whose 127.0.0.1 is Windows' is
// Windows' own next hop (consomme: 198.18.0.2 under a TUN proxy,
// #1230), not Windows: an agent left on it is moved to 127.0.0.1
// (wslMovedFrom)
if wslrun.HostLoopback(d.Net) {
d.Gateway = ""
}
// (wslMovedFrom). A bridged distro's is the LAN's router: Windows is
// at its address on the bridge's adapter (wslrun.HostAt), and an agent
// an older magpie pointed at the router is written over on the next
// sync, the router being among the addresses it was seen at (Was)
d.Gateway = wslrun.HostAt(d.Net, d.Gateway, gateway.WSLNets())
return d
}
+100
View File
@@ -0,0 +1,100 @@
package agent
import (
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/gateway"
)
// ecalpal_ on Discord (magpie 0.1.2689, WSL 3.0.3.0, Ubuntu 22.04.5,
// .wslconfig vmSwitch=WSL_Bridge_Switch, networkingMode=Bridged,
// dhcp=false): in bridged networking the distro's default route is the
// LAN's router, 192.168.9.1, while Windows is at 192.168.9.147/24 on
// vEthernet (WSL_Bridge_Switch). magpie wrote the router into wsl.json and
// into Pi's models.json, where nothing listens. Windows' address on the
// bridge is the distro's way to it, and its key is the WSL key that
// address takes. NAT and mirrored keep their own values.
func TestWSLBridgedReachesWindowsOnTheBridge(t *testing.T) {
for _, c := range []struct {
net, cidr, route, want string
}{
{"bridged", "192.168.9.147/24", "192.168.9.1", "192.168.9.147"},
{"nat", "172.20.0.1/20", "172.20.0.1", "172.20.0.1"},
{"mirrored", "192.168.9.147/24", "192.168.9.1", ""},
} {
fakeWSLNet(t, c.cidr)
d := parseProbe("Ubuntu-22.04", "home:/home/me\ndir:.pi\nroute:default via "+c.route+" dev eth0 proto static\nnet:"+c.net+"\n")
if d == nil || d.Gateway != c.want {
t.Fatalf("%s: %+v", c.net, d)
}
d.mirror("")
want := gateway.URL()
if c.want != "" {
want = "http://" + c.want + ":" + gateway.Port()
}
if d.base() != want {
t.Errorf("%s: %s, want %s", c.net, d.base(), want)
}
}
}
// One an older magpie set up on the router has its wsl.json and Pi's
// models.json written over once magpie starts again and probes the
// running distro: the address and the key with it.
func TestWSLBridgedOldRouterWrittenOver(t *testing.T) {
root, home := piDistroHome(t, `{"defaultProvider": "xai", "defaultModel": "grok-4.6"}`)
models := filepath.Join(home, ".pi", "agent", "models.json")
// what 0.1.2689 wrote: Pi on the router, with the gateway's token
old := distro{Name: "Ubuntu-22.04", Root: root, Home: "/home/me", Has: map[string]bool{"dir:.pi": true},
Gateway: "192.168.9.1", Net: "bridged", Running: true}
if err := wslPi(old).Apply("model", "magpie/relay/glm-4.6"); err != nil {
t.Fatal(err)
}
pi := func() map[string]any {
var f struct {
Providers map[string]map[string]any `json:"providers"`
}
if err := json.Unmarshal([]byte(readFile(models)), &f); err != nil {
t.Fatal(err)
}
return f.Providers["magpie"]
}
if p := pi(); p["baseUrl"] != "http://192.168.9.1:"+gateway.Port()+"/v1" {
t.Fatalf("old config: %v", p)
}
fakeWSL(t, "Ubuntu-22.04\r\n", "Ubuntu-22.04\r\n", map[string]string{
"Ubuntu-22.04": "home:/home/me\ndir:.pi\nroute:default via 192.168.9.1 dev eth0 proto static\nnet:bridged\n",
}, map[string]string{"Ubuntu-22.04": root})
os.MkdirAll(filepath.Dir(wslStatePath()), 0o755)
if err := os.WriteFile(wslStatePath(), []byte(`{"Ubuntu-22.04":{"name":"Ubuntu-22.04","home":"/home/me","root":"","has":{"dir:.pi":true},"probe":`+
jsonInt(wslProbeVersion)+`,"net":"bridged","gateway":"192.168.9.1"}}`), 0o644); err != nil {
t.Fatal(err)
}
fakeWSLNet(t, "192.168.9.147/24")
ds := wslDistros()
if len(ds) != 1 || ds[0].Gateway != "192.168.9.147" || len(ds[0].Was) != 1 || ds[0].Was[0] != "192.168.9.1" {
t.Fatalf("%+v", ds)
}
wslSave()
var saved map[string]distro
if err := json.Unmarshal([]byte(readFile(wslStatePath())), &saved); err != nil || saved["Ubuntu-22.04"].Gateway != "192.168.9.147" {
t.Fatalf("wsl.json: %v\n%s", err, readFile(wslStatePath()))
}
a := wslPi(ds[0])
if !a.Wired() {
t.Fatalf("not wired: SyncCatalog would leave it: %v live %v\n%s", a.Values(), ds[0].live(), readFile(filepath.Join(home, ".pi", "agent", "settings.json")))
}
if err := a.Sync(); err != nil {
t.Fatal(err)
}
p := pi()
if p["baseUrl"] != "http://192.168.9.147:"+gateway.Port()+"/v1" || p["apiKey"] != gateway.WSLKey() || gateway.WSLKey() == "" {
t.Fatalf("after a sync: %v (WSL key %q)", p, gateway.WSLKey())
}
}
func jsonInt(n int) string { b, _ := json.Marshal(n); return string(b) }
+4 -26
View File
@@ -19,6 +19,7 @@ import (
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/wslrun"
)
// A WSL distro in NAT networking (WSL's default) reaches Windows at the
@@ -36,34 +37,11 @@ import (
// of Docker Desktop's, which shares that network, has no key.
// WSLNets are the networks Windows has an address on that WSL distros reach
// it through: the IPv4 addresses of the vEthernet (WSL) adapters (named
// "vEthernet (WSL)" or, with the Hyper-V firewall, "vEthernet (WSL (Hyper-V
// firewall))"), there while WSL's VM runs. None off Windows. A var for the
// tests.
// it through (wslrun.Nets): the vEthernet (WSL…) adapters', NAT's and a
// bridged switch's. None off Windows. A var for the tests.
var WSLNets = wslNets
func wslNets() []*net.IPNet {
if runtime.GOOS != "windows" {
return nil
}
ifs, err := net.Interfaces()
if err != nil {
return nil
}
var out []*net.IPNet
for _, i := range ifs {
if i.Flags&net.FlagUp == 0 || !strings.Contains(i.Name, "(WSL") {
continue
}
addrs, _ := i.Addrs()
for _, a := range addrs {
if n, ok := a.(*net.IPNet); ok && n.IP.To4() != nil && !n.IP.IsLinkLocalUnicast() {
out = append(out, n)
}
}
}
return out
}
func wslNets() []*net.IPNet { return wslrun.Nets() }
// OnWSLNet says base (an agent's gateway URL) names an address Windows has
// on a WSL network: where a distro under NAT reaches the gateway.
+75
View File
@@ -0,0 +1,75 @@
package wslrun
import (
"net"
"testing"
)
func ipNet(t *testing.T, cidr string) *net.IPNet {
t.Helper()
ip, n, err := net.ParseCIDR(cidr)
if err != nil {
t.Fatal(err)
}
n.IP = ip
return n
}
// ecalpal_ on Discord (WSL 3.0.3.0, .wslconfig vmSwitch=WSL_Bridge_Switch,
// networkingMode=Bridged, dhcp=false): the distro's default route is the
// LAN's router, 192.168.9.1, and Windows is at 192.168.9.147/24 on
// vEthernet (WSL_Bridge_Switch). Each mode is checked with its own values.
func TestHostAt(t *testing.T) {
bridge := []*net.IPNet{ipNet(t, "192.168.9.147/24")}
nat := []*net.IPNet{ipNet(t, "172.20.0.1/20")}
both := append(append([]*net.IPNet{}, nat...), bridge...)
for _, c := range []struct {
mode, route string
nets []*net.IPNet
want string
}{
{"bridged", "192.168.9.1", bridge, "192.168.9.147"},
{"bridged", "192.168.9.1", both, "192.168.9.147"},
// a .wslconfig-only bridged WSL (no wslinfo) is told by the network
{"", "192.168.9.1", bridge, "192.168.9.147"},
// the router on no network Windows has on WSL's adapters: nothing
// tells which is Windows, NAT's adapter being up beside a bridge
{"bridged", "10.0.0.1", bridge, "10.0.0.1"},
{"bridged", "10.0.0.1", nat, "10.0.0.1"},
// nothing to tell by: kept
{"bridged", "192.168.9.1", nil, "192.168.9.1"},
// NAT: the next hop is Windows' own address there
{"nat", "172.20.0.1", nat, "172.20.0.1"},
{"nat", "172.20.0.1", both, "172.20.0.1"},
{"nat", "172.20.0.1", nil, "172.20.0.1"},
{"", "172.20.0.1", nat, "172.20.0.1"},
// mirrored and consomme: Windows' 127.0.0.1
{"mirrored", "192.168.9.1", bridge, ""},
{"consomme", "198.18.0.2", nat, ""},
{"bridged", "", bridge, ""},
} {
if got := HostAt(c.mode, c.route, c.nets); got != c.want {
t.Errorf("%s via %s on %v: %q, want %q", c.mode, c.route, c.nets, got, c.want)
}
}
}
// A WSL command found in a bridged distro reaches Windows at its address on
// the bridge, so a proxy at Windows' 127.0.0.1 is handed on there.
func TestParseProbeBridged(t *testing.T) {
old := Nets
t.Cleanup(func() { Nets = old })
Nets = func() []*net.IPNet { return []*net.IPNet{ipNet(t, "192.168.9.147/24")} }
out := "bin:/home/me/.local/bin/claude\nroute:default via 192.168.9.1 dev eth0 proto static\nnet:bridged\n"
tool, ok := parseProbe("Ubuntu-22.04", out)
if !ok || tool.Host != "192.168.9.147" {
t.Fatalf("%+v", tool)
}
if p := tool.proxy("http://127.0.0.1:7890"); p != "http://192.168.9.147:7890" {
t.Errorf("proxy: %s", p)
}
tool, _ = parseProbe("Ubuntu", "bin:/usr/bin/claude\nroute:default via 172.20.0.1 dev eth0\nnet:nat\n")
if tool.Host != "172.20.0.1" {
t.Errorf("nat: %+v", tool)
}
}
+65 -3
View File
@@ -316,12 +316,74 @@ func parseProbe(distro, out string) (Tool, bool) {
if dir := t.Path[:strings.LastIndex(t.Path, "/")]; dir != "" && !onPath(t.PATH, dir) {
t.PATH = dir + ":" + t.PATH
}
if HostLoopback(net_) {
t.Host = ""
}
t.Host = HostAt(net_, t.Host, Nets())
return t, true
}
// Nets are the networks Windows has an address on that WSL distros reach
// it through: the IPv4 addresses of its vEthernet (WSL…) adapters (NAT's
// "vEthernet (WSL)" or "vEthernet (WSL (Hyper-V firewall))", a bridged
// switch's "vEthernet (WSL_Bridge_Switch)"), there while WSL's VM runs.
// None off Windows. A var for the tests.
var Nets = nets
func nets() []*net.IPNet {
if runtime.GOOS != "windows" {
return nil
}
ifs, err := net.Interfaces()
if err != nil {
return nil
}
var out []*net.IPNet
for _, i := range ifs {
if i.Flags&net.FlagUp == 0 || !strings.Contains(i.Name, "(WSL") {
continue
}
addrs, _ := i.Addrs()
for _, a := range addrs {
if n, ok := a.(*net.IPNet); ok && n.IP.To4() != nil && !n.IP.IsLinkLocalUnicast() {
out = append(out, n)
}
}
}
return out
}
// HostAt is the address a distro in networking mode reaches Windows at,
// from its default route's next hop (route) and the networks Windows has
// on WSL's adapters (nets, Nets): "" where its 127.0.0.1 is Windows'
// (HostLoopback). Under NAT the next hop is Windows' address on
// vEthernet (WSL) itself, and is kept. Under bridged networking the
// distro is a peer on the LAN and its next hop is the LAN's router
// (192.168.9.1, ecalpal_ on Discord), not Windows: Windows is at its own
// address on the bridge's adapter, the one whose network holds that
// router. A next hop on no WSL network is kept as it was: NAT's
// vEthernet (WSL) can be up beside a bridge on another subnet, and is
// not where a bridged distro reaches Windows.
func HostAt(mode, route string, nets []*net.IPNet) string {
if HostLoopback(mode) {
return ""
}
ip := net.ParseIP(route)
if ip == nil {
return route
}
var in []*net.IPNet
for _, n := range nets {
if n.IP.Equal(ip) {
return route // Windows' own: NAT's
}
if n.Contains(ip) {
in = append(in, n)
}
}
if len(in) == 1 {
return in[0].IP.String()
}
return route
}
// HostLoopback reports whether 127.0.0.1 inside a WSL 2 distro reaches
// Windows' own 127.0.0.1 in networking mode, as wslinfo --networking-mode
// prints it: mirrored, and consomme (WSL 2.9's name for what was