Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ undone by a rollback. Revoking also drops the hash, so a name used again never b
| Scope | Actions |
|---|---|
| `read` | `status`, `config`, `config.raw`, `schema`, `history`, `history.diff`, `job`, `net`, `net.ports`, `net.routes`, `net.wan`, `wifi.status`, `wifi.stations`, `wifi.survey`, `wifi.health`, `dns.stats`, `dns.leases`, `fw.stats`, `proxy.status`, `proxy.routes`, `mon.now`, `mon.history`, `mon.devices`, `mon.conns`, `mon.procs`, `mon.dmesg`, `mon.traffic` (monthly traffic), `sys.services`, `sys.time`, `sys.doctor` (runs the health checks), `sys.events` (the event log), `sys.edge`, `dev.paused` (active pauses) |
| `operate` | + `net.redial`, `wifi.kick`, `wifi.scan`, `dns.release`, `dns.adblock`, `proxy.delay`, `proxy.select`, `proxy.check` (POST, local DNS probes), `service` (start / stop / restart), `sys.heal` (restart wanted services that do not run, like `mr doctor --heal`), `diag`, `sys.speedtest` (POST, ~20 s), `dev.pause` (`{target, duration}`: a device, `group:NAME`, dhcp.hosts name or MAC; `30m` … `7d`), `dev.unpause` (`{target}`, `all`) |
| `operate` | + `net.redial`, `net.dial_restore`, `net.wan_mac`, `wifi.kick`, `wifi.scan`, `dns.release`, `dns.adblock`, `proxy.delay`, `proxy.select`, `proxy.check` (POST, local DNS probes), `service` (start / stop / restart), `sys.heal` (restart wanted services that do not run, like `mr doctor --heal`), `diag`, `sys.speedtest` (POST, ~20 s), `dev.pause` (`{target, duration}`: a device, `group:NAME`, dhcp.hosts name or MAC; `30m` … `7d`), `dev.unpause` (`{target}`, `all`) |
| `apply` | + `plan`, `validate`, `apply`, `confirm`, `revert`, `rollback` |

Never, whatever the scope: login / sessions, the web UI password, logs (`logs`, `sys.logs`: they can
Expand Down
2 changes: 2 additions & 0 deletions docs/modules/net.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,8 @@ conntrack 会把后续包当作 invalid 丢掉。
| `mr wan detect <port> [--timeout N]` | 一次性探测链路、PPPoE PADO、DHCP OFFER 和 IPv6 RA;默认最多 8 秒,不申请租约、不改地址 / 路由 / 服务 |
| API `net.wan_detect` | POST `{"port":"wan","timeout":8}`,返回探测结果、`recommendation`(`pppoe` / `dhcp` / `static` / `unknown`)及 LAN 冲突建议 |
| API `net.redial` | POST `{"wan":"wan2"}`:重启该 WAN 的服务(重新拨号 / 重新获取) |
| API `net.dial_restore` | POST `{}`:按已应用的 `multiwan.dial_order` 只重拨乱序 / 晚到的线路,返回 `redialled`、`failed` 和 `reason`;scope `operate` |
| API `net.wan_mac` | POST `{"wan":"wan2","device":"wan","vlan":0}`:为同一物理口的第 2 条及后续 PPPoE WAN 返回本地管理单播 MAC;scope `operate` |

## 对家里配置(examples/router.yaml)输出的改动(都是有意的)

Expand Down
4 changes: 2 additions & 2 deletions mr/api_token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ func TestTokenScopes(t *testing.T) {
want int
}{
{"reader", "status", 200}, {"reader", "config", 200}, {"reader", "mon.conns", 200}, {"reader", "history", 200}, {"reader", "schema", 200},
{"reader", "apply", 403}, {"reader", "plan", 403}, {"reader", "net.redial", 403}, {"reader", "confirm", 403},
{"ops", "net.redial", 200}, {"ops", "wifi.kick", 200}, {"ops", "status", 200}, {"ops", "apply", 403}, {"ops", "rollback", 403},
{"reader", "apply", 403}, {"reader", "plan", 403}, {"reader", "net.redial", 403}, {"reader", "net.dial_restore", 403}, {"reader", "net.wan_mac", 403}, {"reader", "confirm", 403},
{"ops", "net.redial", 200}, {"ops", "net.dial_restore", 200}, {"ops", "net.wan_mac", 200}, {"ops", "wifi.kick", 200}, {"ops", "status", 200}, {"ops", "apply", 403}, {"ops", "rollback", 403},
{"agent", "apply", 200}, {"agent", "plan", 200}, {"agent", "rollback", 200}, {"agent", "revert", 200}, {"agent", "net.redial", 200}, {"agent", "status", 200},
{"ha", "status", 200}, {"ha", "mon.now", 200}, {"ha", "mon.devices", 200}, {"ha", "config", 403}, {"ha", "wifi.stations", 403},
{"old", "status", 401},
Expand Down
16 changes: 9 additions & 7 deletions mr/mod_net.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,14 +293,16 @@ func init() {
RestartOrder: []string{"mr-pppoe.", "mr-udhcpc.", "mr-dhcpcd", "igmpproxy", "mr-wanmon"},
Verify: netVerify,
Status: netStatus,
TokenScope: map[string]string{"net": "read", "net.ports": "read", "net.routes": "read", "net.wan": "read", "net.wan_detect": "operate", "net.redial": "operate"},
TokenScope: map[string]string{"net": "read", "net.ports": "read", "net.routes": "read", "net.wan": "read", "net.wan_detect": "operate", "net.redial": "operate", "net.dial_restore": "operate", "net.wan_mac": "operate"},
API: map[string]func(r apiReq) apiResp{
"net": func(apiReq) apiResp { return apiNet() },
"net.ports": func(apiReq) apiResp { return apiNetPorts() },
"net.routes": func(apiReq) apiResp { return apiNetRoutes() },
"net.wan": func(apiReq) apiResp { return apiNetWAN() },
"net.wan_detect": apiNetWANDetect,
"net.redial": apiNetRedial,
"net": func(apiReq) apiResp { return apiNet() },
"net.ports": func(apiReq) apiResp { return apiNetPorts() },
"net.routes": func(apiReq) apiResp { return apiNetRoutes() },
"net.wan": func(apiReq) apiResp { return apiNetWAN() },
"net.wan_detect": apiNetWANDetect,
"net.redial": apiNetRedial,
"net.dial_restore": apiNetDialRestore,
"net.wan_mac": apiNetWANMac,
},
Commands: map[string]func(c *Config, args []string) error{
"wan": wanCommand,
Expand Down
51 changes: 43 additions & 8 deletions mr/mod_net_dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,28 +248,50 @@ func dialDue(late []string, st map[string]int64, now int64) []string {

// dialRestore is `mr wan dial-restore` (detached from the ppp-up hook, or crond): redials the late WANs
// in dial order, each after the previous one has its new session (or dial_wait passed).
func dialRestore(c *Config) error {
type dialRestoreResult struct {
Redialled []string
Failed []string
Reason string
}

// dialRestoreWithOptions restores only WANs that arrived out of order. Manual requests force a
// one-shot run even when the scheduled dial_restore setting is off and bypass the automatic cooldown.
func dialRestoreWithOptions(c *Config, force bool) (dialRestoreResult, error) {
var result dialRestoreResult
m := c.MultiWAN
if !dialRestoreOn(m) {
return nil
if !force && !dialRestoreOn(m) {
result.Reason = "disabled"
return result, nil
}
lk := flock(dialLockFile, false)
if lk == nil {
return nil // a restore is running
result.Reason = "already_running"
return result, nil // a restore is running
}
defer lk.Close()
late := dialLate(c)
if len(late) == 0 {
return nil
result.Reason = "order_ok"
return result, nil
}
st := map[string]int64{}
readJSONFile(dialStateFile, &st)
due := dialDue(late, st, eventNow().Unix())
due := late
if !force {
due = dialDue(late, st, eventNow().Unix())
}
if len(due) < len(late) {
logf("dial order: broken (%s), redialling only %d of them (at most once per %d minutes each)", strings.Join(late, ", "), len(due), dialRestoreGap/60)
}
if len(due) == 0 {
return nil
result.Reason = "rate_limited"
return result, nil
}
if force {
now := eventNow().Unix()
for _, n := range due {
st[n] = now
}
}
b, _ := json.Marshal(st)
writeAtomic(dialStateFile, b, 0644)
Expand All @@ -279,8 +301,21 @@ func dialRestore(c *Config) error {
eventAdd(c, "dial", "info", n, fmt.Sprintf("%s redialled to restore the dial order %s", n, strings.Join(m.DialOrder, " → ")), true)
t0 := eventNow().Unix()
if dialRestart(svc) == nil {
result.Redialled = append(result.Redialled, n)
dialWaitUp(c, []string{n}, t0, eventNow().Add(m.dialWait()))
} else {
result.Failed = append(result.Failed, n)
}
}
return nil
if len(result.Redialled) > 0 {
result.Reason = "redialled"
} else {
result.Reason = "failed"
}
return result, nil
}

func dialRestore(c *Config) error {
_, err := dialRestoreWithOptions(c, false)
return err
}
24 changes: 24 additions & 0 deletions mr/mod_net_dial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,27 @@ func TestDialRestore(t *testing.T) {
t.Errorf("after 11 minutes: restarted %v", restarted)
}
}

func TestDialRestoreManualResult(t *testing.T) {
c, now, _, _ := dialEnv(t)
c.MultiWAN.DialRestore = "off"
for i := range c.WAN {
c.WAN[i].IPv6PD = false
}
var restarted []string
dialRestart = func(svc string) error {
restarted = append(restarted, svc)
writeLease(strings.TrimPrefix(svc, "mr-pppoe."), wanLease{IP: "192.0.2.1", Since: now.Unix()})
return nil
}
writeLease("wan", wanLease{IP: "192.0.2.1", Since: now.Unix() - 100})
writeLease("wan2", wanLease{IP: "192.0.2.2", Since: now.Unix()})
got, err := dialRestoreWithOptions(c, true)
if err != nil || got.Reason != "redialled" || strings.Join(got.Redialled, ",") != "wan" || strings.Join(restarted, ",") != "mr-pppoe.wan" {
t.Fatalf("manual restore: result=%+v restarted=%v err=%v", got, restarted, err)
}
got, err = dialRestoreWithOptions(c, true)
if err != nil || got.Reason != "order_ok" || len(got.Redialled) != 0 {
t.Fatalf("manual restore after order fixed: result=%+v err=%v", got, err)
}
}
89 changes: 89 additions & 0 deletions mr/mod_net_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -480,3 +480,92 @@ func apiNetRedial(r apiReq) apiResp {
startDetached("rc-service", svc, "restart")
return apiResp{body: map[string]any{"ok": true, "service": svc}}
}

// apiNetDialRestore starts the same ordered restore used by the ppp-up hook and crond.
// It is an operate action: it changes runtime sessions but does not edit router.yaml.
func apiNetDialRestore(r apiReq) apiResp {
if r.method != "POST" {
return errResp(405, "POST required")
}
c, err := loadConfig(ConfigPath, SecretsPath)
if err != nil {
return errResp(500, "%v", err)
}
if len(c.MultiWAN.DialOrder) < 2 {
return errResp(400, "multiwan.dial_order is not configured")
}
result, err := dialRestoreWithOptions(c, true)
if err != nil {
return errResp(500, "%v", err)
}
if len(result.Redialled) > 0 {
appendChangeLog("webui: restore WAN dial order (" + strings.Join(result.Redialled, ", ") + ")")
}
return apiResp{body: map[string]any{
"ok": len(result.Failed) == 0,
"redialled": result.Redialled,
"failed": result.Failed,
"reason": result.Reason,
}}
}

// apiNetWANMac returns the stable locally administered MAC used by `mr wan mac`.
// The device/vlan fields allow the UI to generate one for a newly added, not-yet-applied WAN.
type wanMACRequest struct {
WAN string `json:"wan"`
Device string `json:"device"`
VLAN int `json:"vlan"`
}

func wanMACCandidate(c *Config, in wanMACRequest) (string, error) {
if !reName.MatchString(in.WAN) {
return "", fmt.Errorf("bad wan name")
}
var w WAN
if configured := c.WANByName(in.WAN); configured != nil {
w = *configured
if w.Proto != "pppoe" {
return "", fmt.Errorf("WAN %s is not PPPoE", w.Name)
}
for _, prior := range c.WAN {
if prior.Proto == "pppoe" && prior.LinkDev() == w.LinkDev() {
if prior.Name == w.Name {
return "", fmt.Errorf("WAN %s is the first PPPoE WAN on %s; use the port MAC", w.Name, w.LinkDev())
}
break
}
}
} else {
if !validDev(in.Device) || strings.Contains(in.Device, "..") {
return "", fmt.Errorf("bad device")
}
if in.VLAN < 0 || in.VLAN > 4094 {
return "", fmt.Errorf("bad vlan")
}
w = WAN{Name: in.WAN, Device: in.Device, VLAN: in.VLAN, Proto: "pppoe"}
}
portMAC := wanPortMAC(c, w, readFile)
if !reMAC.MatchString(portMAC) || !unicastMAC(portMAC) {
return "", fmt.Errorf("cannot read the MAC address of %s", w.LinkDev())
}
return wanMACSuggest(portMAC, w.Name), nil
}

func apiNetWANMac(r apiReq) apiResp {
if r.method != "POST" {
return errResp(405, "POST required")
}
var in wanMACRequest
if err := json.Unmarshal(r.body, &in); err != nil {
return errResp(400, "bad request")
}
c, err := loadConfig(ConfigPath, SecretsPath)
if err != nil {
return errResp(500, "%v", err)
}
mac, err := wanMACCandidate(c, in)
if err != nil {
return errResp(400, "%v", err)
}
return apiResp{body: map[string]any{"mac": mac}}
}
23 changes: 23 additions & 0 deletions mr/mod_net_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,29 @@ func TestInitInstancesAndRedialInput(t *testing.T) {
if r := apiNetRedial(apiReq{method: "POST", body: []byte(`{"wan":"../../etc"}`)}); r.status != 400 {
t.Errorf("redial with bad name: %d", r.status)
}
if r := apiNetDialRestore(apiReq{method: "GET"}); r.status != 405 {
t.Errorf("dial restore via GET: %d", r.status)
}
if r := apiNetWANMac(apiReq{method: "GET"}); r.status != 405 {
t.Errorf("wan mac via GET: %d", r.status)
}
}

func TestWANMACCandidateGuardsPrimary(t *testing.T) {
c := testConfig(t)
if _, err := wanMACCandidate(c, wanMACRequest{WAN: "wan"}); err == nil || !strings.Contains(err.Error(), "first PPPoE WAN") {
t.Fatalf("primary WAN was allowed to receive a generated MAC: %v", err)
}
if _, err := wanMACCandidate(c, wanMACRequest{WAN: "wan2"}); err != nil {
t.Fatalf("secondary WAN rejected: %v", err)
} else if got, _ := wanMACCandidate(c, wanMACRequest{WAN: "wan2"}); got != wanMACSuggest(c.WAN[0].MAC, "wan2") {
t.Fatalf("secondary MAC %q, want %q", got, wanMACSuggest(c.WAN[0].MAC, "wan2"))
}
for _, in := range []wanMACRequest{{WAN: "../../etc"}, {WAN: "new", Device: "wan..x"}, {WAN: "new", Device: "wan", VLAN: 4095}} {
if _, err := wanMACCandidate(c, in); err == nil {
t.Errorf("invalid request accepted: %+v", in)
}
}
}

// A WAN that left router.yaml (or moved to another interface) has its lease record dropped;
Expand Down
Loading
Loading