From 77d285e47590d88eb0fe04ad0c6afd8cabdf4cb8 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:35:26 -0600 Subject: [PATCH 01/21] Firmware 4.0 protocol: client API 2, code-only refusals, exit code 7 Sync the error catalog (BP0001-BP0079) and the features table (rev 10, api 2) from the fw-3.11-cutover branch. ClientAPI is 2. Refusals are classified by their code only: every catalog code has a kind (refused, locked, busy, forbidden, update the pod, update the CLI), a coded reply without a message renders from the catalog, and a refusal without a code is shown as the pod wrote it. The text matching is gone (ClassifyRefusal, translateRefusal, explainRefusal, the lease, SPI busy, reply too large and LAN gate texts), and with it internal/fwrefusals. A pod below API level 2 (firmware 3.x) stops a command with exit code 7 and "this pod needs firmware 4.0: benchpod flash-self"; the CLI reads the pod's status once before its first command (LAN, USB network and the cloud). status, flash-self, install-blobs, dfu, bootsel, discover and identity still run against a pod of any level. README: exit codes and error codes. Co-Authored-By: Claude Opus 5.5 --- README.md | 58 +- cmd/benchpod-cli/adcrange.go | 2 +- cmd/benchpod-cli/busmaster.go | 4 +- cmd/benchpod-cli/busmaster_test.go | 31 +- cmd/benchpod-cli/ci_lease.go | 13 +- cmd/benchpod-cli/ci_phase4_test.go | 4 +- cmd/benchpod-cli/ci_status_test.go | 2 +- cmd/benchpod-cli/ci_test.go | 4 +- cmd/benchpod-cli/cloudcfg.go | 27 +- cmd/benchpod-cli/cloudcfg_test.go | 93 +-- cmd/benchpod-cli/errors.go | 204 +---- cmd/benchpod-cli/errors_test.go | 190 ++--- cmd/benchpod-cli/flash_self_cloud_test.go | 8 + cmd/benchpod-cli/flash_self_network.go | 5 +- cmd/benchpod-cli/flash_self_network_test.go | 14 +- cmd/benchpod-cli/gateware_reload_test.go | 5 + cmd/benchpod-cli/generate16_test.go | 2 +- cmd/benchpod-cli/identity.go | 2 +- cmd/benchpod-cli/lantls.go | 7 +- cmd/benchpod-cli/lapins_subset_test.go | 7 +- cmd/benchpod-cli/lavoltage.go | 2 +- cmd/benchpod-cli/lavoltage_test.go | 6 +- cmd/benchpod-cli/newerpod_test.go | 8 +- cmd/benchpod-cli/podclient_test.go | 16 +- cmd/benchpod-cli/policy.go | 13 +- cmd/benchpod-cli/policy_test.go | 7 +- cmd/benchpod-cli/pull_test.go | 2 +- cmd/benchpod-cli/refusals_test.go | 158 ---- cmd/benchpod-cli/root.go | 21 +- cmd/benchpod-cli/sensor.go | 2 +- cmd/benchpod-cli/sensor_test.go | 21 +- cmd/benchpod-cli/status.go | 2 +- cmd/benchpod-cli/usbnetwork.go | 2 +- internal/cloudpod/cloudpod.go | 33 +- internal/cloudpod/cloudpod_test.go | 34 +- internal/errcatalog/errors.json | 796 +++++++++++++++++++- internal/features/features.json | 72 +- internal/fwrefusals/fwrefusals.go | 172 ----- internal/fwrefusals/fwrefusals_test.go | 96 --- internal/fwrefusals/refusals.json | 126 ---- internal/serialconsole/refusals_test.go | 27 - internal/spiflash/refusals_internal_test.go | 31 +- internal/spiflash/spiflash.go | 6 +- internal/spiflash/spiflash_test.go | 3 +- internal/spiflash/spiflashtest/fake.go | 10 +- internal/tcpclient/client.go | 3 + internal/tcpclient/clientapi.go | 128 +++- internal/tcpclient/clientapi_test.go | 92 ++- internal/tcpclient/codes_test.go | 73 +- internal/tcpclient/errors.go | 201 +++-- internal/tcpclient/lease.go | 16 +- internal/tcpclient/lease_test.go | 2 +- internal/tcpclient/refusals_test.go | 62 +- internal/tcpclient/session.go | 3 + internal/tcpclient/swd.go | 3 + 55 files changed, 1633 insertions(+), 1298 deletions(-) delete mode 100644 cmd/benchpod-cli/refusals_test.go delete mode 100644 internal/fwrefusals/fwrefusals.go delete mode 100644 internal/fwrefusals/fwrefusals_test.go delete mode 100644 internal/fwrefusals/refusals.json delete mode 100644 internal/serialconsole/refusals_test.go diff --git a/README.md b/README.md index 8e1b391..7fe25d4 100644 --- a/README.md +++ b/README.md @@ -1038,25 +1038,33 @@ stderr with a `[benchpod]` prefix. | `3` | Refused: the pod refused the command (a locked LAN, a missing role, a bad request). | | `4` | Busy: the pod or one of its engines is in use (a cloud job's lease, another session). | | `5` | Unreachable: nothing answered on the pod's address, no pod was found on USB, or the pod is offline on embeddedci.com. | -| `6` | Update the CLI: the pod's firmware needs a newer benchpod CLI (see [Firmware newer than the CLI](#firmware-newer-than-the-cli)). | +| `6` | Update the CLI: the pod's firmware needs a newer benchpod CLI (see [Firmware and CLI levels](#firmware-and-cli-levels)). | +| `7` | Update the pod: its firmware is older than this CLI drives (firmware before 4.0: run `benchpod flash-self`), or it lacks what the command needs (`BP0002`, `BP0017`, `BP0060`). | `benchpod ci` has its own exit codes (a CI result, not a command's): see [Exit codes of `benchpod ci`](#exit-codes-of-benchpod-ci). -#### Firmware newer than the CLI +#### Firmware and CLI levels Every JSON command the CLI sends to the pod (on the LAN, over USB networking and through -embeddedci.com) carries `"client_api"`, the pod API level this CLI was built for, and -`"client"`, its name and version (`"cli 0.9.5"`). Firmware 3.10.13 and older ignores both. -Newer firmware announces its own level in `status`; it goes up only when the firmware changes -a reply in a way an older CLI would misread. When the pod's level is above this CLI's (a pod -without one counts as level 1), a command that reads the pod's status stops with exit code -`6` and says so. `status`, `flash-self`, `install-blobs`, `dfu`, `bootsel`, `discover` and -`identity` still run: `status` prints the same line as a warning, and the firmware commands are -how such a pod is updated or rolled back. +embeddedci.com) carries `"client_api"`, the pod API level this CLI was built for (2), and +`"client"`, its name and version (`"cli 0.10.0"`). The pod announces its own level in `status`; +it goes up only when the firmware changes a reply in a way an older CLI would misread. + +This CLI drives firmware 4.0 (level 2) only. Before a pod's first command it reads the pod's +status once and stops when the level does not match: + +- A pod above level 2 needs a newer CLI: exit code `6`. +- A pod below level 2 (firmware 3.x announces no level, which counts as 1) needs firmware 4.0: + exit code `7`, with `this pod needs firmware 4.0: benchpod flash-self`. + +`status`, `flash-self`, `install-blobs`, `dfu`, `bootsel`, `discover` and `identity` still run +against a pod of any level: `status` prints the same line as a warning, and the firmware commands +are how such a pod is updated or rolled back. Against firmware 3.x they send what 3.x takes. ```text -[benchpod] la voltage: this pod's firmware 3.11.0 needs a newer benchpod CLI (pod API 2, this CLI handles 1): brew upgrade --cask benchpod, or download the latest release from https://github.com/embeddedci-com/benchpod-cli/releases/latest +[benchpod] la voltage: this pod's firmware 3.10.13 is too old for this benchpod CLI (pod API 1, this CLI needs 2): this pod needs firmware 4.0: benchpod flash-self +[benchpod] la voltage: this pod's firmware 5.0.0 needs a newer benchpod CLI (pod API 3, this CLI handles 2): brew upgrade --cask benchpod, or download the latest release from https://github.com/embeddedci-com/benchpod-cli/releases/latest ``` A pod that no longer takes commands from a CLI this old refuses them with `BP0030`, which @@ -1064,19 +1072,21 @@ the CLI reports the same way. Update the CLI as you installed it (see [Installation](#installation)). Commands that only talk to embeddedci.com or work locally are not affected, and neither is the USB console. -Firmware 3.10.8 and later sends more and more refusals with a stable error code (`BP0001` and up). -The CLI then shows the code, what went wrong and what to run, from the error catalog it ships -with, plus a link to the code's page; `benchpod explain ` prints the whole entry. The -exit code follows the code: a session, the bus engine, the storage or a lease in use -(`BP0003`, `BP0004`, `BP0005`, `BP0016`, `BP0025`) is `4`, every other code `3`. - -A refusal without a code (older firmware, or one that has no code yet) is printed word for -word as the pod sent it. For a `locked:` (LAN policy), -`busy:` (cloud lease) or `forbidden:` (missing role) refusal the CLI adds what to do next. -So it does for `la voltage not set` (run `benchpod la voltage 3.3V` or 1.8V, or set it on -the web app's Wiring tab) and for a `pin conflict: LA4 is in use by ...`, where the raw -JSON command the firmware suggests is replaced by where to free the pin (the web app, -the SDK or the MCP session that holds it). +#### Error codes + +Every refusal a script or user acts on has a stable error code (`BP0001` and up), and firmware +4.0 sends only the code and its values. The CLI shows the code, what went wrong and what to run, +from the error catalog it ships with, plus a link to the code's page; `benchpod explain ` +prints the whole entry. The exit code follows the code: + +- `4` (busy): a session, the bus engine, the storage, a lease or the pod in use (`BP0003`, + `BP0004`, `BP0005`, `BP0016`, `BP0025`, `BP0047` to `BP0052`, `BP0066`). +- `7` (update the pod): `BP0002`, `BP0017`, `BP0060`. +- `6` (update the CLI): `BP0030`. +- `3` (refused): every other code. + +A refusal without a code (a bad argument, a failure only a person reads) is printed word for +word as the pod sent it, with exit code `3`. The CLI never reads a refusal's text. ### `benchpod setup` diff --git a/cmd/benchpod-cli/adcrange.go b/cmd/benchpod-cli/adcrange.go index b0a1c47..9553c7f 100644 --- a/cmd/benchpod-cli/adcrange.go +++ b/cmd/benchpod-cli/adcrange.go @@ -99,7 +99,7 @@ func adcRange(ctx context.Context, c podCommander, via, action, what string, out return errors.New(adcRangeMissing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/busmaster.go b/cmd/benchpod-cli/busmaster.go index a20ac7c..19eef21 100644 --- a/cmd/benchpod-cli/busmaster.go +++ b/cmd/benchpod-cli/busmaster.go @@ -41,7 +41,7 @@ func busCommand(ctx context.Context, t *podTarget, what, feature string, req map if isUnknownCommand(err) { return &shownRefusal{msg: what + ": " + tooOldForBusMaster(feature), pe: pe} } - return refusedError(what, pe, !t.spec.IsCloud()) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } @@ -574,7 +574,7 @@ type laPinsCommander interface { func laPinsFetch(ctx context.Context, c laPinsCommander, pins []int) (json.RawMessage, error) { if pins == nil { raw, err := c.Command(ctx, map[string]any{"cmd": "la_pins"}) - if err == nil || !strings.Contains(err.Error(), "reply too large") { // no code yet + if err == nil || !tcpclient.HasCode(err, "BP0053") { // reply_too_large return raw, err } first, err1 := laPinsQuery(ctx, c, []int{1, 2, 3, 4, 5, 6, 7}) diff --git a/cmd/benchpod-cli/busmaster_test.go b/cmd/benchpod-cli/busmaster_test.go index 56ca21a..79b1a10 100644 --- a/cmd/benchpod-cli/busmaster_test.go +++ b/cmd/benchpod-cli/busmaster_test.go @@ -191,7 +191,7 @@ func TestBusMasterOnOldFirmwareNamesTheUpdate(t *testing.T) { pod, g := newFakeSensorPod(t) pod.reply = func(req map[string]any) (any, string) { if req["cmd"] != "status" { - return nil, "unknown cmd" + return nil, "BP0002" } return nil, "" } @@ -207,19 +207,20 @@ func TestBusMasterOnOldFirmwareNamesTheUpdate(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "gateware v55 or later") || !strings.Contains(err.Error(), "benchpod flash-self") { t.Fatalf("%v: err = %v", c.args, err) } - if exitCode(err) != exitRefused { + if exitCode(err) != exitUpdatePod { t.Fatalf("%v: exit %d", c.args, exitCode(err)) } } - // The new firmware on old gateware says it itself; the CLI adds the command. + // Firmware 4.0 on old gateware says so with BP0017; the catalog names the command. pod.reply = func(req map[string]any) (any, string) { if req["cmd"] == "i2c_start" { - return nil, "the I2C master needs gateware v55+: update the pod's firmware" + return nil, `BP0017 {"feature":"I2C master","min":55}` } return nil, "" } _, err := runBus(t, g, newI2CCmd(g), "start", "--sda", "1", "--scl", "2") - if err == nil || !strings.Contains(err.Error(), "needs gateware v55+") || !strings.Contains(err.Error(), "benchpod flash-self") { + if err == nil || !strings.Contains(err.Error(), "I2C master needs gateware v55 or later") || !strings.Contains(err.Error(), "benchpod flash-self") || + exitCode(err) != exitUpdatePod { t.Fatalf("err = %v", err) } } @@ -228,7 +229,7 @@ func TestI2CPullupRefusalNamesTheCLICommand(t *testing.T) { pod, g := newFakeSensorPod(t) pod.reply = func(req map[string]any) (any, string) { if req["cmd"] == "i2c_start" { - return nil, `I2C needs pull-ups: switch on LA1's with {"cmd":"la","la":1,"pullup":"on"}, or pass "pullups":"external"` + return nil, `BP0061 {"la":1}` } return nil, "" } @@ -237,24 +238,6 @@ func TestI2CPullupRefusalNamesTheCLICommand(t *testing.T) { strings.Contains(err.Error(), `{"cmd"`) { t.Fatalf("err = %v", err) } - // firmware with la_pull_dir names the pull form - pod.reply = func(req map[string]any) (any, string) { - if req["cmd"] == "i2c_start" { - return nil, `I2C needs pull-ups: switch on LA2's with {"cmd":"la","la":2,"pull":"up"}, or pass "pullups":"external"` - } - return nil, "" - } - _, err = runBus(t, g, newI2CCmd(g), "start", "--sda", "1", "--scl", "2") - if err == nil || !strings.Contains(err.Error(), "benchpod la pull 2 up") || strings.Contains(err.Error(), `{"cmd"`) { - t.Fatalf("err = %v", err) - } -} - -func TestPinConflictWithTheI2CMaster(t *testing.T) { - shown, hint := translateRefusal(`pin conflict: LA1 is in use by i2cm_sda; stop the I2C session first ({"cmd":"i2c_stop"})`) - if shown != "pin conflict: LA1 is in use by i2cm_sda" || !strings.Contains(hint, "benchpod i2c stop") { - t.Fatalf("%q, %q", shown, hint) - } } func TestLADirSendsPins(t *testing.T) { diff --git a/cmd/benchpod-cli/ci_lease.go b/cmd/benchpod-cli/ci_lease.go index 5f95655..20beea4 100644 --- a/cmd/benchpod-cli/ci_lease.go +++ b/cmd/benchpod-cli/ci_lease.go @@ -266,7 +266,7 @@ const ( ) func isLeaseBusy(pe *tcpclient.PodError) bool { - return pe.Code == codeLeaseBusy || pe.Kind() == tcpclient.Busy // Kind: the text fallback without a code + return pe.Code == codeLeaseBusy || pe.Kind() == tcpclient.Busy } // busyText is " holds this pod (, N s left)" from a lease_busy refusal. @@ -285,8 +285,7 @@ func busyText(pe *tcpclient.PodError) string { } return s } - // fallback: BP0025's holder/purpose/left_s args replace it (firmware without codes) - return strings.TrimPrefix(strings.TrimSpace(pe.Reason), "busy: ") + return strings.TrimSpace(pe.Reason) } // leaseLostText is why a lease_lost / lease_not_held refusal says the lease is gone. @@ -297,16 +296,12 @@ func leaseLostText(pe *tcpclient.PodError) string { } return "the pod lease was stopped during the run" } - return "the pod lease was lost (" + strings.TrimSpace(pe.Reason) + "): the pod rebooted, or the lease expired" + return "the pod lease was lost: the pod rebooted, or the lease expired" } // isLeaseLost is a command refused because the run's lease was stopped (BP0026) or expired (BP0027). func isLeaseLost(pe *tcpclient.PodError) bool { - if pe.Code == codeLeaseLost || pe.Code == codeLeaseNotHeld { - return true - } - // fallback: BP0026 / BP0027 replace it (firmware without codes) - return strings.HasPrefix(strings.TrimSpace(pe.Reason), "lease lost") + return pe.Code == codeLeaseLost || pe.Code == codeLeaseNotHeld } // ── the server's lease (embeddedci.com) ───────────────────────────────────── diff --git a/cmd/benchpod-cli/ci_phase4_test.go b/cmd/benchpod-cli/ci_phase4_test.go index b5f2e36..f1e1b46 100644 --- a/cmd/benchpod-cli/ci_phase4_test.go +++ b/cmd/benchpod-cli/ci_phase4_test.go @@ -130,7 +130,7 @@ func TestGitHubActionsSignIn(t *testing.T) { _, _ = w.Write([]byte(`{"access_token":"gha-token","token_type":"Bearer","expires_at":"` + time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + `","devices":["benchpod-a1b2c3"]}`)) case "/api/cloud/devices/command": g.cmdPath, g.cmdAuth = r.URL.RequestURI(), r.Header.Get("Authorization") - _, _ = w.Write([]byte(`{"status":"ok","data":{"version":"3.10.13"}}`)) + _, _ = w.Write([]byte(`{"status":"ok","data":{"version":"4.0.0","api":2,"min_client_api":2}}`)) case "/api/cloud/devices/lease": g.leaseAuth = r.Header.Get("Authorization") _, _ = w.Write([]byte(`{"lease_id":"L-1"}`)) @@ -157,7 +157,7 @@ func TestGitHubActionsSignIn(t *testing.T) { t.Fatalf("cloud pod %+v", cp) } data, err := cp.Command(ctx, map[string]any{"cmd": "status"}) - if err != nil || !strings.Contains(string(data), "3.10.13") { + if err != nil || !strings.Contains(string(data), "4.0.0") { t.Fatalf("command %s %v", data, err) } lease, err := acquireCloudLease(ctx, cp.API, cp.Credential, cp.Name, "L-1", 0, time.Hour, io.Discard) diff --git a/cmd/benchpod-cli/ci_status_test.go b/cmd/benchpod-cli/ci_status_test.go index b6cb02c..63a0566 100644 --- a/cmd/benchpod-cli/ci_status_test.go +++ b/cmd/benchpod-cli/ci_status_test.go @@ -61,7 +61,7 @@ func (p *statusFormPod) reply(req map[string]any) []byte { ok := func(data any) []byte { b, _ := json.Marshal(map[string]any{"status": "ok", "data": data}); return b } switch req["cmd"] { case "status": - st := map[string]any{"version": "3.10.13", "board_rev": "v3", "gateware": 58, "analog": true, + st := map[string]any{"version": "4.0.0", "board_rev": "v3", "gateware": 58, "analog": true, "api": 2, "min_client_api": 2, "lease": map[string]any{"held": false, "holder": "", "left_s": 0}} if caps, set := req["caps"]; p.featuresRev > 0 && set && caps == false { st["features_rev"] = p.featuresRev diff --git a/cmd/benchpod-cli/ci_test.go b/cmd/benchpod-cli/ci_test.go index 81e7d81..4a1a7d9 100644 --- a/cmd/benchpod-cli/ci_test.go +++ b/cmd/benchpod-cli/ci_test.go @@ -69,7 +69,7 @@ func (p *fakeCIPod) Command(_ context.Context, req map[string]any) (json.RawMess if p.statusErr != nil { return nil, p.statusErr } - st := map[string]any{"version": p.version, "board_rev": "v3", "analog": true, "gateware": 58, "features_rev": 4, "la_vccio_mv": 3300} + st := map[string]any{"version": p.version, "board_rev": "v3", "analog": true, "gateware": 58, "features_rev": 4, "la_vccio_mv": 3300, "api": 2, "min_client_api": 2} p.mu.Lock() if len(p.uptimes) > 0 { st["uptime_ms"] = p.uptimes[0] @@ -653,7 +653,7 @@ func TestLocalLeaseRequests(t *testing.T) { renewErr = &tcpclient.PodError{Reason: "lease not held", Code: "BP0027"} mu.Unlock() time.Sleep(70 * time.Millisecond) - if !strings.Contains(l.Lost(), "lease not held") { + if !strings.Contains(l.Lost(), "lease was lost") { t.Errorf("lost %q", l.Lost()) } l.Release(context.Background()) diff --git a/cmd/benchpod-cli/cloudcfg.go b/cmd/benchpod-cli/cloudcfg.go index 2911a94..7b3057a 100644 --- a/cmd/benchpod-cli/cloudcfg.go +++ b/cmd/benchpod-cli/cloudcfg.go @@ -42,25 +42,8 @@ const ( caLANChunk = 768 // raw bytes per ota_data line (as the hwe2e LAN OTA sends) caMissing = "this firmware has no company CA support; update the pod's firmware" proxyMissing = "this firmware has no HTTP proxy support; update the pod's firmware" - lanGateHint = "the pod only takes this change over USB or from the cloud, never from Ethernet or Wi-Fi; run it with --connection usb" ) -// lanGateRefusals are the tails of the firmware's refusal of a cloud link change from the LAN -// (pod_policy_cloud_link_gate): "cloud_ca: ..." or "cloud_proxy: ...". Firmware 3.9.0 also takes -// the change over its USB network adapter and says so; older firmware names the console. -var lanGateRefusals = []string{": change it from the cloud or over USB", ": change it from the cloud or the USB console"} - -// isLANGateRefusal reports whether msg is the firmware's refusal to change the company CA or -// the HTTP proxy from the LAN. -func isLANGateRefusal(msg string) bool { - for _, tail := range lanGateRefusals { - if verb, ok := strings.CutSuffix(strings.TrimSpace(msg), tail); ok { - return verb == "cloud_ca" || verb == "cloud_proxy" - } - } - return false -} - func newCloudCmd(g *globalFlags) *cobra.Command { root := &cobra.Command{ Use: "cloud", @@ -414,17 +397,11 @@ func cloudCfgError(what, missing string, lan bool, err error) error { if errors.Is(err, serialconsole.ErrUnknownCommand) { return errors.New(missing) } - // "unknown target": no code yet (a cloud_ca / cloud_proxy target older firmware lacks) - if isUnknownCommand(err) || strings.Contains(err.Error(), "unknown target") { + if isUnknownCommand(err) || tcpclient.HasCode(err, "BP0060") { // ota_unknown_target return errors.New(missing) } if pe, ok := tcpclient.AsPodError(err); ok { - // A console refusal (Cmd set) came over USB, a JSON reply over the LAN. - lan = lan && pe.Cmd == "" - if lan && isLANGateRefusal(pe.Reason) { - return refusedWithHint(what, pe, lanGateHint) - } - return refusedError(what, pe, lan) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/cloudcfg_test.go b/cmd/benchpod-cli/cloudcfg_test.go index 9eb3b6e..d858ab7 100644 --- a/cmd/benchpod-cli/cloudcfg_test.go +++ b/cmd/benchpod-cli/cloudcfg_test.go @@ -25,7 +25,6 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // testCertPEM makes a self-signed certificate; isCA sets the CA basic constraint and cert-sign @@ -259,27 +258,6 @@ func TestCloudCAUSBOldFirmware(t *testing.T) { } } -func TestCloudCAUSBUnknownTarget(t *testing.T) { - // Firmware that knows `ca` but whose upload path refuses the target still reads as old. - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - saved := openCloudConsole - openCloudConsole = func(g *globalFlags, d string, to time.Duration) (cloudConsole, string, context.Context, context.CancelFunc, error) { - _, p, ctx, c, err := saved(g, d, to) - return uploadRefuser{fc}, p, ctx, c, err - } - _, _, err := runCACapture(&globalFlags{connection: "usb"}, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))) - if err == nil || err.Error() != caMissing { - t.Fatalf("err = %v", err) - } -} - -type uploadRefuser struct{ *fakeCloudConsole } - -func (uploadRefuser) Upload(context.Context, string, []byte, int, func(int, int)) error { - return fmt.Errorf("upload ca: begin: error unknown target") -} - func TestCloudCABadPEMTouchesNoPod(t *testing.T) { fc := &fakeCloudConsole{} withFakeCloudConsole(t, fc) @@ -407,6 +385,11 @@ func okReply(data any) string { return string(b) } +func codeReply(code string, args map[string]any) string { + b, _ := json.Marshal(map[string]any{"status": "error", "code": code, "args": args}) + return string(b) +} + func errReply(msg string) string { b, _ := json.Marshal(map[string]any{"status": "error", "message": msg}) return string(b) @@ -419,18 +402,18 @@ func (p *lanCfgPod) handle(req map[string]any) string { cmd, _ := req["cmd"].(string) changes := req["set"] != nil || req["clear"] != nil || strings.HasPrefix(cmd, "ota_") && cmd != "ota_abort" if p.locked != "" && changes { - return errReply("locked: " + cmd + " needs the cloud or the USB console") + return codeReply("BP0040", map[string]any{"cmd": cmd}) } if p.gated && (cmd == "cloud_ca" || cmd == "cloud_proxy") && changes { - return errReply(cmd + ": change it from the cloud or over USB") + return codeReply("BP0042", map[string]any{"setting": cmd}) } if p.gated && cmd == "ota_begin" && req["target"] == "ca" { - return errReply("cloud_ca: change it from the cloud or the USB console") + return codeReply("BP0042", map[string]any{"setting": "cloud_ca"}) } switch cmd { case "cloud_ca": if p.old { - return errReply("unknown cmd") + return codeReply("BP0002", map[string]any{"cmd": cmd}) } if req["clear"] == true { p.certs = nil @@ -438,7 +421,7 @@ func (p *lanCfgPod) handle(req map[string]any) string { return okReply(map[string]any{"present": len(p.certs) > 0, "certs": p.certs}) case "cloud_proxy": if p.old { - return errReply("unknown cmd") + return codeReply("BP0002", map[string]any{"cmd": cmd}) } if req["clear"] == true { p.proxy = proxyReply{} @@ -455,7 +438,7 @@ func (p *lanCfgPod) handle(req map[string]any) string { return okReply(p.proxy) case "ota_begin": if p.old || req["target"] != "ca" { - return errReply("unknown target") + return codeReply("BP0060", map[string]any{"target": req["target"]}) } p.staged = make([]byte, int(req["size"].(float64))) p.sha, p.state = req["sha256"].(string), "receiving" @@ -486,7 +469,7 @@ func (p *lanCfgPod) handle(req map[string]any) string { case "ota_abort": p.state = "idle" default: - return errReply("unknown cmd") + return codeReply("BP0002", map[string]any{"cmd": cmd}) } return okReply(map[string]any{"state": p.state, "target": "ca", "error": ""}) } @@ -537,15 +520,15 @@ func TestCloudCALANLocked(t *testing.T) { pod := &lanCfgPod{t: t, locked: "yes"} addr := pod.start() _, _, err := runCACapture(&globalFlags{connection: addr}, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))) - want := "cloud ca set: the pod refused: locked: ota_begin needs the cloud or the USB console (" + lockedUSBHint + ")" - if err == nil || err.Error() != want { + want := "cloud ca set: the pod refused: BP0040: The pod's LAN is locked: ota_begin needs the cloud or USB; run this over USB with --connection usb, or from the cloud" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("err = %v\nwant %s", err, want) } if !strings.HasSuffix(pod.cmds(), "ota_begin,ota_abort") { t.Fatalf("requests = %s", pod.cmds()) } _, _, err = runProxyCapture(&globalFlags{connection: addr}, "clear", "", "", "") - if err == nil || !strings.Contains(err.Error(), "locked: cloud_proxy needs") || !strings.Contains(err.Error(), "--connection usb") { + if err == nil || !strings.Contains(err.Error(), "BP0040: The pod's LAN is locked: cloud_proxy needs") || !strings.Contains(err.Error(), "--connection usb") { t.Fatalf("proxy clear: err = %v", err) } // Showing still works on a locked LAN. @@ -560,16 +543,16 @@ func TestCloudLANGated(t *testing.T) { g := &globalFlags{connection: addr} _, _, err := runCACapture(g, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))) - want := "cloud ca set: the pod refused: cloud_ca: change it from the cloud or the USB console (" + lanGateHint + ")" - if err == nil || err.Error() != want { + want := "cloud ca set: the pod refused: BP0042: cloud_ca cannot be changed over the LAN: change it from the cloud or over USB; run this over USB with --connection usb, or from the cloud" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("ca set: err = %v\nwant %s", err, want) } if !strings.HasSuffix(pod.cmds(), "ota_begin,ota_abort") { t.Fatalf("requests = %s", pod.cmds()) } _, _, err = runCACapture(g, "clear", "") - want = "cloud ca clear: the pod refused: cloud_ca: change it from the cloud or over USB (" + lanGateHint + ")" - if err == nil || err.Error() != want { + want = "cloud ca clear: the pod refused: BP0042: cloud_ca cannot be changed" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("ca clear: err = %v\nwant %s", err, want) } for _, action := range []string{"set", "clear"} { @@ -578,14 +561,11 @@ func TestCloudLANGated(t *testing.T) { addrArg, user, pw = "proxy.corp:3128", "alice", "s3cret" } _, _, err = runProxyCapture(g, action, addrArg, user, pw) - want = "cloud proxy " + action + ": the pod refused: cloud_proxy: change it from the cloud or over USB (" + lanGateHint + ")" - if err == nil || err.Error() != want { + want = "cloud proxy " + action + ": the pod refused: BP0042: cloud_proxy cannot be changed over the LAN" + if err == nil || !strings.HasPrefix(err.Error(), want) { t.Fatalf("proxy %s: err = %v\nwant %s", action, err, want) } } - if !strings.Contains(lanGateHint, "--connection usb") { - t.Fatalf("hint names no USB connection: %s", lanGateHint) - } // Reading still works from the LAN. if _, _, err := runCACapture(g, "show", ""); err != nil { t.Fatalf("ca show: %v", err) @@ -595,37 +575,6 @@ func TestCloudLANGated(t *testing.T) { } } -func TestCloudCfgErrorLANGate(t *testing.T) { - for _, tc := range []struct { - msg string - gate bool - }{ - {"cloud_ca: change it from the cloud or the USB console", true}, - {"cloud_proxy: change it from the cloud or the USB console", true}, - {"cloud_proxy: change it from the cloud or the USB console\n", true}, - {"lan_policy: change it from the cloud or the USB console", false}, - {"sig_policy: change it from the cloud or the USB console", false}, - {"cloud_proxy: bad host", false}, - {"", false}, - } { - if got := isLANGateRefusal(tc.msg); got != tc.gate { - t.Errorf("isLANGateRefusal(%q) = %v, want %v", tc.msg, got, tc.gate) - } - } - msg := "cloud_proxy: change it from the cloud or the USB console" - // Only a LAN connection gets the hint; the same words from elsewhere pass through as is. - if err := cloudCfgError("cloud proxy clear", proxyMissing, true, &tcpclient.PodError{Reason: msg}); !strings.Contains(err.Error(), lanGateHint) { - t.Fatalf("LAN: %v", err) - } - if err := cloudCfgError("cloud proxy clear", proxyMissing, false, &tcpclient.PodError{Reason: msg}); err.Error() != "cloud proxy clear: the pod refused: "+msg { - t.Fatalf("not LAN: %v", err) - } - ce := &serialconsole.CommandError{Cmd: "proxy", Reason: msg} - if err := cloudCfgError("cloud proxy clear", proxyMissing, false, ce); strings.Contains(err.Error(), lanGateHint) { - t.Fatalf("USB got the LAN hint: %v", err) - } -} - func TestCloudLANOldFirmware(t *testing.T) { pod := &lanCfgPod{t: t, old: true} addr := pod.start() diff --git a/cmd/benchpod-cli/errors.go b/cmd/benchpod-cli/errors.go index 78e5d1f..72d46dd 100644 --- a/cmd/benchpod-cli/errors.go +++ b/cmd/benchpod-cli/errors.go @@ -3,7 +3,6 @@ package main import ( "errors" "fmt" - "regexp" "strings" "github.com/embeddedci-com/benchpod-cli/internal/cloudpod" @@ -14,159 +13,38 @@ import ( // ── refusals ──────────────────────────────────────────────────────────────── // -// Every refusal from the pod, over the LAN JSON API or the USB console, is a *tcpclient.PodError. -// A refusal with a stable code (BP0001...) is classified by tcpclient's code table (the exit code) -// and worded from the catalog (internal/errcatalog: its message and fix.cli, codedRefusal). A -// refusal without one (older firmware, or a refusal with no code yet) falls back to its text: the -// policy refusals carry a firmware prefix (locked:, busy:, forbidden:; internal/fwrefusals pins -// the texts) and explainRefusal is the one place that says what to do about each. Each text match -// below names what replaces it: a code, or "no code yet". - -const ( - lockedUSBHint = "the pod's external LAN policy is locked; run this over USB with --connection usb" - leaseBusyHint = "on the LAN the pod can only be read while a cloud job holds it; try again when the job ends" - heavyBusyHint = "the pod is running another long command; try again when it ends" - forbiddenHint = "API keys need the benchpod:admin scope" -) - -// laVoltageUnsetHint answers the firmware's "la voltage not set; ..." (it names the raw JSON command -// or the profile key rather than what a CLI user runs). The pod and the tools take the voltage from -// the wiring profile, so the lasting fix is to set it there. -const laVoltageUnsetHint = "the wiring profile sets no I/O voltage: set it in the profile (the I/O voltage " + - "at the top of the Pins pane in the web or desktop app), or for now `benchpod la voltage 3.3V` (or 1.8V)" - -// pinConflictRE matches the firmware's "pin conflict: LA%u is in use by %s; %s" (la_pins.c). -// A sensor pin names its function too: "is in use by sensor:env (i2c_sda); ...", and an I2C -// line several sensors share "sensor:env+1". -var pinConflictRE = regexp.MustCompile(`^pin conflict: (LA\d+) is in use by (\S+)(?: \(([a-z0-9_]+)\))?; (.*)$`) - -// emulationImageRE matches the refusal of a feature the emulation image lacks -// (command_handler_dac.c image_hint) and the image-switch refusal (fpga_image). -var emulationImageRE = regexp.MustCompile(`\{"cmd":"sensor_stop","all":true\} then \{"cmd":"fpga_image","image":"(loop|deep)"\}$`) - -// pinReleaseHints maps the firmware's release hints (la_pins.c release_hint) to what a CLI user -// does about them. The benchpod CLI has no command that holds a pin past its own run, so a pin in -// use is held by another client of the pod; the hint names where to free it. A hint missing from -// this map (a new owner) is shown as the firmware wrote it. -var pinReleaseHints = []struct { - prefix string // the firmware hint starts with this - hint string // %s = the pin (LA4) -}{ - {`release it with {"cmd":"gpio"`, "another session (the web app, a test or an MCP session) holds %s as a GPIO; " + - "release it there (gpio_release)"}, - {"stop the uart proxy first", "a UART session (the web app's Terminal, a test or an MCP session) " + - "is open on %s; close it there"}, - {"end the SWD session first", "an SWD session (a flash or an OpenOCD run) is using %s; wait for it to end"}, - {"stop the sensor emulation first", "an emulated sensor is running on %s; stop it with " + - "`benchpod sensor stop` (or where it was started: the web app, the SDK or MCP sensor_stop)"}, - {"stop the SPI session first", "an SPI session is open on %s; end it where it was started " + - "(the web app, the SDK or an MCP session)"}, - {"stop the I2C session first", "the I2C master is using %s; end it with `benchpod i2c stop`"}, -} - -// i2cPullupRE matches i2c_start's "I2C needs pull-ups: switch on LA1's with -// {"cmd":"la","la":1,"pullup":"on"}, or pass "pullups":"external"". -// Firmware with la_pull_dir names {"cmd":"la","la":1,"pull":"up"} instead. -var i2cPullupRE = regexp.MustCompile(`^(I2C needs pull-ups): switch on LA(\d+)'s with \{"cmd":"la","la":\d+,"(?:pullup":"on|pull":"up)"\}`) - -// translateRefusal rewords a refusal whose firmware text names a raw JSON command: it returns the -// text to show and the hint to add ("" for none). Other refusals come back unchanged with no hint. -func translateRefusal(msg string) (shown, hint string) { - msg = strings.TrimSpace(msg) - if strings.HasPrefix(msg, "la voltage not set") { // fallback: BP0001 replaces it - return msg, laVoltageUnsetHint - } - if m := i2cPullupRE.FindStringSubmatch(msg); m != nil { // no code yet - return m[1], fmt.Sprintf("pull LA%s up with `benchpod la pull %s up`, or pass --pullups external "+ - "when the board has its own", m[2], m[2]) - } - // fallback: BP0017 (gateware_too_old) replaces it - if strings.HasSuffix(msg, "need gateware v55+: update the pod's firmware") || - strings.HasSuffix(msg, "needs gateware v55+: update the pod's firmware") { - return msg, "update it with `benchpod flash-self`" - } - if m := emulationImageRE.FindStringSubmatchIndex(msg); m != nil { // no code yet - image := msg[m[2]:m[3]] - return strings.TrimSuffix(strings.TrimSpace(msg[:m[0]]), ":"), fmt.Sprintf( - "stop the sensors with `benchpod sensor stop`, then switch with `benchpod sensor image %s`", image) - } - if strings.HasPrefix(msg, "image switch refused:") { // no code yet - if i := strings.Index(msg, "; stop them first ("); i > 0 { - return msg[:i], "stop them with `benchpod sensor stop` first" - } - } - if m := pinConflictRE.FindStringSubmatch(msg); m != nil { // no code yet - owner := m[2] - if m[3] != "" { - owner += " (" + m[3] + ")" - } - if inst, ok := strings.CutPrefix(m[2], "sensor:"); ok { - inst, _, _ = strings.Cut(strings.TrimRight(inst, ";"), "+") - return "pin conflict: " + m[1] + " is in use by " + owner, fmt.Sprintf( - "the emulated sensor %s is using %s; stop it with `benchpod sensor stop %s`", inst, m[1], inst) - } - for _, h := range pinReleaseHints { - if strings.HasPrefix(m[4], h.prefix) { - return "pin conflict: " + m[1] + " is in use by " + owner, fmt.Sprintf(h.hint, m[1]) - } - } - } - return msg, "" -} - -// explainRefusal returns the hint for a refusal without a code, by its text, or "" when the -// message says it all. overLAN is whether the refusal came over the LAN JSON API: only the LAN -// refuses with locked: or a cloud lease, so elsewhere those texts stand alone. A coded refusal -// gets the catalog's fix.cli instead (refusalHint). -func explainRefusal(msg string, overLAN bool) string { - msg = strings.TrimSpace(msg) - switch tcpclient.ClassifyRefusal(msg) { - case tcpclient.Locked: // no code yet - if overLAN { - return lockedUSBHint - } - case tcpclient.Busy: - switch { - case overLAN && strings.HasPrefix(msg, "busy: a cloud job holds"): // fallback: BP0025 replaces it - return leaseBusyHint - case msg == "busy": // no code yet - return heavyBusyHint - } - case tcpclient.Forbidden: // no code yet - return forbiddenHint - } - _, hint := translateRefusal(msg) - return hint -} - -// refusalHint is what to do about a refusal: the catalog's fix.cli for a coded one, else -// explainRefusal's hint from the text ("" for none). -func refusalHint(pe *tcpclient.PodError, overLAN bool) string { +// Every refusal from the pod, over the JSON API (LAN, USB network, embeddedci.com) or the USB +// console, is a *tcpclient.PodError. A refusal with a stable code (BP0001...) is classified by +// tcpclient's code table (the exit code) and worded from the catalog (internal/errcatalog: its +// message and fix.cli, codedRefusal). A refusal without a code is shown as the pod wrote it: the +// CLI never matches on a refusal's text. + +// refusalHint is what to do about a refusal: the catalog's fix.cli for a coded one, "" otherwise. +func refusalHint(pe *tcpclient.PodError) string { if pe.Code != "" { if e, ok := errcatalog.Lookup(pe.Code); ok { return errcatalog.Fill(e.Fix["cli"], pe.Args) } } - return explainRefusal(pe.Reason, overLAN) + return "" } -// refusedError is the one line for a refusal from a command: ": the pod refused: ", -// plus refusalHint's hint (a coded refusal: the catalog's message and fix.cli). -func refusedError(what string, pe *tcpclient.PodError, overLAN bool) error { - return refusedWithHint(what, pe, refusalHint(pe, overLAN)) +// refusedError is the one line for a refusal from a command: ": the pod refused: " +// (a coded refusal: the catalog's message and fix.cli). +func refusedError(what string, pe *tcpclient.PodError) error { + return refusedWithHint(what, pe, "") } -// isUnknownCommand says the pod does not know the command it was sent: its firmware is older -// than the command. BP0002, else (firmware without codes) the text "unknown cmd". +// isUnknownCommand says the pod does not know the command it was sent (BP0002). func isUnknownCommand(err error) bool { return tcpclient.IsUnknownCommand(err) } -// refusedWithHint is refusedError with the hint given ("" for none). +// refusedWithHint is refusedError with a hint of the caller's for a refusal without a code ("" for +// none); a coded refusal always shows the catalog's fix. func refusedWithHint(what string, pe *tcpclient.PodError, hint string) error { if coded, ok := codedRefusal(pe); ok { return &shownRefusal{msg: what + ": the pod refused: " + coded, pe: pe} } - shown, _ := translateRefusal(pe.Reason) - msg := what + ": the pod refused: " + shown + msg := what + ": the pod refused: " + strings.TrimSpace(pe.Reason) if hint != "" { msg += " (" + hint + ")" } @@ -183,10 +61,9 @@ type shownRefusal struct { func (e *shownRefusal) Error() string { return e.msg } func (e *shownRefusal) Unwrap() error { return e.pe } -// withRefusalHint adds explainRefusal's hint to an error that carries a refusal and does not -// show the hint yet. Execute applies it to every command's error, so a command that just wraps -// the client's error (%w) still gets the hint. A JSON reply (no console command) came over the -// LAN. +// withRefusalHint words a coded refusal from the catalog in an error that does not show it yet. +// Execute applies it to every command's error, so a command that just wraps the client's error +// (%w) still gets the catalog's message and fix. func withRefusalHint(err error) error { // embeddedci.com's own failures (a held lease, a missing role) say what to do already. var ce *cloudpod.Error @@ -197,26 +74,15 @@ func withRefusalHint(err error) error { if !ok { return err } - if coded, ok := codedRefusal(pe); ok { - if strings.Contains(err.Error(), coded) { - return err - } - msg := strings.Replace(err.Error(), strings.TrimSpace(pe.Reason), coded, 1) - if msg == err.Error() { - msg = err.Error() + ": " + coded - } - return &shownRefusal{msg: msg, pe: pe} - } - hint := explainRefusal(pe.Reason, pe.Cmd == "") - if hint == "" || strings.Contains(err.Error(), hint) { + coded, ok := codedRefusal(pe) + if !ok || strings.Contains(err.Error(), coded) { return err } - if shown, _ := translateRefusal(pe.Reason); shown != strings.TrimSpace(pe.Reason) { - // Drop the raw JSON the firmware suggests; the hint says it in CLI terms. - msg := strings.Replace(err.Error(), strings.TrimSpace(pe.Reason), shown, 1) - return &shownRefusal{msg: msg + " (" + hint + ")", pe: pe} + msg := strings.Replace(err.Error(), strings.TrimSpace(pe.Reason), coded, 1) + if msg == err.Error() { + msg = err.Error() + ": " + coded } - return fmt.Errorf("%w (%s)", err, hint) + return &shownRefusal{msg: msg, pe: pe} } // withSavedConnectionHint adds where the address came from when the pod did not answer at the @@ -245,6 +111,7 @@ const ( exitBusy = 4 // the pod or one of its engines is in use (a cloud lease, another session) exitUnreachable = 5 // the pod did not answer on its address, no pod on USB, or offline on embeddedci.com exitUpdateCLI = 6 // the pod's firmware needs a newer CLI (its API level is above this CLI's, or BP0030) + exitUpdatePod = 7 // the pod's firmware is too old for this CLI or the command (below firmware 4.0, BP0002, BP0017) ) // exitCodesHelp is the exit-code table for the root command's help. @@ -256,7 +123,9 @@ const exitCodesHelp = "Exit codes:\n" + " 4 busy: the pod or one of its engines is in use (a cloud job's lease, another session)\n" + " 5 unreachable: nothing answered on the pod's address, no pod found on USB, or the\n" + " pod is offline on embeddedci.com\n" + - " 6 update the CLI: the pod's firmware needs a newer benchpod CLI" + " 6 update the CLI: the pod's firmware needs a newer benchpod CLI\n" + + " 7 update the pod: its firmware is too old for this CLI (firmware before 4.0:\n" + + " `benchpod flash-self`) or lacks what the command needs" // usageError marks a command-line mistake (exit code 2). type usageError struct{ err error } @@ -286,9 +155,18 @@ func exitCode(err error) int { if errors.As(err, &upd) { return exitUpdateCLI } + var old *tcpclient.FirmwareTooOldError + if errors.As(err, &old) { + return exitUpdatePod + } if pe, ok := tcpclient.AsPodError(err); ok { - if pe.Kind() == tcpclient.Busy { + switch pe.Kind() { + case tcpclient.Busy: return exitBusy + case tcpclient.FirmwareTooOld: + return exitUpdatePod + case tcpclient.ClientTooOld: + return exitUpdateCLI } return exitRefused } @@ -328,5 +206,5 @@ func codedRefusal(pe *tcpclient.PodError) (string, bool) { if text, ok := errcatalog.Render(pe.Code, pe.Args, "cli"); ok { return text, true } - return fmt.Sprintf("%s: %s (%s)", pe.Code, strings.TrimSpace(pe.Reason), errcatalog.DocsURL(pe.Code)), true + return fmt.Sprintf("%s: %s (%s)", strings.ToUpper(pe.Code), strings.TrimSpace(pe.Reason), errcatalog.DocsURL(pe.Code)), true } diff --git a/cmd/benchpod-cli/errors_test.go b/cmd/benchpod-cli/errors_test.go index 27038db..d3f4dc3 100644 --- a/cmd/benchpod-cli/errors_test.go +++ b/cmd/benchpod-cli/errors_test.go @@ -1,10 +1,12 @@ package main import ( + "bufio" "context" "encoding/json" "errors" "fmt" + "io" "log" "net" "net/http" @@ -14,54 +16,34 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/errcatalog" - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" "github.com/embeddedci-com/benchpod-cli/internal/serverapi" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) -// explainRefusal is the one place a policy refusal gets its hint; the texts come from the -// firmware (internal/fwrefusals). -func TestExplainRefusal(t *testing.T) { - for _, c := range []struct { - id string - overLAN bool - want string - }{ - {"lan_locked", true, lockedUSBHint}, - {"lan_locked", false, ""}, - {"lease_busy", true, leaseBusyHint}, - {"lease_busy", false, ""}, - {"heavy_busy", true, heavyBusyHint}, - {"heavy_busy", false, heavyBusyHint}, - {"tunnel_forbidden", false, forbiddenHint}, - {"psram_bus_busy", true, ""}, // says what to do already - {"swd_busy_spi_session", true, ""}, - {"unknown_cmd", true, ""}, - } { - if got := explainRefusal(fwrefusals.Example(c.id), c.overLAN); got != c.want { - t.Errorf("%s (LAN %v): got %q, want %q", c.id, c.overLAN, got, c.want) - } - } -} - -func TestWithRefusalHintAddsTheHintOnce(t *testing.T) { - msg := fwrefusals.Example("lan_locked") - err := withRefusalHint(fmt.Errorf("la pullup: %w", &tcpclient.PodError{Reason: msg})) - if got := err.Error(); got != "la pullup: "+msg+" ("+lockedUSBHint+")" { - t.Fatalf("got %q", got) +// A coded refusal is worded from the catalog once; a refusal without a code is shown as the pod +// wrote it, with no hint (the CLI never reads a refusal's text). +func TestWithRefusalHint(t *testing.T) { + pe := &tcpclient.PodError{Reason: "The pod's LAN is locked: flash needs the cloud or USB", Code: "BP0040", + Args: map[string]any{"cmd": "flash"}} + err := withRefusalHint(fmt.Errorf("flash: %w", pe)) + want := "flash: BP0040: The pod's LAN is locked: flash needs the cloud or USB; run this over USB with --connection usb, or from the cloud (" + + errcatalog.DocsURL("BP0040") + ")" + if err.Error() != want { + t.Fatalf("got %q\nwant %q", err, want) } if _, ok := tcpclient.AsPodError(err); !ok { t.Fatal("the hint hid the refusal") } - // Already explained (refusedError): left alone. - once := refusedError("cloud ca set", &tcpclient.PodError{Reason: msg}, true) - if got := withRefusalHint(once).Error(); strings.Count(got, lockedUSBHint) != 1 { + once := refusedError("flash", pe) + if got := withRefusalHint(once).Error(); got != once.Error() { t.Fatalf("got %q", got) } - // A console refusal did not come over the LAN, and other errors pass through. - usb := &tcpclient.PodError{Cmd: "proxy-set", Reason: msg} - if got := withRefusalHint(usb); got != error(usb) { - t.Fatalf("got %v", got) + plainRefusal := &tcpclient.PodError{Reason: "locked: flash needs the cloud or USB"} + if got := withRefusalHint(plainRefusal); got != error(plainRefusal) { + t.Fatalf("uncoded: got %v", got) + } + if got := refusedError("generate", &tcpclient.PodError{Reason: "unknown waveform"}).Error(); got != "generate: the pod refused: unknown waveform" { + t.Fatalf("uncoded refusedError: %q", got) } plain := errors.New("connect to pod at 10.0.0.1:8080: i/o timeout") if got := withRefusalHint(plain); got != plain { @@ -73,14 +55,16 @@ func TestWithRefusalHintAddsTheHintOnce(t *testing.T) { func TestExitCodes(t *testing.T) { t.Setenv("BENCHPOD_CONNECTION", "") t.Setenv("BENCHPOD_TIMEOUT", "") - reply := func(id string) string { - b, _ := json.Marshal(map[string]string{"status": "error", "message": fwrefusals.Example(id)}) + reply := func(code string) string { + b, _ := json.Marshal(map[string]any{"status": "error", "code": code, "args": map[string]any{"cmd": "ping"}}) return string(b) } - locked, _ := fakeLANPod(t, reply("lan_locked")) - leased, _ := fakeLANPod(t, reply("lease_busy")) - swd, _ := fakeLANPod(t, reply("swd_busy")) - forbidden, _ := fakeLANPod(t, reply("tunnel_forbidden")) + locked, _ := fakeLANPod(t, reply("BP0040")) + leased, _ := fakeLANPod(t, reply("BP0025")) + swd, _ := fakeLANPod(t, reply("BP0050")) + forbidden, _ := fakeLANPod(t, reply("BP0045")) + gateware, _ := fakeLANPod(t, reply("BP0017")) + uncoded, _ := fakeLANPod(t, `{"status":"error","message":"busy: anything"}`) ok, _ := fakeLANPod(t, `{"status":"ok","data":"pong"}`) // A port nothing listens on: grab one, then close it. ln, err := net.Listen("tcp", "127.0.0.1:0") @@ -103,6 +87,8 @@ func TestExitCodes(t *testing.T) { {[]string{"ping", "--connection", forbidden}, exitRefused}, {[]string{"ping", "--connection", leased}, exitBusy}, {[]string{"ping", "--connection", swd}, exitBusy}, + {[]string{"ping", "--connection", gateware}, exitUpdatePod}, + {[]string{"ping", "--connection", uncoded}, exitRefused}, // its text is never read {[]string{"ping", "--connection", closed, "--timeout", "1s"}, exitUnreachable}, } { if got := run(c.args); got != c.want { @@ -129,10 +115,10 @@ func TestShownRefusalsKeepTheirExitCode(t *testing.T) { err error want int }{ - {cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: fwrefusals.Example("lan_locked")}), exitRefused}, - {cloudCfgError("cloud proxy clear", proxyMissing, true, &tcpclient.PodError{Reason: fwrefusals.Example("cloud_proxy_from_lan")}), exitRefused}, - {cloudCfgError("cloud ca set", caMissing, false, &tcpclient.PodError{Cmd: "ca", Reason: fwrefusals.Example("ota_owner_busy")}), exitBusy}, - {cloudPolicyError(sigPolicy, "audit", &serverapi.APIError{Status: http.StatusConflict, Message: fwrefusals.Example("sig_policy_loosen")}), exitRefused}, + {cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: "x", Code: "BP0040"}), exitRefused}, + {cloudCfgError("cloud proxy clear", proxyMissing, true, &tcpclient.PodError{Reason: "x", Code: "BP0042"}), exitRefused}, + {cloudCfgError("cloud ca set", caMissing, false, &tcpclient.PodError{Reason: "x", Code: "BP0051"}), exitBusy}, + {cloudPolicyError(lanPolicy, "off", &serverapi.APIError{Status: http.StatusConflict, Code: "BP0041", Message: "BP0041"}), exitRefused}, {cloudPolicyError(lanPolicy, "off", &serverapi.APIError{Status: http.StatusForbidden}), exitRefused}, } { if got := exitCode(c.err); got != c.want { @@ -150,6 +136,7 @@ func TestEveryCodedRefusal(t *testing.T) { wantExit := map[tcpclient.RefusalKind]int{ tcpclient.Refused: exitRefused, tcpclient.Locked: exitRefused, tcpclient.Forbidden: exitRefused, tcpclient.Busy: exitBusy, + tcpclient.FirmwareTooOld: exitUpdatePod, tcpclient.ClientTooOld: exitUpdateCLI, } args := map[string]any{"cmd": "x", "arg": "la", "name": "k66", "rev": 3, "max": 8, "bytes": 9000, "expected": 0, "feature": "i2c", "min": 55, "la": 4, "rx": 1, "tx": 2, "have": "up", "want": "down", @@ -169,15 +156,15 @@ func TestEveryCodedRefusal(t *testing.T) { if !ok { t.Fatal("no kind") } - pe := &tcpclient.PodError{Reason: "pod returned an error", Code: code, Args: args} + pe, _ := tcpclient.AsPodError(tcpclient.RefusalError("", code, args)) // no message: 4.0 if got := exitCode(fmt.Errorf("x: %w", pe)); got != wantExit[kind] { t.Errorf("exit %d, want %d", got, wantExit[kind]) } fix := errcatalog.Fill(e.Fix["cli"], args) - if got := refusalHint(pe, true); got != fix { + if got := refusalHint(pe); got != fix { t.Errorf("hint %q, want %q", got, fix) } - msg := refusedError("cmd", pe, true).Error() + msg := refusedError("cmd", pe).Error() if !strings.Contains(msg, code+": "+errcatalog.Fill(e.Message, args)) || !strings.Contains(msg, fix) { t.Errorf("refusedError = %q", msg) } @@ -188,46 +175,65 @@ func TestEveryCodedRefusal(t *testing.T) { } } -// The text fallbacks still classify a refusal without a code as before (older firmware). -func TestUncodedRefusalsKeepTheirExitCodes(t *testing.T) { - for id, want := range map[string]int{ - "lan_locked": exitRefused, "lan_locked_v39": exitRefused, "tunnel_forbidden": exitRefused, - "lease_busy": exitBusy, "heavy_busy": exitBusy, "psram_bus_busy": exitBusy, "swd_busy": exitBusy, - "uart_busy": exitBusy, "spi_busy": exitBusy, "swd_or_spi_busy": exitBusy, "unknown_cmd": exitRefused, - "la_voltage_unset": exitRefused, "pin_conflict": exitRefused, - } { - if got := exitCode(&tcpclient.PodError{Reason: fwrefusals.Example(id)}); got != want { - t.Errorf("%s: exit %d, want %d", id, got, want) - } - } -} - -// One helper says "the firmware lacks this command": BP0002, or the old text. +// "The firmware lacks this command" is BP0002 only. func TestIsUnknownCommandHelper(t *testing.T) { - if !isUnknownCommand(fmt.Errorf("x: %w", &tcpclient.PodError{Code: "BP0002", Reason: "pod returned an error"})) || - !isUnknownCommand(&tcpclient.PodError{Reason: fwrefusals.Example("unknown_cmd")}) || + if !isUnknownCommand(fmt.Errorf("x: %w", &tcpclient.PodError{Code: "BP0002"})) || + isUnknownCommand(&tcpclient.PodError{Reason: "unknown cmd"}) || isUnknownCommand(&tcpclient.PodError{Code: "BP0006", Reason: "missing la"}) || isUnknownCommand(errors.New("unknown cmd")) { t.Fatal("isUnknownCommand") } } -// unknownCmdReplies are a pod's answers to a command its firmware lacks: the text of firmware -// without codes, and BP0002 (with no text: a build without texts). +// unknownCmdReplies are a pod's answers to a command its firmware lacks: BP0002, with no message. var unknownCmdReplies = []string{ - `{"status":"error","message":"unknown cmd"}`, `{"status":"error","code":"BP0002","args":{"cmd":"x"}}`, } -// A pod whose firmware announces a newer API than this CLI handles stops a command that reads -// its status, with its own exit code; so does BP0030. A pod with api 1 or none works. -func TestNewerPodFirmwareNeedsANewerCLI(t *testing.T) { - newer, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.11.0","api":2,"min_client_api":0}}`) - newerPing, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.11.0","api":2,"min_client_api":0}}`) - same, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.10.14","api":1,"min_client_api":0}}`) - old, _ := fakeLANPod(t, `{"status":"ok","data":{"version":"3.10.13"}}`) +// fakeLANPodByCmd is a LAN pod that answers each command by name ("" for any other). +func fakeLANPodByCmd(t *testing.T, replies map[string]string) string { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + line, _ := bufio.NewReader(conn).ReadString('\n') + var req map[string]any + _ = json.Unmarshal([]byte(line), &req) + cmd, _ := req["cmd"].(string) + reply, ok := replies[cmd] + if !ok { + reply = replies[""] + } + _, _ = io.WriteString(conn, reply+"\n") + conn.Close() + } + }() + return ln.Addr().String() +} + +// A pod whose firmware announces a newer API than this CLI handles, or one older than firmware 4.0 +// (api 1, or none), stops a command with its own exit code (6, 7); so does BP0030. The firmware +// commands (status and the update commands) still run against it. +func TestPodAPILevels(t *testing.T) { + apiProbe = true + defer func() { apiProbe = false; tcpclient.ResetAPIProbe() }() + pod := func(status string) string { + return fakeLANPodByCmd(t, map[string]string{"status": `{"status":"ok","data":` + status + `}`, "": `{"status":"ok","data":"pong"}`}) + } + newer := pod(`{"version":"5.0.0","api":3,"min_client_api":3}`) + same := pod(`{"version":"4.0.0","api":2,"min_client_api":2}`) + old := pod(`{"version":"3.10.13"}`) + dev := pod(`{"version":"3.10.14","api":1,"min_client_api":0}`) tooOld, _ := fakeLANPod(t, `{"status":"error","code":"BP0030","args":{"client_api":1,"min_client_api":2,"api":2},`+ - `"message":"update the BenchPod SDK, MCP or CLI: this firmware needs client API 2 or newer (this client sent 1)"}`) + `"message":"Update the BenchPod SDK, MCP or CLI: this firmware needs client API 2 or newer (this client sent 1)"}`) var logged strings.Builder log.SetOutput(&logged) defer log.SetOutput(os.Stderr) @@ -236,12 +242,17 @@ func TestNewerPodFirmwareNeedsANewerCLI(t *testing.T) { want int msg string }{ - // status still shows the pod (it is how the user finds out), with the update line as a warning. + // status still shows the pod (it is how the user finds out), with the line as a warning. {[]string{"status", "--connection", newer}, exitOK, - "Warning: this pod's firmware 3.11.0 needs a newer benchpod CLI (pod API 2, this CLI handles 1): brew upgrade --cask benchpod"}, + "Warning: this pod's firmware 5.0.0 needs a newer benchpod CLI (pod API 3, this CLI handles 2): brew upgrade --cask benchpod"}, + {[]string{"status", "--connection", old}, exitOK, + "Warning: this pod's firmware 3.10.13 is too old for this benchpod CLI (pod API 1, this CLI needs 2): this pod needs firmware 4.0: benchpod flash-self"}, + {[]string{"ping", "--connection", newer}, exitUpdateCLI, "needs a newer benchpod CLI"}, + {[]string{"ping", "--connection", old}, exitUpdatePod, "this pod needs firmware 4.0: benchpod flash-self"}, + {[]string{"ping", "--connection", dev}, exitUpdatePod, "this pod needs firmware 4.0: benchpod flash-self"}, + {[]string{"ping", "--connection", same}, exitOK, ""}, {[]string{"ping", "--connection", tooOld}, exitUpdateCLI, - "this pod's firmware needs a newer benchpod CLI (pod API 2, this CLI handles 1): brew upgrade --cask benchpod"}, - {[]string{"ping", "--connection", newerPing}, exitOK, ""}, // ping reads no status + "this pod's firmware needs a newer benchpod CLI (pod API 2, this CLI handles 2): brew upgrade --cask benchpod"}, } { logged.Reset() if got := run(c.args); got != c.want { @@ -251,17 +262,14 @@ func TestNewerPodFirmwareNeedsANewerCLI(t *testing.T) { t.Errorf("%v: logged %q", c.args, logged.String()) } } - for _, addr := range []string{same, old} { - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - _, err := (&tcpclient.Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "status", "caps": false}) - cancel() - if err != nil { - t.Errorf("%s: %v", addr, err) - } + if got := exitCode(fmt.Errorf("x: %w", &tcpclient.UpdateRequiredError{PodAPI: 3})); got != exitUpdateCLI { + t.Errorf("wrapped: exit %d", got) } - if got := exitCode(fmt.Errorf("x: %w", &tcpclient.UpdateRequiredError{PodAPI: 2})); got != exitUpdateCLI { + if got := exitCode(fmt.Errorf("x: %w", &tcpclient.FirmwareTooOldError{PodAPI: 1})); got != exitUpdatePod { t.Errorf("wrapped: exit %d", got) } + _ = context.Background + _ = time.Second } // Every JSON command the CLI sends carries client_api and client ("cli "), on the LAN and diff --git a/cmd/benchpod-cli/flash_self_cloud_test.go b/cmd/benchpod-cli/flash_self_cloud_test.go index 30ecceb..7e800da 100644 --- a/cmd/benchpod-cli/flash_self_cloud_test.go +++ b/cmd/benchpod-cli/flash_self_cloud_test.go @@ -76,6 +76,7 @@ func (o *otaServer) start() *serverapi.Client { var cloudFlashGlobals = &globalFlags{connection: "embeddedci:benchpod-7a32b5", noFirmwareReport: true} func TestFlashSelfCloudUploadsImageAndSig(t *testing.T) { + allowAnyPodAPI(t) images, sigs := sigVectors(t) fw := filepath.Join(t.TempDir(), "bench_pod_stm32.bin") writeFile(t, fw, images["firmware"]) @@ -113,6 +114,7 @@ func TestFlashSelfCloudUploadsImageAndSig(t *testing.T) { } func TestFlashSelfCloudLatestRelease(t *testing.T) { + allowAnyPodAPI(t) o := &otaServer{t: t, phases: []map[string]any{{"phase": "done", "version_after": "3.10.2"}}} o.start() if err := runFlashSelfCloud(cloudFlashGlobals, &flashSelfFlags{network: true}, noFlagChanged, nil, "benchpod-7a32b5"); err != nil { @@ -138,6 +140,7 @@ func TestFlashSelfCloudLatestRelease(t *testing.T) { // --skip-blobs (or --blobs-dir) with a release is noted and ignored: the server installs the // release's blobs with it, and there is nothing to skip on its side. func TestFlashSelfCloudReleaseIgnoresSkipBlobs(t *testing.T) { + allowAnyPodAPI(t) o := &otaServer{t: t, phases: []map[string]any{{"phase": "done", "version_after": "3.10.6"}}} o.start() var err error @@ -157,6 +160,7 @@ func TestFlashSelfCloudReleaseIgnoresSkipBlobs(t *testing.T) { } func TestFlashSelfCloudRefusals(t *testing.T) { + allowAnyPodAPI(t) fw, _ := fwImage(t, 4096, 1024) for _, tc := range []struct { status int @@ -186,6 +190,7 @@ func TestFlashSelfCloudRefusals(t *testing.T) { } func TestFlashSelfCloudFailedJob(t *testing.T) { + allowAnyPodAPI(t) fw, _ := fwImage(t, 4096, 1024) o := &otaServer{t: t, phases: []map[string]any{{"phase": "error", "error": "signature refused by the pod's policy"}}} o.start() @@ -199,6 +204,7 @@ func TestFlashSelfCloudFailedJob(t *testing.T) { } func TestFlashSelfCloudTooBigAndDFUFlags(t *testing.T) { + allowAnyPodAPI(t) (&otaServer{t: t}).start() fw, _ := fwImage(t, 4096, 2048) err := runFlashSelfCloud(cloudFlashGlobals, &flashSelfFlags{}, noFlagChanged, []string{fw}, "benchpod-7a32b5") @@ -212,6 +218,7 @@ func TestFlashSelfCloudTooBigAndDFUFlags(t *testing.T) { } func TestAbortCloudOTA(t *testing.T) { + allowAnyPodAPI(t) o := &otaServer{t: t} api := o.start() pod := &cloudpod.Client{API: api, Credential: "tok", DeviceID: "id-1", Name: "benchpod-7a32b5"} @@ -226,6 +233,7 @@ func TestAbortCloudOTA(t *testing.T) { } func TestExplicitCloud(t *testing.T) { + allowAnyPodAPI(t) if name, ok := (&globalFlags{connection: "embeddedci:benchpod-7a32b5"}).explicitCloud(); !ok || name != "benchpod-7a32b5" { t.Errorf("%q %v", name, ok) } diff --git a/cmd/benchpod-cli/flash_self_network.go b/cmd/benchpod-cli/flash_self_network.go index 6f760bd..a54ac8e 100644 --- a/cmd/benchpod-cli/flash_self_network.go +++ b/cmd/benchpod-cli/flash_self_network.go @@ -137,9 +137,8 @@ func uploadFirmwareLAN(ctx context.Context, lan lanSession, image, manifest []by if err := lan.cmd(ctx, map[string]any{"cmd": "ota_commit"}, nil); err != nil && !lan.s.Broken() { // A refusal (no verified image, busy, locked, signature policy) comes back as the pod's // error reply. A connection that drops is the pod restarting: the expected end. - if pe, ok := tcpclient.AsPodError(err); ok && !strings.Contains(strings.ToLower(pe.Reason), "timeout") && - !errors.Is(err, context.DeadlineExceeded) { - return fmt.Errorf("commit: %s", pe.Reason) + if _, ok := tcpclient.AsPodError(err); ok && !errors.Is(err, context.DeadlineExceeded) { + return fmt.Errorf("commit: %w", err) } } return nil diff --git a/cmd/benchpod-cli/flash_self_network_test.go b/cmd/benchpod-cli/flash_self_network_test.go index 0b7716a..9f00933 100644 --- a/cmd/benchpod-cli/flash_self_network_test.go +++ b/cmd/benchpod-cli/flash_self_network_test.go @@ -85,13 +85,13 @@ func (p *fwNetPod) handle(req map[string]any) (string, bool) { if p.blobErr != "" { return errReply(p.blobErr), false } - return errReply("unknown cmd"), false + return codeReply("BP0002", map[string]any{"cmd": "blob_status"}), false case "ota_begin": if p.refuse != "" { return errReply(p.refuse), false } if _, ok := req["target"]; ok { - return errReply("unknown target"), false + return codeReply("BP0060", map[string]any{"target": req["target"]}), false } p.staged = make([]byte, int(req["size"].(float64))) p.sha, p.state = req["sha256"].(string), "receiving" @@ -114,7 +114,7 @@ func (p *fwNetPod) handle(req map[string]any) (string, bool) { case "ota_abort": p.state = "idle" default: - return errReply("unknown cmd"), false + return codeReply("BP0002", map[string]any{"cmd": cmd}), false } return okReply(map[string]any{"state": p.state}), false } @@ -149,6 +149,7 @@ func fastNetworkFlash(t *testing.T) { func noFlagChanged(string) bool { return false } func TestFlashSelfNetworkUpdates(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048} addr := pod.start() @@ -170,6 +171,7 @@ func TestFlashSelfNetworkUpdates(t *testing.T) { } func TestFlashSelfNetworkVerifyFailureWritesNothing(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048, corrupt: true} addr := pod.start() @@ -187,6 +189,7 @@ func TestFlashSelfNetworkVerifyFailureWritesNothing(t *testing.T) { } func TestFlashSelfNetworkPodRefusal(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048, refuse: "locked: ota_begin needs the cloud or USB"} addr := pod.start() @@ -198,6 +201,7 @@ func TestFlashSelfNetworkPodRefusal(t *testing.T) { } func TestFlashSelfNetworkImageTooBig(t *testing.T) { + allowAnyPodAPI(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 1024} addr := pod.start() file, _ := fwImage(t, 2000, 2048) @@ -211,6 +215,7 @@ func TestFlashSelfNetworkImageTooBig(t *testing.T) { } func TestFlashSelfNetworkRefusesDFUFlags(t *testing.T) { + allowAnyPodAPI(t) err := runFlashSelfNetwork(&globalFlags{connection: "127.0.0.1:1"}, &flashSelfFlags{network: true}, func(name string) bool { return name == "enter-dfu" }, nil) if err == nil || !strings.Contains(err.Error(), "--enter-dfu is for USB DFU") { @@ -237,6 +242,7 @@ func blobsDirWith(t *testing.T, names ...string) string { // look like one with nothing to install: flash-self warns, naming the skipped blobs and the // retry, and keeps its exit status (the firmware itself is in). func TestFlashSelfNetworkWarnsWhenBlobStatusFails(t *testing.T) { + allowAnyPodAPI(t) fastNetworkFlash(t) pod := &fwNetPod{t: t, version: "3.9.0", flashKB: 2048, blobErr: "reply too large"} addr := pod.start() @@ -265,6 +271,7 @@ func TestFlashSelfNetworkWarnsWhenBlobStatusFails(t *testing.T) { // install-blobs (installBlobsList) fails when the pod does not list its slots. func TestInstallBlobsFailsWhenBlobStatusFails(t *testing.T) { + allowAnyPodAPI(t) pod := &fwNetPod{t: t, version: "3.10.3", flashKB: 2048, blobErr: "reply too large"} addr := pod.start() ctx := context.Background() @@ -289,6 +296,7 @@ func TestInstallBlobsFailsWhenBlobStatusFails(t *testing.T) { // "unknown cmd" still means firmware with its blobs built in, not a failure. func TestInstallBlobsBuiltInIsNotABlobStatusFailure(t *testing.T) { + allowAnyPodAPI(t) pod := &fwNetPod{t: t, version: "3.4.0", flashKB: 2048} addr := pod.start() ctx := context.Background() diff --git a/cmd/benchpod-cli/gateware_reload_test.go b/cmd/benchpod-cli/gateware_reload_test.go index 9692527..0605457 100644 --- a/cmd/benchpod-cli/gateware_reload_test.go +++ b/cmd/benchpod-cli/gateware_reload_test.go @@ -160,6 +160,7 @@ func installOnGWPod(t *testing.T, pod *gwPod, version int) string { // The bench case: back from a v55 dev build to a release that carries v54, with the emulation // image running (firmware 3.10.3 does not check after a gw2 install). The CLI reloads image 2. func TestInstallBlobsReloadsStaleGateware(t *testing.T) { + allowAnyPodAPI(t) pod := &gwPod{t: t, running: 55, kind: 2, embedded: 54, slots: map[string]int{"gw0": 55, "gw1": 55, "gw2": 55}} out := installOnGWPod(t, pod, 54) if pod.running != 54 || pod.kind != 2 { @@ -178,6 +179,7 @@ func TestInstallBlobsReloadsStaleGateware(t *testing.T) { // When the firmware's own check already reloaded the gateware, the CLI only looks. func TestInstallBlobsLeavesMatchingGatewareAlone(t *testing.T) { + allowAnyPodAPI(t) pod := &gwPod{t: t, running: 55, kind: 0, embedded: 54, slots: map[string]int{"gw0": 55, "gw1": 55, "gw2": 55}, hookFixes: true} out := installOnGWPod(t, pod, 54) if strings.Contains(pod.cmds(), "fpga_image") || strings.Contains(out, "reloading") { @@ -186,6 +188,7 @@ func TestInstallBlobsLeavesMatchingGatewareAlone(t *testing.T) { } func TestInstallBlobsReportsAFailedReload(t *testing.T) { + allowAnyPodAPI(t) pod := &gwPod{t: t, running: 55, kind: 1, embedded: 54, slots: map[string]int{"gw0": 55, "gw1": 55, "gw2": 55}, failImage: "busy"} out := installOnGWPod(t, pod, 54) if !strings.Contains(out, "the reload failed (busy)") || !strings.Contains(out, "restart the pod (tap RESET) to load gateware v54") { @@ -195,6 +198,7 @@ func TestInstallBlobsReportsAFailedReload(t *testing.T) { // reloadStaleGateware on its own: no reload without a mismatch, or with a version unknown. func TestReloadStaleGatewareOnlyOnAMismatch(t *testing.T) { + allowAnyPodAPI(t) for _, st := range []map[string]any{ {"gateware": 54, "gateware_embedded": 54}, {"gateware": 54}, @@ -216,6 +220,7 @@ func TestReloadStaleGatewareOnlyOnAMismatch(t *testing.T) { } func TestInstalledGateware(t *testing.T) { + allowAnyPodAPI(t) if installedGateware([]blobEntry{{Name: "esp"}}) || !installedGateware([]blobEntry{{Name: "esp"}, {Name: "gw2"}}) { t.Fatal("installedGateware") } diff --git a/cmd/benchpod-cli/generate16_test.go b/cmd/benchpod-cli/generate16_test.go index 306f65b..fd5dff3 100644 --- a/cmd/benchpod-cli/generate16_test.go +++ b/cmd/benchpod-cli/generate16_test.go @@ -11,7 +11,7 @@ import ( func TestGenerateCalibrated(t *testing.T) { t.Setenv("BENCHPOD_CONNECTION", "") t.Setenv("BENCHPOD_TIMEOUT", "") - addr, got := fakeLANPod(t, `{"status":"ok","data":{"caps":["dac","generate16"],"bits":16}}`) + addr, got := fakeLANPod(t, `{"status":"ok","data":{"caps":["dac","generate16"],"bits":16,"api":2,"min_client_api":2}}`) sent := func() map[string]any { t.Helper() var req map[string]any diff --git a/cmd/benchpod-cli/identity.go b/cmd/benchpod-cli/identity.go index 093d363..fc767b8 100644 --- a/cmd/benchpod-cli/identity.go +++ b/cmd/benchpod-cli/identity.go @@ -137,7 +137,7 @@ func identityErr(what string, err error) error { return errors.New(identityMissing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/lantls.go b/cmd/benchpod-cli/lantls.go index e9929e7..d2b6660 100644 --- a/cmd/benchpod-cli/lantls.go +++ b/cmd/benchpod-cli/lantls.go @@ -153,13 +153,10 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { // lanTLSError turns a refusal into one clear line. func lanTLSError(what string, err error) error { if pe, ok := tcpclient.AsPodError(err); ok { - r := pe.Reason - switch { - case isUnknownCommand(err): + if isUnknownCommand(err) { return errors.New(lanTLSMissing) - case strings.Contains(r, "change it over TLS"): - return fmt.Errorf("%s: %s", what, lanTLSPlainHint) } + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/lapins_subset_test.go b/cmd/benchpod-cli/lapins_subset_test.go index 49999fe..ede9c3c 100644 --- a/cmd/benchpod-cli/lapins_subset_test.go +++ b/cmd/benchpod-cli/lapins_subset_test.go @@ -3,10 +3,11 @@ package main import ( "context" "encoding/json" - "errors" "reflect" "strings" "testing" + + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // fakeLAPins answers la_pins like the firmware: "la" selects pins when subset is true (firmware @@ -23,7 +24,7 @@ func (f *fakeLAPins) Command(_ context.Context, req map[string]any) (json.RawMes has = false } if !has && f.tooLarge { - return nil, errors.New("pod error: reply too large") + return nil, tcpclient.RefusalError("", "BP0053", nil) } var pins []map[string]any for la := 1; la <= 14; la++ { @@ -89,7 +90,7 @@ func TestLAPinsTooLargeReadsInTwoParts(t *testing.T) { // Firmware without the subset cannot help: the error stands. f = &fakeLAPins{tooLarge: true} _, err = laPinsFetch(context.Background(), f, nil) - if err == nil || !strings.Contains(err.Error(), "reply too large") || + if err == nil || !strings.Contains(err.Error(), "did not fit") || !strings.Contains(err.Error(), "firmware after 3.10.12 reads this list in parts") { t.Fatalf("want the too-large error with the update hint, got %v", err) } diff --git a/cmd/benchpod-cli/lavoltage.go b/cmd/benchpod-cli/lavoltage.go index 8918d81..9a7b1bb 100644 --- a/cmd/benchpod-cli/lavoltage.go +++ b/cmd/benchpod-cli/lavoltage.go @@ -269,7 +269,7 @@ func laVoltageError(what string, err error) error { if isUnknownCommand(err) { return errors.New(laVoltageMissing) } - return refusedError(what, pe, pe.Cmd == "") + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/lavoltage_test.go b/cmd/benchpod-cli/lavoltage_test.go index 674821f..a0ab249 100644 --- a/cmd/benchpod-cli/lavoltage_test.go +++ b/cmd/benchpod-cli/lavoltage_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" ) @@ -104,10 +103,9 @@ func TestLAVoltageLANRefusals(t *testing.T) { t.Fatalf("old firmware: %v", err) } } - msg := fwrefusals.Example("lan_locked") - addr, _ := fakeLANPod(t, `{"status":"error","message":"`+msg+`"}`) + addr, _ := fakeLANPod(t, `{"status":"error","code":"BP0040","args":{"cmd":"la_voltage"}}`) err := runLAVoltage(&globalFlags{connection: addr}, 3300, &bytes.Buffer{}, &bytes.Buffer{}) - if err == nil || err.Error() != "la voltage: the pod refused: "+msg+" ("+lockedUSBHint+")" { + if err == nil || !strings.HasPrefix(err.Error(), "la voltage: the pod refused: BP0040: The pod's LAN is locked: la_voltage needs the cloud or USB; run this over USB") { t.Fatalf("locked: %v", err) } if code := exitCode(err); code != exitRefused { diff --git a/cmd/benchpod-cli/newerpod_test.go b/cmd/benchpod-cli/newerpod_test.go index e2b56b2..3b2b31b 100644 --- a/cmd/benchpod-cli/newerpod_test.go +++ b/cmd/benchpod-cli/newerpod_test.go @@ -16,21 +16,21 @@ func TestAllowsNewerPod(t *testing.T) { return c } for _, name := range []string{"status", "flash-self", "install-blobs", "dfu", "bootsel", "discover", "identity"} { - if !allowsNewerPod(sub(name, root)) { + if !allowsAnyPodAPI(sub(name, root)) { t.Errorf("%s: want allowed", name) } } for _, name := range []string{"uart", "la", "power"} { - if allowsNewerPod(sub(name, root)) { + if allowsAnyPodAPI(sub(name, root)) { t.Errorf("%s: want stopped", name) } } // A nested "status" (sensor status, bus status) is not the top-level status. sensor := sub("sensor", root) - if allowsNewerPod(sub("status", sensor)) { + if allowsAnyPodAPI(sub("status", sensor)) { t.Error("sensor status: want stopped") } - if allowsNewerPod(root) { + if allowsAnyPodAPI(root) { t.Error("root: want stopped") } } diff --git a/cmd/benchpod-cli/podclient_test.go b/cmd/benchpod-cli/podclient_test.go index 25ed5ab..1d7f78d 100644 --- a/cmd/benchpod-cli/podclient_test.go +++ b/cmd/benchpod-cli/podclient_test.go @@ -36,6 +36,9 @@ func TestMain(m *testing.M) { // Requests compare whole: without client_api and client (TestEveryRequestCarriesTheClientFields // turns them on). tcpclient.SetClientFields(false) + // Fake pods answer status without an api: no API probe before their commands + // (TestAPIProbe turns it on). + apiProbe = false // Never probe this machine's USB ports for a pod's USB network adapter. usbNetwork = func(*globalFlags, string) (serialconsole.USBNet, error) { return serialconsole.USBNet{}, errors.New("no pod on USB (tests)") @@ -134,7 +137,7 @@ func TestCloudPingStatusAndLAVoltage(t *testing.T) { f := &fakeCloud{reply: podReplies(map[string]string{ "ping": `"pong"`, - "status": `{"version":"3.8.0","ip":"192.168.1.220","net":"eth","la_vccio_mv":3300,"gateware":48}`, + "status": `{"version":"4.0.0","ip":"192.168.1.220","net":"eth","la_vccio_mv":3300,"gateware":48,"api":2,"min_client_api":2}`, "cloud_status": `{"state":"connected","configured":true,"device_id":"id-1"}`, "target_status": `{"efuse1":{"enabled":1,"fault":0},"efuse2":{"enabled":0,"fault":0}}`, "la_voltage": `{"mv":3300,"readback_mv":3300}`, @@ -150,7 +153,7 @@ func TestCloudPingStatusAndLAVoltage(t *testing.T) { if code != exitOK { t.Fatalf("status: exit %d", code) } - for _, want := range []string{"BenchPod bench-1 on embeddedci.com", "3.8.0", "3.3 V", "internal 5 V on", "on your account as bench-1"} { + for _, want := range []string{"BenchPod bench-1 on embeddedci.com", "4.0.0", "3.3 V", "internal 5 V on", "on your account as bench-1"} { if !strings.Contains(out, want) { t.Errorf("status output lacks %q:\n%s", want, out) } @@ -417,3 +420,12 @@ func fakeCloudStatusPod(t *testing.T, id string) string { }() return ln.Addr().String() } + +// allowAnyPodAPI is what the root command does for the firmware commands (flash-self, +// install-blobs, status, ...): they run against a pod of any API level, a 3.x one included. For +// tests that call such a command's code directly. +func allowAnyPodAPI(t *testing.T) { + t.Helper() + tcpclient.SetAllowAnyPodAPI(true) + t.Cleanup(func() { tcpclient.SetAllowAnyPodAPI(false) }) +} diff --git a/cmd/benchpod-cli/policy.go b/cmd/benchpod-cli/policy.go index e001e19..99f1ca4 100644 --- a/cmd/benchpod-cli/policy.go +++ b/cmd/benchpod-cli/policy.go @@ -293,7 +293,7 @@ func runPolicyCloud(g *globalFlags, p podPolicy, t policyTarget, set string, out const adminNeeded = "this needs an organization owner or admin (API keys: the benchpod:admin scope)" // cloudPolicyError turns a failed policy call into one clear line: the server's or pod's own -// message, plus the USB way out when the cloud refused to loosen the signature policy. +// message, or a coded refusal of the pod's worded from the catalog. func cloudPolicyError(p podPolicy, set string, err error) error { what := p.cmd if set != "" { @@ -313,10 +313,11 @@ func cloudPolicyError(p podPolicy, set string, err error) error { if msg == "" { return fmt.Errorf("%s: %w", what, err) } - // "loosen": no code yet (sig_policy's "only the USB console can loosen the policy") - if set != "" && p.cmd == sigPolicy.cmd && strings.Contains(strings.ToLower(msg), "loosen") { - return relayedRefusal(p, fmt.Sprintf("%s: the pod refused: %s. Loosen it over the pod's USB console: benchpod sig-policy set %s --connection usb", - what, msg, set), msg) + // A refusal the pod sent with a code, relayed by the server: worded from the catalog. + if strings.HasPrefix(strings.ToUpper(apiErr.Code), "BP") { + if pe, ok := tcpclient.AsPodError(tcpclient.RefusalError(msg, apiErr.Code, nil)); ok { + return refusedError(what, pe) + } } if set != "" { return relayedRefusal(p, what+": the pod refused: "+msg, msg) @@ -376,7 +377,7 @@ func runPolicyUSB(g *globalFlags, p podPolicy, device, set string, out, warn io. return errors.New(p.missing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/policy_test.go b/cmd/benchpod-cli/policy_test.go index fb9181a..44f3a57 100644 --- a/cmd/benchpod-cli/policy_test.go +++ b/cmd/benchpod-cli/policy_test.go @@ -154,13 +154,12 @@ func TestPolicyCloudRefusedLoosening(t *testing.T) { srv := &policyServer{t: t, supported: true, policy: map[string]string{"sig-policy": "required"}, put: func(w http.ResponseWriter, _, _ string) bool { w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{"error":"sig_policy: only the USB console can loosen the policy (now required)"}`)) + _, _ = w.Write([]byte(`{"error":"BP0074","code":"BP0074"}`)) return true }} _, _, err := runPolicyCapture(t, &globalFlags{}, sigPolicy, cloudTarget(t, srv.start().URL), "permissive") - want := "sig-policy set: the pod refused: only the USB console can loosen the policy (now required). " + - "Loosen it over the pod's USB console: benchpod sig-policy set permissive --connection usb" - if err == nil || err.Error() != want { + want := "sig-policy set: the pod refused: BP0074: " + if err == nil || !strings.HasPrefix(err.Error(), want) || exitCode(err) != exitRefused { t.Fatalf("err = %v\nwant %q", err, want) } } diff --git a/cmd/benchpod-cli/pull_test.go b/cmd/benchpod-cli/pull_test.go index 1a2413d..b726209 100644 --- a/cmd/benchpod-cli/pull_test.go +++ b/cmd/benchpod-cli/pull_test.go @@ -20,7 +20,7 @@ type pullPod struct { func (p *pullPod) Command(_ context.Context, req map[string]any) (json.RawMessage, error) { if req["cmd"] == "status" { return json.Marshal(map[string]any{"version": "3.10.11", "features_rev": p.rev, "gateware": 58, - "fpga_image": "deep", "hw": []string{"nrst_pin"}}) + "fpga_image": "deep", "hw": []string{"nrst_pin"}, "api": 2, "min_client_api": 2}) } p.sent = append(p.sent, req) return json.Marshal(map[string]any{"la": req["la"], "ok": true}) diff --git a/cmd/benchpod-cli/refusals_test.go b/cmd/benchpod-cli/refusals_test.go deleted file mode 100644 index ab7e24c..0000000 --- a/cmd/benchpod-cli/refusals_test.go +++ /dev/null @@ -1,158 +0,0 @@ -package main - -import ( - "fmt" - "net/http" - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" - "github.com/embeddedci-com/benchpod-cli/internal/serverapi" - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// The hints the CLI adds to a refusal hang on the firmware's exact wording -// (internal/fwrefusals pins it against the firmware source). - -func TestALockedLANRefusalGetsTheUSBHint(t *testing.T) { - msg := fwrefusals.Example("lan_locked") - err := cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: msg}) - if !strings.Contains(err.Error(), msg) || !strings.Contains(err.Error(), lockedUSBHint) { - t.Fatalf("got %v", err) - } - // Not over the cloud or USB: there the refusal stands alone. - if err := cloudCfgError("cloud ca set", caMissing, false, &tcpclient.PodError{Reason: msg}); strings.Contains(err.Error(), lockedUSBHint) { - t.Fatalf("got %v", err) - } -} - -func TestTheCloudLinkGateRefusalsGetTheLANHint(t *testing.T) { - for _, id := range []string{"cloud_ca_from_lan", "cloud_proxy_from_lan"} { - msg := fwrefusals.Example(id) - if !isLANGateRefusal(msg) { - t.Errorf("%s: %q not recognized", id, msg) - } - if err := cloudCfgError("cloud", caMissing, true, &tcpclient.PodError{Reason: msg}); !strings.Contains(err.Error(), lanGateHint) { - t.Errorf("%s: got %v", id, err) - } - } - // The policy commands use the same tail, but they are not cloud link settings. - for _, id := range []string{"sig_policy_from_lan", "lan_policy_from_lan", "lan_locked"} { - if isLANGateRefusal(fwrefusals.Example(id)) { - t.Errorf("%s: %q taken for a cloud link refusal", id, fwrefusals.Example(id)) - } - } -} - -func TestOldFirmwareRefusalsMeanTheFeatureIsMissing(t *testing.T) { - // Firmware without codes: the texts. - for _, id := range []string{"unknown_cmd", "unknown_target"} { - err := cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: fwrefusals.Example(id)}) - if err.Error() != caMissing { - t.Errorf("%s: got %v", id, err) - } - } - // With codes: BP0002, whatever the text (a build without texts sends none). - err := cloudCfgError("cloud ca set", caMissing, true, &tcpclient.PodError{Reason: "pod returned an error", Code: "BP0002", - Args: map[string]any{"cmd": "cloud_ca"}}) - if err.Error() != caMissing { - t.Errorf("BP0002: got %v", err) - } -} - -func TestACloudRefusalToLoosenTheSignaturePolicyPointsAtUSB(t *testing.T) { - msg := fwrefusals.Example("sig_policy_loosen") - err := cloudPolicyError(sigPolicy, "audit", &serverapi.APIError{Status: http.StatusConflict, Message: msg}) - if !strings.Contains(err.Error(), "only the USB console can loosen") || - !strings.Contains(err.Error(), "benchpod sig-policy set audit --connection usb") { - t.Fatalf("got %v", err) - } - // Other refusals get no USB recipe. - err = cloudPolicyError(sigPolicy, "audit", &serverapi.APIError{Status: http.StatusConflict, - Message: fwrefusals.Example("sig_policy_unknown")}) - if strings.Contains(err.Error(), "--connection usb") { - t.Fatalf("got %v", err) - } -} - -func TestFirmwareRefusalsKeepTheirPrefixes(t *testing.T) { - // The SDK and MCP classify by these prefixes (locked:, busy:, forbidden:); the CLI shows them - // as they are. Pin the prefix of each policy refusal. - for id, prefix := range map[string]string{ - "lan_locked": "locked: ", - "lease_busy": "busy: ", - "ota_owner_busy": "busy: ", - "psram_bus_busy": "busy: ", - "tunnel_forbidden": "forbidden: ", - } { - if msg := fwrefusals.Example(id); !strings.HasPrefix(msg, prefix) { - t.Errorf("%s: %q does not start with %q", id, msg, prefix) - } - } -} - -func TestTheLAVoltageRefusalNamesTheCLICommand(t *testing.T) { - pe := &tcpclient.PodError{Reason: fwrefusals.Example("la_voltage_unset")} - err := withRefusalHint(fmt.Errorf("flash: %w", pe)) - if !strings.Contains(err.Error(), "benchpod la voltage 3.3V") || !strings.Contains(err.Error(), "Pins pane") { - t.Fatalf("got %v", err) - } - if exitCode(err) != exitRefused { - t.Fatalf("exit code %d", exitCode(err)) - } -} - -func TestPinConflictHintsAreTranslated(t *testing.T) { - for _, tc := range []struct{ owner, hintID, want string }{ - {"gpio", "pin_hint_gpio", "holds LA4 as a GPIO"}, - {"uart_rx", "pin_hint_uart", "UART session"}, - {"swd_clk", "pin_hint_swd", "SWD session"}, - {"i2c_sda", "pin_hint_sensor", "benchpod sensor stop"}, - {"spi_sck", "pin_hint_spi", "SPI session"}, - } { - msg := "pin conflict: LA4 is in use by " + tc.owner + "; " + fwrefusals.Example(tc.hintID) - err := withRefusalHint(fmt.Errorf("la step: %w", &tcpclient.PodError{Reason: msg})) - if !strings.Contains(err.Error(), tc.want) || strings.Contains(err.Error(), `{"cmd"`) { - t.Errorf("%s: got %v", tc.hintID, err) - } - if !strings.Contains(err.Error(), "pin conflict: LA4 is in use by "+tc.owner) || exitCode(err) != exitRefused { - t.Errorf("%s: got %v (exit %d)", tc.hintID, err, exitCode(err)) - } - } - // A user-defined sensor instance owns its pins as sensor:. - msg0 := `pin conflict: LA2 is in use by sensor:env; stop the sensor emulation first ({"cmd":"sensor_stop","instance":"env"})` - if err := withRefusalHint(&tcpclient.PodError{Reason: msg0}); !strings.Contains(err.Error(), "`benchpod sensor stop env`") || - strings.Contains(err.Error(), `{"cmd"`) { - t.Fatalf("got %v", err) - } - // The firmware also names the pin's function, and a shared I2C line "sensor:env+1". - msg1 := `pin conflict: LA2 is in use by sensor:env+1 (i2c_sda); stop the sensor emulation first ({"cmd":"sensor_stop","instance":"env"})` - if shown, hint := translateRefusal(msg1); shown != "pin conflict: LA2 is in use by sensor:env+1 (i2c_sda)" || - !strings.Contains(hint, "`benchpod sensor stop env`") { - t.Fatalf("got %q / %q", shown, hint) - } - // The emulation image refusals name the CLI's commands. - msg2 := `control loop is not in the emulation image, which the emulated sensors use: {"cmd":"sensor_stop","all":true} then {"cmd":"fpga_image","image":"loop"}` - if shown, hint := translateRefusal(msg2); shown != "control loop is not in the emulation image, which the emulated sensors use" || - hint != "stop the sensors with `benchpod sensor stop`, then switch with `benchpod sensor image loop`" { - t.Fatalf("got %q / %q", shown, hint) - } - msg3 := `image switch refused: the emulated sensors env, imu need the emulation image; stop them first ({"cmd":"sensor_stop","all":true})` - if shown, hint := translateRefusal(msg3); strings.Contains(shown, `{"cmd"`) || !strings.Contains(hint, "benchpod sensor stop") { - t.Fatalf("got %q / %q", shown, hint) - } - // The pinned example renders the gpio case. - if shown, hint := translateRefusal(fwrefusals.Example("pin_conflict")); shown != "pin conflict: LA4 is in use by gpio" || hint == "" { - t.Fatalf("got %q / %q", shown, hint) - } - // A hint the CLI does not know (the step train's is already plain) stays as the pod wrote it. - msg := "pin conflict: LA2 is in use by step; " + fwrefusals.Example("pin_hint_step") - if err := withRefusalHint(&tcpclient.PodError{Reason: msg}); err.Error() != (&tcpclient.PodError{Reason: msg}).Error() { - t.Fatalf("got %v", err) - } - // refusedError shows the translated text too. - pe := &tcpclient.PodError{Reason: fwrefusals.Example("pin_conflict")} - if err := refusedError("flash", pe, true); strings.Contains(err.Error(), `{"cmd"`) || !strings.Contains(err.Error(), "gpio_release") { - t.Fatalf("got %v", err) - } -} diff --git a/cmd/benchpod-cli/root.go b/cmd/benchpod-cli/root.go index fe93b43..d1f316e 100644 --- a/cmd/benchpod-cli/root.go +++ b/cmd/benchpod-cli/root.go @@ -88,7 +88,8 @@ func newRootCmd() *cobra.Command { SilenceErrors: true, // Apply Viper precedence (flag > env > default) into g before any RunE. PersistentPreRunE: func(c *cobra.Command, _ []string) error { - tcpclient.SetAllowNewerPod(allowsNewerPod(c)) + tcpclient.SetAllowAnyPodAPI(allowsAnyPodAPI(c)) + tcpclient.SetAPIProbe(apiProbe) g.connection = viper.GetString("connection") g.configFile = viper.GetString("config-file") g.outputFilename = viper.GetString("output-filename") @@ -199,14 +200,20 @@ func run(args []string) int { return exitCode(err) } -// newerPodCommands still run against a pod whose firmware needs a newer CLI (exit code 6 -// otherwise): they show the pod's state or change its firmware, which is how such a pod is -// rolled back or looked at. `status` prints a warning instead. -var newerPodCommands = map[string]bool{ +// apiProbe: before a pod's first command, read its status once and stop on an API level this CLI +// does not drive (tcpclient.SetAPIProbe). Tests whose fake pods answer status without an api +// turn it off. +var apiProbe = true + +// anyPodAPICommands still run against a pod whose firmware this CLI does not drive: one that needs +// a newer CLI (exit code 6 otherwise) or one older than firmware 4.0 (exit code 7 otherwise). They +// show the pod's state or change its firmware, which is how such a pod is upgraded, rolled back +// or looked at; over firmware 3.x they keep the requests 3.x takes. `status` prints a warning. +var anyPodAPICommands = map[string]bool{ "status": true, "flash-self": true, "install-blobs": true, "dfu": true, "bootsel": true, "discover": true, "identity": true, } -func allowsNewerPod(c *cobra.Command) bool { - return c.Parent() != nil && !c.Parent().HasParent() && newerPodCommands[c.Name()] +func allowsAnyPodAPI(c *cobra.Command) bool { + return c.Parent() != nil && !c.Parent().HasParent() && anyPodAPICommands[c.Name()] } diff --git a/cmd/benchpod-cli/sensor.go b/cmd/benchpod-cli/sensor.go index 544d0ae..85d8c9f 100644 --- a/cmd/benchpod-cli/sensor.go +++ b/cmd/benchpod-cli/sensor.go @@ -295,7 +295,7 @@ func sensorCommand(ctx context.Context, t *podTarget, what string, req map[strin raw, err := t.client.Command(ctx, req) if err != nil { if pe, ok := tcpclient.AsPodError(err); ok { - return nil, refusedError(what, pe, !t.spec.IsCloud()) + return nil, refusedError(what, pe) } return nil, fmt.Errorf("%s: %w", what, err) } diff --git a/cmd/benchpod-cli/sensor_test.go b/cmd/benchpod-cli/sensor_test.go index 3a3fee4..e955605 100644 --- a/cmd/benchpod-cli/sensor_test.go +++ b/cmd/benchpod-cli/sensor_test.go @@ -46,7 +46,9 @@ func newFakeSensorPod(t *testing.T, caps ...string) (*fakeSensorPod, *globalFlag _ = json.Unmarshal([]byte(line), &req) data, msg := p.handle(req) var out []byte - if msg != "" { + if code, args, ok := codedFakeError(msg); ok { + out, _ = json.Marshal(map[string]any{"status": "error", "code": code, "args": args}) + } else if msg != "" { out, _ = json.Marshal(map[string]any{"status": "error", "message": msg}) } else { out, _ = json.Marshal(map[string]any{"status": "ok", "data": data}) @@ -61,6 +63,21 @@ func newFakeSensorPod(t *testing.T, caps ...string) (*fakeSensorPod, *globalFlag return p, &globalFlags{connection: ln.Addr().String(), configFile: filepath.Join(t.TempDir(), "config.json")} } +// codedFakeError reads a fake's error "BP0061" or "BP0061 {"la":1}" as a coded refusal (firmware +// 4.0 sends a code and its args, no message). +func codedFakeError(msg string) (string, map[string]any, bool) { + if len(msg) < 6 || !strings.HasPrefix(msg, "BP") { + return "", nil, false + } + var args map[string]any + if rest := strings.TrimSpace(msg[6:]); rest != "" { + if json.Unmarshal([]byte(rest), &args) != nil { + return "", nil, false + } + } + return msg[:6], args, true +} + func (p *fakeSensorPod) handle(req map[string]any) (any, string) { p.mu.Lock() defer p.mu.Unlock() @@ -72,7 +89,7 @@ func (p *fakeSensorPod) handle(req map[string]any) (any, string) { } switch req["cmd"] { case "status": - return map[string]any{"board": "stm32h563", "caps": p.caps}, "" + return map[string]any{"board": "stm32h563", "caps": p.caps, "api": 2, "min_client_api": 2}, "" case "sensor_define", "sensor_stimulus": key, _ := req["instance"].(string) chunk, _ := base64.StdEncoding.DecodeString(req["data_b64"].(string)) diff --git a/cmd/benchpod-cli/status.go b/cmd/benchpod-cli/status.go index e92a04c..cc40063 100644 --- a/cmd/benchpod-cli/status.go +++ b/cmd/benchpod-cli/status.go @@ -57,7 +57,7 @@ func newStatusCmd(g *globalFlags) *cobra.Command { return fmt.Errorf("status: %w", err) } if upd := tcpclient.CheckPodAPI(data); upd != nil { - // Shown, not refused: status is how the user finds out (see allowsNewerPod). + // Shown, not refused: status is how the user finds out (see allowsAnyPodAPI). log.Printf("Warning: %v", upd) } out, closeOut, err := resolveOutput(g.outputFilename) diff --git a/cmd/benchpod-cli/usbnetwork.go b/cmd/benchpod-cli/usbnetwork.go index 408a961..4e74ee0 100644 --- a/cmd/benchpod-cli/usbnetwork.go +++ b/cmd/benchpod-cli/usbnetwork.go @@ -106,7 +106,7 @@ func runUSBNetwork(g *globalFlags, set string, out io.Writer) error { return errors.New(usbNetworkMissing) } if pe, ok := tcpclient.AsPodError(err); ok { - return refusedError(what, pe, false) + return refusedError(what, pe) } return fmt.Errorf("%s: %w", what, err) } diff --git a/internal/cloudpod/cloudpod.go b/internal/cloudpod/cloudpod.go index 3b50b18..cdd889e 100644 --- a/internal/cloudpod/cloudpod.go +++ b/internal/cloudpod/cloudpod.go @@ -32,6 +32,26 @@ type Client struct { // ByName: the credential is a cloud token (GitHub Actions), which reaches the pod by name on // the /api/cloud/devices routes instead of by id on the user's device routes. ByName bool + + probed bool // the pod's API level was checked (probeAPI) +} + +// probeAPI reads the pod's status once before its first other command and stops on an API +// level this CLI does not drive (tcpclient.CheckPodAPI), like the LAN client does. +func (c *Client) probeAPI(ctx context.Context, req map[string]any) error { + if c.probed || !tcpclient.APIProbe(req) { + return nil + } + _, err := c.Command(ctx, map[string]any{"cmd": "status", "caps": false}) + var upd *tcpclient.UpdateRequiredError + var old *tcpclient.FirmwareTooOldError + if errors.As(err, &upd) || errors.As(err, &old) { + return err + } + if err == nil { + c.probed = true + } + return nil // a failed probe: the command reports what is wrong } // Resolve finds the pod named name (or with that id) among the devices the credential can see. @@ -138,6 +158,9 @@ func (c *Client) Command(ctx context.Context, req map[string]any) (json.RawMessa timeout = maxTimeout } } + if err := c.probeAPI(ctx, req); err != nil { + return nil, err + } var resp *serverapi.CommandResponse var err error // The server passes the command on as it is, so it carries client_api and client like a LAN one. @@ -157,7 +180,7 @@ func (c *Client) Command(ctx context.Context, req map[string]any) (json.RawMessa } return nil, tcpclient.RefusalError(msg, resp.Code, resp.Args) } - if tcpclient.IsStatus(req) && !tcpclient.NewerPodAllowed() { + if tcpclient.IsStatus(req) && !tcpclient.AnyPodAPIAllowed() { if err := tcpclient.CheckPodAPI(resp.Data); err != nil { return nil, err } @@ -227,10 +250,12 @@ func (e *Error) Is(target error) bool { // one, so the CLI's exit code says busy (4) or refused (3) as it does on the LAN. func (e *Error) Unwrap() error { switch e.Code { - case "lease_held", "device_busy": - return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "busy"} + case "lease_held": + return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "the pod is in use", Code: "BP0025"} + case "device_busy": + return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "the pod is busy", Code: "BP0047"} case "forbidden_tier": - return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "forbidden: needs an organization owner or admin"} + return &tcpclient.PodError{Cmd: "embeddedci.com", Reason: "needs an organization owner or admin", Code: "BP0045"} } return nil } diff --git a/internal/cloudpod/cloudpod_test.go b/internal/cloudpod/cloudpod_test.go index 8682539..ed27b08 100644 --- a/internal/cloudpod/cloudpod_test.go +++ b/internal/cloudpod/cloudpod_test.go @@ -53,7 +53,7 @@ func jsonError(w http.ResponseWriter, status int, msg, code string) { func TestResolveAndCommand(t *testing.T) { f := &fakeServer{reply: func(w http.ResponseWriter) { - _, _ = w.Write([]byte(`{"request_id":"r","device_id":"id-b","status":"ok","data":{"version":"3.8.0"}}`)) + _, _ = w.Write([]byte(`{"request_id":"r","device_id":"id-b","status":"ok","data":{"version":"4.0.0","api":2}}`)) }} api := f.start(t) c, err := Resolve(context.Background(), api, "ApiKey eci_test", "bench-b") @@ -72,7 +72,7 @@ func TestResolveAndCommand(t *testing.T) { if err != nil { t.Fatal(err) } - if string(data) != `{"version":"3.8.0"}` || f.command["cmd"] != "status" { + if string(data) != `{"version":"4.0.0","api":2}` || f.command["cmd"] != "status" { t.Errorf("data %s, sent %v", data, f.command) } if f.timeout < 15000 || f.timeout > 20000 { @@ -247,24 +247,36 @@ func TestCloudCommandCarriesTheClientFields(t *testing.T) { } } -// The status check and BP0030 work through embeddedci.com too. -func TestCloudNewerPodNeedsANewerCLI(t *testing.T) { +// The status check and BP0030 work through embeddedci.com too: a newer pod needs a newer CLI, a +// pod older than firmware 4.0 (api 1, or none) needs a firmware update. +func TestCloudPodAPILevels(t *testing.T) { for _, c := range []struct { cmd, reply string - bad bool + newer, old bool }{ - {"status", `{"status":"ok","data":{"version":"3.11.0","api":2}}`, true}, - {"status", `{"status":"ok","data":{"version":"3.10.13"}}`, false}, - {"status", `{"status":"ok","data":{"api":1}}`, false}, - {"ping", `{"status":"ok","data":{"api":2}}`, false}, - {"la", `{"status":"error","code":"BP0030","args":{"client_api":1,"min_client_api":2,"api":2}}`, true}, + {"status", `{"status":"ok","data":{"version":"5.0.0","api":3}}`, true, false}, + {"status", `{"status":"ok","data":{"version":"4.0.0","api":2,"min_client_api":2}}`, false, false}, + {"status", `{"status":"ok","data":{"version":"3.10.13"}}`, false, true}, + {"status", `{"status":"ok","data":{"api":1}}`, false, true}, + {"ping", `{"status":"ok","data":{"api":1}}`, false, false}, // no probe: tcpclient.SetAPIProbe is off + {"la", `{"status":"error","code":"BP0030","args":{"client_api":1,"min_client_api":3,"api":3}}`, true, false}, } { f := &fakeServer{reply: func(w http.ResponseWriter) { _, _ = w.Write([]byte(c.reply)) }} cl := &Client{API: f.start(t), Credential: "tok", DeviceID: "id-b", Name: "bench-b"} _, err := cl.Command(context.Background(), map[string]any{"cmd": c.cmd}) var upd *tcpclient.UpdateRequiredError - if got := errors.As(err, &upd); got != c.bad || (!c.bad && err != nil) { + var old *tcpclient.FirmwareTooOldError + if errors.As(err, &upd) != c.newer || errors.As(err, &old) != c.old || (!c.newer && !c.old && err != nil) { t.Errorf("%s %s: err = %v", c.cmd, c.reply, err) } } + // With the probe on, the first other command reads status first. + tcpclient.SetAPIProbe(true) + defer tcpclient.SetAPIProbe(false) + f := &fakeServer{reply: func(w http.ResponseWriter) { _, _ = w.Write([]byte(`{"status":"ok","data":{"version":"3.10.13"}}`)) }} + cl := &Client{API: f.start(t), Credential: "tok", DeviceID: "id-b", Name: "bench-b"} + var old *tcpclient.FirmwareTooOldError + if _, err := cl.Command(context.Background(), map[string]any{"cmd": "la_pins"}); !errors.As(err, &old) || f.command["cmd"] != "status" { + t.Fatalf("probe: err = %v, sent %v", err, f.command) + } } diff --git a/internal/errcatalog/errors.json b/internal/errcatalog/errors.json index 9549d8d..0b1525c 100644 --- a/internal/errcatalog/errors.json +++ b/internal/errcatalog/errors.json @@ -1,7 +1,7 @@ { "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", "version": 1, - "catalog_sha256": "1fdf57bcda663e4e263d034fc81e30b23d565347daafb03b09b5cd7d7e63a332", + "catalog_sha256": "d7359d9f78117efb1b33c0137326effd869c3e8801fd5409ead47e8e1f38f5dc", "docs_url": "https://embeddedci.com/docs/errors#{code}", "codes": { "BP0001": { @@ -467,8 +467,8 @@ "name": "client_too_old", "area": "protocol", "since": "next", - "message": "This client is too old for the pod's firmware: it needs client API {min_client_api} or newer (this client sent {client_api})", - "cause": "The firmware on the pod changed a reply or a message in a way that clients built for client API {client_api} would misread, so it refuses their commands instead of giving them answers they get wrong. The firmware speaks client API {api} and takes {min_client_api} or newer. A client that sends no client_api counts as 0. status, diag, ping and lease_release still work.", + "message": "Update the BenchPod SDK, MCP or CLI: this firmware needs client API {min_client_api} or newer (this client sent {client_api})", + "cause": "The firmware on the pod changed a reply or a message in a way that clients built for client API {client_api} would misread, so it refuses their commands instead of giving them answers they get wrong. The firmware speaks client API {api} and takes {min_client_api} or newer. A client that sends no client_api counts as 0. These still run for any client: ping, status, diag, identity_public, lease_release, ota_status, ota_begin, ota_data, ota_end, ota_commit, ota_abort, ota_selftest and blob_status, so a client can see the levels, let go of the pod, and update the pod's firmware and blobs or roll them back.", "args": { "client_api": "int", "min_client_api": "int", @@ -480,6 +480,796 @@ "mcp": "tell the user the BenchPod MCP server is too old for this pod's firmware; they can update it (run `uvx embeddedci-mcp@latest`, or pip install -U embeddedci-mcp; with the benchpod plugin, update the plugin), then reconnect", "web": "Reload the page to get the latest web app." } + }, + "BP0031": { + "name": "la_pin_in_use", + "area": "io", + "since": "next", + "message": "LA{la} is in use by {owner}", + "cause": "Each LA channel has one owner at a time: a GPIO, a UART, SWD, SPI or I2C session, a step train or an emulated sensor. {owner} holds LA{la}, so the pod refuses to give it to anything else until that owner lets it go. function is the owner's function (gpio, uart_tx, i2c_sda, ...), and instance the emulated sensor's name, empty for anything else.", + "args": { + "la": "int", + "owner": "str", + "function": "str", + "instance": "str" + }, + "fix": { + "sdk": "free LA{la} first: bp.release_gpio({la}) for a GPIO, close the UART, SPI or I2C session that uses it, wait for the flash or step train, or stop the emulated sensor (bp.sensors.stop(name)); bp.la_pins() shows each channel's owner", + "cli": "free LA{la} where it was taken (the web app, a test or an MCP session holds it), or stop an emulated sensor with `benchpod sensor stop `; `benchpod la pins` shows each channel's owner", + "mcp": "free LA{la} first: gpio_release(la=[{la}]) for a GPIO, uart_close, spi or i2c_close for a session, sensor_stop with the sensor's instance for an emulated sensor, or wait for a flash; la_pins shows each channel's owner", + "web": "LA{la} is in use by {owner}. Free it there first (the Pins pane shows each pin's owner)." + } + }, + "BP0032": { + "name": "la_pull_down_engaged", + "area": "io", + "since": "next", + "message": "LA{la} has its {ohms} pull-down on, which {function} cannot work with ({reason})", + "cause": "A pull-down holds the line low. An open-drain bus (I2C), an idle-high UART line or SWDIO needs the line to rest high, so the pod refuses to start {function} on LA{la} while its pull-down is on.", + "args": { + "la": "int", + "ohms": "str", + "function": "str", + "reason": "str" + }, + "fix": { + "sdk": "switch the pull-down off with bp.set_pull({la}, \"off\"), or use another channel", + "cli": "switch the pull-down off with `benchpod la pull {la} off`, or use another channel", + "mcp": "call set_pull(las=[{la}], pull=\"off\"), or use another channel", + "web": "Switch off LA{la}'s pull-down in the Pins pane, or pick another pin." + } + }, + "BP0033": { + "name": "la_pull_down_conflict", + "area": "io", + "since": "next", + "message": "LA{la} is used by {function}, which cannot work with the {ohms} pull-down ({reason})", + "cause": "A pull-down holds the line low. {function} on LA{la} needs the line to rest high, so the pod refuses to switch the pull-down on under it.", + "args": { + "la": "int", + "ohms": "str", + "function": "str", + "reason": "str" + }, + "fix": { + "sdk": "stop what uses LA{la} first (bp.la_pins() shows it), or pull another channel down", + "cli": "stop what uses LA{la} first (`benchpod la pins` shows it), or pull another channel down", + "mcp": "stop what uses LA{la} first (la_pins shows it), or pull another channel down", + "web": "LA{la} is in use by {function}. Stop it before you switch on the pull-down." + } + }, + "BP0034": { + "name": "la_dut_output", + "area": "io", + "since": "next", + "message": "LA{la} is wired to a DUT output, and {function} would drive against it", + "cause": "The wiring marks LA{la} as a pin the DUT drives (la_dir dut_output). Two push-pull outputs on one wire fight each other, which can damage either side, so the pod refuses to drive it. There is no override.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "use an open_drain GPIO on LA{la}, or fix the wiring (bp.la_dir) if LA{la} is not a DUT output", + "cli": "use an open-drain GPIO on LA{la}, or fix the pin's direction in the wiring profile if it is not a DUT output", + "mcp": "use gpio_mode(mode=\"open_drain\") on LA{la}, or fix the wiring with la_dir if LA{la} is not a DUT output", + "web": "LA{la} is wired to a DUT output. Use open drain, or fix the pin's direction in the wiring." + } + }, + "BP0035": { + "name": "la_driven_pin", + "area": "io", + "since": "next", + "message": "LA{la} is driven by {function}, so it cannot be marked as a DUT output", + "cause": "{function} drives LA{la} from the pod. Marking the pin as one the DUT drives would put two outputs on one wire, so the pod refuses until the pod's side stops driving it.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "stop what drives LA{la} first (bp.la_pins() shows it), then set its direction", + "cli": "stop what drives LA{la} first (`benchpod la pins` shows it), then set its direction", + "mcp": "stop what drives LA{la} first (la_pins shows it), then call la_dir again", + "web": "LA{la} is driven by {function}. Stop it before you mark the pin as a DUT output." + } + }, + "BP0036": { + "name": "la_not_gpio_output", + "area": "io", + "since": "next", + "message": "LA{la} is not a GPIO output (it is {function})", + "cause": "Writing a level or sending a gpio step needs the channel set up as a GPIO output or open drain first.", + "args": { + "la": "int", + "function": "str" + }, + "fix": { + "sdk": "make it an output first: bp.gpio({la}, \"output\") (or \"open_drain\")", + "cli": "make LA{la} a GPIO output first", + "mcp": "call gpio_mode(la=[{la}], mode=\"output\") (or \"open_drain\") first", + "web": "Set LA{la} to output in the Pins pane first." + } + }, + "BP0037": { + "name": "la_voltage_pins_in_use", + "area": "io", + "since": "next", + "message": "The I/O voltage cannot change while pins are in use: {pins}", + "cause": "Changing the I/O voltage under a running GPIO, UART, flash or sensor would put the wrong level on the DUT's pins, so the pod refuses until they are free.", + "args": { + "pins": "str" + }, + "fix": { + "sdk": "stop what uses those pins first (release the GPIOs, close the sessions, bp.sensors.stop()), then set the voltage", + "cli": "stop what uses those pins first, then set the voltage again", + "mcp": "stop what uses those pins first (gpio_release, uart_close, sensor_stop), then call set_la_voltage again", + "web": "Stop what uses those pins first, then change the I/O voltage." + } + }, + "BP0038": { + "name": "trigger_timeout", + "area": "capture", + "since": "next", + "message": "No {edge} edge on LA{la} within {timeout_ms} ms", + "cause": "A triggered capture waits for its trigger condition before it records. The DUT never made a {edge} edge on LA{la} in the time given, so the pod stopped waiting and recorded nothing.", + "args": { + "la": "int", + "edge": "str", + "timeout_ms": "int" + }, + "fix": { + "sdk": "check that the DUT drives LA{la} and that the edge is right, or give a longer trigger_timeout_ms", + "cli": "check that the DUT drives LA{la} and that the edge is right, or give a longer trigger timeout", + "mcp": "check the DUT drives LA{la} and the edge is right, or retry with a longer trigger timeout", + "web": "Nothing happened on LA{la} in time. Check the wiring and the edge, or wait longer." + } + }, + "BP0039": { + "name": "sensor_trigger_timeout", + "area": "capture", + "since": "next", + "message": "No I2C start on LA{la} (SDA of {instance}) within {timeout_ms} ms: the DUT did not use the I2C bus", + "cause": "A sensor bus capture with trigger \"start\" waits for the DUT's first I2C start condition on the emulated sensor's SDA. None came in time.", + "args": { + "la": "int", + "instance": "str", + "timeout_ms": "int" + }, + "fix": { + "sdk": "make the DUT talk to the sensor during the capture (reset it, or start the capture first), or pass trigger=\"none\"", + "cli": "make the DUT talk to the sensor during the capture, or capture without the start trigger", + "mcp": "make the DUT talk to the sensor during the capture (reset_target), or call sensor_capture with trigger \"none\"", + "web": "The DUT did not talk to the sensor in time. Reset it during the capture, or capture without the trigger." + } + }, + "BP0040": { + "name": "lan_locked", + "area": "policy", + "since": "next", + "message": "The pod's LAN is locked: {cmd} needs the cloud or USB", + "cause": "The pod's LAN policy is locked, so commands that change settings, flash or update (tiers T2 and T3) only run from the cloud or over USB. Reads and tests still run on the LAN.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) or the cloud (\"embeddedci:\") for {cmd}, or open the LAN policy over USB", + "cli": "run this over USB with --connection usb, or from the cloud", + "mcp": "connect over USB ('usb') or the cloud ('embeddedci:') for {cmd}; ask the user before opening the LAN policy", + "web": "The pod's LAN is locked. Use the pod from the cloud or over USB for this." + } + }, + "BP0041": { + "name": "policy_not_from_lan", + "area": "policy", + "since": "next", + "message": "{setting} cannot be changed over the LAN: change it from the cloud or the USB console", + "cause": "Policies that decide who may change the pod are only changed by someone with the pod's cloud account or its USB cable, never by anyone on the network.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "change {setting} from the cloud or the USB console", + "cli": "change {setting} over USB (`--connection usb`) or from the cloud", + "mcp": "tell the user {setting} is changed from the cloud or the USB console", + "web": "Change {setting} from the cloud or over the pod's USB console." + } + }, + "BP0042": { + "name": "setting_cloud_or_usb", + "area": "policy", + "since": "next", + "message": "{setting} cannot be changed over the LAN: change it from the cloud or over USB", + "cause": "Settings that decide what the pod trusts (LAN TLS, the cloud CA, the cloud proxy) are not changed from the network. TLS on port 8443 has no client authentication, so it does not count either.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) or the cloud (\"embeddedci:\") to change {setting}", + "cli": "run this over USB with --connection usb, or from the cloud", + "mcp": "connect over USB ('usb') or the cloud to change {setting}", + "web": "Change {setting} from the cloud or over USB." + } + }, + "BP0043": { + "name": "setting_device_only", + "area": "policy", + "since": "next", + "message": "{setting} can only be changed on the device: the USB console, or over the USB link", + "cause": "This setting changes how the pod can be reached or updated, so it needs someone at the pod: its USB console or its USB network link. Neither the LAN nor the cloud may change it.", + "args": { + "setting": "str" + }, + "fix": { + "sdk": "connect over USB (BenchPod(\"usb\")) to change {setting}", + "cli": "run this over USB with --connection usb", + "mcp": "connect over USB ('usb') to change {setting}, or ask the user to do it at the pod", + "web": "Change {setting} with the pod plugged in over USB." + } + }, + "BP0044": { + "name": "policy_loosen_usb_only", + "area": "policy", + "since": "next", + "message": "Only the USB console can loosen {setting} (now {now})", + "cause": "The cloud may make the pod stricter but never looser: a stolen cloud account must not be able to lower the pod's firmware signature policy.", + "args": { + "setting": "str", + "now": "str" + }, + "fix": { + "sdk": "loosen {setting} on the pod's USB console", + "cli": "loosen {setting} over USB with `benchpod policy` and --connection usb", + "mcp": "tell the user {setting} can only be loosened on the pod's USB console", + "web": "Loosen {setting} on the pod's USB console." + }, + "retired": "4.0.0", + "replaced_by": "BP0074" + }, + "BP0045": { + "name": "role_required", + "area": "policy", + "since": "next", + "message": "{cmd} needs an organization owner or admin", + "cause": "A cloud session runs commands up to the tier the server allows its user. {cmd} changes or updates the pod, which needs an owner or admin of the pod's organization.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "use an API key or session of an organization owner or admin (API keys need the benchpod:admin scope)", + "cli": "sign in as an organization owner or admin; API keys need the benchpod:admin scope", + "mcp": "tell the user {cmd} needs an organization owner or admin (an API key with the benchpod:admin scope)", + "web": "Ask an owner or admin of your organization to do this." + } + }, + "BP0046": { + "name": "no_analog_front_end", + "area": "board", + "since": "next", + "message": "This BenchPod has no analog front end, so it cannot run {cmd}", + "cause": "The digital board has no DAC, ADC or analog outputs. The pod checks at boot; after fitting an analog add-on, restart it.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "use a pod with an analog front end (bp.capabilities shows it), or leave out the analog step", + "cli": "use a pod with an analog front end", + "mcp": "this pod has no analog front end; skip the analog step or use another pod", + "web": "This pod has no analog front end." + } + }, + "BP0047": { + "name": "pod_busy", + "area": "busy", + "since": "next", + "message": "The pod is running another long command (a capture, measurement, upload or update)", + "cause": "Captures, measurements, waveform uploads and firmware updates share the pod's sample memory, so one runs at a time. Light commands (status, GPIO, ...) still run.", + "args": {}, + "fix": { + "sdk": "wait for the other command to finish, then try again", + "cli": "the pod is running another long command; try again when it ends", + "mcp": "wait for the other call to finish, then try again", + "web": "The pod is busy with another capture or upload. Try again when it ends." + } + }, + "BP0048": { + "name": "storage_bus_busy", + "area": "busy", + "since": "next", + "message": "The pod's storage bus is in use: {what}", + "cause": "The flash that holds settings, gateware and update images shares a bus with the sample memory. While {what}, the pod cannot write it.", + "args": { + "what": "str" + }, + "fix": { + "sdk": "try again when it ends", + "cli": "try again when it ends", + "mcp": "wait until it ends, then try again", + "web": "Try again when it ends." + } + }, + "BP0049": { + "name": "uart_session_open", + "area": "uart", + "since": "next", + "message": "A UART session is already open", + "cause": "The pod runs one UART at a time: the web app's Terminal, a test, an MCP session or a flash over the UART holds it.", + "args": {}, + "fix": { + "sdk": "close the open UART session first (session.close(), or leave its with block)", + "cli": "close the other UART session (the web app's Terminal, a test or an MCP session) first", + "mcp": "call uart_close first", + "web": "Close the open terminal session first." + } + }, + "BP0050": { + "name": "swd_session_open", + "area": "flash", + "since": "next", + "message": "An SWD session is already running", + "cause": "The pod runs one SWD session (a flash or a debug run) at a time.", + "args": {}, + "fix": { + "sdk": "wait for the running flash to finish, then try again", + "cli": "wait for the running flash to finish, then try again", + "mcp": "wait for the running flash to finish, then try again", + "web": "Wait for the running flash to finish." + } + }, + "BP0051": { + "name": "update_in_progress", + "area": "update", + "since": "next", + "message": "A {target} update from {holder} is in progress", + "cause": "The pod takes one update at a time, from one place. Another one is running.", + "args": { + "target": "str", + "holder": "str" + }, + "fix": { + "sdk": "wait for the other update to finish (or ota_abort it from where it runs), then try again", + "cli": "wait for the other update to finish, then try again", + "mcp": "tell the user another update is running and wait for it", + "web": "Another update is running. Wait for it to finish." + } + }, + "BP0052": { + "name": "cloud_command_busy", + "area": "busy", + "since": "next", + "message": "The pod is still running the previous cloud command", + "cause": "Over the cloud command channel the pod runs one command at a time. The server retries, so this is usually brief.", + "args": {}, + "fix": { + "sdk": "try again in a moment", + "cli": "try again in a moment", + "mcp": "retry in a moment", + "web": "Try again in a moment." + } + }, + "BP0053": { + "name": "reply_too_large", + "area": "protocol", + "since": "next", + "message": "The reply did not fit the pod's reply buffer", + "cause": "The command worked, but its answer is larger than the pod can send at once. Commands that can grow (la_pins) take a subset.", + "args": {}, + "fix": { + "sdk": "ask for less at once (bp.la_pins(la=[...]) reads a subset); update the SDK if it keeps happening", + "cli": "ask for less at once; update the CLI if it keeps happening", + "mcp": "ask for fewer channels or less data per call", + "web": "Reload the page; if it keeps happening, update the pod's firmware." + } + }, + "BP0054": { + "name": "cloud_reply_too_large", + "area": "protocol", + "since": "next", + "message": "The reply is too large for the cloud channel ({bytes} bytes, limit {limit})", + "cause": "Cloud command replies travel in one frame of at most {limit} bytes. This one is {bytes}. Large data (captures) go through the cloud byte tunnel instead.", + "args": { + "bytes": "int", + "limit": "int" + }, + "fix": { + "sdk": "ask for less at once (bp.la_pins(la=[...]) reads a subset), or connect over the LAN or USB", + "cli": "ask for less at once, or connect over the LAN or USB", + "mcp": "ask for fewer channels or less data per call", + "web": "Ask for less at once." + } + }, + "BP0055": { + "name": "sensor_instance_unknown", + "area": "sensors", + "since": "next", + "message": "The pod has no emulated sensor {instance}", + "cause": "The instance was never defined or started on this pod, was stopped, or the pod restarted.", + "args": { + "instance": "str" + }, + "fix": { + "sdk": "list the running sensors with bp.sensors.status(), or start {instance} first", + "cli": "list the running sensors with `benchpod sensor status`, or start {instance} first", + "mcp": "call sensor_status to list the running sensors, or sensor_start {instance} first", + "web": "{instance} is not running. Start it first." + } + }, + "BP0056": { + "name": "no_module_link", + "area": "board", + "since": "next", + "message": "This BenchPod has no module link, so it cannot run {cmd}", + "cause": "Only boards with a module header (digital v3r3) talk to an add-on module.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "skip the module step on this board", + "cli": "this board has no module link", + "mcp": "this pod has no module link; skip the module step", + "web": "This pod has no module link." + } + }, + "BP0057": { + "name": "image_switch_sensors_running", + "area": "sensors", + "since": "next", + "message": "The emulated sensors {sensors} need the emulation image; stop them before switching", + "cause": "I2C, SPI and UART sensors run in the emulation gateware image. Switching to another image would stop them mid-run, so the pod refuses.", + "args": { + "sensors": "str" + }, + "fix": { + "sdk": "stop them with bp.sensors.stop(), then switch the image", + "cli": "stop them with `benchpod sensor stop` first", + "mcp": "call sensor_stop (all) first, then fpga_image", + "web": "Stop the emulated sensors first." + } + }, + "BP0058": { + "name": "fpga_image_required", + "area": "firmware", + "since": "next", + "message": "{feature} is not in the running gateware image; it needs the {image} image", + "cause": "The pod's FPGA runs one of three images (loop, deep replay, emulation), and each has some features. {feature} is in the {image} image.", + "args": { + "feature": "str", + "image": "str" + }, + "fix": { + "sdk": "switch with bp.fpga_image(FpgaImage.LOOP) (or DEEP_REPLAY for the deep image), then try again", + "cli": "switch with `benchpod sensor image {image}`, then try again", + "mcp": "call fpga_image(image=\"{image}\"), then try again", + "web": "Switch the FPGA image to {image} first." + } + }, + "BP0059": { + "name": "fpga_image_sensors_first", + "area": "sensors", + "since": "next", + "message": "{feature} is not in the emulation image the emulated sensors use; stop them, then switch to the {image} image", + "cause": "Emulated I2C, SPI and UART sensors run in the emulation gateware image, which has no room for {feature}. It needs the {image} image, and switching stops the sensors.", + "args": { + "feature": "str", + "image": "str" + }, + "fix": { + "sdk": "bp.sensors.stop(), then bp.fpga_image(...) for the {image} image", + "cli": "stop the sensors with `benchpod sensor stop`, then switch with `benchpod sensor image {image}`", + "mcp": "call sensor_stop (all), then fpga_image(image=\"{image}\")", + "web": "Stop the emulated sensors, then switch to the {image} image." + } + }, + "BP0060": { + "name": "ota_unknown_target", + "area": "update", + "since": "next", + "message": "{target} is not an update target this firmware knows", + "cause": "The firmware on the pod is older than the tool, or the target name is wrong.", + "args": { + "target": "str" + }, + "fix": { + "sdk": "update the pod's firmware first (`benchpod flash-self`)", + "cli": "update the pod's firmware with `benchpod flash-self` first", + "mcp": "tell the user the pod's firmware does not know this update target; update the firmware first", + "web": "Update the pod's firmware first." + } + }, + "BP0061": { + "name": "i2c_needs_pullups", + "area": "i2c", + "since": "next", + "message": "I2C needs pull-ups: LA{la} has none switched on", + "cause": "I2C lines are open drain: something must pull them high. The pod can do it with its own pull-ups, or the board has its own.", + "args": { + "la": "int" + }, + "fix": { + "sdk": "switch the pull-up on (bp.enable_pullup({la})), or pass pullups=\"external\" when the board has its own", + "cli": "pull LA{la} up with `benchpod la pull {la} up`, or pass --pullups external when the board has its own", + "mcp": "call set_pull(las=[{la}], pull=\"up\"), or pass pullups=\"external\" when the board has its own", + "web": "Switch on LA{la}'s pull-up, or say the board has its own." + } + }, + "BP0062": { + "name": "i2c_session_not_open", + "area": "i2c", + "since": "next", + "message": "No I2C session is open", + "cause": "I2C transactions run inside a session that i2c_start opens.", + "args": {}, + "fix": { + "sdk": "open one with bp.open_i2c() first", + "cli": "start the I2C master first", + "mcp": "call i2c_open first", + "web": "Open an I2C session first." + } + }, + "BP0063": { + "name": "i2c_engine_reset", + "area": "i2c", + "since": "next", + "message": "The I2C engine was reset, which ended the session", + "cause": "A gateware reload (an image switch, a recovery) resets the I2C engine, so the open session is gone.", + "args": {}, + "fix": { + "sdk": "open the session again with bp.open_i2c()", + "cli": "start the I2C command again", + "mcp": "call i2c_open again", + "web": "Open the I2C session again." + } + }, + "BP0064": { + "name": "loop_sweep_with_map", + "area": "dac", + "since": "next", + "message": "The sweep input cannot be combined with an input map on this gateware", + "cause": "The sweep spans the raw count range, not the mapped window, so most of each pass would sit at one end of the curve.", + "args": {}, + "fix": { + "sdk": "step the input with bp.loop_input() instead of the sweep", + "cli": "step the loop input instead of using the sweep", + "mcp": "step the input with loop_input instead", + "web": "Step the input instead of sweeping it." + } + }, + "BP0065": { + "name": "output_used_by_sensor", + "area": "sensors", + "since": "next", + "message": "The {output} output is played by the emulated sensor {instance}", + "cause": "An analog emulated sensor drives the pod's {output} output, so a DAC or current command would fight it.", + "args": { + "output": "str", + "instance": "str" + }, + "fix": { + "sdk": "stop it first with bp.sensors.stop(\"{instance}\")", + "cli": "stop it first with `benchpod sensor stop {instance}`", + "mcp": "call sensor_stop(instance=\"{instance}\") first", + "web": "Stop the emulated sensor {instance} first." + } + }, + "BP0066": { + "name": "step_busy", + "area": "io", + "since": "next", + "message": "A step pulse train is running", + "cause": "The pod runs one step train at a time.", + "args": {}, + "fix": { + "sdk": "wait for the step train to finish (or stop it), then try again", + "cli": "wait for the step train to finish, then try again", + "mcp": "wait for the la_step train to finish, then try again", + "web": "Wait for the step train to finish." + } + }, + "BP0067": { + "name": "samples_out_of_range", + "area": "capture", + "since": "next", + "message": "samples must be 1 to {max} for this capture", + "cause": "Each capture holds a fixed number of samples: the shallow ADC capture what fits the RAM buffer, the deep ones what fits their PSRAM region at the rate asked for. A deep ADC capture is capture_dual with la_samples 0.", + "args": { + "max": "int" + }, + "fix": { + "sdk": "ask for at most {max} samples, or use a deep capture (capture_dual) for more", + "cli": "ask for at most {max} samples", + "mcp": "ask for at most {max} samples, or use capture_correlated / a deep capture for more", + "web": "Capture at most {max} samples." + } + }, + "BP0068": { + "name": "la_rate_above_ceiling", + "area": "capture", + "since": "next", + "message": "LA at {rate_mhz} MS/s does not fit: with ADC samples in the capture the raw LA runs at most {max_mhz} MS/s on this gateware, {fit_mhz} MS/s for {samples} samples", + "cause": "On gateware before v53 the raw LA runs at most {max_mhz} MS/s when the same capture records ADC samples: faster, the PSRAM writer starved the ADC. The pod refuses an explicit rate it cannot run instead of slowing it down. {fit_mhz} MS/s is the fastest rate that fits {samples} samples. Above 12 MS/s the LA records its changes instead.", + "args": { + "rate_mhz": "str", + "max_mhz": "str", + "fit_mhz": "str", + "samples": "int" + }, + "fix": { + "sdk": "ask for at most {max_mhz} MS/s ({fit_mhz} MS/s for {samples} samples), leave the rate out for the fastest that fits, or update the pod's gateware", + "cli": "ask for at most {max_mhz} MS/s, or leave the rate out for the fastest that fits", + "mcp": "retry with la_sample_rate_hz at most {fit_mhz} MHz in Hz (or leave it out for the fastest that fits)", + "web": "Pick {fit_mhz} MS/s or less, or leave the rate on automatic." + } + }, + "BP0069": { + "name": "la_rate_too_deep", + "area": "capture", + "since": "next", + "message": "LA at {rate_mhz} MS/s does not fit {samples} samples: at most {max_samples} samples at {rate_mhz} MS/s, or at most {fit_mhz} MS/s for {samples} samples", + "cause": "The raw LA samples into a burst buffer that drains to the PSRAM more slowly than the fastest rates. A capture deeper than the buffer holds at {rate_mhz} MS/s would drop samples, so the pod refuses it instead of slowing it down. Either way out works: fewer samples at this rate, or a lower rate for this depth.", + "args": { + "rate_mhz": "str", + "samples": "int", + "max_samples": "int", + "fit_mhz": "str" + }, + "fix": { + "sdk": "capture at most {max_samples} samples at {rate_mhz} MS/s, or at most {fit_mhz} MS/s for {samples} samples (leave the rate out for the fastest that fits)", + "cli": "capture at most {max_samples} samples at {rate_mhz} MS/s, or ask for {fit_mhz} MS/s or less (or leave the rate out)", + "mcp": "retry with at most {max_samples} samples, or with the rate at most {fit_mhz} MS/s (or leave it out for the fastest that fits)", + "web": "Capture at most {max_samples} samples at {rate_mhz} MS/s, or pick {fit_mhz} MS/s or less." + } + }, + "BP0070": { + "name": "capture_dual_too_deep", + "area": "capture", + "since": "next", + "message": "capture_dual takes at most {la_max} LA and {adc_max} ADC samples", + "cause": "Each stream of a capture_dual has its own PSRAM region of a fixed size. A deeper LA-only capture fits la_capture, which takes up to {la_capture_max} LA samples.", + "args": { + "la_max": "int", + "adc_max": "int", + "la_capture_max": "int" + }, + "fix": { + "sdk": "ask for at most {la_max} LA and {adc_max} ADC samples, or use la_capture for up to {la_capture_max} LA samples", + "cli": "ask for at most {la_max} LA and {adc_max} ADC samples", + "mcp": "ask for at most {la_max} LA and {adc_max} ADC samples, or use capture_la for up to {la_capture_max} LA samples", + "web": "Capture at most {la_max} LA and {adc_max} ADC samples." + } + }, + "BP0071": { + "name": "capture_overflowed", + "area": "capture", + "since": "next", + "message": "The capture overflowed: the PSRAM could not keep up with LA {la_ksps} kS/s and ADC {adc_ksps} kS/s", + "cause": "The capture started, but its streams wrote to the PSRAM faster than it could take them, so samples were lost and the pod returns none.", + "args": { + "la_ksps": "int", + "adc_ksps": "int" + }, + "fix": { + "sdk": "lower la_sample_rate_hz or adc_sample_rate_hz, or capture fewer samples", + "cli": "lower the LA or ADC rate, or capture fewer samples", + "mcp": "retry with a lower la_sample_rate_hz or adc_sample_rate_hz, or fewer samples", + "web": "Lower the LA or ADC rate, or capture fewer samples." + } + }, + "BP0072": { + "name": "psram_too_small", + "area": "capture", + "since": "next", + "message": "The capture is too deep: LA, ADC and a loaded DAC waveform together exceed the 8 MB PSRAM", + "cause": "A capture_dual packs its LA region, its ADC region and any deep-replay waveform still loaded into the pod's 8 MB PSRAM, and refuses up front when they do not fit.", + "args": {}, + "fix": { + "sdk": "capture fewer LA or ADC samples, or free the replay waveform (bp.dac_stop()) first", + "cli": "capture fewer samples", + "mcp": "retry with fewer la_samples or adc_samples, or call dac_stop to free a loaded replay waveform", + "web": "Capture fewer samples, or stop the DAC replay first." + } + }, + "BP0073": { + "name": "psram_bandwidth", + "area": "capture", + "since": "next", + "message": "The combined sample rate is more than the PSRAM bus can take", + "cause": "The LA, the ADC and a running deep replay share one PSRAM bus. The pod adds up their sustained rates and refuses a capture that would overrun it, instead of losing samples.", + "args": {}, + "fix": { + "sdk": "lower la_sample_rate_hz or adc_sample_rate_hz, or stop the DAC replay first", + "cli": "lower the LA or ADC rate", + "mcp": "retry with a lower la_sample_rate_hz or adc_sample_rate_hz, or call dac_stop first", + "web": "Lower the LA or ADC rate, or stop the DAC replay first." + } + }, + "BP0074": { + "name": "signatures_always_required", + "area": "policy", + "since": "next", + "message": "{setting} cannot be set to {want}: this firmware installs only signed images", + "cause": "Firmware 4.0.0 and later take an update (firmware, gateware, the Wi-Fi chip's image) only with a good signature, on every path: the LAN, the USB network adapter and the cloud. No command loosens that. Dev builds also take images signed with the developer key. Firmware you built yourself goes in over USB DFU (`benchpod flash-self`), which needs the pod on a USB cable.", + "args": { + "setting": "str", + "want": "str" + }, + "fix": { + "sdk": "install a signed release, or install self-built firmware over USB DFU (`benchpod flash-self`)", + "cli": "install a signed release, or install self-built firmware over USB DFU with `benchpod flash-self` (without --network)", + "mcp": "tell the user the pod takes only signed images; self-built firmware goes in over USB DFU (`benchpod flash-self`)", + "web": "The pod takes only signed images. Install self-built firmware over USB with `benchpod flash-self`." + } + }, + "BP0075": { + "name": "lan_plaintext_off", + "area": "policy", + "since": "next", + "message": "The pod serves its JSON API on the LAN over TLS only (port 8443): plaintext port 8080 is off", + "cause": "Firmware 4.0.0 and later serve the JSON API over Ethernet and Wi-Fi on TLS port 8443 only. Plaintext port 8080 still answers on the USB network adapter, and from the LAN when SCPI is switched on, but only for SCPI there. Plaintext JSON on the LAN comes back only when it is switched on over USB or from the cloud.", + "args": {}, + "fix": { + "sdk": "connect to the pod by its address without a port (the SDK uses TLS on 8443 and pins the pod's certificate), or over USB ('usb')", + "cli": "connect by the pod's address without a port (the CLI uses TLS on 8443), or with --connection usb", + "mcp": "connect to the pod's address without :8080 (TLS on 8443 is used), or to 'usb'", + "web": "Connect to the pod over TLS (port 8443) or USB." + } + }, + "BP0076": { + "name": "usb_host_over_usb", + "area": "usb", + "since": "next", + "message": "USB host mode cannot start over the pod's own USB link", + "cause": "While the pod hosts a board on its USB port it is off the computer's USB, so the connection that asked would drop before the answer arrives. USB host mode starts only over the network (LAN or Wi-Fi) or the cloud.", + "args": {}, + "fix": { + "sdk": "connect to the pod over the network or the cloud (Client(host) or 'embeddedci:'), not 'usb', then start USB host mode again", + "cli": "connect to the pod over the network or the cloud (--connection or embeddedci:), not usb, then run the command again", + "mcp": "connect to the pod over the network or the cloud (connect with its host or 'embeddedci:'), not 'usb', then try again", + "web": "Connect to the pod over the network or the cloud to use USB host mode." + } + }, + "BP0077": { + "name": "usb_host_port_unavailable", + "area": "usb", + "since": "next", + "message": "This pod has no USB host port {port}", + "cause": "Only pods with a USB-A host port can host a board there. Every pod can host on its USB-C port, but only on a bench rig with an adapter cable that powers the pod and carries the data lines to the board under test.", + "args": { + "port": "str" + }, + "fix": { + "sdk": "use port='usb_c' with a USB-C adapter rig, or a pod with the USB-A host port", + "cli": "use --port usb_c with a USB-C adapter rig, or a pod with the USB-A host port", + "mcp": "tell the user this pod has no USB-A host port; port 'usb_c' works only with a USB-C adapter rig", + "web": "This pod has no USB-A host port." + } + }, + "BP0078": { + "name": "usb_host_no_crystal", + "area": "usb", + "since": "next", + "message": "USB host mode needs the pod's crystal clock, which is not running", + "cause": "A USB host keeps the bus timing itself and needs a precise clock. The pod runs on its internal oscillator because the crystal did not start at boot.", + "args": {}, + "fix": { + "sdk": "power cycle the pod; if bp.status() still shows the internal clock, contact support", + "cli": "power cycle the pod; if `benchpod status` still shows the internal clock, contact support", + "mcp": "ask the user to power cycle the pod; if it keeps happening, the pod needs support", + "web": "Power cycle the pod. If this keeps happening, contact support." + } + }, + "BP0079": { + "name": "usb_host_other_port", + "area": "usb", + "since": "next", + "message": "USB host mode is already running on {port}", + "cause": "The pod hosts one port at a time. A start for the same port renews the timeout; another port needs a stop first.", + "args": { + "port": "str" + }, + "fix": { + "sdk": "stop USB host mode first (enabled=False), then start it on the other port", + "cli": "stop USB host mode first, then start it on the other port", + "mcp": "stop USB host mode first, then start it on the other port", + "web": "Stop USB host mode first." + } } } } diff --git a/internal/features/features.json b/internal/features/features.json index bbc5dbd..5f38864 100644 --- a/internal/features/features.json +++ b/internal/features/features.json @@ -1,10 +1,10 @@ { "_generated": "GENERATED by tools/gen_features.py from features/features.toml. DO NOT EDIT: edit the table.", "schema": 1, - "revision": 8, - "api": 1, - "min_client_api": 0, - "table_sha256": "02f6411c240dcbc0cedda72648ba8713eb498a9a878ecca7f9fc817a3da586b2", + "revision": 10, + "api": 2, + "min_client_api": 2, + "table_sha256": "5d21dab2bbea4f38b11856057ecad75eb284772d4f2417d29c23894b0812e850", "floor": "3.9.2", "docs_base": "https://github.com/embeddedci-com/benchpod-firmware/blob/main/docs/", "facts": { @@ -223,7 +223,7 @@ "board": "any", "legacy_caps": "capture_b64", "legacy_frame": "capture_b64", - "docs": "API.md#base64-samples-encb64" + "docs": "API.md#base64-samples-the-default" }, "blob_slots": { "rev": 1, @@ -237,7 +237,7 @@ "board": "any", "legacy_caps": "can", "legacy_frame": "can", - "docs": "API.md#can_config--bring-can-up" + "docs": "API.md#can_start--bring-can-up" }, "ota_sig": { "rev": 1, @@ -347,7 +347,7 @@ "board": "any", "legacy_caps": "can_fd", "legacy_frame": "can_fd", - "docs": "API.md#can_config--bring-can-up" + "docs": "API.md#can_start--bring-can-up" }, "la_dir": { "rev": 1, @@ -661,13 +661,13 @@ "rev": 3, "firmware": "3.10.12", "board": "any", - "docs": "API.md#switch-or-query-an-la-pin-pull-resistor" + "docs": "API.md#la_pull--la-pin-pull-resistors" }, "la_pull_1v8": { "rev": 4, "firmware": "3.10.13", "board": "any", - "docs": "API.md#switch-or-query-an-la-pin-pull-resistor" + "docs": "API.md#la_pull--la-pin-pull-resistors" }, "log_level": { "rev": 4, @@ -704,6 +704,60 @@ "firmware": "next", "board": "any", "docs": "API.md#client-compatibility" + }, + "lan_tls_default": { + "rev": 9, + "firmware": "next", + "board": "any", + "docs": "API.md#lan_tls--the-lan-api-over-tls" + }, + "sig_always_required": { + "rev": 9, + "firmware": "next", + "board": "any", + "docs": "API.md#sig_policy--which-firmware-and-blob-updates-the-pod-accepts" + }, + "generate_volts_only": { + "rev": 10, + "firmware": "next", + "board": "analog", + "docs": "API.md#generate--dac-waveform-output" + }, + "json_names_4": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#commands" + }, + "can_start_stop": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#can_start--bring-can-up" + }, + "la_step_pull_split": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#la_pull--la-pin-pull-resistors" + }, + "json_booleans_4": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#target_power--enabledisable-a-target-power-efuse" + }, + "console_recovery_json": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "usb-serial-interface.md#removed-in-firmware-400" + }, + "usb_host": { + "rev": 10, + "firmware": "next", + "board": "any", + "docs": "API.md#usb_host--usb-host-mode" } } } diff --git a/internal/fwrefusals/fwrefusals.go b/internal/fwrefusals/fwrefusals.go deleted file mode 100644 index cf65cd1..0000000 --- a/internal/fwrefusals/fwrefusals.go +++ /dev/null @@ -1,172 +0,0 @@ -// Package fwrefusals holds the firmware refusal texts the CLI shows or matches on, copied from -// benchpod-firmware, for tests. Each entry keeps the C string literal as it appears in the -// firmware source and one rendering of it; Check verifies the literals against a firmware -// checkout, so a wording change in the firmware fails the CLI tests instead of silently breaking -// a hint or a retry. -package fwrefusals - -import ( - _ "embed" - "encoding/json" - "fmt" - "os" - "path/filepath" - "regexp" - "sort" - "strings" -) - -//go:embed refusals.json -var raw []byte - -// Refusal is one firmware text. -type Refusal struct { - ID string `json:"id"` - File string `json:"file"` // relative to the firmware repository root - Kind string `json:"kind"` // "json" (an error reply), "console", "console_upload" - Format string `json:"format"` // the C literal, escapes kept - Example string `json:"example"` // one rendering, without a trailing newline or prompt - // Removed is the firmware version that no longer sends this text ("3.9.0"), "" while current. - // Such a text stays pinned: the CLI still meets it on pods running older firmware. Check skips it. - Removed string `json:"removed,omitempty"` - // Pending names the firmware pull request that adds this text ("benchpod-firmware#49") while - // it is not on the firmware's main branch yet: Check then reports it as pending, not as a - // change. Drop the field once that PR is merged. - Pending string `json:"pending,omitempty"` -} - -type doc struct { - Refusals []Refusal `json:"refusals"` - Tiers map[string]string `json:"tiers"` -} - -func load() doc { - var d doc - if err := json.Unmarshal(raw, &d); err != nil { - panic(fmt.Sprintf("fwrefusals: %v", err)) - } - return d -} - -// All returns every refusal. -func All() []Refusal { return load().Refusals } - -// Example returns the example text of refusal id; it panics on an unknown id. -func Example(id string) string { - for _, r := range All() { - if r.ID == id { - return r.Example - } - } - panic("fwrefusals: unknown id " + id) -} - -// TierFile is the firmware file the tiers come from. -func TierFile() string { return load().Tiers["_file"] } - -// Tiers maps a command to its pinned tier name ("T0".."T3"). -func Tiers() map[string]string { - out := map[string]string{} - for k, v := range load().Tiers { - if !strings.HasPrefix(k, "_") { - out[k] = v - } - } - return out -} - -var cEscapes = strings.NewReplacer(`\"`, `"`, `\\`, `\`, `\r`, "\r", `\n`, "\n", `\t`, "\t") - -// Pattern turns a refusal's C format into a regexp that matches its example: printf verbs -// match any text, a trailing newline and console prompt are dropped. -func (r Refusal) Pattern() *regexp.Regexp { - text := strings.TrimRight(cEscapes.Replace(r.Format), "\r\n> ") - verb := regexp.MustCompile(`%[-+ #0]*[0-9]*(?:l|ll|z|h)?[sdiuxX]`) - var b strings.Builder - b.WriteString("^") - last := 0 - for _, loc := range verb.FindAllStringIndex(text, -1) { - b.WriteString(regexp.QuoteMeta(text[last:loc[0]])) - b.WriteString(".+") - last = loc[1] - } - b.WriteString(regexp.QuoteMeta(text[last:])) - b.WriteString("$") - return regexp.MustCompile(b.String()) -} - -// FirmwareDir returns a benchpod-firmware checkout to check against: $BENCHPOD_FIRMWARE_DIR, else -// a benchpod-firmware directory next to this repository. "" when there is none. -func FirmwareDir() string { - if d := os.Getenv("BENCHPOD_FIRMWARE_DIR"); d != "" { - return d - } - wd, err := os.Getwd() - if err != nil { - return "" - } - for dir := wd; ; { - cand := filepath.Join(filepath.Dir(dir), "benchpod-firmware") - if _, err := os.Stat(filepath.Join(cand, "stm32h563", "src")); err == nil { - if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { - return cand - } - } - parent := filepath.Dir(dir) - if parent == dir { - return "" - } - dir = parent - } -} - -// adjacent joins C string literals split over lines ("a " "b" -> "a b"). -var adjacent = regexp.MustCompile(`"\s*\n\s*"`) - -// Check returns one problem per refusal format or tier missing from the firmware at dir. -func Check(dir string) []string { - var problems []string - sources := map[string]string{} - read := func(file string) (string, error) { - if s, ok := sources[file]; ok { - return s, nil - } - b, err := os.ReadFile(filepath.Join(dir, file)) - if err != nil { - return "", err - } - s := adjacent.ReplaceAllString(string(b), "") - sources[file] = s - return s, nil - } - for _, r := range All() { - if r.Removed != "" { - continue // older firmware only: the current tree has dropped it - } - src, err := read(r.File) - if err != nil { - problems = append(problems, fmt.Sprintf("%s: %v", r.ID, err)) - continue - } - if !strings.Contains(src, `"`+r.Format+`"`) && r.Pending == "" { - problems = append(problems, fmt.Sprintf("%s: %q is no longer in %s", r.ID, r.Format, r.File)) - } - } - src, err := read(TierFile()) - if err != nil { - return append(problems, fmt.Sprintf("tiers: %v", err)) - } - tiers := Tiers() - cmds := make([]string, 0, len(tiers)) - for c := range tiers { - cmds = append(cmds, c) - } - sort.Strings(cmds) - for _, c := range cmds { - re := regexp.MustCompile(`\{\s*"` + regexp.QuoteMeta(c) + `"\s*,\s*CMD_TIER_` + tiers[c] + `\s*\}`) - if !re.MatchString(src) { - problems = append(problems, fmt.Sprintf("tier: %s is no longer %s in %s", c, tiers[c], TierFile())) - } - } - return problems -} diff --git a/internal/fwrefusals/fwrefusals_test.go b/internal/fwrefusals/fwrefusals_test.go deleted file mode 100644 index 3bff906..0000000 --- a/internal/fwrefusals/fwrefusals_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package fwrefusals - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -func TestEveryExampleMatchesItsFormat(t *testing.T) { - seen := map[string]bool{} - for _, r := range All() { - if seen[r.ID] { - t.Errorf("duplicate id %s", r.ID) - } - seen[r.ID] = true - if r.File == "" || r.Format == "" || r.Example == "" || r.Kind == "" { - t.Errorf("%s: incomplete entry %+v", r.ID, r) - } - if !r.Pattern().MatchString(r.Example) { - t.Errorf("%s: example %q does not match format %q (%s)", r.ID, r.Example, r.Format, r.Pattern()) - } - } - if len(Tiers()) == 0 || TierFile() == "" { - t.Fatal("no tiers pinned") - } -} - -// The firmware still has every pinned text. CI checks benchpod-firmware out and points -// BENCHPOD_FIRMWARE_DIR at it; locally a sibling checkout is used. A failure means the firmware's -// wording changed: update refusals.json and whatever in the CLI matches on that text. -func TestFirmwareStillSendsThePinnedTexts(t *testing.T) { - dir := FirmwareDir() - if dir == "" { - if os.Getenv("CI") != "" { - t.Fatal("no benchpod-firmware checkout: set BENCHPOD_FIRMWARE_DIR") - } - t.Skip("no benchpod-firmware checkout next to this repository (set BENCHPOD_FIRMWARE_DIR)") - } - for _, p := range Check(dir) { - t.Error(p) - } -} - -func TestCheckReportsAChangedText(t *testing.T) { - dir := t.TempDir() - write := func(rel, body string) { - path := filepath.Join(dir, rel) - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { - t.Fatal(err) - } - if err := os.WriteFile(path, []byte(body), 0o644); err != nil { - t.Fatal(err) - } - } - // A firmware tree with every text as pinned, then one reworded. - files := map[string]*strings.Builder{} - for _, r := range All() { - if files[r.File] == nil { - files[r.File] = &strings.Builder{} - } - files[r.File].WriteString(`send_error(c, "` + r.Format + "\");\n") - } - tiers := &strings.Builder{} - for c, tier := range Tiers() { - tiers.WriteString(`{ "` + c + `", CMD_TIER_` + tier + " },\n") - } - files[TierFile()] = tiers - for f, b := range files { - write(f, b.String()) - } - if p := Check(dir); len(p) != 0 { - t.Fatalf("a matching tree reported %v", p) - } - lockedFile := "" - for _, r := range All() { - if r.ID == "lan_locked" { - lockedFile = r.File - } - } - write(lockedFile, strings.Replace(files[lockedFile].String(), "needs the cloud", "requires the cloud", 1)) - write(TierFile(), strings.Replace(tiers.String(), `"ota_begin", CMD_TIER_T3`, `"ota_begin", CMD_TIER_T2`, 1)) - p := Check(dir) - if len(p) != 2 || !strings.Contains(p[0], "lan_locked") || !strings.Contains(p[1], "ota_begin") { - t.Fatalf("problems = %v", p) - } -} - -func TestAdjacentLiteralsAreJoined(t *testing.T) { - src := "return x ? \"busy: a capture, upload or update is using the PSRAM bus; \"\n" + - " \"try again when it ends\" : NULL;\n" - if got := adjacent.ReplaceAllString(src, ""); !strings.Contains(got, `"`+ - "busy: a capture, upload or update is using the PSRAM bus; try again when it ends"+`"`) { - t.Fatalf("not joined: %q", got) - } -} diff --git a/internal/fwrefusals/refusals.json b/internal/fwrefusals/refusals.json deleted file mode 100644 index 7cc6c16..0000000 --- a/internal/fwrefusals/refusals.json +++ /dev/null @@ -1,126 +0,0 @@ -{ - "_comment": "Firmware refusal texts the CLI shows or matches on, copied from benchpod-firmware main (897f057; la voltage + pin conflict texts 6e31527). format is the C string literal exactly as it appears in the source (adjacent literals joined, escapes kept); example is one rendering of it. The CLI tests check every example against its format, that the CLI shows or classifies it as intended, and, when a benchpod-firmware checkout is available (CI checks it out; locally the sibling directory), that each format is still in its source file, so a firmware wording change fails here. tiers pins cmd_tier.c entries for commands the CLI sends.", - "refusals": [ - {"id": "lan_locked_v39", "file": "stm32h563/src/cmd_gate.c", "kind": "json", - "format": "locked: %s needs the cloud or USB", - "example": "locked: cloud_set needs the cloud or USB"}, - {"id": "lan_locked", "file": "stm32h563/src/cmd_gate.c", "removed": "3.9.0", "kind": "json", - "format": "locked: %s needs the cloud or the USB console", - "example": "locked: cloud_set needs the cloud or the USB console"}, - {"id": "lease_busy", "file": "stm32h563/src/cmd_gate.c", "kind": "json", - "format": "busy: a cloud job holds this pod (%s, %lu s left)", - "example": "busy: a cloud job holds this pod (ci-run-42, 37 s left)"}, - {"id": "tunnel_forbidden", "file": "stm32h563/src/cmd_gate.c", "kind": "json", - "format": "forbidden: %s needs an organization owner or admin", - "example": "forbidden: ota_begin needs an organization owner or admin"}, - {"id": "heavy_busy", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "busy", - "example": "busy"}, - {"id": "psram_bus_busy", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "busy: a capture, upload or update is using the PSRAM bus; try again when it ends", - "example": "busy: a capture, upload or update is using the PSRAM bus; try again when it ends"}, - {"id": "swd_busy_spi_session", "file": "stm32h563/src/command_handler_dap.c", "kind": "json", - "format": "swd busy: an SPI session is using the engine ({\\\"cmd\\\":\\\"spi_stop\\\"})", - "example": "swd busy: an SPI session is using the engine ({\"cmd\":\"spi_stop\"})"}, - {"id": "swd_busy", "file": "stm32h563/src/command_handler_dap.c", "kind": "json", - "format": "swd busy", - "example": "swd busy"}, - {"id": "uart_busy", "file": "stm32h563/src/command_handler_uart.c", "kind": "json", - "format": "uart busy", - "example": "uart busy"}, - {"id": "la_voltage_unset", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "la voltage not set; set la_mv (1800 or 3300) in the active wiring profile, or call la_voltage (mv 1800 or 3300) first", - "example": "la voltage not set; set la_mv (1800 or 3300) in the active wiring profile, or call la_voltage (mv 1800 or 3300) first"}, - {"id": "la_voltage_unset_v3109", "file": "stm32h563/src/command_handler.c", "removed": "3.10.10", "kind": "json", - "format": "la voltage not set; set it with la_voltage (mv 1800 or 3300) first", - "example": "la voltage not set; set it with la_voltage (mv 1800 or 3300) first"}, - {"id": "pin_conflict", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "pin conflict: LA%u is in use by %s; %s", - "example": "pin conflict: LA4 is in use by gpio; release it with {\"cmd\":\"gpio\",\"la\":4,\"mode\":\"off\"}"}, - {"id": "pin_hint_gpio", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "release it with {\\\"cmd\\\":\\\"gpio\\\",\\\"la\\\":%u,\\\"mode\\\":\\\"off\\\"}", - "example": "release it with {\"cmd\":\"gpio\",\"la\":4,\"mode\":\"off\"}"}, - {"id": "pin_hint_uart", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "stop the uart proxy first", - "example": "stop the uart proxy first"}, - {"id": "pin_hint_swd", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "end the SWD session first", - "example": "end the SWD session first"}, - {"id": "pin_hint_sensor", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "stop the sensor emulation first ({\\\"cmd\\\":\\\"sensor_stop\\\",\\\"instance\\\":\\\"%s\\\"})", - "example": "stop the sensor emulation first ({\"cmd\":\"sensor_stop\",\"instance\":\"env\"})"}, - {"id": "pin_hint_step", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "wait for the step train to finish", - "example": "wait for the step train to finish"}, - {"id": "pin_hint_spi", "file": "stm32h563/src/la_pins.c", "kind": "json", - "format": "stop the SPI session first ({\\\"cmd\\\":\\\"spi_stop\\\"})", - "example": "stop the SPI session first ({\"cmd\":\"spi_stop\"})"}, - {"id": "unknown_cmd", "file": "stm32h563/src/command_handler.c", "kind": "json", - "format": "unknown cmd", - "example": "unknown cmd"}, - {"id": "spi_busy", "file": "stm32h563/src/command_handler_spi.c", "kind": "json", - "format": "spi busy: send spi_stop first", - "example": "spi busy: send spi_stop first"}, - {"id": "swd_or_spi_busy", "file": "stm32h563/src/command_handler_spi.c", "kind": "json", - "format": "swd or spi busy: end the SWD session first", - "example": "swd or spi busy: end the SWD session first"}, - {"id": "unknown_target", "file": "stm32h563/src/command_handler_ota.c", "kind": "json", - "format": "unknown target", - "example": "unknown target"}, - {"id": "ota_owner_busy", "file": "stm32h563/src/ota.c", "kind": "json", - "format": "busy: %s update from %s is in progress", - "example": "busy: firmware update from the cloud is in progress"}, - {"id": "sig_policy_unknown", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "sig_policy: unknown policy", - "example": "sig_policy: unknown policy"}, - {"id": "sig_policy_from_lan", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "sig_policy: change it from the cloud or the USB console", - "example": "sig_policy: change it from the cloud or the USB console"}, - {"id": "sig_policy_loosen", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "sig_policy: only the USB console can loosen the policy (now %s)", - "example": "sig_policy: only the USB console can loosen the policy (now required)"}, - {"id": "lan_policy_unknown", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "lan_policy: unknown policy", - "example": "lan_policy: unknown policy"}, - {"id": "lan_policy_from_lan", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "lan_policy: change it from the cloud or the USB console", - "example": "lan_policy: change it from the cloud or the USB console"}, - {"id": "usb_network_not_device", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "usb_network: change it on the device (the USB console, or over the USB link)", - "example": "usb_network: change it on the device (the USB console, or over the USB link)"}, - {"id": "cloud_ca_from_lan_v39", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "%s: change it from the cloud or over USB", - "example": "cloud_ca: change it from the cloud or over USB"}, - {"id": "cloud_ca_from_lan", "file": "stm32h563/src/pod_policy.c", "removed": "3.9.0", "kind": "json", - "format": "%s: change it from the cloud or the USB console", - "example": "cloud_ca: change it from the cloud or the USB console"}, - {"id": "cloud_proxy_from_lan_v39", "file": "stm32h563/src/pod_policy.c", "kind": "json", - "format": "%s: change it from the cloud or over USB", - "example": "cloud_proxy: change it from the cloud or over USB"}, - {"id": "cloud_proxy_from_lan", "file": "stm32h563/src/pod_policy.c", "removed": "3.9.0", "kind": "json", - "format": "%s: change it from the cloud or the USB console", - "example": "cloud_proxy: change it from the cloud or the USB console"}, - {"id": "console_unknown_command", "file": "stm32h563/src/console.c", "kind": "console", - "format": " unknown command '%s' (try 'help')\\r\\n", - "example": " unknown command 'cloud-ca' (try 'help')"}, - {"id": "console_upload_busy", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-data busy\\r\\n> ", - "example": "upload-data busy"}, - {"id": "console_upload_retry_crc", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-data retry crc\\r\\n> ", - "example": "upload-data retry crc"}, - {"id": "console_upload_ok", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-data ok %lu\\r\\n> ", - "example": "upload-data ok 4096"}, - {"id": "console_upload_end_busy", "file": "stm32h563/src/console.c", "removed": "3.9.0", "kind": "console_upload", - "format": "upload-end error %s\\r\\n", - "example": "upload-end error busy: firmware update from the cloud is in progress"} - ], - "tiers": { - "_file": "stm32h563/src/cmd_tier.c", - "cloud_set": "T2", "cloud_clear": "T2", - "ota_begin": "T3", "ota_data": "T3", "ota_end": "T3", "ota_commit": "T3", "ota_abort": "T3", - "cloud_ca": "T0", "cloud_proxy": "T0", "sig_policy": "T0", "lan_policy": "T0", - "status": "T0", "dap_start": "T1", "spi_start": "T1", "spi_flash": "T1" - } -} diff --git a/internal/serialconsole/refusals_test.go b/internal/serialconsole/refusals_test.go deleted file mode 100644 index a11a0f9..0000000 --- a/internal/serialconsole/refusals_test.go +++ /dev/null @@ -1,27 +0,0 @@ -package serialconsole - -import ( - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" -) - -// The console upload replies the CLI waits for start with a word it recognizes, and the console's -// unknown-command line still says "unknown command" (how the CLI spots old firmware). -func TestConsoleRepliesTheCLIRecognizes(t *testing.T) { - for _, r := range fwrefusals.All() { - switch r.Kind { - case "console_upload": - cmd, rest, _ := strings.Cut(r.Example, " ") - word := strings.Fields(rest)[0] - if !strings.HasPrefix(cmd, "upload-") || !uploadReplyWords[word] { - t.Errorf("%s: %q: reply word %q is not one awaitReply accepts", r.ID, r.Example, word) - } - case "console": - if !strings.Contains(r.Example, "unknown command") { - t.Errorf("%s: %q no longer says unknown command", r.ID, r.Example) - } - } - } -} diff --git a/internal/spiflash/refusals_internal_test.go b/internal/spiflash/refusals_internal_test.go index 7f640b5..2f99dff 100644 --- a/internal/spiflash/refusals_internal_test.go +++ b/internal/spiflash/refusals_internal_test.go @@ -2,25 +2,28 @@ package spiflash import ( "errors" + "fmt" "testing" - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) -// isSPIBusy decides whether a failed spi_start was another session's: it must match the -// firmware's SPI refusals and nothing else. -func TestIsSPIBusyMatchesTheFirmwareTexts(t *testing.T) { - for id, want := range map[string]bool{ - "spi_busy": true, - "swd_or_spi_busy": true, - "swd_busy_spi_session": false, - "swd_busy": false, - "heavy_busy": false, - "psram_bus_busy": false, - "lease_busy": false, +// isSPIBusy decides whether a failed spi_start was another session's: by its code only. +func TestIsSPIBusyByCode(t *testing.T) { + for code, want := range map[string]bool{ + "BP0004": true, // spi_session_open + "BP0005": true, // bus_engine_busy + "BP0050": false, // swd_session_open + "BP0047": false, // pod_busy + "BP0025": false, // lease_busy + "": false, } { - if got := isSPIBusy(errors.New(fwrefusals.Example(id))); got != want { - t.Errorf("isSPIBusy(%s: %q) = %v, want %v", id, fwrefusals.Example(id), got, want) + err := fmt.Errorf("spi_start: %w", tcpclient.RefusalError("spi busy", code, nil)) + if got := isSPIBusy(err); got != want { + t.Errorf("isSPIBusy(%q) = %v, want %v", code, got, want) } } + if isSPIBusy(errors.New("spi busy: send spi_stop first")) { + t.Error("a text without a code taken for busy") + } } diff --git a/internal/spiflash/spiflash.go b/internal/spiflash/spiflash.go index 5f88a6c..57449ad 100644 --- a/internal/spiflash/spiflash.go +++ b/internal/spiflash/spiflash.go @@ -17,6 +17,7 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/features" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // Firmware limits per command. @@ -287,9 +288,10 @@ func Session(ctx context.Context, main, cleanup Commander, cfg Config, nreset bo return fn(ctx, p, s) } +// isSPIBusy is spi_start refused because another session has the SPI master (BP0004) or the bus +// engine (BP0005). func isSPIBusy(err error) bool { - m := err.Error() - return strings.Contains(m, "spi busy") || strings.Contains(m, "swd or spi busy") + return tcpclient.HasCode(err, "BP0004") || tcpclient.HasCode(err, "BP0005") } // HasCap reports whether the pod whose status reply this is has capability name: from the diff --git a/internal/spiflash/spiflash_test.go b/internal/spiflash/spiflash_test.go index 22205cd..82bba95 100644 --- a/internal/spiflash/spiflash_test.go +++ b/internal/spiflash/spiflash_test.go @@ -12,6 +12,7 @@ import ( "github.com/embeddedci-com/benchpod-cli/internal/spiflash" "github.com/embeddedci-com/benchpod-cli/internal/spiflash/spiflashtest" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) func randBytes(n int) []byte { @@ -202,7 +203,7 @@ func TestSessionStartFailureReleasesReset(t *testing.T) { t.Fatal("fn ran without a session") return nil }) - if err == nil || !strings.Contains(err.Error(), "spi busy") { + if !tcpclient.HasCode(err, "BP0004") { t.Fatalf("got %v", err) } // Busy means another session owns the engine: no spi_stop, but reset released. diff --git a/internal/spiflash/spiflashtest/fake.go b/internal/spiflash/spiflashtest/fake.go index bd1a298..68883f4 100644 --- a/internal/spiflash/spiflashtest/fake.go +++ b/internal/spiflash/spiflashtest/fake.go @@ -15,6 +15,7 @@ import ( "testing" "github.com/embeddedci-com/benchpod-cli/internal/spiflash" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // FakePod models the firmware's SPI commands over an in-memory 16 MB NOR part: @@ -70,13 +71,13 @@ func (f *FakePod) Command(ctx context.Context, req map[string]any) (json.RawMess switch r["cmd"] { case "status": - return ok(map[string]any{"caps": f.Caps}) + return ok(map[string]any{"caps": f.Caps, "api": 2, "min_client_api": 2}) case "nrst": f.NRST = r["assert"].(bool) return ok(map[string]any{"asserted": f.NRST}) case "spi_start": if f.Busy || f.Armed { - return nil, errors.New("spi busy: send spi_stop first") + return nil, tcpclient.RefusalError("", "BP0004", nil) } f.Armed = true return ok(map[string]any{"sck": num("sck"), "mosi": num("mosi"), "miso": num("miso"), "cs": num("cs"), "hz": 1000000, "mode": num("mode")}) @@ -133,7 +134,7 @@ func (f *FakePod) Command(ctx context.Context, req map[string]any) (json.RawMess return ok(map[string]any{"addr": addr, "len": len(d), "verified": verify, "ms": 1}) } } - return nil, errors.New("unknown cmd") + return nil, tcpclient.RefusalError("", "BP0002", nil) } // Ops returns the command log. @@ -173,6 +174,9 @@ func Serve(t *testing.T, f *FakePod) string { data, err := f.Command(context.Background(), req) if err != nil { reply = map[string]any{"status": "error", "message": err.Error()} + if pe, ok := tcpclient.AsPodError(err); ok && pe.Code != "" { + reply = map[string]any{"status": "error", "code": pe.Code} + } } else { reply = map[string]any{"status": "ok", "data": data} } diff --git a/internal/tcpclient/client.go b/internal/tcpclient/client.go index 7c4a894..f096854 100644 --- a/internal/tcpclient/client.go +++ b/internal/tcpclient/client.go @@ -214,6 +214,9 @@ func (c *Client) dialAndSend(ctx context.Context, req map[string]any) (net.Conn, return nil, nil, fmt.Errorf("pod address is empty; run `benchpod set-connection ` first") } + if err := c.probePodAPI(ctx, req); err != nil { + return nil, nil, err + } budget := c.DialTimeout if budget <= 0 { budget = DefaultDialTimeout diff --git a/internal/tcpclient/clientapi.go b/internal/tcpclient/clientapi.go index 61d4706..ea70cf9 100644 --- a/internal/tcpclient/clientapi.go +++ b/internal/tcpclient/clientapi.go @@ -1,9 +1,12 @@ package tcpclient import ( + "context" "encoding/json" + "errors" "fmt" "strings" + "sync" "sync/atomic" ) @@ -13,11 +16,21 @@ import ( // status (benchpod-firmware docs/API.md, Client compatibility). The level goes up only for a change // an older client would misread, so this CLI stops when a pod announces a level above ClientAPI, // and every JSON command says which level it was built for ("client_api") and who sent it -// ("client"). Older firmware ignores both fields and announces no api, which counts as 1. +// ("client"). Firmware up to 3.10.13 announces no api, which counts as 1. +// +// This CLI speaks level 2 (firmware 4.0) only: a pod below MinPodAPI is refused too (it would +// misread the 4.0 names and units), except by the commands that look at or update the firmware +// (SetAllowAnyPodAPI), so such a pod can still be upgraded. // ClientAPI is the highest pod API level this CLI handles: the "api" of the features.json it embeds // (a test checks that). -const ClientAPI = 1 +const ClientAPI = 2 + +// MinPodAPI is the lowest pod API level this CLI drives: firmware 4.0. +const MinPodAPI = 2 + +// FirmwareUpdatePath is how to bring a pod up to firmware 4.0. +const FirmwareUpdatePath = "this pod needs firmware 4.0: benchpod flash-self" // CodeClientTooOld is the pod refusing a client below its min_client_api. const CodeClientTooOld = "BP0030" @@ -133,9 +146,27 @@ func IsStatus(req map[string]any) bool { return cmd == "status" } +// FirmwareTooOldError is a pod whose firmware is older than this CLI drives: it announces an API +// level below MinPodAPI (firmware 3.x announces none: level 1). Only the firmware commands +// (status, flash-self, install-blobs, dfu, bootsel, discover, identity) still run against it. +type FirmwareTooOldError struct { + Firmware string // the pod's firmware version, "" when not known + PodAPI int // the pod's client API level +} + +func (e *FirmwareTooOldError) Error() string { + fw := "this pod's firmware" + if e.Firmware != "" { + fw += " " + e.Firmware + } + return fmt.Sprintf("%s is too old for this benchpod CLI (pod API %d, this CLI needs %d): %s", + fw, e.PodAPI, MinPodAPI, FirmwareUpdatePath) +} + // CheckPodAPI checks a status reply's API level: an *UpdateRequiredError when the pod announces -// an "api" (or a "min_client_api") above ClientAPI, nil otherwise. A reply without "api" -// (firmware 3.10.13 and older) is level 1; a reply that does not parse is left to its reader. +// an "api" (or a "min_client_api") above ClientAPI, a *FirmwareTooOldError when it is below +// MinPodAPI, nil otherwise. A reply without "api" (firmware 3.10.13 and older) is level 1; a +// reply that does not parse is left to its reader. func CheckPodAPI(statusReply json.RawMessage) error { var st struct { Version string `json:"version"` @@ -149,29 +180,96 @@ func CheckPodAPI(statusReply json.RawMessage) error { if st.API != nil { api = *st.API } + if api < MinPodAPI { + return &FirmwareTooOldError{Firmware: st.Version, PodAPI: api} + } if api <= ClientAPI && st.MinClientAPI <= ClientAPI { return nil } return &UpdateRequiredError{Firmware: st.Version, PodAPI: max(api, st.MinClientAPI), MinClientAPI: st.MinClientAPI} } -// newerPodAllowed turns the status check off for the commands that must work against firmware -// this CLI is too old for: showing the status, updating or rolling back the firmware and blobs, -// DFU, discovery. Set before each command runs (SetAllowNewerPod). -var newerPodAllowed atomic.Bool +// anyPodAPIAllowed turns the API check off for the commands that must work against firmware of +// any level: showing the status, updating or rolling back the firmware and blobs, DFU, discovery, +// the identity. Set before each command runs (SetAllowAnyPodAPI). +var anyPodAPIAllowed atomic.Bool -// SetAllowNewerPod lets status replies through (true) even when the pod's API level is above -// ClientAPI, or checks them again (false). -func SetAllowNewerPod(allow bool) { newerPodAllowed.Store(allow) } +// SetAllowAnyPodAPI lets status replies through (true) whatever the pod's API level, and skips +// the probe before other commands; false checks them again. +func SetAllowAnyPodAPI(allow bool) { anyPodAPIAllowed.Store(allow) } -// NewerPodAllowed says whether SetAllowNewerPod(true) is in effect. -func NewerPodAllowed() bool { return newerPodAllowed.Load() } +// AnyPodAPIAllowed says whether SetAllowAnyPodAPI(true) is in effect. +func AnyPodAPIAllowed() bool { return anyPodAPIAllowed.Load() } // checkReply is CheckPodAPI on a status command's reply, nil for any other command and when -// SetAllowNewerPod(true) is in effect. +// SetAllowAnyPodAPI(true) is in effect. func checkReply(req map[string]any, data json.RawMessage) error { - if !IsStatus(req) || NewerPodAllowed() { + if !IsStatus(req) || AnyPodAPIAllowed() { return nil } return CheckPodAPI(data) } + +// ── the API probe ─────────────────────────────────────────────────────────── +// +// Firmware 3.x ignores client_api, so it would run a 4.0 command with names and units it reads +// differently. Before the first other command to an address, the client reads status once and +// checks the level (cached for the process). The CLI turns the probe on (SetAPIProbe); a status +// command is checked on its own reply. + +var apiProbeOn atomic.Bool + +// SetAPIProbe turns the status probe before a pod's first command on or off (the default). +func SetAPIProbe(on bool) { apiProbeOn.Store(on) } + +// APIProbe says whether the probe is on, and the command at hand takes only a pod of this +// CLI's level (a transport other than this package's, embeddedci.com, probes when it is). +func APIProbe(req map[string]any) bool { + return apiProbeOn.Load() && !AnyPodAPIAllowed() && !IsStatus(req) +} + +var ( + probeMu sync.Mutex + probeRes = map[string]error{} // address -> the probe's verdict (nil: the level is fine) +) + +// ResetAPIProbe forgets every probe's verdict (tests, and a pod that was updated meanwhile). +func ResetAPIProbe() { + probeMu.Lock() + defer probeMu.Unlock() + probeRes = map[string]error{} +} + +// probePodAPI checks the pod's API level before req, once per address: nil when the level is +// fine, the probe is off, req is status itself or the command takes any level. +func (c *Client) probePodAPI(ctx context.Context, req map[string]any) error { + if !APIProbe(req) { + return nil + } + addr := strings.TrimSpace(c.Addr) + probeMu.Lock() + verdict, done := probeRes[addr] + probeMu.Unlock() + if done { + return verdict + } + probe := &Client{Addr: c.Addr, DialTimeout: c.DialTimeout, TLS: c.TLS, NoLeaseJoin: true} + data, err := probe.Command(ctx, map[string]any{"cmd": "status", "caps": false}) + var upd *UpdateRequiredError + var old *FirmwareTooOldError + switch { + case errors.As(err, &upd) || errors.As(err, &old): + verdict = err + case err != nil: + if _, refused := AsPodError(err); refused { + return nil // status always runs; a refusal here is the command's to report + } + return err // the pod is not reachable: the command would fail the same way + default: + verdict = CheckPodAPI(data) + } + probeMu.Lock() + probeRes[addr] = verdict + probeMu.Unlock() + return verdict +} diff --git a/internal/tcpclient/clientapi_test.go b/internal/tcpclient/clientapi_test.go index cca7778..f1c315c 100644 --- a/internal/tcpclient/clientapi_test.go +++ b/internal/tcpclient/clientapi_test.go @@ -146,37 +146,44 @@ func TestEveryRequestBuilderCarriesTheClientFields(t *testing.T) { func TestCheckPodAPI(t *testing.T) { for _, c := range []struct { - status string - bad bool + status string + newer, old bool }{ - {`{"version":"3.10.13"}`, false}, // no api: level 1 - {`{"version":"3.10.14","api":1,"min_client_api":0}`, false}, - {`{"version":"3.11.0","api":2,"min_client_api":0}`, true}, - {`{"version":"3.11.0","api":2,"min_client_api":2}`, true}, - {`not json`, false}, + {`{"version":"3.10.13"}`, false, true}, // no api: level 1 + {`{"version":"3.10.14","api":1,"min_client_api":0}`, false, true}, + {`{"version":"4.0.0","api":2,"min_client_api":2}`, false, false}, + {`{"version":"5.0.0","api":3,"min_client_api":0}`, true, false}, + {`{"version":"5.0.0","api":3,"min_client_api":3}`, true, false}, + {`not json`, false, false}, } { err := CheckPodAPI(json.RawMessage(c.status)) var upd *UpdateRequiredError - if got := errors.As(err, &upd); got != c.bad { + var old *FirmwareTooOldError + if errors.As(err, &upd) != c.newer || errors.As(err, &old) != c.old { t.Errorf("%s: err = %v", c.status, err) } } - err := CheckPodAPI(json.RawMessage(`{"version":"3.11.0","api":2}`)) - want := "this pod's firmware 3.11.0 needs a newer benchpod CLI (pod API 2, this CLI handles 1): " + UpdatePath + err := CheckPodAPI(json.RawMessage(`{"version":"5.0.0","api":3}`)) + want := "this pod's firmware 5.0.0 needs a newer benchpod CLI (pod API 3, this CLI handles 2): " + UpdatePath + if err == nil || err.Error() != want { + t.Fatalf("err = %v, want %q", err, want) + } + err = CheckPodAPI(json.RawMessage(`{"version":"3.10.13"}`)) + want = "this pod's firmware 3.10.13 is too old for this benchpod CLI (pod API 1, this CLI needs 2): this pod needs firmware 4.0: benchpod flash-self" if err == nil || err.Error() != want { t.Fatalf("err = %v, want %q", err, want) } } // Reading status checks the pod's API level, on a connection and in a session; other commands -// do not. +// do not unless the probe is on. func TestStatusOfANewerPodStops(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - addr, _ := requestServer(t, `{"status":"ok","data":{"version":"3.11.0","api":2,"min_client_api":0}}`) + addr, _ := requestServer(t, `{"status":"ok","data":{"version":"5.0.0","api":3,"min_client_api":0}}`) c := &Client{Addr: addr, TLS: TLSOff} var upd *UpdateRequiredError - if _, err := c.Command(ctx, map[string]any{"cmd": "status", "caps": false}); !errors.As(err, &upd) || upd.PodAPI != 2 || upd.Firmware != "3.11.0" { + if _, err := c.Command(ctx, map[string]any{"cmd": "status", "caps": false}); !errors.As(err, &upd) || upd.PodAPI != 3 || upd.Firmware != "5.0.0" { t.Fatalf("status: err = %v", err) } if _, err := c.Command(ctx, map[string]any{"cmd": "ping"}); err != nil { @@ -190,12 +197,59 @@ func TestStatusOfANewerPodStops(t *testing.T) { if _, err := s.Command(ctx, map[string]any{"cmd": "status"}); !errors.As(err, &upd) { t.Fatalf("session status: err = %v", err) } + addr, _ = requestServer(t, `{"status":"ok","data":{"api":2,"min_client_api":2}}`) + if _, err := (&Client{Addr: addr, TLS: TLSOff}).Command(ctx, map[string]any{"cmd": "status"}); err != nil { + t.Fatalf("api 2: %v", err) + } + // The firmware commands see any level. + SetAllowAnyPodAPI(true) + defer SetAllowAnyPodAPI(false) + addr, _ = requestServer(t, `{"status":"ok","data":{"version":"3.10.13"}}`) + if _, err := (&Client{Addr: addr, TLS: TLSOff}).Command(ctx, map[string]any{"cmd": "status"}); err != nil { + t.Fatalf("allowed: %v", err) + } +} - for _, ok := range []string{`{"status":"ok","data":{"version":"3.10.13"}}`, `{"status":"ok","data":{"api":1}}`} { - addr, _ := requestServer(t, ok) - if _, err := (&Client{Addr: addr, TLS: TLSOff}).Command(ctx, map[string]any{"cmd": "status"}); err != nil { - t.Fatalf("%s: %v", ok, err) - } +// With the probe on, the first command to an address reads status first (once), and a 3.x pod +// stops it; the firmware commands skip the probe. +func TestAPIProbe(t *testing.T) { + SetAPIProbe(true) + defer func() { SetAPIProbe(false); ResetAPIProbe() }() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + addr, got := requestServer(t, `{"status":"ok","data":{"version":"3.10.13"}}`) + c := &Client{Addr: addr, TLS: TLSOff} + var old *FirmwareTooOldError + if _, err := c.Command(ctx, map[string]any{"cmd": "la_pins"}); !errors.As(err, &old) || old.PodAPI != 1 { + t.Fatalf("err = %v", err) + } + if req := <-got; req["cmd"] != "status" { + t.Fatalf("probe sent %v", req) + } + // Cached: the second command does not ask again. + if _, err := c.Samples(ctx, map[string]any{"cmd": "capture"}); !errors.As(err, &old) { + t.Fatalf("err = %v", err) + } + select { + case req := <-got: + t.Fatalf("asked again: %v", req) + default: + } + SetAllowAnyPodAPI(true) + if _, err := c.Command(ctx, map[string]any{"cmd": "ota_status"}); err != nil { + t.Fatalf("firmware command: %v", err) + } + SetAllowAnyPodAPI(false) + if req := <-got; req["cmd"] != "ota_status" { + t.Fatalf("sent %v", req) + } + + addr, got = requestServer(t, `{"status":"ok","data":{"version":"4.0.0","api":2,"min_client_api":2}}`) + if _, err := (&Client{Addr: addr, TLS: TLSOff}).Command(ctx, map[string]any{"cmd": "la_pins"}); err != nil { + t.Fatal(err) + } + if a, b := <-got, <-got; a["cmd"] != "status" || b["cmd"] != "la_pins" { + t.Fatalf("sent %v then %v", a, b) } } @@ -213,7 +267,7 @@ func TestClientTooOldRefusal(t *testing.T) { if _, ok := AsPodError(err); ok { t.Fatal("BP0030 is not a *PodError") } - want := "this pod's firmware needs a newer benchpod CLI (pod API 2, this CLI handles 1): " + UpdatePath + want := "this pod's firmware needs a newer benchpod CLI (pod API 2, this CLI handles 2): " + UpdatePath if err.Error() != want { t.Fatalf("err = %q, want %q", err, want) } diff --git a/internal/tcpclient/codes_test.go b/internal/tcpclient/codes_test.go index 6fd848a..4182552 100644 --- a/internal/tcpclient/codes_test.go +++ b/internal/tcpclient/codes_test.go @@ -1,6 +1,7 @@ package tcpclient import ( + "strings" "testing" "github.com/embeddedci-com/benchpod-cli/internal/errcatalog" @@ -20,39 +21,29 @@ func TestCodeKindsCoverTheCatalog(t *testing.T) { } } -// A coded refusal is classified by its code, whatever its text. +// A refusal is classified by its code only; its text is never read. func TestPodErrorKindByCode(t *testing.T) { for _, c := range []struct { code, reason string want RefusalKind }{ - {"BP0001", "la voltage not set", Refused}, - {"BP0002", "unknown cmd", Refused}, + {"BP0001", "", Refused}, + {"BP0002", "", FirmwareTooOld}, {"BP0003", "", Busy}, - {"BP0004", "", Busy}, - {"BP0005", "swd or spi busy: ...", Busy}, - {"BP0016", "pod returned an error", Busy}, - {"BP0025", "busy: a cloud job holds this pod (ci, 3 s left)", Busy}, - {"BP0025", "pod returned an error", Busy}, // a build without texts - {"BP0026", "lease lost", Refused}, - {"BP0027", "", Refused}, - {"BP0017", "busy", Refused}, // the code wins over the text + {"BP0005", "", Busy}, + {"BP0016", "", Busy}, + {"BP0017", "busy", FirmwareTooOld}, // the code wins over the text + {"BP0025", "", Busy}, + {"BP0026", "", Refused}, + {"BP0040", "", Locked}, + {"BP0045", "", Forbidden}, + {"BP0047", "", Busy}, + {"BP0074", "", Refused}, {"bp0003", "", Busy}, - } { - if got := (&PodError{Code: c.code, Reason: c.reason}).Kind(); got != c.want { - t.Errorf("%s %q: kind %v, want %v", c.code, c.reason, got, c.want) - } - } - // Without a code, or with one this table does not know (newer firmware), the text decides. - for _, c := range []struct { - code, reason string - want RefusalKind - }{ - {"", "locked: x needs the cloud or USB", Locked}, - {"", "forbidden: x needs an organization owner or admin", Forbidden}, - {"", "uart busy", Busy}, - {"", "unknown cmd", Refused}, - {"BP9999", "busy", Busy}, + // Without a code, or with one this table does not know (newer firmware): Refused. + {"", "locked: x needs the cloud or USB", Refused}, + {"", "uart busy", Refused}, + {"BP9999", "busy", Refused}, } { if got := (&PodError{Code: c.code, Reason: c.reason}).Kind(); got != c.want { t.Errorf("%s %q: kind %v, want %v", c.code, c.reason, got, c.want) @@ -65,14 +56,36 @@ func TestIsUnknownCommand(t *testing.T) { pe *PodError want bool }{ - {&PodError{Code: "BP0002", Reason: "pod returned an error"}, true}, - {&PodError{Reason: "unknown cmd"}, true}, - {&PodError{Reason: "unknown command 'x'"}, true}, + {&PodError{Code: "BP0002"}, true}, + {&PodError{Reason: "unknown cmd"}, false}, // a text is never matched {&PodError{Code: "BP0006", Reason: "missing la"}, false}, - {&PodError{Reason: "uart busy"}, false}, } { if got := IsUnknownCommand(c.pe); got != c.want { t.Errorf("%+v: got %v", c.pe, got) } } } + +// A coded reply without a message is shown from the catalog, its args filled in. +func TestCodedReplyRendersFromTheCatalog(t *testing.T) { + err := RefusalError("", "BP0031", map[string]any{"la": 4.0, "owner": "gpio"}) + pe, ok := AsPodError(err) + if !ok || pe.Reason != "LA4 is in use by gpio" || pe.Code != "BP0031" { + t.Fatalf("pe = %+v", pe) + } + // Over the cloud channel the message is the code itself. + pe, _ = AsPodError(RefusalError("BP0047", "BP0047", nil)) + if !strings.HasPrefix(pe.Reason, "The pod is running another long command") { + t.Fatalf("cloud: %q", pe.Reason) + } + // A code this catalog does not know shows as the code. + pe, _ = AsPodError(RefusalError("", "BP9999", nil)) + if pe.Reason != "BP9999" { + t.Fatalf("unknown: %q", pe.Reason) + } + // A refusal without a code keeps the pod's text. + pe, _ = AsPodError(RefusalError("unknown waveform", "", nil)) + if pe.Reason != "unknown waveform" { + t.Fatalf("uncoded: %q", pe.Reason) + } +} diff --git a/internal/tcpclient/errors.go b/internal/tcpclient/errors.go index 51639dc..c59f29c 100644 --- a/internal/tcpclient/errors.go +++ b/internal/tcpclient/errors.go @@ -4,20 +4,23 @@ import ( "context" "errors" "strings" + + "github.com/embeddedci-com/benchpod-cli/internal/errcatalog" ) // PodError is the pod refusing a command, as opposed to a transport failure: an error reply -// from the JSON API ({"status":"error","message":...}) or, over the USB console, a command's -// " error " line. It is the one error type for a refusal across the CLI; the USB -// console's errors are the same type. +// from the JSON API ({"status":"error","code":"BP0031","args":{...}}, or a refusal without a code, +// {"status":"error","message":"..."}) or, over the USB console, a command's " error " +// line. It is the one error type for a refusal across the CLI. // -// Cmd is the console command a USB refusal answers ("proxy-set", "lan-policy"); it is "" for a -// JSON reply, whose message stands alone. +// Cmd is the console command a USB refusal answers ("lan-policy"); it is "" for a JSON reply. type PodError struct { - Cmd string + Cmd string + // Reason is the text to show: for a coded refusal the catalog's message filled with Args + // (firmware 4.0 sends no message with a code), else the pod's own text. Reason string - // Code and Args: the pod's stable error code (BP0001...) and its values, from firmware that - // sends them (benchpod-firmware errors/catalog.toml); "" / nil otherwise. + // Code and Args: the pod's stable error code (BP0001...) and its values + // (benchpod-firmware errors/catalog.toml); "" / nil for a refusal without a code. Code string Args map[string]any } @@ -29,56 +32,111 @@ func (e *PodError) Error() string { return e.Cmd + ": " + e.Reason } -// RefusalKind classifies a refusal by the firmware's own prefix. +// RefusalKind is what a refusal means for the caller, from its code. The exit code follows it. type RefusalKind int const ( - // Refused is any other refusal: a bad argument, a missing feature, a failed operation. + // Refused is any other refusal: a bad argument, a missing feature, a failed operation, and + // every refusal without a code (the client never reads a refusal's text). Refused RefusalKind = iota - // Locked is the LAN policy refusing a command on the LAN ("locked: ..."). + // Locked is the LAN policy refusing a command on the LAN (BP0040). Locked - // Busy is the pod or one of its engines in use: a cloud lease ("busy: a cloud job holds - // this pod ..."), the PSRAM bus, or an SWD, SPI or UART session ("swd busy", "uart busy"). + // Busy is the pod or one of its engines in use: a lease, the PSRAM bus, another session. Busy - // Forbidden is a cloud tunnel without the role a command needs ("forbidden: ..."). + // Forbidden is a cloud tunnel without the role a command needs (BP0045). Forbidden + // FirmwareTooOld is a pod whose firmware or gateware lacks what the command needs: update + // the pod (BP0002, BP0017, BP0060). + FirmwareTooOld + // ClientTooOld is a pod that needs a newer client (BP0030; it arrives as an + // *UpdateRequiredError). + ClientTooOld ) // codeKinds is the one table from a refusal's stable code (benchpod-firmware errors/catalog.toml, // internal/errcatalog) to its kind, for every code in the catalog; the exit code follows the kind, // and the CLI's hint for a coded refusal is the catalog's fix.cli. A test keeps it in step with -// the catalog. A code the table does not have (newer firmware) falls back to the text. +// the catalog. A code the table does not have (newer firmware) is Refused. var codeKinds = map[string]RefusalKind{ - "BP0001": Refused, // la_voltage_not_set - "BP0002": Refused, // unknown_command: also IsUnknownCommand, for "this firmware lacks it" messages - "BP0003": Busy, // i2c_session_open - "BP0004": Busy, // spi_session_open - "BP0005": Busy, // bus_engine_busy - "BP0006": Refused, // missing_argument - "BP0007": Refused, // wiring_profile_not_found - "BP0008": Refused, // wiring_bad_name - "BP0009": Refused, // wiring_revision_conflict - "BP0010": Refused, // wiring_store_full - "BP0011": Refused, // wiring_profile_too_large - "BP0012": Refused, // wiring_not_json_object - "BP0013": Refused, // wiring_delete_default - "BP0014": Refused, // wiring_upload_out_of_order - "BP0015": Refused, // wiring_storage_failed - "BP0016": Busy, // storage_busy - "BP0017": Refused, // gateware_too_old - "BP0018": Refused, // uart_same_pin - "BP0019": Refused, // uart_half_duplex_two_pins - "BP0020": Refused, // uart_entry_no_reset_pin - "BP0021": Refused, // uart_entry_invalid - "BP0022": Refused, // uart_de_pin - "BP0023": Refused, // la_no_pull - "BP0024": Refused, // la_pull_direction - "BP0025": Busy, // lease_busy: args holder, purpose, left_s - "BP0026": Refused, // lease_lost: args by (benchpod ci handles it: the run is invalid) - "BP0027": Refused, // lease_not_held - "BP0028": Refused, // vref_5v_missing - "BP0029": Refused, // pull_rail_down - "BP0030": Refused, // client_too_old: arrives as an *UpdateRequiredError, not a *PodError (RefusalError) + "BP0001": Refused, // la_voltage_not_set + "BP0002": FirmwareTooOld, // unknown_command + "BP0003": Busy, // i2c_session_open + "BP0004": Busy, // spi_session_open + "BP0005": Busy, // bus_engine_busy + "BP0006": Refused, // missing_argument + "BP0007": Refused, // wiring_profile_not_found + "BP0008": Refused, // wiring_bad_name + "BP0009": Refused, // wiring_revision_conflict + "BP0010": Refused, // wiring_store_full + "BP0011": Refused, // wiring_profile_too_large + "BP0012": Refused, // wiring_not_json_object + "BP0013": Refused, // wiring_delete_default + "BP0014": Refused, // wiring_upload_out_of_order + "BP0015": Refused, // wiring_storage_failed + "BP0016": Busy, // storage_busy + "BP0017": FirmwareTooOld, // gateware_too_old + "BP0018": Refused, // uart_same_pin + "BP0019": Refused, // uart_half_duplex_two_pins + "BP0020": Refused, // uart_entry_no_reset_pin + "BP0021": Refused, // uart_entry_invalid + "BP0022": Refused, // uart_de_pin + "BP0023": Refused, // la_no_pull + "BP0024": Refused, // la_pull_direction + "BP0025": Busy, // lease_busy + "BP0026": Refused, // lease_lost + "BP0027": Refused, // lease_not_held + "BP0028": Refused, // vref_5v_missing + "BP0029": Refused, // pull_rail_down + "BP0030": ClientTooOld, // client_too_old + "BP0031": Refused, // la_pin_in_use + "BP0032": Refused, // la_pull_down_engaged + "BP0033": Refused, // la_pull_down_conflict + "BP0034": Refused, // la_dut_output + "BP0035": Refused, // la_driven_pin + "BP0036": Refused, // la_not_gpio_output + "BP0037": Refused, // la_voltage_pins_in_use + "BP0038": Refused, // trigger_timeout + "BP0039": Refused, // sensor_trigger_timeout + "BP0040": Locked, // lan_locked + "BP0041": Refused, // policy_not_from_lan + "BP0042": Refused, // setting_cloud_or_usb + "BP0043": Refused, // setting_device_only + "BP0044": Refused, // policy_loosen_usb_only (retired) + "BP0045": Forbidden, // role_required + "BP0046": Refused, // no_analog_front_end + "BP0047": Busy, // pod_busy + "BP0048": Busy, // storage_bus_busy + "BP0049": Busy, // uart_session_open + "BP0050": Busy, // swd_session_open + "BP0051": Busy, // update_in_progress + "BP0052": Busy, // cloud_command_busy + "BP0053": Refused, // reply_too_large + "BP0054": Refused, // cloud_reply_too_large + "BP0055": Refused, // sensor_instance_unknown + "BP0056": Refused, // no_module_link + "BP0057": Refused, // image_switch_sensors_running + "BP0058": Refused, // fpga_image_required + "BP0059": Refused, // fpga_image_sensors_first + "BP0060": FirmwareTooOld, // ota_unknown_target + "BP0061": Refused, // i2c_needs_pullups + "BP0062": Refused, // i2c_session_not_open + "BP0063": Refused, // i2c_engine_reset + "BP0064": Refused, // loop_sweep_with_map + "BP0065": Refused, // output_used_by_sensor + "BP0066": Busy, // step_busy + "BP0067": Refused, // samples_out_of_range + "BP0068": Refused, // la_rate_above_ceiling + "BP0069": Refused, // la_rate_too_deep + "BP0070": Refused, // capture_dual_too_deep + "BP0071": Refused, // capture_overflowed + "BP0072": Refused, // psram_too_small + "BP0073": Refused, // psram_bandwidth + "BP0074": Refused, // signatures_always_required + "BP0075": Refused, // lan_plaintext_off + "BP0076": Refused, // usb_host_over_usb + "BP0077": Refused, // usb_host_port_unavailable + "BP0078": Refused, // usb_host_no_crystal + "BP0079": Refused, // usb_host_other_port } // CodeKind is the kind of a refusal code; ok is false for a code the table does not have. @@ -87,34 +145,17 @@ func CodeKind(code string) (kind RefusalKind, ok bool) { return kind, ok } -// Kind classifies the refusal: by its code, else (a reply without one, from older firmware or a -// refusal with no code yet) by its text. +// Kind classifies the refusal by its code; a refusal without one (or with a code this table +// does not know) is Refused. The text is never read. func (e *PodError) Kind() RefusalKind { - if k, ok := CodeKind(e.Code); ok { - return k - } - return ClassifyRefusal(e.Reason) + k, _ := CodeKind(e.Code) + return k } -// ClassifyRefusal classifies a firmware refusal text by its prefix: "locked:", "forbidden:", -// or a first clause ending in "busy" ("busy", "busy: ...", "swd busy", "swd or spi busy: ..."). -// It is the fallback for a refusal without a code. -func ClassifyRefusal(msg string) RefusalKind { - msg = strings.TrimSpace(msg) - switch { - case strings.HasPrefix(msg, "locked:"): // no code yet (the LAN policy gate) - return Locked - case strings.HasPrefix(msg, "forbidden:"): // no code yet (the cloud tunnel role gate) - return Forbidden - } - // "busy: a cloud job holds ..." / "busy: holds ...": BP0025 on firmware after - // 3.10.13; the engine texts ("swd busy", "uart busy", "busy: ... PSRAM bus"): no code yet - // (BP0003-BP0005 and BP0016 cover the I2C, SPI, bus engine and storage cases). - head, _, _ := strings.Cut(msg, ":") - if head == "busy" || strings.HasSuffix(head, " busy") { - return Busy - } - return Refused +// HasCode says err carries a refusal with this code. +func HasCode(err error, code string) bool { + pe, ok := AsPodError(err) + return ok && strings.EqualFold(strings.TrimSpace(pe.Code), code) } // AsPodError returns the refusal in err's chain, if any. @@ -152,18 +193,30 @@ func firmwareMessage(msg string) string { return msg } -// podError is an error reply from the JSON API. -func podError(msg string) error { return &PodError{Reason: firmwareMessage(msg)} } +// codedReason is the text of a coded refusal: the catalog's message filled with args. The pod +// sends no message with a code (firmware 4.0); over the cloud channel the message is the code +// itself. A code this CLI's catalog does not know shows as the code. +func codedReason(code string, args map[string]any) string { + if e, ok := errcatalog.Lookup(code); ok { + return errcatalog.Fill(e.Message, args) + } + return strings.ToUpper(strings.TrimSpace(code)) +} // replyError is an error reply from the JSON API with its code and args. func replyError(r *reply) error { return RefusalError(r.Message, r.Code, r.Args) } // RefusalError is a refusal with its text, code and args, from any JSON transport (the LAN, the // USB network, embeddedci.com's command channel): a *PodError, or for BP0030 (the pod takes no -// client this old) an *UpdateRequiredError. +// client this old) an *UpdateRequiredError. A coded refusal's text comes from the catalog, never +// from the pod (only BP0030 still carries a message, for clients older than the codes). func RefusalError(msg, code string, args map[string]any) error { + code = strings.TrimSpace(code) pe := &PodError{Reason: firmwareMessage(msg), Code: code, Args: args} - if strings.EqualFold(strings.TrimSpace(code), CodeClientTooOld) { + if code != "" { + pe.Reason = codedReason(code, args) + } + if strings.EqualFold(code, CodeClientTooOld) { return updateRequiredFromRefusal(pe) } return pe diff --git a/internal/tcpclient/lease.go b/internal/tcpclient/lease.go index f2ad7bb..b84c191 100644 --- a/internal/tcpclient/lease.go +++ b/internal/tcpclient/lease.go @@ -1,7 +1,6 @@ package tcpclient import ( - "strings" "sync/atomic" ) @@ -30,19 +29,8 @@ func LeaseAcquireRequest(j *LeaseJoin) map[string]any { return map[string]any{"cmd": "lease_acquire", "id": j.ID, "holder": j.Holder, "purpose": j.Purpose, "ttl_s": j.TTL} } -// IsUnknownCommand says the pod does not know the command it was sent (older firmware). -func IsUnknownCommand(err error) bool { - pe, ok := AsPodError(err) - if !ok { - return false - } - if pe.Code == "BP0002" { - return true - } - // fallback: BP0002 replaces it (firmware without codes) - r := strings.ToLower(strings.TrimSpace(pe.Reason)) - return strings.HasPrefix(r, "unknown cmd") || strings.HasPrefix(r, "unknown command") -} +// IsUnknownCommand says the pod does not know the command it was sent (BP0002: older firmware). +func IsUnknownCommand(err error) bool { return HasCode(err, "BP0002") } // tagRequest is req as this client sends it: with the client fields and, unless NoLeaseJoin, the // lease (clientapi.go). diff --git a/internal/tcpclient/lease_test.go b/internal/tcpclient/lease_test.go index 511264c..91ccb53 100644 --- a/internal/tcpclient/lease_test.go +++ b/internal/tcpclient/lease_test.go @@ -73,7 +73,7 @@ func TestLeaseTagOnEveryCommand(t *testing.T) { mu.Lock() got = append(got, req) mu.Unlock() - return `{"status":"ok","data":{}}` + return `{"status":"ok","data":{"api":2,"min_client_api":2}}` }) SetLeaseJoin(&LeaseJoin{ID: "L-1", TTL: 300}) t.Cleanup(func() { SetLeaseJoin(nil) }) diff --git a/internal/tcpclient/refusals_test.go b/internal/tcpclient/refusals_test.go index 81fd0ef..68f3fe1 100644 --- a/internal/tcpclient/refusals_test.go +++ b/internal/tcpclient/refusals_test.go @@ -9,65 +9,26 @@ import ( "strings" "testing" "time" - - "github.com/embeddedci-com/benchpod-cli/internal/fwrefusals" ) -// Every firmware refusal reaches the user word for word: the CLI's hints and retries match on -// these texts, and a user reads them. -func TestFirmwareRefusalsAreShownVerbatim(t *testing.T) { - for _, r := range fwrefusals.All() { - if r.Kind != "json" { - continue - } - t.Run(r.ID, func(t *testing.T) { - reply, _ := json.Marshal(map[string]string{"status": "error", "message": r.Example}) +// A coded error reply over the LAN is a *PodError of its code's kind, worded from the catalog. +func TestCodedRepliesArePodErrorsOfTheirKind(t *testing.T) { + for code, want := range map[string]RefusalKind{"BP0040": Locked, "BP0045": Forbidden, "BP0025": Busy, "BP0049": Busy, "BP0006": Refused} { + t.Run(code, func(t *testing.T) { + reply, _ := json.Marshal(map[string]any{"status": "error", "code": code, "args": map[string]any{"cmd": "flash"}}) addr, _ := mockServer(t, []string{string(reply)}) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - _, err := (&Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "status"}) - if err == nil || err.Error() != r.Example { - t.Fatalf("err = %v, want %q", err, r.Example) - } - }) - } -} - -// Every error reply is a *PodError, classified by the firmware's own prefix. -func TestFirmwareRefusalsArePodErrorsOfTheirKind(t *testing.T) { - want := map[string]RefusalKind{ - "lan_locked": Locked, - "lan_locked_v39": Locked, - "tunnel_forbidden": Forbidden, - "lease_busy": Busy, - "heavy_busy": Busy, - "psram_bus_busy": Busy, - "ota_owner_busy": Busy, - "swd_busy": Busy, - "swd_busy_spi_session": Busy, - "uart_busy": Busy, - "spi_busy": Busy, - "swd_or_spi_busy": Busy, - } - for _, r := range fwrefusals.All() { - if r.Kind != "json" { - continue - } - t.Run(r.ID, func(t *testing.T) { - reply, _ := json.Marshal(map[string]string{"status": "error", "message": r.Example}) - addr, _ := mockServer(t, []string{string(reply)}) - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - _, err := (&Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "status"}) + _, err := (&Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "ping"}) pe, ok := AsPodError(fmt.Errorf("wrapped: %w", err)) if !ok { t.Fatalf("err = %#v, not a *PodError", err) } - if pe.Cmd != "" || pe.Reason != r.Example { + if pe.Cmd != "" || pe.Code != code || pe.Reason == "" || pe.Reason == "pod returned an error" { t.Fatalf("pe = %+v", pe) } - if got := pe.Kind(); got != want[r.ID] { - t.Fatalf("kind = %d, want %d", got, want[r.ID]) + if got := pe.Kind(); got != want { + t.Fatalf("kind = %d, want %d", got, want) } }) } @@ -80,11 +41,6 @@ func TestPodErrorText(t *testing.T) { if got := (&PodError{Cmd: "proxy-set", Reason: "w25q write failed"}).Error(); got != "proxy-set: w25q write failed" { t.Fatalf("got %q", got) } - for _, msg := range []string{"busybox missing", "unbusy: x", "ready: busy later", ""} { - if k := ClassifyRefusal(msg); k != Refused { - t.Errorf("%q: kind %d", msg, k) - } - } } func TestAFailedConnectIsUnreachable(t *testing.T) { diff --git a/internal/tcpclient/session.go b/internal/tcpclient/session.go index 6e4bebb..820a03d 100644 --- a/internal/tcpclient/session.go +++ b/internal/tcpclient/session.go @@ -35,6 +35,9 @@ func (c *Client) Open(ctx context.Context) (*Session, error) { if addr == "" { return nil, fmt.Errorf("pod address is empty; run `benchpod set-connection ` first") } + if err := c.probePodAPI(ctx, map[string]any{"cmd": "session"}); err != nil { + return nil, err + } budget := c.DialTimeout if budget <= 0 { budget = DefaultDialTimeout diff --git a/internal/tcpclient/swd.go b/internal/tcpclient/swd.go index 493e4bb..d58b021 100644 --- a/internal/tcpclient/swd.go +++ b/internal/tcpclient/swd.go @@ -46,6 +46,9 @@ func (c *Client) StartRaw(ctx context.Context, req map[string]any) (net.Conn, er return nil, fmt.Errorf("pod address is empty; run `benchpod set-connection ` first") } cmd, _ := req["cmd"].(string) + if err := c.probePodAPI(ctx, req); err != nil { + return nil, err + } budget := c.DialTimeout if budget <= 0 { From 84007d8444b8d2cf4290c406572a84f29bc477a0 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:36:28 -0600 Subject: [PATCH 02/21] discover: read the API level from mDNS and say what a pod needs Firmware 4.0 advertises api=2 in its _benchpod._tcp TXT record. A pod below level 2 (none: firmware 3.x) shows "needs firmware update", one above it "needs a newer CLI". Co-Authored-By: Claude Opus 5.5 --- README.md | 5 ++++ cmd/benchpod-cli/commands_discover.go | 33 +++++++++++++++++++++- cmd/benchpod-cli/commands_discover_test.go | 23 +++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7fe25d4..873ccd5 100644 --- a/README.md +++ b/README.md @@ -1180,6 +1180,11 @@ LAN address when the pod has one, and `usb` when it was only heard on its USB li `10.237.x.y` address only works while the pod is plugged into this computer, so it is never saved; `usb` finds the pod again on any port. +The API level a pod advertises over mDNS (`api` in its TXT record, firmware 4.0 and later; none +is level 1) marks a pod this CLI does not drive: `needs firmware update` for firmware before 4.0 +(update it with `benchpod flash-self`), `needs a newer CLI` for a pod above level 2. See +[Firmware and CLI levels](#firmware-and-cli-levels). + Each pod on USB also gets a `MAC` line: its Ethernet MAC and, on firmware after 3.10.7 with Wi-Fi, the MAC it uses on Wi-Fi (`not known yet` until a `benchpod scan-wifi` or a join). Give them to your network admin when the network hands out addresses only to registered devices. diff --git a/cmd/benchpod-cli/commands_discover.go b/cmd/benchpod-cli/commands_discover.go index 8907485..9eb9a21 100644 --- a/cmd/benchpod-cli/commands_discover.go +++ b/cmd/benchpod-cli/commands_discover.go @@ -8,6 +8,7 @@ import ( "net" "os" "sort" + "strconv" "strings" "text/tabwriter" "time" @@ -43,6 +44,7 @@ type discoveredPod struct { // lanAddr is what gets saved, since it works from other machines and after the pod is unplugged. lanAddr string id string // full base64url Ed25519 pubkey (TXT id=) + api int // the pod's client API level (TXT api=); firmware 3.x sends none: 1 // Filled in by the health check. reachable bool @@ -80,7 +82,10 @@ func newDiscoverCmd(g *globalFlags) *cobra.Command { "with the cloud, not merely that something replied to a broadcast. When a pod\n" + "is reachable both ways the two entries are matched up as one physical pod.\n" + "When this machine is signed in (`benchpod login`), a registered pod is also\n" + - "checked against that account, so a pod on another account is called out.\n\n" + + "checked against that account, so a pod on another account is called out.\n" + + "A pod whose firmware this CLI does not drive is marked from the API level it\n" + + "advertises: \"needs firmware update\" (firmware before 4.0: `benchpod flash-self`)\n" + + "or \"needs a newer CLI\".\n\n" + "With --save and exactly one pod present, it is stored as the default connection\n" + "(like set-connection): its Ethernet or Wi-Fi address when it has one, else `usb`\n" + "for a pod only reached over its USB network link (that 10.237.x.y address only\n" + @@ -240,6 +245,7 @@ func discoverPods(wait time.Duration) ([]discoveredPod, error) { instance: unescapeDNSSD(e.Instance), hostname: strings.TrimSuffix(e.HostName, "."), id: txtValue(e.Text, "id"), + api: txtAPI(e.Text), } ips[e.Instance] = append(ips[e.Instance], e.AddrIPv4...) // Prefer a numeric IPv4 over the .local name so we don't depend on @@ -390,6 +396,28 @@ func unescapeDNSSD(s string) string { return b.String() } +// txtAPI is the client API level a pod advertises (TXT api=, firmware 4.0 and later); 1 when it +// advertises none (firmware 3.x). +func txtAPI(txt []string) int { + n, err := strconv.Atoi(txtValue(txt, "api")) + if err != nil || n < 1 { + return 1 + } + return n +} + +// apiVerdict says what a pod's advertised API level needs: "" when this CLI drives it (or the +// level is not known: 0). +func apiVerdict(api int) string { + switch { + case api > 0 && api < tcpclient.MinPodAPI: + return "needs firmware update (`benchpod flash-self`)" + case api > tcpclient.ClientAPI: + return "needs a newer CLI" + } + return "" +} + // txtValue returns the value of key=... from a DNS-SD TXT record, or "". func txtValue(txt []string, key string) string { prefix := key + "=" @@ -755,6 +783,9 @@ func describeHealth(p discoveredPod) string { parts = append(parts, fmt.Sprintf("registered, cloud %s", strings.ToLower(strings.TrimSpace(p.cloud.State)))) } } + if v := apiVerdict(p.api); v != "" { + parts = append(parts, v) + } if p.lanAddr != "" && p.lanAddr != p.addr { parts = append(parts, "LAN address "+p.lanAddr) } diff --git a/cmd/benchpod-cli/commands_discover_test.go b/cmd/benchpod-cli/commands_discover_test.go index 51e2900..7f3b43d 100644 --- a/cmd/benchpod-cli/commands_discover_test.go +++ b/cmd/benchpod-cli/commands_discover_test.go @@ -400,3 +400,26 @@ func TestDescribeSerialMACs(t *testing.T) { } } } + +// discover reads the API level from the mDNS TXT record and says what a pod needs. +func TestDiscoverAPILevel(t *testing.T) { + for _, c := range []struct { + txt []string + api int + want string + }{ + {[]string{"id=abc"}, 1, "needs firmware update (`benchpod flash-self`)"}, + {[]string{"id=abc", "api=2", "https_only=1", "tls=8443"}, 2, ""}, + {[]string{"api=3"}, 3, "needs a newer CLI"}, + {[]string{"api=x"}, 1, "needs firmware update"}, + } { + api := txtAPI(c.txt) + if api != c.api { + t.Errorf("%v: api %d, want %d", c.txt, api, c.api) + } + got := describeHealth(discoveredPod{reachable: true, api: api}) + if c.want == "" && got != "API ok" || c.want != "" && !strings.Contains(got, c.want) { + t.Errorf("%v: %q", c.txt, got) + } + } +} From 72801374f748b6b63b7f89f1dbac5a48dadadac4 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:38:07 -0600 Subject: [PATCH 03/21] lan-tls: scpi switch, firmware 4.0 TLS defaults benchpod lan-tls scpi on|off sends lan_tls scpi; show prints it. The switches (https-only, scpi, regenerate, set-cert) only work over USB or through embeddedci.com: the pod refuses them from Ethernet and Wi-Fi with BP0042, which the catalog words. README and help: the LAN is TLS only from firmware 4.0 and the CLI pins on first use, with nothing to set up. Co-Authored-By: Claude Opus 5.5 --- README.md | 60 ++++++++++++++--------- cmd/benchpod-cli/lantls.go | 86 ++++++++++++++++++-------------- cmd/benchpod-cli/lantls_test.go | 87 +++++++++++++++++---------------- cmd/benchpod-cli/root.go | 2 +- 4 files changed, 132 insertions(+), 103 deletions(-) diff --git a/README.md b/README.md index 873ccd5..ca857f3 100644 --- a/README.md +++ b/README.md @@ -147,10 +147,11 @@ reach the pod; the transport is inferred from its value: | `embeddedci:` | Through embeddedci.com to the pod with that name on your account (see below). | | *(omitted)* | the default saved by `benchpod discover --save`, `benchpod setup` or `benchpod set-connection`. | -**TLS.** Pods with firmware 3.9.3 or later also serve the API on port 8443 with -TLS. For a network address on the default port (`192.168.1.5`, `:8080`, a pod -name) `benchpod` connects to 8443 first and falls back to plaintext 8080 only when -the pod has no TLS port and has never been pinned. The pod's certificate is +**TLS.** Firmware 4.0 serves the API on Ethernet and Wi-Fi on port 8443 with TLS only +(plaintext 8080 answers on its USB network adapter). For a network address on the default +port (`192.168.1.5`, `:8080`, a pod name) `benchpod` connects to 8443 first, with nothing to +set up, and falls back to plaintext 8080 only when the pod has no TLS port (firmware before +3.9.3, for `flash-self`) and has never been pinned. The pod's certificate is pinned the first time (trust on first use) in `known_pods.json` next to the config; a different certificate later stops the command with both fingerprints. `:8443` means TLS only, any other port and the USB network adapter mean @@ -465,15 +466,18 @@ LAN policy of benchpod-baea06: locked (read and instrument control only on the L #### LAN TLS: encrypted LAN API -The pod's API on port 8443 is the same as on 8080, over TLS (firmware 3.9.3+). The -pod makes its own key and self-signed certificate on first boot; `benchpod` -pins it on first use. `benchpod lan-tls` shows it: +The pod's API on port 8443 is the same as on 8080, over TLS. From firmware 4.0 it is the only +port the JSON API answers on over Ethernet and Wi-Fi (HTTPS-only is on by default), and SCPI is +off until you switch it on. The pod makes its own key and self-signed certificate on first boot +and keeps it across updates; `benchpod` pins it on first use, so this needs no action from you. +`benchpod lan-tls` shows it: ``` $ benchpod lan-tls --connection 192.168.1.220 LAN TLS of 192.168.1.220:8080 (connected over TLS) port 8443 - https-only off + https-only on + scpi off sessions 1 certificate CN=benchpod-baea06 (generated, EC P-256), valid to 9999-12-31 names benchpod-baea06, benchpod-baea06.local @@ -481,9 +485,11 @@ LAN TLS of 192.168.1.220:8080 (connected over TLS) pinned yes, for 192.168.1.220:8443 ``` -- `benchpod lan-tls https-only on` turns plaintext 8080 off on Ethernet and Wi-Fi - (the pod keeps it on its USB link). Use it when the LAN path is shared, for - example through a Wi-Fi bridge. +- `benchpod lan-tls https-only off` turns plaintext 8080 back on for Ethernet and + Wi-Fi (for older tools); `on`, the default, takes only TLS there. The pod keeps + 8080 on its USB link either way. +- `benchpod lan-tls scpi on` turns SCPI on: it then answers on 8443 and on 8080 (on + the LAN, 8080 takes SCPI only while HTTPS-only is on); `off` turns it off again. - `benchpod lan-tls set-cert --cert pod.pem --key pod.key` installs your own certificate (with its chain) and unencrypted key; `regenerate` makes a new self-signed one. Both update this computer's pin. @@ -494,9 +500,11 @@ LAN TLS of 192.168.1.220:8080 (connected over TLS) - A TLS handshake costs the pod about 0.5 s; `benchpod` keeps the pod's session ticket for an hour in `tls_sessions.json` (mode 0600, next to the pins), so later runs resume in about 40 ms. -- The pod refuses `https-only off`, `regenerate` and `set-cert` over plaintext - Ethernet or Wi-Fi: use TLS (the default), `--connection usb` or - `--connection embeddedci:`. +- `https-only`, `scpi`, `regenerate` and `set-cert` only work over USB + (`--connection usb`, the pod's USB network adapter) or through embeddedci.com + (`--connection embeddedci:`): the pod refuses them from Ethernet and Wi-Fi, + TLS or not (`BP0042`). The pod's USB console has the same switches + (`lan-tls https-only on|off`, `lan-tls scpi on|off`). - `benchpod lan-tls show --pem > pod.pem` saves the certificate, for curl or socat (VISA raw sockets have no TLS; see the firmware API docs, LAN TLS). @@ -1003,7 +1011,7 @@ and `token.json` for the embeddedci.com session. | `--config-file` | `~/.config/benchpod-cli/config.json` | The CLI's config file, where `set-connection` saves the default. | | `--output-filename` | (stdout) | Write command output to this file instead of stdout. | | `--timeout` | `0` (per-command default) | Overall command deadline; `0` uses each command's own default. | -| `--tls` | `auto` | TLS to the pod's LAN API: `auto` (8443 when the pod has it, pinned on first use), `on` (TLS only) or `off` (plaintext 8080). Also `BENCHPOD_TLS`. See [Connection](#connection). | +| `--tls` | `auto` | TLS to the pod's LAN API: `auto` (8443 when the pod has it, pinned on first use), `on` (TLS only) or `off` (plaintext 8080; firmware 4.0 answers it on the LAN only after `benchpod lan-tls https-only off`). Also `BENCHPOD_TLS`. See [Connection](#connection). | | `--tls-ca` | (none) | PEM file of CA certificates: verify the pod's certificate and name against them instead of pinning. Also `BENCHPOD_TLS_CA`. | | `--org` | (the active organization) | The embeddedci.com organization cloud calls act in: its id, slug or name. Also `BENCHPOD_ORG`. See [Organizations](#organizations). | | `--wiring-profile` | (the pod's default profile) | The wiring profile stored on the pod that fills in the pins a command leaves out (`flash`, `i2c`, `spi-flash`, ...). Also `BENCHPOD_WIRING_PROFILE`. See [`benchpod wiring`](#benchpod-wiring). | @@ -2202,8 +2210,8 @@ Every code is also on [embeddedci.com/docs/errors](https://embeddedci.com/docs/e ### `benchpod lan-tls` -Show the pod's LAN TLS certificate, its SHA-256, the HTTPS-only setting and -whether this computer has it pinned (firmware 3.9.3+). See +Show the pod's LAN TLS certificate, its SHA-256, the HTTPS-only and SCPI settings +and whether this computer has it pinned. See [LAN TLS](#lan-tls-encrypted-lan-api). Over the network, USB or embeddedci.com. | Flag | Default | Purpose | @@ -2220,20 +2228,28 @@ Same as `benchpod lan-tls`. ### `benchpod lan-tls https-only ` -`on`: the pod refuses plaintext 8080 on Ethernet and Wi-Fi and answers only on -8443 there; its USB link keeps 8080. `off` needs a TLS, USB or embeddedci.com -connection. Stored on the pod. +`on` (the default from firmware 4.0): the pod refuses plaintext 8080 on Ethernet and +Wi-Fi and answers only on 8443 there; its USB link keeps 8080. `off`: plaintext 8080 +on the LAN too. Only over USB (`--connection usb`) or embeddedci.com. Stored on the pod. + +### `benchpod lan-tls scpi ` + +`on`: SCPI answers on the pod's TCP ports (8443, and 8080; on the LAN 8080 takes SCPI +only while HTTPS-only is on), and the pod advertises `_scpi-raw._tcp`. `off` (the +default from firmware 4.0) closes SCPI sessions. Only over USB (`--connection usb`) +or embeddedci.com. Stored on the pod. ### `benchpod lan-tls regenerate` A new key and self-signed certificate on the pod; this computer's pin follows. -Needs a TLS, USB or embeddedci.com connection. +Only over USB (`--connection usb`) or embeddedci.com. ### `benchpod lan-tls set-cert` Install your own certificate and key. Checks them here first (they must match, the key must not be encrypted, at most 7.6 KB together), uploads them over the -network (TLS or the USB network adapter), checks the pod reports the new +pod's USB network adapter (`--connection usb`; the pod refuses the upload from +Ethernet and Wi-Fi), checks the pod reports the new certificate and updates the pin. | Flag | Default | Purpose | diff --git a/cmd/benchpod-cli/lantls.go b/cmd/benchpod-cli/lantls.go index d2b6660..74ca8b3 100644 --- a/cmd/benchpod-cli/lantls.go +++ b/cmd/benchpod-cli/lantls.go @@ -20,16 +20,15 @@ import ( // ── lan-tls ───────────────────────────────────────────────────────────────── // -// The pod's LAN API over TLS (firmware 3.9.3+, benchpod-firmware docs/design/lan-tls.md): the -// certificate on port 8443 and the HTTPS-only setting. The client side (TLS by default, pinning) -// is internal/tcpclient/tls.go. +// The pod's LAN API over TLS (benchpod-firmware docs/design/lan-tls.md): the certificate on port +// 8443, the HTTPS-only setting and SCPI. The client side (TLS by default, pinning) is +// internal/tcpclient/tls.go. // -// The pod takes changes (https-only off, regenerate, set-cert) over TLS, over USB and from the -// cloud, never over plaintext Ethernet or Wi-Fi. +// The pod takes changes (https-only, scpi, regenerate, set-cert) over its USB network adapter or +// from the cloud only, never over Ethernet or Wi-Fi (BP0042), TLS or not. const ( - lanTLSMissing = "this pod's firmware has no LAN TLS; update its firmware (3.9.3 or later)" - lanTLSPlainHint = "the pod takes this only over TLS, USB or embeddedci.com, not over plaintext; connect with --tls on, --connection usb or --connection embeddedci:" + lanTLSMissing = "this pod's firmware has no LAN TLS; update its firmware with `benchpod flash-self`" lanTLSMaxUpload = 7664 // the pod's limit on the certificate + key bundle (LAN_TLS_UPLOAD_MAX) ) @@ -37,6 +36,7 @@ const ( type lanTLSReply struct { Port int `json:"port"` HTTPSOnly bool `json:"https_only"` + SCPI bool `json:"scpi"` Sessions int `json:"sessions"` Origin string `json:"origin"` Key string `json:"key"` @@ -67,20 +67,23 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { } root := &cobra.Command{ Use: "lan-tls [show]", - Short: "Show or change the pod's LAN TLS certificate and the HTTPS-only setting", - Long: "The pod serves its API on port 8443 with TLS as well as on plaintext 8080\n" + - "(firmware 3.9.3+). benchpod connects with TLS when the pod has it and pins the\n" + - "pod's certificate the first time (trust on first use, in known_pods.json next to\n" + - "the CLI config). --tls off forces plaintext; --tls-ca verifies a certificate\n" + - "signed by your own CA instead of pinning.\n\n" + - " show the certificate, its SHA-256 and whether it is pinned here\n" + - " https-only on: the pod answers plaintext 8080 only on its USB link\n" + + Short: "Show or change the pod's LAN TLS certificate, HTTPS-only and SCPI", + Long: "Firmware 4.0 serves its API on Ethernet and Wi-Fi on port 8443 with TLS only;\n" + + "plaintext 8080 answers on its USB network adapter. benchpod connects to a LAN pod\n" + + "with TLS and pins the pod's certificate the first time (trust on first use, in\n" + + "known_pods.json next to the CLI config): nothing to set up. --tls-ca verifies a\n" + + "certificate signed by your own CA instead of pinning.\n\n" + + " show the certificate, its SHA-256, the settings and whether it is pinned here\n" + + " https-only on (the default): the LAN takes TLS only; off: plaintext 8080 on the LAN too\n" + + " scpi on: SCPI answers on the pod's TCP ports (off by default)\n" + " regenerate a new key and self-signed certificate\n" + " set-cert install your own certificate and key\n" + " trust pin the certificate the pod presents now\n" + " forget drop the pin for this pod\n\n" + - "Turning HTTPS-only off, regenerating and set-cert need a TLS, USB or\n" + - "embeddedci.com connection: the pod refuses them over plaintext Ethernet or Wi-Fi.", + "https-only, scpi, regenerate and set-cert only work over USB (--connection usb,\n" + + "the pod's USB network adapter) or through embeddedci.com (--connection\n" + + "embeddedci:): the pod refuses them from Ethernet and Wi-Fi, TLS or not. The\n" + + "pod's USB console has the same switches (`lan-tls https-only on|off`, `lan-tls scpi on|off`).", Args: cobra.NoArgs, RunE: show, } @@ -94,8 +97,8 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { Short: "Install your own certificate and private key for port 8443", Long: "Install a certificate (optionally followed by its chain) and its unencrypted\n" + "private key (EC P-256/P-384 or RSA 2048-4096). The pod checks both and that the\n" + - "key matches before it stores them; new TLS connections use it. Over the network\n" + - "only (TLS or the USB network adapter). This computer's pin is updated.", + "key matches before it stores them; new TLS connections use it. Over the pod's USB\n" + + "network adapter only (--connection usb). This computer's pin is updated.", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error { return run(func(out, warn io.Writer) error { return runLanTLSSetCert(g, certFile, keyFile, out, warn) }) @@ -116,21 +119,27 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { } trust.Flags().StringVar(&expect, "sha256", "", "only trust a certificate with this SHA-256 (from the pod's console `lan-tls` or the web app)") - root.AddCommand(showCmd, &cobra.Command{ - Use: "https-only ", - Short: "Turn plaintext 8080 off (on) or back on (off) for Ethernet and Wi-Fi", - Args: cobra.ExactArgs(1), - ValidArgs: []string{"on", "off"}, - RunE: func(_ *cobra.Command, args []string) error { - v := strings.ToLower(strings.TrimSpace(args[0])) - if v != "on" && v != "off" { - return fmt.Errorf("lan-tls https-only: %q is not on or off", args[0]) - } - return run(func(out, warn io.Writer) error { - return runLanTLS(g, map[string]any{"https_only": v == "on"}, out, warn) - }) - }, - }, &cobra.Command{ + onOffCmd := func(use, key, short string) *cobra.Command { + return &cobra.Command{ + Use: use + " ", + Short: short + " (over USB or embeddedci.com only)", + Args: cobra.ExactArgs(1), + ValidArgs: []string{"on", "off"}, + RunE: func(_ *cobra.Command, args []string) error { + v := strings.ToLower(strings.TrimSpace(args[0])) + if v != "on" && v != "off" { + return usageErrorf("lan-tls %s: %q is not on or off", use, args[0]) + } + return run(func(out, warn io.Writer) error { + return runLanTLS(g, map[string]any{key: v == "on"}, out, warn) + }) + }, + } + } + root.AddCommand(showCmd, + onOffCmd("https-only", "https_only", "Take only TLS on Ethernet and Wi-Fi (on, the default) or plaintext 8080 too (off)"), + onOffCmd("scpi", "scpi", "Turn SCPI on the pod's TCP ports on or off (off by default)"), + &cobra.Command{ Use: "regenerate", Short: "Make a new key and self-signed certificate on the pod", Args: cobra.NoArgs, @@ -191,9 +200,11 @@ func runLanTLS(g *globalFlags, change map[string]any, out, warn io.Writer) error } } printLanTLS(out, t.label, addr, rep, lastTLS(t)) - if hs, ok := change["https_only"].(bool); ok && hs { - fmt.Fprintln(warn, "Plaintext port 8080 now answers only on the pod's USB link. Tools that need it there:\n"+ - "VISA raw sockets and older benchpod/SDK releases (see the pod's API docs, LAN TLS).") + if hs, ok := change["https_only"].(bool); ok && !hs { + fmt.Fprintln(warn, "Plaintext port 8080 now answers on Ethernet and Wi-Fi too: anyone on the LAN can read and drive the pod without TLS.") + } + if sc, ok := change["scpi"].(bool); ok && sc && rep.HTTPSOnly { + fmt.Fprintln(warn, "SCPI answers on 8443 (TLS) and on plaintext 8080; on the LAN 8080 takes SCPI only while https-only is on.") } return nil } @@ -221,6 +232,7 @@ func printLanTLS(out io.Writer, label, addr string, r lanTLSReply, via string) { fmt.Fprintf(out, "LAN TLS of %s (connected over %s)\n", label, via) fmt.Fprintf(out, " port %d\n", r.Port) fmt.Fprintf(out, " https-only %s\n", onOff[r.HTTPSOnly]) + fmt.Fprintf(out, " scpi %s\n", onOff[r.SCPI]) fmt.Fprintf(out, " sessions %d\n", r.Sessions) if r.SHA256 == "" { fmt.Fprintf(out, " certificate none (%s)\n", valueOr(r.Error, "unknown")) diff --git a/cmd/benchpod-cli/lantls_test.go b/cmd/benchpod-cli/lantls_test.go index 4c54ec6..5b7c087 100644 --- a/cmd/benchpod-cli/lantls_test.go +++ b/cmd/benchpod-cli/lantls_test.go @@ -1,57 +1,58 @@ package main import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" + "encoding/json" + "log" "os" - "path/filepath" "strings" "testing" - "time" ) -func writeCertKey(t *testing.T, dir, name string) (certFile, keyFile string) { - t.Helper() - key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name}, - NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), DNSNames: []string{name + ".local"}} - der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) - if err != nil { - t.Fatal(err) +// lan-tls scpi and https-only send the lan_tls switches; the LAN refusal (BP0042) says to use USB +// or the cloud. +func TestLanTLSSwitches(t *testing.T) { + t.Setenv("BENCHPOD_CONNECTION", "") + addr, got := fakeLANPod(t, `{"status":"ok","data":{"port":8443,"https_only":true,"scpi":true,"sessions":0,`+ + `"origin":"generated","key":"EC P-256","subject":"CN=benchpod-a1b2c3","sha256":"ab"}}`) + out := t.TempDir() + "/out.txt" + for _, c := range []struct { + args []string + want map[string]any + }{ + {[]string{"lan-tls", "scpi", "on"}, map[string]any{"cmd": "lan_tls", "scpi": true}}, + {[]string{"lan-tls", "https-only", "off"}, map[string]any{"cmd": "lan_tls", "https_only": false}}, + {[]string{"lan-tls"}, map[string]any{"cmd": "lan_tls"}}, + } { + if code := run(append(c.args, "--connection", addr, "--output-filename", out)); code != exitOK { + t.Fatalf("%v: exit %d", c.args, code) + } + var req map[string]any + _ = json.Unmarshal([]byte(<-got), &req) + if len(req) != len(c.want) { + t.Fatalf("%v: sent %v", c.args, req) + } + for k, v := range c.want { + if req[k] != v { + t.Fatalf("%v: sent %v", c.args, req) + } + } } - kder, _ := x509.MarshalECPrivateKey(key) - certFile, keyFile = filepath.Join(dir, name+".pem"), filepath.Join(dir, name+".key") - os.WriteFile(certFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), 0o600) - os.WriteFile(keyFile, pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kder}), 0o600) - return -} - -func TestCheckCertKey(t *testing.T) { - dir := t.TempDir() - c1, k1 := writeCertKey(t, dir, "pod1") - _, k2 := writeCertKey(t, dir, "pod2") - - bundle, leaf, err := checkCertKey(c1, k1) - if err != nil { - t.Fatalf("matching pair refused: %v", err) + b, _ := os.ReadFile(out) + if !strings.Contains(string(b), " scpi on\n") || !strings.Contains(string(b), " https-only on\n") { + t.Fatalf("show:\n%s", b) } - if leaf.Subject.CommonName != "pod1" { - t.Errorf("leaf = %v", leaf.Subject) + if code := run([]string{"lan-tls", "scpi", "maybe", "--connection", addr}); code != exitUsage { + t.Fatalf("bad value: exit %d", code) } - if !strings.Contains(string(bundle), "BEGIN CERTIFICATE") || !strings.Contains(string(bundle), "BEGIN EC PRIVATE KEY") { - t.Errorf("bundle lacks the certificate or the key:\n%s", bundle) - } - if _, _, err := checkCertKey(c1, k2); err == nil { - t.Error("a key that does not match the certificate was accepted") + + refused, _ := fakeLANPod(t, `{"status":"error","code":"BP0042","args":{"setting":"lan_tls"}}`) + var logged strings.Builder + log.SetOutput(&logged) + defer log.SetOutput(os.Stderr) + if code := run([]string{"lan-tls", "scpi", "on", "--connection", refused}); code != exitRefused { + t.Fatalf("LAN: exit %d", code) } - enc := filepath.Join(dir, "enc.key") - os.WriteFile(enc, []byte("-----BEGIN ENCRYPTED PRIVATE KEY-----\nAAAA\n-----END ENCRYPTED PRIVATE KEY-----\n"), 0o600) - if _, _, err := checkCertKey(c1, enc); err == nil || !strings.Contains(err.Error(), "encrypted") { - t.Errorf("encrypted key: err = %v", err) + if !strings.Contains(logged.String(), "BP0042: lan_tls cannot be changed over the LAN") || !strings.Contains(logged.String(), "--connection usb") { + t.Fatalf("LAN refusal: %s", logged.String()) } } diff --git a/cmd/benchpod-cli/root.go b/cmd/benchpod-cli/root.go index d1f316e..3de5d12 100644 --- a/cmd/benchpod-cli/root.go +++ b/cmd/benchpod-cli/root.go @@ -116,7 +116,7 @@ func newRootCmd() *cobra.Command { pf.StringVar(&g.outputFilename, "output-filename", "", "write command output to this file instead of stdout") pf.DurationVar(&g.timeout, "timeout", 0, "overall command deadline (0 = per-command default)") pf.StringVar(&g.tls, "tls", "auto", - "TLS to the pod's LAN API: auto (TLS on 8443 when the pod has it, pinned on first use), on (TLS only) or off (plaintext 8080)") + "TLS to the pod's LAN API: auto (TLS on 8443 when the pod has it, pinned on first use), on (TLS only) or off (plaintext 8080: firmware 4.0 answers it on the LAN only after `benchpod lan-tls https-only off`)") pf.StringVar(&g.tlsCA, "tls-ca", "", "PEM file of CA certificates: verify the pod's TLS certificate and name against them instead of pinning") pf.StringVar(&g.org, "org", "", "embeddedci.com organization for cloud calls (embeddedci:, login-backed commands): its id, slug or name (default: the active organization in the web app; also BENCHPOD_ORG)") From 7f00929abb5023156aa0d826355ffb400b245d04 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:41:30 -0600 Subject: [PATCH 04/21] install-blobs, flash-self: drop the console blob upload (firmware before 3.9.0) Blobs go over the pod's USB network adapter or its network address only. A pod older than 3.9.0 (no USB network adapter) gets an error that names flash-self, which installs its blobs over USB DFU. A pod with USB networking off is told how to turn it back on (usb-network on, or net-reset when Wi-Fi keeps it off). Co-Authored-By: Claude Opus 5.5 --- README.md | 7 ++-- cmd/benchpod-cli/blobs.go | 24 ++++---------- cmd/benchpod-cli/blobs_target.go | 29 ++++------------- cmd/benchpod-cli/blobs_target_test.go | 27 ++++++---------- cmd/benchpod-cli/flash_self.go | 46 +++++++++++---------------- cmd/benchpod-cli/flash_self_test.go | 25 --------------- cmd/benchpod-cli/usbnet.go | 10 ++++-- 7 files changed, 53 insertions(+), 115 deletions(-) diff --git a/README.md b/README.md index ca857f3..0b817a8 100644 --- a/README.md +++ b/README.md @@ -204,7 +204,7 @@ the pod reports (the `usb` line of its console `status`), never from its own ver | | Pod firmware before 3.9.0 | Pod firmware 3.9.0 and later | |---|---|---| -| **This CLI (0.6.0+)** | Works as before: the USB console for `status`, `la voltage`, `install-blobs`, `flash-self`, `set-wifi`, the policies, `cloud ca`/`proxy` and `identity`; the network commands need the pod's network address, as before, and say so. The serial auto-detect still finds `0483:5740` and `2E8A` consoles. | Over `usb`, every command uses the pod's USB network adapter when it is up (including `flash`, which the STM32 pod's console never ran), and the console for the commands that stay there. When USB networking is off (Wi-Fi configured) or not up, the network commands use the pod's Ethernet or Wi-Fi address from its console `status` if this computer reaches it, say so, and are subject to the pod's external LAN policy there (`benchpod clear-wifi` turns USB networking back on). | +| **This CLI (0.6.0+)** | Works as before: the USB console for `status`, `la voltage`, `flash-self`, `set-wifi`, the policies, `cloud ca`/`proxy` and `identity` (not `install-blobs`, whose console upload CLI 0.10 dropped: update the pod with `flash-self`); the network commands need the pod's network address, as before, and say so. The serial auto-detect still finds `0483:5740` and `2E8A` consoles. | Over `usb`, every command uses the pod's USB network adapter when it is up (including `flash`, which the STM32 pod's console never ran), and the console for the commands that stay there. When USB networking is off (Wi-Fi configured) or not up, the network commands use the pod's Ethernet or Wi-Fi address from its console `status` if this computer reaches it, say so, and are subject to the pod's external LAN policy there (`benchpod clear-wifi` turns USB networking back on). | | **An older CLI (0.5.x)** | Unchanged. | The kept console commands keep their names and replies (`status`, `dfu`, `identity`, `identity wipe`, `lan-policy`, `sig-policy`, `set-wifi`, `show-network`, `clear-wifi`, `cloud ca show`/`clear`, `cloud proxy`), so those still work, and `flash-self` still flashes over DFU. What 3.9.0 moved to the network API (`la voltage` over USB, and every upload: `install-blobs`, the blob step of `flash-self` and `set-wifi`, `cloud ca set`) prints the pod's "moved to the network API ... update the benchpod CLI to 0.6.0 or later" line: update the CLI with the firmware. Over a network address everything works. | Which command works over which connection: @@ -1866,7 +1866,10 @@ download's checksum does not match, or dfu-util fails. A local file's signature ### `benchpod install-blobs` Install the gateware and ESP32-C3 images the pod's firmware goes with (USB: over the -pod's USB network adapter when it is up, firmware 3.9.0+, else its console). By +pod's USB network adapter when it is up, else the pod's network address; firmware 3.9.0 +and later). Firmware before 3.9.0 took blobs over its console, which this CLI no longer +uses: update such a pod with `benchpod flash-self` (USB DFU). With USB networking off, +`benchpod usb-network on --connection usb` turns it back on. By default they come from the release that matches the firmware the pod runs. Each blob's signature is reported; for now a missing or failing one never stops it. When the pod does not list its blob slots (its `blob_status` command fails), it installs diff --git a/cmd/benchpod-cli/blobs.go b/cmd/benchpod-cli/blobs.go index ff85b97..a38e4dd 100644 --- a/cmd/benchpod-cli/blobs.go +++ b/cmd/benchpod-cli/blobs.go @@ -26,7 +26,7 @@ import ( const blobsManifestName = "blobs-manifest.json" -// blobsInstallTimeout bounds a whole install: ~1.3 MB over the USB console plus the slot writes. +// blobsInstallTimeout bounds a whole install: ~1.3 MB over USB plus the slot writes. const blobsInstallTimeout = 10 * time.Minute type blobEntry struct { @@ -267,19 +267,6 @@ func espLast(todo []blobEntry) []blobEntry { return append(out, esp...) } -// podFirmwareRelease is the release tag of the firmware a pod runs ("v3.4.0"), "" if unknown. -func podFirmwareRelease(ctx context.Context, console *serialconsole.Console) string { - raw, err := console.Status(ctx) - if err != nil { - return "" - } - v := serialconsole.FirmwareVersion(raw) - if v != "" && !strings.HasPrefix(v, "v") { - v = "v" + v - } - return v -} - func newInstallBlobsCmd(g *globalFlags) *cobra.Command { var dir, release, only string var force bool @@ -288,8 +275,9 @@ func newInstallBlobsCmd(g *globalFlags) *cobra.Command { Short: "Install the gateware and ESP32-C3 images the pod's firmware goes with (over USB)", Long: "The pod keeps its iCE40 gateware images and its ESP32-C3 Wi-Fi image in the\n" + "W25Q flash next to the FPGA, not in its firmware. This sends the ones it lacks\n" + - "over USB: the pod's USB network adapter when it is up (firmware 3.9.0+), else its\n" + - "USB console. By default they come from the GitHub release that matches\n" + + "over the pod's USB network adapter (firmware 3.9.0+), else its network address.\n" + + "USB networking off: `benchpod usb-network on --connection usb` (the console's\n" + + "`usb-network on`). By default they come from the GitHub release that matches\n" + "the firmware the pod runs; --dir takes them from a local build (stm32h563/build/blobs).\n\n" + "Each blob's signature (blob-*.bin.sig) is checked and reported, and handed to\n" + "firmware that checks it too; for now a missing or failing one never stops an install.", @@ -301,8 +289,8 @@ func newInstallBlobsCmd(g *globalFlags) *cobra.Command { } ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(blobsInstallTimeout)) defer cancel() - // This computer's end of the pod's USB network link (firmware 3.9.0+) needs no console; - // else the console names the way in: the USB network when it is up, else the console. + // This computer's end of the pod's USB network link needs no console; else the console + // names the way in: the USB network when it is up, else the pod's network address. target, closeTarget := g.localBlobTarget(ctx) path := "the USB network" if target == nil { diff --git a/cmd/benchpod-cli/blobs_target.go b/cmd/benchpod-cli/blobs_target.go index fd56abf..85242e3 100644 --- a/cmd/benchpod-cli/blobs_target.go +++ b/cmd/benchpod-cli/blobs_target.go @@ -16,8 +16,8 @@ import ( ) // blobTarget is where install-blobs reads the pod's W25Q slots and sends blobs: the pod's network -// API (over its USB network adapter, firmware 3.9.0+: blob_status and ota_* with a target) or its -// USB console (blobs and upload-*, older firmware). +// API (blob_status and ota_* with a target), over its USB network adapter or its network address +// (firmware 3.9.0 and later; older firmware had a console upload this CLI no longer sends). type blobTarget interface { Blobs(ctx context.Context) ([]serialconsole.BlobSlot, error) UploadSigned(ctx context.Context, target string, data []byte, version int, manifest []byte, @@ -33,24 +33,6 @@ type blobTarget interface { Method() string } -// consoleBlobs is the USB console. -type consoleBlobs struct { - *serialconsole.Console - path string -} - -func (c consoleBlobs) Release(ctx context.Context) string { return podFirmwareRelease(ctx, c.Console) } -func (c consoleBlobs) Via() string { return c.path } -func (c consoleBlobs) Method() string { return "usb_console" } - -func (c consoleBlobs) Identity(ctx context.Context) (string, string) { - id, err := c.Console.Identity(ctx) - if err != nil { - return "", "" - } - return id.PublicKey, id.ShortID -} - // lanBlobChunk is the raw bytes per ota_data line (as the LAN OTA in hwe2e sends). const lanBlobChunk = 768 @@ -244,7 +226,8 @@ func (l lanBlobs) waitApplied(ctx context.Context, target string) error { func blobTargetFor(ctx context.Context, console *serialconsole.Console, path string) (blobTarget, func(), error) { u, err := console.USBNetwork(ctx) if errors.Is(err, serialconsole.ErrNoUSBNet) { - return consoleBlobs{Console: console, path: path}, func() {}, nil // firmware before 3.9.0 + return nil, func() {}, errors.New("this pod's firmware is older than 3.9.0 and takes blobs only over its USB console, " + + "which this CLI no longer uses: update the pod with `benchpod flash-self` (USB DFU), which installs its blobs") } if err != nil { return nil, func() {}, fmt.Errorf("read the pod's status: %w", err) @@ -272,8 +255,8 @@ func blobTargetFor(ctx context.Context, console *serialconsole.Console, path str return t, c, nil } } - return nil, func() {}, errors.New("this pod's firmware (3.9.0 or later) takes blobs over the network, and neither its USB " + - "network adapter (Wi-Fi configured on the pod turns it off: `benchpod clear-wifi`) nor its network address answers") + return nil, func() {}, errors.New("the pod takes blobs over the network, and neither its USB network adapter " + + "nor its network address answers. " + usbNetworkOffHint) } // localBlobTarget is the pod's network API on this computer's end of its USB network link diff --git a/cmd/benchpod-cli/blobs_target_test.go b/cmd/benchpod-cli/blobs_target_test.go index f248661..1a7a469 100644 --- a/cmd/benchpod-cli/blobs_target_test.go +++ b/cmd/benchpod-cli/blobs_target_test.go @@ -42,23 +42,14 @@ func (c *textConsole) Close() error { return nil } var _ io.ReadWriteCloser = (*textConsole)(nil) -// New CLI + firmware without a usable USB network: install-blobs keeps today's console path. -func TestBlobTargetFallsBackToTheConsole(t *testing.T) { - cases := map[string]string{ - "firmware before 3.9.0": " device : benchpod\r\n ip : 192.168.1.220\r\n", - } - for name, status := range cases { - c := serialconsole.NewConsole(&textConsole{status: status}) - ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - target, closeT, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1") - cancel() - if err != nil { - t.Fatalf("%s: %v", name, err) - } - closeT() - if _, ok := target.(consoleBlobs); !ok || target.Via() != "/dev/cu.usbmodem1" { - t.Fatalf("%s: target %T via %s, want the console", name, target, target.Via()) - } +// Firmware before 3.9.0 has no USB network adapter: its console upload is gone, so a clear error +// that names flash-self. +func TestBlobTargetBefore39IsAnError(t *testing.T) { + c := serialconsole.NewConsole(&textConsole{status: " device : benchpod\r\n ip : 192.168.1.220\r\n"}) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if _, _, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1"); err == nil || !strings.Contains(err.Error(), "benchpod flash-self") { + t.Fatalf("err = %v", err) } } @@ -72,7 +63,7 @@ func TestBlobTargetOn39WithoutANetworkIsAnError(t *testing.T) { " usb : net off (Wi-Fi configured) pod 10.237.8.85 host 10.237.8.86 link down rx 0 (drop 0) tx 0 (full 0)\r\n"}) ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() - if _, _, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1"); err == nil || !strings.Contains(err.Error(), "clear-wifi") { + if _, _, err := blobTargetFor(ctx, c, "/dev/cu.usbmodem1"); err == nil || !strings.Contains(err.Error(), "usb-network on") { t.Fatalf("err = %v", err) } } diff --git a/cmd/benchpod-cli/flash_self.go b/cmd/benchpod-cli/flash_self.go index 84ba68c..ea526d4 100644 --- a/cmd/benchpod-cli/flash_self.go +++ b/cmd/benchpod-cli/flash_self.go @@ -548,9 +548,6 @@ func checkImageFitsPod(ctx context.Context, dfuPath, file string) error { return nil } -// skipUSBNetForBlobs keeps installBlobsAfterFlash on the console (tests). -var skipUSBNetForBlobs = false - // flashedPodSerial is the USB serial number of the pod flash-self rebooted into DFU over its // console ("" when it was put in DFU by hand): it finds the pod again after the update. var flashedPodSerial string @@ -562,6 +559,7 @@ var ( // adapter), and Windows installs drivers and may assign a new COM port before the console appears. flashedConsoleWait = 150 * time.Second flashedConsoleRetry = time.Second + flashedNetTries = 20 // seconds the computer may need to bring the USB network adapter up openFlashedConsole = func(g *globalFlags) (*serialconsole.Console, error) { device := g.serialDevice() if flashedPodSerial != "" { @@ -607,32 +605,26 @@ func installBlobsAfterFlash(g *globalFlags, src blobSource) (after podVersions, ctx, cancel := context.WithTimeout(context.Background(), blobsInstallTimeout) defer cancel() after = consoleVersions(ctx, console) - target := blobTarget(consoleBlobs{Console: console, path: "the USB console"}) - if !skipUSBNetForBlobs { - // Firmware before 3.9.0: the console. 3.9.0+: the USB network (or the pod's network - // address), which may need some seconds on the computer's side after the reboot. - var lastErr error - for i := 0; i < 20; i++ { - t, closeT, err := blobTargetFor(ctx, console, "the USB console") - if err == nil { - target = t - defer closeT() - lastErr = nil - if _, ok := t.(lanBlobs); ok || i >= 10 { - break - } - if u, uerr := console.USBNetwork(ctx); uerr != nil || !u.On { - break // older firmware, or USB networking off: no point waiting for it - } - } else { - lastErr = err - } - time.Sleep(time.Second) + // The USB network (or the pod's network address), which may need some seconds on the + // computer's side after the reboot. + var target blobTarget + var lastErr error + for i := 0; i < flashedNetTries; i++ { + t, closeT, err := blobTargetFor(ctx, console, "the USB console") + if err == nil { + target, lastErr = t, nil + defer closeT() + break } - if lastErr != nil { - return after, installed, fmt.Errorf("flash-self: the firmware is flashed, but its blobs are not installed: %w "+ - "(retry with `benchpod install-blobs`)", lastErr) + lastErr = err + if u, uerr := console.USBNetwork(ctx); uerr != nil || !u.On { + break // firmware before 3.9.0, or USB networking off: no point waiting for it } + time.Sleep(time.Second) + } + if lastErr != nil { + return after, installed, fmt.Errorf("flash-self: the firmware is flashed, but its blobs are not installed: %w "+ + "(retry with `benchpod install-blobs`)", lastErr) } if _, err := target.Blobs(ctx); err != nil { if errors.Is(err, serialconsole.ErrNoBlobSlots) { diff --git a/cmd/benchpod-cli/flash_self_test.go b/cmd/benchpod-cli/flash_self_test.go index b7d31ad..ae3bc5b 100644 --- a/cmd/benchpod-cli/flash_self_test.go +++ b/cmd/benchpod-cli/flash_self_test.go @@ -114,28 +114,3 @@ func TestInstallBlobsAfterFlashFailsWhenTheConsoleNeverReturns(t *testing.T) { } } -// After a DFU flash, a pod that does not list its blob slots gets a warning naming the skipped -// blobs and the retry; flash-self keeps its exit status (the firmware itself is in). -func TestInstallBlobsAfterFlashWarnsWhenTheSlotsAreNotListed(t *testing.T) { - oldWait, oldRetry, oldOpen, oldSkip := flashedConsoleWait, flashedConsoleRetry, openFlashedConsole, skipUSBNetForBlobs - t.Cleanup(func() { - flashedConsoleWait, flashedConsoleRetry, openFlashedConsole, skipUSBNetForBlobs = oldWait, oldRetry, oldOpen, oldSkip - }) - skipUSBNetForBlobs = true - openFlashedConsole = func(*globalFlags) (*serialconsole.Console, error) { - return serialconsole.NewConsole(&textConsole{status: " device : benchpod\r\n"}), nil - } - var err error - var installed []blobEntry - out := captureStderr(t, func() { - _, installed, err = installBlobsAfterFlash(&globalFlags{}, blobSource{base: blobsDirWith(t, "gw0", "gw2", "esp")}) - }) - if err != nil || len(installed) != 0 { - t.Fatalf("err = %v, installed = %v; want a warning only", err, installed) - } - for _, want := range []string{"WARNING", "NOT installed: gw0, gw2, esp", "benchpod install-blobs"} { - if !strings.Contains(out, want) { - t.Fatalf("stderr lacks %q:\n%s", want, out) - } - } -} diff --git a/cmd/benchpod-cli/usbnet.go b/cmd/benchpod-cli/usbnet.go index 0235ca9..e811097 100644 --- a/cmd/benchpod-cli/usbnet.go +++ b/cmd/benchpod-cli/usbnet.go @@ -18,6 +18,12 @@ import ( // needs the network and is given a USB connection uses it; the console stays for the commands // that only the console runs and as the fallback. +// usbNetworkOffHint is how a user brings the pod's USB network adapter back, for the commands +// that run over it (JSON over USB) when it is off. +const usbNetworkOffHint = "Turn USB networking on with `benchpod usb-network on --connection usb` (the pod's console " + + "`usb-network on`); Wi-Fi set on the pod keeps it off: clear it with `benchpod clear-wifi` over the pod's network " + + "address, or `benchpod net-reset` over USB" + // usbNetProbeTimeout bounds the TCP check of the pod's address on the USB link. const usbNetProbeTimeout = 2 * time.Second @@ -70,9 +76,9 @@ func (g *globalFlags) usbNetAddr(device string) (string, error) { var why error switch { case !u.On && u.OffBySetting: - why = errors.New("USB networking is turned off on the pod (`benchpod usb-network on` over its USB console turns it back on)") + why = errors.New("USB networking is turned off on the pod (`benchpod usb-network on --connection usb`, the pod's console `usb-network on`, turns it back on)") case !u.On: - why = errors.New("USB networking is off because Wi-Fi is configured on the pod (`benchpod clear-wifi` turns it back on)") + why = errors.New("USB networking is off because Wi-Fi is configured on the pod (`benchpod clear-wifi` over its network address, or `benchpod net-reset` over USB, turns it back on)") case !u.Link: why = fmt.Errorf("the pod's USB network adapter (%s) is not up on this computer; "+ "macOS ignores a new adapter while the screen is locked: unlock and run `benchpod usb-reattach`", u.PodIP) From ecf94aa79d94b425d2b7bb2a18341ea734c565cf Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:43:56 -0600 Subject: [PATCH 05/21] cloud ca, cloud proxy: JSON over the USB network adapter, no console Over USB both go to the pod's USB network adapter (cloud_ca, cloud_proxy, ota_* target ca), which may change them; the console commands are gone in firmware 4.0. Without the adapter the error says how to turn it on. Co-Authored-By: Claude Opus 5.5 --- README.md | 25 ++-- cmd/benchpod-cli/cloudcfg.go | 156 +++++++---------------- cmd/benchpod-cli/cloudcfg_test.go | 204 ++++++++---------------------- 3 files changed, 109 insertions(+), 276 deletions(-) diff --git a/README.md b/README.md index 0b817a8..51fb91e 100644 --- a/README.md +++ b/README.md @@ -548,26 +548,26 @@ belongs to the old record. On a network whose proxy inspects TLS, the pod's cloud link fails: the proxy re-signs embeddedci.com with a company root the pod does not trust. Some networks also only reach the internet through an HTTP proxy. `benchpod cloud` sets both -over the USB console (`--connection usb`) or through embeddedci.com +over the pod's USB network adapter (`--connection usb`) or through embeddedci.com (`--connection embeddedci:`: `cloud proxy` show, set and clear, `cloud ca` show and clear; the CA upload needs USB, and a change needs an organization owner or -admin). The LAN (`--connection
`) can show them; current firmware refuses -changes from the LAN: +admin). The LAN (`--connection
`) can show them; the pod refuses changes +from the LAN. With USB networking off, `benchpod usb-network on --connection usb` +turns it back on: ``` $ benchpod cloud ca set acme-root.pem --connection usb acme-root.pem: 1 certificate CN=Acme Root CA,O=Acme Corp SHA-256 3b1f...c2d9 -Uploading 652 bytes to the pod on /dev/cu.usbmodem1101 ... -Company CA of the pod on /dev/cu.usbmodem1101 is now 1 certificate +Company CA of 10.237.8.85:8080 is now 1 certificate CN=Acme Root CA,O=Acme Corp SHA-256 3b1f...c2d9 The pod reconnects to the cloud, trusting this CA in addition to its built-in roots. $ benchpod cloud proxy set proxy.corp:3128 --user alice --connection usb Proxy password: -HTTP proxy of the pod on /dev/cu.usbmodem1101 is now proxy.corp:3128 (with a user and password) +HTTP proxy of 10.237.8.85:8080 is now proxy.corp:3128 (with a user and password) The pod reconnects to the cloud through proxy.corp:3128. ``` @@ -584,20 +584,15 @@ The pod reconnects to the cloud through proxy.corp:3128. TCP and the password would cross the network unencrypted. - `show` (the default) reports what the pod holds. The pod reconnects to the cloud after every change. -- Current firmware refuses `set` and `clear` from the LAN, whatever its LAN - policy: only USB or the cloud link may change the company CA or the proxy. The - CLI then prints the pod's reason and a hint to rerun with `--connection usb`: +- The pod refuses `set` and `clear` from the LAN, whatever its LAN policy: only + USB or the cloud link may change the company CA or the proxy (`BP0042`). The + CLI shows the code, the reason and to rerun with `--connection usb`: ``` $ benchpod cloud proxy clear --connection 192.168.1.50 - [benchpod] cloud proxy clear: the pod refused: cloud_proxy: change it from the cloud or over USB (the pod only takes this change over USB or from the cloud, never from Ethernet or Wi-Fi; run it with --connection usb) + [benchpod] cloud proxy clear: the pod refused: BP0042: cloud_proxy cannot be changed over the LAN: change it from the cloud or over USB; run this over USB with --connection usb, or from the cloud (https://embeddedci.com/docs/errors#BP0042) ``` - Older firmware with its LAN policy `locked` refuses the same way, with its own - message. -- Firmware without them gets "this firmware has no company CA support; update the - pod's firmware" (or the same for the HTTP proxy). - Run `benchpod -h` for the flags of any subcommand. #### Flashing: CMSIS-DAP diff --git a/cmd/benchpod-cli/cloudcfg.go b/cmd/benchpod-cli/cloudcfg.go index 7b3057a..82d9de8 100644 --- a/cmd/benchpod-cli/cloudcfg.go +++ b/cmd/benchpod-cli/cloudcfg.go @@ -18,7 +18,6 @@ import ( "strings" "time" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" ) @@ -51,11 +50,12 @@ func newCloudCmd(g *globalFlags) *cobra.Command { Long: "Configure the pod's link to embeddedci.com on networks that need it.\n\n" + " ca a company root certificate, for networks whose proxy inspects TLS\n" + " proxy an HTTP proxy the pod tunnels its cloud connection through\n\n" + - "Both work over the pod's USB console (--connection usb) and through\n" + + "Both work over the pod's USB network adapter (--connection usb) and through\n" + "embeddedci.com (--connection embeddedci:; a change there needs an\n" + "organization owner or admin, and `cloud ca set` needs USB). The LAN\n" + - "(--connection
) can show them; current firmware refuses changes from\n" + - "the LAN, so change them over USB. The pod reconnects to the cloud after a change.", + "(--connection
) can show them; the pod refuses changes from the LAN,\n" + + "so change them over USB. The pod reconnects to the cloud after a change.\n" + + "USB networking off: `benchpod usb-network on --connection usb`.", Args: cobra.NoArgs, } root.AddCommand(newCloudCACmd(g), newCloudProxyCmd(g)) @@ -291,7 +291,7 @@ func readCAFile(path string) ([]byte, error) { } // printCACerts writes the certificate list the pod reports. -func printCACerts(out io.Writer, label string, certs []serialconsole.CACert, changed bool) { +func printCACerts(out io.Writer, label string, certs []podCACert, changed bool) { verb := ":" if changed { verb = " is now" @@ -339,25 +339,20 @@ func runCloudCA(g *globalFlags, action, file string, out, warn io.Writer) error return err } var label string - var certs []serialconsole.CACert + var certs []podCACert switch { case spec.IsCloud() && action == "set": return cloudCASetRefusal(what) case spec.IsCloud(): label, certs, err = cloudCACloud(g, spec, action) case spec.IsSerial(): - // Firmware 3.9.0+: over the USB network link, which may change the CA (physical presence). - if addr := g.usbLinkAddr(spec.Device, spec.Pod); addr != "" { - label = addr - certs, err = cloudCALAN(g, addr, action, upload, warn) - break - } - label, certs, err = cloudCAUSB(g, spec.Device, action, upload, warn) - if err != nil && strings.Contains(err.Error(), "moved to the network API") { - err = errors.New("this pod's firmware (3.9.0 or later) installs a CA over the network: its USB network " + - "adapter is not usable here (Wi-Fi configured on the pod turns it off: `benchpod clear-wifi`), so use the " + - "cloud (`--connection embeddedci:`) or turn USB networking back on") + // Over the USB network link, which may change the CA (physical presence). + var nt ConnSpec + if nt, err = g.networkTarget(what); err != nil { + return err } + label = nt.Addr + certs, err = cloudCALAN(g, nt.Addr, action, upload, warn) default: label = spec.Addr certs, err = cloudCALAN(g, spec.Addr, action, upload, warn) @@ -379,7 +374,7 @@ func runCloudCA(g *globalFlags, action, file string, out, warn io.Writer) error return nil } -func sameCerts(local []caCert, pod []serialconsole.CACert) bool { +func sameCerts(local []caCert, pod []podCACert) bool { if len(local) != len(pod) { return false } @@ -394,9 +389,6 @@ func sameCerts(local []caCert, pod []serialconsole.CACert) bool { // cloudCfgError turns a failed command into one clear line: old firmware, a locked LAN, a change // the pod refuses from the LAN, or the pod's own reason. func cloudCfgError(what, missing string, lan bool, err error) error { - if errors.Is(err, serialconsole.ErrUnknownCommand) { - return errors.New(missing) - } if isUnknownCommand(err) || tcpclient.HasCode(err, "BP0060") { // ota_unknown_target return errors.New(missing) } @@ -406,67 +398,17 @@ func cloudCfgError(what, missing string, lan bool, err error) error { return fmt.Errorf("%s: %w", what, err) } -// ── USB console ───────────────────────────────────────────────────────────── - -// cloudConsole is the part of the USB console the cloud ca/proxy commands use. -type cloudConsole interface { - CloudCA(ctx context.Context) ([]serialconsole.CACert, error) - CloudCAClear(ctx context.Context) error - CloudProxy(ctx context.Context) (serialconsole.ProxyConfig, error) - CloudProxySet(ctx context.Context, addr, user, password string) (serialconsole.ProxyConfig, error) - CloudProxyClear(ctx context.Context) (serialconsole.ProxyConfig, error) - Upload(ctx context.Context, target string, data []byte, version int, progress func(done, total int)) error - Close() error -} - -// openCloudConsole opens the pod's USB console; tests replace it with a fake. -var openCloudConsole = func(g *globalFlags, device string, timeout time.Duration) (cloudConsole, string, context.Context, context.CancelFunc, error) { - console, path, ctx, cancel, err := g.openSerialConsole(device, timeout) - if err != nil { - return nil, "", nil, cancel, err - } - return console, path, ctx, cancel, nil -} - -func cloudCAUSB(g *globalFlags, device, action string, upload []byte, warn io.Writer) (string, []serialconsole.CACert, error) { - console, path, ctx, cancel, err := openCloudConsole(g, device, g.effectiveTimeout(60*time.Second)) - if err != nil { - return "", nil, err - } - defer cancel() - defer console.Close() - label := "the pod on " + path - - switch action { - case "set": - // Ask first, so old firmware gets the clear message rather than a refused upload. - if _, err := console.CloudCA(ctx); err != nil { - return label, nil, err - } - fmt.Fprintf(warn, "Uploading %d bytes to %s ...\n", len(upload), label) - if err := console.Upload(ctx, "ca", upload, 0, nil); err != nil { - return label, nil, err - } - case "clear": - if err := console.CloudCAClear(ctx); err != nil { - return label, nil, err - } - } - certs, err := console.CloudCA(ctx) - return label, certs, err -} - // ── embeddedci.com ────────────────────────────────────────────────────────── // cloudCASetRefusal: installing a CA is an upload, which the command channel does not carry. func cloudCASetRefusal(what string) error { - return fmt.Errorf("%s does not work over embeddedci.com from the CLI: the certificate upload needs the pod's USB console. "+ + return fmt.Errorf("%s does not work over embeddedci.com from the CLI: the certificate upload needs the pod's USB network adapter. "+ "Run it with --connection usb", what) } // cloudCACloud shows or clears the company CA through embeddedci.com. The pod reconnects after a // clear, so the reply to the clear is what it reports; a read-back could race the reconnect. -func cloudCACloud(g *globalFlags, spec ConnSpec, action string) (string, []serialconsole.CACert, error) { +func cloudCACloud(g *globalFlags, spec ConnSpec, action string) (string, []podCACert, error) { req := map[string]any{"cmd": "cloud_ca"} if action == "clear" { req["clear"] = true @@ -479,7 +421,7 @@ func cloudCACloud(g *globalFlags, spec ConnSpec, action string) (string, []seria // cloudProxyCloud shows, sets or clears the HTTP proxy through embeddedci.com (HTTPS, so a proxy // password does not cross the network in the clear). Like the CA, a change makes the pod // reconnect, so the change's own reply is what it reports. -func cloudProxyCloud(g *globalFlags, spec ConnSpec, action, set, user, password string) (string, serialconsole.ProxyConfig, error) { +func cloudProxyCloud(g *globalFlags, spec ConnSpec, action, set, user, password string) (string, proxyConfig, error) { req := map[string]any{"cmd": "cloud_proxy"} switch action { case "set": @@ -527,7 +469,7 @@ func openLAN(ctx context.Context, addr string) (lanSession, error) { type caReply struct { Present bool `json:"present"` - Certs []serialconsole.CACert `json:"certs"` + Certs []podCACert `json:"certs"` } // otaReply is the pod's ota_* status. @@ -536,7 +478,7 @@ type otaReply struct { Error string `json:"error"` } -func cloudCALAN(g *globalFlags, addr, action string, upload []byte, warn io.Writer) ([]serialconsole.CACert, error) { +func cloudCALAN(g *globalFlags, addr, action string, upload []byte, warn io.Writer) ([]podCACert, error) { ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(60*time.Second)) defer cancel() defer installSignalHandler(ctx, cancel)() @@ -608,6 +550,18 @@ func uploadOTALAN(ctx context.Context, lan lanSession, data []byte, target strin return nil } +// podCACert is one company CA certificate the pod holds. +type podCACert struct { + Subject string `json:"subject"` + SHA256 string `json:"sha256"` // hex SHA-256 of the DER certificate +} + +// proxyConfig is the pod's HTTP proxy. Addr is "" when no proxy is set. +type proxyConfig struct { + Addr string // host:port + Auth bool // a user and password are stored (the pod never reports the password) +} + func valueOr(s, def string) string { if strings.TrimSpace(s) == "" { return def @@ -636,7 +590,7 @@ func checkProxyAddr(addr string) (string, error) { return net.JoinHostPort(strings.ToLower(host), port), nil } -func describeProxy(p serialconsole.ProxyConfig) string { +func describeProxy(p proxyConfig) string { switch { case p.Addr == "": return "none (the pod connects to the cloud directly)" @@ -663,18 +617,18 @@ func runCloudProxy(g *globalFlags, action, addr, user, password string, out, war return err } var label string - var p serialconsole.ProxyConfig + var p proxyConfig switch { case spec.IsCloud(): label, p, err = cloudProxyCloud(g, spec, action, addr, user, password) case spec.IsSerial(): - // Firmware 3.9.0+: over the USB network link, which may change the proxy (physical presence). - if link := g.usbLinkAddr(spec.Device, spec.Pod); link != "" { - label = link - p, err = cloudProxyLAN(g, link, action, addr, user, password) - break + // Over the USB network link, which may change the proxy (physical presence). + var nt ConnSpec + if nt, err = g.networkTarget(what); err != nil { + return err } - label, p, err = cloudProxyUSB(g, spec.Device, action, addr, user, password) + label = nt.Addr + p, err = cloudProxyLAN(g, nt.Addr, action, addr, user, password) default: label = spec.Addr p, err = cloudProxyLAN(g, spec.Addr, action, addr, user, password) @@ -701,26 +655,6 @@ func runCloudProxy(g *globalFlags, action, addr, user, password string, out, war return nil } -func cloudProxyUSB(g *globalFlags, device, action, addr, user, password string) (string, serialconsole.ProxyConfig, error) { - console, path, ctx, cancel, err := openCloudConsole(g, device, g.effectiveTimeout(15*time.Second)) - if err != nil { - return "", serialconsole.ProxyConfig{}, err - } - defer cancel() - defer console.Close() - label := "the pod on " + path - var p serialconsole.ProxyConfig - switch action { - case "set": - p, err = console.CloudProxySet(ctx, addr, user, password) - case "clear": - p, err = console.CloudProxyClear(ctx) - default: - p, err = console.CloudProxy(ctx) - } - return label, p, err -} - // proxyReply is the pod's JSON proxy report: {"host":"...","port":3128,"auth":true}, with no // host when none is set. type proxyReply struct { @@ -729,21 +663,21 @@ type proxyReply struct { Auth bool `json:"auth"` } -func (r proxyReply) config() serialconsole.ProxyConfig { +func (r proxyReply) config() proxyConfig { if r.Host == "" { - return serialconsole.ProxyConfig{} + return proxyConfig{} } - return serialconsole.ProxyConfig{Addr: net.JoinHostPort(r.Host, strconv.Itoa(r.Port)), Auth: r.Auth} + return proxyConfig{Addr: net.JoinHostPort(r.Host, strconv.Itoa(r.Port)), Auth: r.Auth} } -func cloudProxyLAN(g *globalFlags, addr, action, set, user, password string) (serialconsole.ProxyConfig, error) { +func cloudProxyLAN(g *globalFlags, addr, action, set, user, password string) (proxyConfig, error) { ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(15*time.Second)) defer cancel() defer installSignalHandler(ctx, cancel)() lan, err := openLAN(ctx, addr) if err != nil { - return serialconsole.ProxyConfig{}, err + return proxyConfig{}, err } defer lan.s.Close() @@ -759,13 +693,13 @@ func cloudProxyLAN(g *globalFlags, addr, action, set, user, password string) (se } var rep proxyReply if err := lan.cmd(ctx, req, &rep); err != nil { - return serialconsole.ProxyConfig{}, err + return proxyConfig{}, err } if action != "show" { // Report what the pod holds now, not what the change's reply happened to carry. rep = proxyReply{} if err := lan.cmd(ctx, map[string]any{"cmd": "cloud_proxy"}, &rep); err != nil { - return serialconsole.ProxyConfig{}, err + return proxyConfig{}, err } } return rep.config(), nil diff --git a/cmd/benchpod-cli/cloudcfg_test.go b/cmd/benchpod-cli/cloudcfg_test.go index d858ab7..0151c3e 100644 --- a/cmd/benchpod-cli/cloudcfg_test.go +++ b/cmd/benchpod-cli/cloudcfg_test.go @@ -3,7 +3,6 @@ package main import ( "bufio" "bytes" - "context" "crypto/ecdsa" "crypto/elliptic" "crypto/rand" @@ -110,76 +109,6 @@ func TestCheckCAPEM(t *testing.T) { // ── USB ───────────────────────────────────────────────────────────────────── // fakeCloudConsole stands in for the pod's USB console. -type fakeCloudConsole struct { - certs []serialconsole.CACert - proxy serialconsole.ProxyConfig - err error // returned by every command - uploadTo string - uploaded []byte - calls []string -} - -func (f *fakeCloudConsole) CloudCA(context.Context) ([]serialconsole.CACert, error) { - f.calls = append(f.calls, "ca") - return f.certs, f.err -} - -func (f *fakeCloudConsole) CloudCAClear(context.Context) error { - f.calls = append(f.calls, "ca-clear") - if f.err == nil { - f.certs = nil - } - return f.err -} - -func (f *fakeCloudConsole) CloudProxy(context.Context) (serialconsole.ProxyConfig, error) { - f.calls = append(f.calls, "proxy") - return f.proxy, f.err -} - -func (f *fakeCloudConsole) CloudProxySet(_ context.Context, addr, user, password string) (serialconsole.ProxyConfig, error) { - f.calls = append(f.calls, strings.TrimSpace("proxy-set "+addr+" "+user+" "+password)) - if f.err != nil { - return serialconsole.ProxyConfig{}, f.err - } - f.proxy = serialconsole.ProxyConfig{Addr: addr, Auth: user != ""} - return f.proxy, nil -} - -func (f *fakeCloudConsole) CloudProxyClear(context.Context) (serialconsole.ProxyConfig, error) { - f.calls = append(f.calls, "proxy-clear") - f.proxy = serialconsole.ProxyConfig{} - return f.proxy, f.err -} - -func (f *fakeCloudConsole) Upload(_ context.Context, target string, data []byte, _ int, _ func(int, int)) error { - f.calls = append(f.calls, "upload "+target) - f.uploadTo, f.uploaded = target, data - certs, _, err := checkCAPEM(data) - if err != nil { - return err - } - f.certs = nil - for _, c := range certs { - f.certs = append(f.certs, serialconsole.CACert{Subject: c.Subject, SHA256: c.SHA256}) - } - return nil -} - -func (f *fakeCloudConsole) Close() error { return nil } - -func withFakeCloudConsole(t *testing.T, fc *fakeCloudConsole) { - t.Helper() - saved := openCloudConsole - openCloudConsole = func(_ *globalFlags, device string, _ time.Duration) (cloudConsole, string, context.Context, context.CancelFunc, error) { - if device == "" { - device = "/dev/cu.usbmodem1101" - } - return fc, device, context.Background(), func() {}, nil - } - t.Cleanup(func() { openCloudConsole = saved }) -} - func runCACapture(g *globalFlags, action, file string) (string, string, error) { var out, warn bytes.Buffer err := runCloudCA(g, action, file, &out, &warn) @@ -192,116 +121,91 @@ func runProxyCapture(g *globalFlags, action, addr, user, password string) (strin return out.String(), warn.String(), err } +// Over USB the company CA and the proxy go over the pod's USB network adapter (JSON, the USB link +// may change them). func TestCloudCAUSB(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - g := &globalFlags{connection: "usb"} + pod := &lanCfgPod{t: t} + addr := pod.start() + g := &globalFlags{connection: "usb", usbAddr: addr} out, _, err := runCACapture(g, "show", "") - if err != nil || out != "Company CA of the pod on /dev/cu.usbmodem1101: none (the pod trusts only its built-in roots)\n" { + if err != nil || out != "Company CA of "+addr+": none (the pod trusts only its built-in roots)\n" { t.Fatalf("show = %q, %v", out, err) } - root := testCertPEM(t, "Acme Root CA", true) out, warn, err := runCACapture(g, "set", tempPEM(t, "acme.pem", root)) - if err != nil { - t.Fatalf("set: %v", err) - } - want := "Company CA of the pod on /dev/cu.usbmodem1101 is now 1 certificate\n" + - " CN=Acme Root CA,O=Acme Corp\n SHA-256 " + pemSHA(t, root) + "\n" - if out != want { - t.Fatalf("set = %q\nwant %q", out, want) - } - if fc.uploadTo != "ca" || !bytes.Equal(fc.uploaded, root) { - t.Fatalf("uploaded %q to %q", fc.uploaded, fc.uploadTo) + if err != nil || !strings.HasPrefix(out, "Company CA of "+addr+" is now 1 certificate\n") { + t.Fatalf("set = %q, %v", out, err) } if !strings.Contains(warn, "reconnects to the cloud") || strings.Contains(warn, "Warning") { t.Fatalf("warn = %q", warn) } - - out, warn, err = runCACapture(g, "clear", "") - if err != nil || !strings.HasSuffix(out, "is now none (the pod trusts only its built-in roots)\n") || - !strings.Contains(warn, "only its built-in roots") { - t.Fatalf("clear = %q, %q, %v", out, warn, err) + if !strings.Contains(pod.cmds(), "ota_begin,ota_data,ota_end,ota_commit") { + t.Fatalf("requests = %s", pod.cmds()) } - if got := strings.Join(fc.calls, ","); got != "ca,ca,upload ca,ca,ca-clear,ca" { - t.Fatalf("calls = %s", got) + out, _, err = runCACapture(g, "clear", "") + if err != nil || !strings.HasSuffix(out, "is now none (the pod trusts only its built-in roots)\n") { + t.Fatalf("clear = %q, %v", out, err) } } func TestCloudCANotMarkedCAWarns(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - _, warn, err := runCACapture(&globalFlags{connection: "usb"}, "set", tempPEM(t, "leaf.pem", testCertPEM(t, "leaf", false))) - if err != nil || !strings.Contains(warn, "Warning: CN=leaf,O=Acme Corp is not marked as a CA") { + pod := &lanCfgPod{t: t} + g := &globalFlags{connection: "usb", usbAddr: pod.start()} + _, warn, err := runCACapture(g, "set", tempPEM(t, "leaf.pem", testCertPEM(t, "leaf", false))) + if !strings.Contains(warn, "Warning: CN=leaf,O=Acme Corp is not marked as a CA") { t.Fatalf("warn = %q, %v", warn, err) } } -func TestCloudCAUSBOldFirmware(t *testing.T) { - fc := &fakeCloudConsole{err: serialconsole.ErrUnknownCommand} - withFakeCloudConsole(t, fc) - g := &globalFlags{connection: "usb"} - for _, action := range []string{"show", "clear"} { - if _, _, err := runCACapture(g, action, ""); err == nil || err.Error() != caMissing { - t.Fatalf("%s: err = %v", action, err) - } - } - if _, _, err := runCACapture(g, "set", tempPEM(t, "a.pem", testCertPEM(t, "A", true))); err == nil || err.Error() != caMissing { - t.Fatalf("set: err = %v", err) - } - if fc.uploadTo != "" { - t.Fatal("old firmware got an upload") - } - if _, _, err := runProxyCapture(g, "show", "", "", ""); err == nil || err.Error() != proxyMissing { - t.Fatalf("proxy: err = %v", err) - } -} - func TestCloudCABadPEMTouchesNoPod(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - _, _, err := runCACapture(&globalFlags{connection: "usb"}, "set", tempPEM(t, "bad.pem", []byte("not a certificate"))) + pod := &lanCfgPod{t: t} + g := &globalFlags{connection: "usb", usbAddr: pod.start()} + _, _, err := runCACapture(g, "set", tempPEM(t, "bad.pem", []byte("not a certificate"))) if err == nil || !strings.Contains(err.Error(), "no CERTIFICATE block") { t.Fatalf("err = %v", err) } - if len(fc.calls) != 0 { - t.Fatalf("a bad PEM reached the pod: %v", fc.calls) + if pod.cmds() != "" { + t.Fatalf("a bad PEM reached the pod: %v", pod.cmds()) } - if _, _, err := runCACapture(&globalFlags{connection: "usb"}, "set", filepath.Join(t.TempDir(), "missing.pem")); err == nil { + if _, _, err := runCACapture(g, "set", filepath.Join(t.TempDir(), "missing.pem")); err == nil { t.Fatal("a missing file passed") } } +// Without the USB network adapter (and no network address that answers), the command says how to +// turn it on. +func TestCloudCfgUSBWithoutTheNetwork(t *testing.T) { + old := usbNetwork + usbNetwork = func(*globalFlags, string) (serialconsole.USBNet, error) { + return serialconsole.USBNet{PodIP: "10.237.8.85", HostIP: "10.237.8.86", OffBySetting: true}, nil + } + t.Cleanup(func() { usbNetwork = old }) + _, _, err := runProxyCapture(&globalFlags{connection: "usb"}, "show", "", "", "") + if err == nil || !strings.Contains(err.Error(), "usb-network on") { + t.Fatalf("err = %v", err) + } +} + func TestCloudProxyUSB(t *testing.T) { - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - g := &globalFlags{connection: "/dev/cu.usbmodem9"} + pod := &lanCfgPod{t: t} + addr := pod.start() + g := &globalFlags{connection: "usb", usbAddr: addr} out, _, err := runProxyCapture(g, "show", "", "", "") - if err != nil || out != "HTTP proxy of the pod on /dev/cu.usbmodem9: none (the pod connects to the cloud directly)\n" { + if err != nil || out != "HTTP proxy of "+addr+": none (the pod connects to the cloud directly)\n" { t.Fatalf("show = %q, %v", out, err) } out, warn, err := runProxyCapture(g, "set", "Proxy.Corp:3128", "alice", "s3cret") - if err != nil || out != "HTTP proxy of the pod on /dev/cu.usbmodem9 is now proxy.corp:3128 (with a user and password)\n" { + if err != nil || out != "HTTP proxy of "+addr+" is now proxy.corp:3128 (with a user and password)\n" { t.Fatalf("set = %q, %v", out, err) } - if warn != "The pod reconnects to the cloud through proxy.corp:3128.\n" { + if warn != "The pod reconnects to the cloud through proxy.corp:3128.\n" || strings.Contains(out+warn, "s3cret") { t.Fatalf("warn = %q", warn) } - if strings.Contains(out+warn, "s3cret") { - t.Fatal("the password was printed") - } - out, warn, err = runProxyCapture(g, "clear", "", "", "") - if err != nil || !strings.HasSuffix(out, "is now none (the pod connects to the cloud directly)\n") || - warn != "The pod reconnects to the cloud directly, without a proxy.\n" { - t.Fatalf("clear = %q, %q, %v", out, warn, err) - } - - fc.err = &serialconsole.CommandError{Cmd: "proxy-set", Reason: "w25q write failed"} - _, _, err = runProxyCapture(g, "set", "p:1", "", "") - if err == nil || err.Error() != "cloud proxy set: the pod refused: w25q write failed" { - t.Fatalf("refusal: %v", err) + out, _, err = runProxyCapture(g, "clear", "", "", "") + if err != nil || !strings.HasSuffix(out, "is now none (the pod connects to the cloud directly)\n") { + t.Fatalf("clear = %q, %v", out, err) } } @@ -318,16 +222,16 @@ func TestCheckProxyAddr(t *testing.T) { t.Errorf("%q passed", in) } } - fc := &fakeCloudConsole{} - withFakeCloudConsole(t, fc) - if _, _, err := runProxyCapture(&globalFlags{connection: "usb"}, "set", "http://p:1", "", ""); err == nil { + pod := &lanCfgPod{t: t} + g := &globalFlags{connection: "usb", usbAddr: pod.start()} + if _, _, err := runProxyCapture(g, "set", "http://p:1", "", ""); err == nil { t.Fatal("a bad address passed") } - if _, _, err := runProxyCapture(&globalFlags{connection: "usb"}, "set", "p:1", "alice", ""); err == nil { + if _, _, err := runProxyCapture(g, "set", "p:1", "alice", ""); err == nil { t.Fatal("a user without a password passed") } - if len(fc.calls) != 0 { - t.Fatalf("a bad value reached the pod: %v", fc.calls) + if pod.cmds() != "" { + t.Fatalf("a bad value reached the pod: %v", pod.cmds()) } } @@ -341,7 +245,7 @@ type lanCfgPod struct { old bool // "unknown cmd" / "unknown target" locked string // the T2/T3 verbs refused with "locked: ..." gated bool // current firmware: every change refused from the LAN (pod_policy_cloud_link_gate) - certs []serialconsole.CACert + certs []podCACert proxy proxyReply staged []byte sha string @@ -463,7 +367,7 @@ func (p *lanCfgPod) handle(req map[string]any) string { } p.certs = nil for _, c := range certs { - p.certs = append(p.certs, serialconsole.CACert{Subject: c.Subject, SHA256: c.SHA256}) + p.certs = append(p.certs, podCACert{Subject: c.Subject, SHA256: c.SHA256}) } p.state = "installed" case "ota_abort": From b3ef4c3a425d0b2812f4fca30612dfc2767ba456 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:48:28 -0600 Subject: [PATCH 06/21] set-wifi, show-network, scan-wifi, clear-wifi: JSON over USB; net-reset Firmware 4.0 has no Wi-Fi commands on its console. The four commands send wifi_set, wifi_status, wifi_scan and wifi_clear over the pod's USB network adapter (or the --connection given). set-wifi follows the join on the address the console reports once USB networking turns off. benchpod net-reset runs the console's net-reset: the way back to a pod no network reaches (forgets Wi-Fi, resets Ethernet). Co-Authored-By: Claude Opus 5.5 --- README.md | 102 +++--- cmd/benchpod-cli/commands_serial.go | 345 +------------------ cmd/benchpod-cli/root.go | 2 +- cmd/benchpod-cli/usbnet.go | 37 ++ cmd/benchpod-cli/wifi.go | 517 ++++++++++++++++++++++++++++ cmd/benchpod-cli/wifi_test.go | 247 +++++++++++++ internal/serialconsole/netreset.go | 38 ++ 7 files changed, 911 insertions(+), 377 deletions(-) create mode 100644 cmd/benchpod-cli/wifi.go create mode 100644 cmd/benchpod-cli/wifi_test.go create mode 100644 internal/serialconsole/netreset.go diff --git a/README.md b/README.md index 51fb91e..f37aceb 100644 --- a/README.md +++ b/README.md @@ -174,13 +174,15 @@ The firmware itself is unauthenticated; `benchpod login` is independent of the device path and authenticates with `embeddedci-server` (device-login flow) for cloud features. Direct firmware commands on the network or USB do not send tokens. -**USB networking (firmware 3.9.0+).** The pod's USB device is also a network -adapter that carries the full network API on a fixed address (`10.237.x.y`, its own -point-to-point link: the computer keeps its default route and DNS). With a USB -connection (`usb` or a device path), a command that needs the network uses that -adapter, so the whole CLI works over one USB cable; the console is still used for -the commands it runs (below) and as the fallback. USB networking is off while Wi-Fi -is configured on the pod (`set-wifi` turns it off, `clear-wifi` back on). If a +**USB networking.** The pod's USB device is also a network adapter that carries the +full network API on a fixed address (`10.237.x.y`, its own point-to-point link: the +computer keeps its default route and DNS, and the link is plaintext 8080). With a USB +connection (`usb` or a device path) every pod command sends its JSON over that adapter, +so the whole CLI works over one USB cable. The USB console is only used for what firmware +4.0 keeps there: `status`, `dfu`, `identity`, `lan-policy`, `usb-network` and +`net-reset`. USB networking is off while Wi-Fi is configured on the pod (`set-wifi` turns +it off; `clear-wifi` over the pod's network address, or `net-reset` over USB, back on) or +when its `usb-network` setting is off (`benchpod usb-network on --connection usb`). If a command says the adapter is not up, unlock the screen (macOS ignores a new adapter while it is locked) and run `benchpod usb-reattach`. `benchpod usb-bridge` carries the pod's cloud link over the same cable. @@ -199,22 +201,20 @@ WSL2 and Docker on Windows are not tested: Windows routes the pod's `10.237.x.y` itself, so a WSL2 distribution or a container on the host network should reach it with `--connection `, but USB auto-detect and mDNS may not work from inside them. -**Compatibility with older firmware and older CLIs.** The CLI decides per pod, from what -the pod reports (the `usb` line of its console `status`), never from its own version: - -| | Pod firmware before 3.9.0 | Pod firmware 3.9.0 and later | -|---|---|---| -| **This CLI (0.6.0+)** | Works as before: the USB console for `status`, `la voltage`, `flash-self`, `set-wifi`, the policies, `cloud ca`/`proxy` and `identity` (not `install-blobs`, whose console upload CLI 0.10 dropped: update the pod with `flash-self`); the network commands need the pod's network address, as before, and say so. The serial auto-detect still finds `0483:5740` and `2E8A` consoles. | Over `usb`, every command uses the pod's USB network adapter when it is up (including `flash`, which the STM32 pod's console never ran), and the console for the commands that stay there. When USB networking is off (Wi-Fi configured) or not up, the network commands use the pod's Ethernet or Wi-Fi address from its console `status` if this computer reaches it, say so, and are subject to the pod's external LAN policy there (`benchpod clear-wifi` turns USB networking back on). | -| **An older CLI (0.5.x)** | Unchanged. | The kept console commands keep their names and replies (`status`, `dfu`, `identity`, `identity wipe`, `lan-policy`, `sig-policy`, `set-wifi`, `show-network`, `clear-wifi`, `cloud ca show`/`clear`, `cloud proxy`), so those still work, and `flash-self` still flashes over DFU. What 3.9.0 moved to the network API (`la voltage` over USB, and every upload: `install-blobs`, the blob step of `flash-self` and `set-wifi`, `cloud ca set`) prints the pod's "moved to the network API ... update the benchpod CLI to 0.6.0 or later" line: update the CLI with the firmware. Over a network address everything works. | +**Firmware 3.x.** This CLI drives firmware 4.0. Against a pod with firmware 3.x it runs only +what upgrades or inspects the pod: `status`, `flash-self`, `install-blobs` (firmware 3.9.0 +and later), `dfu`, `bootsel`, `discover` and `identity`; every other command stops with exit +code `7` and `this pod needs firmware 4.0: benchpod flash-self`. See +[Firmware and CLI levels](#firmware-and-cli-levels). CLI 0.9 keeps working with firmware 3.x. Which command works over which connection: | Connection | Commands | |---------------------|----------| -| Network address | Every pod command except the USB-only ones below. | -| USB | With firmware 3.9.0+ and no Wi-Fi configured, every network command over the pod's USB network adapter, including `status`, `la voltage`, `flash` (SWD), `install-blobs`, `cloud ca` and `cloud proxy`; without it the pod's Ethernet or Wi-Fi address, and the console where it still has the command. Firmware before 3.9.0: the console, as before. `lan-policy`, `sig-policy` and `identity` always use the console (physical presence). | -| `embeddedci:` | `flash-self`, `status`, `ping`, `la voltage`, `la pull`, `la pullup`, `la status`, `la step`, `la pins`, `la dir`, `i2c`, `generate`, `lan-policy`, `sig-policy`, `cloud ca show`, `cloud ca clear`, `cloud proxy` (show, set, clear), `deregister`. | -| USB only | `set-wifi`, `show-network`, `scan-wifi`, `clear-wifi`, `identity`, `install-blobs`, `bootsel`, `dfu`, `usb-bridge`, `usb-reattach`; `flash-self` uses USB DFU (or, with `--connection embeddedci:`, embeddedci.com). These always use the USB console: a saved address or `embeddedci:` default falls through to USB auto-detection, a device path still selects the port, and an explicit `--connection embeddedci:` is refused. | +| Network address | Every pod command except the USB console ones below. Settings the pod changes only over USB or the cloud (`lan-tls` switches, `cloud ca`/`proxy` changes, `identity wipe`, `usb-network`) are refused there with their code. | +| USB | Every pod command, as JSON over the pod's USB network adapter. With USB networking off (Wi-Fi configured), the pod's Ethernet or Wi-Fi address from its console `status` when this computer reaches it (its external LAN policy applies there), and the command says so. | +| `embeddedci:` | `flash-self`, `status`, `ping`, `la voltage`, `la pull`, `la pullup`, `la status`, `la step`, `la pins`, `la dir`, `i2c`, `generate`, `lan-policy`, `sig-policy`, `cloud ca show`, `cloud ca clear`, `cloud proxy` (show, set, clear), `set-wifi`, `show-network`, `scan-wifi`, `clear-wifi`, `deregister`. | +| USB console only | `dfu`, `bootsel`, `net-reset`, `usb-network`, `usb-bridge`, `lan-policy set` over USB; `flash-self` uses USB DFU (or, with `--connection embeddedci:`, embeddedci.com). A saved address or `embeddedci:` default falls through to USB auto-detection, a device path still selects the port, and an explicit `--connection embeddedci:` is refused. | A command that cannot use the connection it is given says so and names what to use instead. @@ -353,13 +353,14 @@ benchpod la dir 9,10 dut_output # the pod refuses push-pull dr benchpod i2c start --sda 1 --scl 2 --hz 400000 # the pod as an I2C master (gateware v55+) benchpod i2c xfer 0x48 --write 0d --read 2 # hex in, hex out -# Network (always over the USB console): +# Network (over the pod's USB network adapter): benchpod set-wifi benchpod show-network # the pod's IP (wired lease included), SSID, state, RSSI -benchpod scan-wifi # networks the pod's Wi-Fi sees (firmware 3.9.4+) +benchpod scan-wifi # networks the pod's Wi-Fi sees benchpod clear-wifi +benchpod net-reset # no network reaches the pod: forget Wi-Fi, reset Ethernet (USB console) -# One USB cable (firmware 3.9.0+, no Wi-Fi configured): +# One USB cable (no Wi-Fi configured): benchpod capture --connection usb ... # network commands use the pod's USB network adapter benchpod usb-bridge # the pod's cloud link through this computer (Ctrl-C stops it) benchpod usb-reattach # re-enumerate on USB (macOS: after unlocking the screen) @@ -1908,14 +1909,19 @@ Reboot a (retired) RP2350 pod into its UF2 bootloader (USB). ### `benchpod set-wifi` -Save Wi-Fi credentials and join (USB). With firmware 3.9.0+ this turns the pod's USB networking off (Wi-Fi and USB networking are one or the other; `clear-wifi` turns it back on). Installs the ESP32-C3 image first when the -pod lacks it; if the pod's image slots cannot be read, it stops and says so -(`--skip-blobs` sets Wi-Fi without the check). +Save Wi-Fi credentials and join. The CLI sends them as JSON (`wifi_set`) over the pod's USB +network adapter (or the `--connection` given: a network address or `embeddedci:`). +Wi-Fi and USB networking are one or the other: once the credentials are stored, USB networking +turns off, and set-wifi follows the join on the address the pod's console reports. `clear-wifi` +over the pod's network address, or `net-reset` over USB, turns it back on. Installs the +ESP32-C3 image first when the pod lacks it; if the pod's image slots cannot be read, it stops +and says so (`--skip-blobs` sets Wi-Fi without the check). With USB networking off, +`benchpod usb-network on --connection usb` turns it back on. -With a Wi-Fi bridge on the pod's Ethernet port (firmware with bridge support), the -credentials go to the bridge instead (the pod sends the password sealed), no ESP32-C3 -image is needed, and set-wifi waits up to 45 s for the bridge to join: it reports a -wrong password or a network the bridge cannot see. The pod keeps its Ethernet address. +With a Wi-Fi bridge on the pod's Ethernet port, the credentials go to the bridge instead (the +pod sends the password sealed), no ESP32-C3 image is needed, USB networking stays on, and +set-wifi waits up to 45 s for the bridge to join: it reports a wrong password or a network the +bridge cannot see. The pod keeps its Ethernet address. | Flag | Default | Purpose | |--------------------|------------|-----------------------------------------------------------| @@ -1926,26 +1932,38 @@ wrong password or a network the bridge cannot see. The pod keeps its Ethernet ad ### `benchpod show-network` -The pod's IP (the wired lease first) plus the stored Wi-Fi SSID, state and RSSI -(USB). With a Wi-Fi bridge, `Via:` names it (MAC, firmware, paired or not), State is -the bridge's (`joining`, `connected`, `auth-failed`, `no-ap`, ...) and `Problem:` says -what the pod sees wrong with it. No flags. +The pod's IP (the wired lease first) plus the stored Wi-Fi SSID, state and RSSI (`status` and +`wifi_status` over the pod's USB network adapter, or the `--connection` given). With a Wi-Fi +bridge, `Via: wifi-bridge`, State is the bridge's (`joining`, `connected`, `auth-failed`, +`no-ap`, ...) and `Problem:` says what the pod sees wrong with it. No flags. ### `benchpod scan-wifi` -List the Wi-Fi networks the pod sees, strongest first: RSSI, channel, security and SSID, -to pick one for `set-wifi` (USB). The pod scans with its built-in Wi-Fi (firmware 3.9.4 or -later), or with a Wi-Fi bridge on its Ethernet port when one is plugged in. A scan takes a few -seconds; a pod that is joined to a network stays joined, and a pod that is joining finishes -that first (up to 30 seconds). No flags. - -On older firmware the pod cannot scan, but it can still join a network: the command says so, -suggests `benchpod flash-self` and `benchpod set-wifi --ssid `, and exits 0. -It fails only on a pod with no Wi-Fi at all. +List the Wi-Fi networks the pod sees, strongest first: RSSI, channel, security and SSID, to pick +one for `set-wifi` (`wifi_scan` over the pod's USB network adapter, or the `--connection` +given). The pod scans with its built-in Wi-Fi, or with a Wi-Fi bridge on its Ethernet port when +one is plugged in. A scan takes a few seconds; a pod that is joined to a network stays joined, +and a pod that is joining finishes that first (up to 30 seconds). No flags. ### `benchpod clear-wifi` -Erase the stored Wi-Fi credentials (USB). Wi-Fi goes down at once, no reboot needed, and USB networking (firmware 3.9.0+) comes back on. Firmware after 3.7.0 also erases the copy older firmware left on the ESP32-C3 Wi-Fi chip, which takes a few seconds more. No flags. +Erase the stored Wi-Fi credentials (`wifi_clear`). Wi-Fi goes down at once, no reboot needed, +and USB networking comes back on. The pod also erases the copy older firmware left on the +ESP32-C3 Wi-Fi chip, which takes a few seconds more. Over USB the CLI uses the pod's USB network +adapter, else (it is off while Wi-Fi is set) the pod's network address from its console. When no +network reaches the pod, use `benchpod net-reset`. No flags. + +### `benchpod net-reset` + +The way back to a pod that no network reaches (firmware 4.0, over the USB console): the pod +forgets its Wi-Fi credentials (its own flash and the ESP32-C3's, or the Wi-Fi bridge's), which +turns USB networking back on, and puts Ethernet back to autonegotiation with a PHY reset and a +new DHCP lease. The LAN and signature policies, the cloud settings and the device key stay. It +prints the pod's `net-reset` lines. + +| Flag | Default | Purpose | +|---------|---------|--------------------------------| +| `--yes` | off | Skip the confirmation prompt. | ### `benchpod usb-bridge` diff --git a/cmd/benchpod-cli/commands_serial.go b/cmd/benchpod-cli/commands_serial.go index 5537733..9c2852d 100644 --- a/cmd/benchpod-cli/commands_serial.go +++ b/cmd/benchpod-cli/commands_serial.go @@ -2,349 +2,19 @@ package main import ( "bufio" - "context" "errors" "fmt" "os" "strings" "time" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/spf13/cobra" ) -// The commands in this file always use the firmware's USB CDC-ACM serial -// console — you cannot provision WiFi or trigger the bootloader over the -// network. They therefore ignore the wifi/serial choice of --connection and -// only honor an explicit device path from it (g.serialDevice()), falling -// back to auto-detection (USB VID 2E8A) otherwise. - -// ── set-wifi ───────────────────────────────────────────────────────────────── - -func newSetWifiCmd(g *globalFlags) *cobra.Command { - var ssid, password string - var passwordStdin, skipBlobs bool - cmd := &cobra.Command{ - Use: "set-wifi", - Short: "Save WiFi credentials and join (over the pod's USB console)", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - if strings.TrimSpace(ssid) == "" { - return errors.New("--ssid is required") - } - pw, err := resolveWifiPassword(password, passwordStdin) - if err != nil { - return fmt.Errorf("set-wifi: %w", err) - } - _, err = runSetWifi(g, ssid, pw, skipBlobs) - return err - }, - } - cmd.Flags().StringVar(&ssid, "ssid", "", "WiFi SSID (required)") - cmd.Flags().StringVar(&password, "password", "", "WiFi password (insecure: visible in shell history); omit to be prompted") - cmd.Flags().BoolVar(&passwordStdin, "password-stdin", false, "read the WiFi password from the first line of stdin") - cmd.Flags().BoolVar(&skipBlobs, "skip-blobs", false, "do not install a missing ESP32-C3 image first (not needed through a Wi-Fi bridge)") - return cmd -} - -// runSetWifi saves Wi-Fi credentials over the USB console and joins, returning the pod's -// address when the join is confirmed ("" when it is not). Shared by set-wifi and setup. -func runSetWifi(g *globalFlags, ssid, pw string, skipBlobs bool) (string, error) { - // wifi-set runs the full reconnect ladder on the device: probe the - // internal modem (with an EN-reset retry), then the external GPIO40/41 - // modem, then AT+CWJAP (up to ~15s) and TCP bring-up. That can take - // ~40s, so wait generously — the command returns as soon as the prompt - // reappears, this is only the upper bound. Override with --timeout. - device, err := g.usbDevice("set-wifi") - if err != nil { - return "", err - } - console, path, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(90*time.Second)) - if err != nil { - return "", err - } - defer cancel() - defer console.Close() - - // A Wi-Fi bridge on the pod's Ethernet port carries Wi-Fi instead of the ESP32-C3: it keeps - // the credentials itself and joins in the background. - before, _ := console.WifiShow(ctx) - if before.ViaBridge() { - return setWifiThroughBridge(ctx, console, path, ssid, pw) - } - - // Wi-Fi runs on the ESP32-C3, whose image the pod keeps in its W25Q: a pod without - // it (fresh board, no network) can only get it over this cable. - if !skipBlobs { - if err := ensureEspBlob(console); err != nil { - return "", fmt.Errorf("set-wifi: %w", err) - } - } - - res, err := console.WifiSet(ctx, ssid, pw) - // Echo the firmware's WiFi/TCP/ESP32 bring-up lines (incl. the - // "[wifi] connected ip=" result) so the IP is visible — even - // when the join didn't confirm. - for _, line := range serialconsole.BringupLines(res.Raw) { - fmt.Fprintf(os.Stderr, " %s\n", line) - } - if err != nil { - return "", fmt.Errorf("set-wifi: %w", err) - } - fmt.Fprintf(os.Stderr, "Wrote WiFi credentials for SSID %q via %s.\n", ssid, path) - - // Read the authoritative state back with wifi-show: the reconnect's - // "[wifi] connected ip=" line can be lost in the device's non-blocking - // USB console output, so don't rely on it alone to report the result. - st, _ := console.WifiShow(ctx) - ip := st.IP - if ip == "" { - ip = res.IP - } - state := strings.ToLower(st.State) - joined := res.Joined || ip != "" && ip != "(none)" || - strings.Contains(state, "ready") || strings.Contains(state, "connected") - if !joined { - fmt.Fprintln(os.Stderr, "Credentials saved; join not confirmed (run `benchpod show-network`).") - return "", nil - } - fmt.Fprintf(os.Stderr, "Joined %q, ip=%s\n", ssid, valueOrDash(ip)) - if ip == "(none)" || ip == "0.0.0.0" { - ip = "" - } - return ip, nil -} - -// bridgeJoinWait bounds how long set-wifi watches a Wi-Fi bridge join: it reports its state -// every few seconds and a WPA2/WPA3 join takes a few seconds more. -var bridgeJoinWait = 45 * time.Second - -// setWifiThroughBridge saves the credentials on the pod's Wi-Fi bridge (the pod seals the -// password for it) and waits for the bridge to join or fail. The pod's address does not change: -// the bridge carries its Ethernet traffic, so the IP is the one it already has. -func setWifiThroughBridge(ctx context.Context, console *serialconsole.Console, path, ssid, pw string) (string, error) { - if _, err := console.WifiSet(ctx, ssid, pw); err != nil { - return "", fmt.Errorf("set-wifi: %w", err) - } - fmt.Fprintf(os.Stderr, "Saved Wi-Fi credentials for SSID %q on the pod's Wi-Fi bridge via %s; waiting for it to join...\n", ssid, path) - deadline := time.Now().Add(bridgeJoinWait) - var st serialconsole.WifiStatus - for { - st, _ = console.WifiShow(ctx) - current := st.BridgeReports(ssid) - if current && st.BridgeJoined() { - ip := st.IP - if ip == "(none)" || ip == "0.0.0.0" { - ip = "" - } - fmt.Fprintf(os.Stderr, "The Wi-Fi bridge joined %q (rssi %s), pod ip=%s\n", ssid, valueOrDash(st.RSSI), valueOrDash(ip)) - return ip, nil - } - if why := st.BridgeJoinFailure(); current && why != "" { - return "", fmt.Errorf("set-wifi: %s (the credentials are saved on the bridge; run set-wifi again to change them)", why) - } - if time.Now().After(deadline) || ctx.Err() != nil { - break - } - select { - case <-ctx.Done(): - case <-time.After(3 * time.Second): - } - } - fmt.Fprintf(os.Stderr, "Credentials saved; the Wi-Fi bridge has not joined yet (state %s; run `benchpod show-network`).\n", valueOrDash(st.State)) - return "", nil -} - -// ensureEspBlob installs the blobs from the pod's firmware release when its ESP32-C3 slot is -// empty or holds a different image, so set-wifi works on a pod that has never had a network. -func ensureEspBlob(console *serialconsole.Console) error { - ctx, cancel := context.WithTimeout(context.Background(), blobsInstallTimeout) - defer cancel() - // Before Wi-Fi is set the pod's USB network is still on (firmware 3.9.0+): use it when up. - target, closeTarget, err := blobTargetFor(ctx, console, "the USB console") - if err != nil { - return err - } - defer closeTarget() - slots, err := target.Blobs(ctx) - missing, err := espBlobMissing(slots, err) - if err != nil || !missing { - return err - } - fmt.Fprintln(os.Stderr, "set-wifi: the pod has no ESP32-C3 image for Wi-Fi yet; installing it over USB first") - return installBlobs(ctx, target, releaseBlobSource(target.Release(ctx)), false, nil) -} - -// espBlobMissing reads the pod's blob listing for set-wifi: whether the ESP32-C3 image needs -// installing. Firmware without blob slots keeps the image built in, which is fine; any other -// error reading the slots is reported, with --skip-blobs as the way past it. -func espBlobMissing(slots []serialconsole.BlobSlot, err error) (bool, error) { - if errors.Is(err, serialconsole.ErrNoBlobSlots) { - return false, nil - } - if err != nil { - return false, fmt.Errorf("check the pod's ESP32-C3 image: %w (pass --skip-blobs to set Wi-Fi without the check)", err) - } - for _, s := range slots { - if s.Name == "esp" && s.NeedsInstall() { - return true, nil - } - } - return false, nil -} - -// ── show-network ───────────────────────────────────────────────────────────── - -// newShowNetworkCmd reports the pod's network state. It is named for what it -// reports rather than for one of the interfaces it can report on: the IP is -// whichever address the pod is actually using, and the pod prefers its wired -// Ethernet lease, so on a cabled pod this prints an address and no SSID at all. -// (It was called show-wifi, which described only the minority case.) -func newShowNetworkCmd(g *globalFlags) *cobra.Command { - return &cobra.Command{ - Use: "show-network", - Short: "Show the pod's network details: IP, plus stored SSID/state/RSSI (over the pod's USB console)", - Long: "Report the pod's network state over the pod's USB console.\n\n" + - "The IP is whichever address the pod is actually using: it prefers the wired\n" + - "Ethernet lease over Wi-Fi, so a pod on a cable reports an address here with no\n" + - "SSID at all. The SSID/state/RSSI fields describe the optional Wi-Fi interface.", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("show-network") - if err != nil { - return err - } - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(15*time.Second)) - if err != nil { - return err - } - defer cancel() - defer console.Close() - - st, err := console.WifiShow(ctx) - if err != nil { - return fmt.Errorf("show-network: %w", err) - } - out, closeOut, err := resolveOutput(g.outputFilename) - if err != nil { - return fmt.Errorf("show-network: open output: %w", err) - } - defer closeOut() - // IP first: it is the field that matters on any pod, and it is - // populated on a wired pod that has no SSID at all. - fmt.Fprintf(out, "IP: %s\n", valueOrDash(st.IP)) - fmt.Fprintf(out, "SSID: %s\n", valueOrDash(st.SSID)) - fmt.Fprintf(out, "State: %s\n", valueOrDash(st.State)) - fmt.Fprintf(out, "RSSI: %s\n", valueOrDash(st.RSSI)) - if st.Via != "" { - fmt.Fprintf(out, "Via: %s\n", st.Via) - } - if st.Problem != "" { - fmt.Fprintf(out, "Problem: %s\n", st.Problem) - } - return nil - }, - } -} - -// ── scan-wifi ──────────────────────────────────────────────────────────────── - -// newScanWifiCmd lists the networks the pod's Wi-Fi sees, to pick the SSID for set-wifi. -func newScanWifiCmd(g *globalFlags) *cobra.Command { - return &cobra.Command{ - Use: "scan-wifi", - Short: "List the Wi-Fi networks the pod sees (over the pod's USB console)", - Long: "List the Wi-Fi networks the pod sees, strongest first, to pick the SSID for set-wifi.\n" + - "The pod scans with its built-in Wi-Fi (firmware 3.9.4 or later), or with a Wi-Fi bridge on\n" + - "its Ethernet port when one is plugged in. A scan takes a few seconds; a joined pod stays\n" + - "joined. On older firmware the command says so and how to join a network anyway (exit 0).", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("scan-wifi") - if err != nil { - return err - } - // 45 s: a pod that is joining waits for the join to finish (up to 30 s) before it scans. - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(45*time.Second)) - if err != nil { - return err - } - defer cancel() - defer console.Close() - - nets, err := console.WifiScan(ctx) - if errors.Is(err, serialconsole.ErrNoWifiScan) { - return scanWifiUnsupported(ctx, console) - } - if err != nil { - return fmt.Errorf("scan-wifi: %w", err) - } - out, closeOut, err := resolveOutput(g.outputFilename) - if err != nil { - return fmt.Errorf("scan-wifi: open output: %w", err) - } - defer closeOut() - fmt.Fprintf(out, "%-6s %-4s %-10s %s\n", "RSSI", "CH", "SECURITY", "SSID") - for _, n := range nets { - ssid := n.SSID - if ssid == "" { - ssid = "(hidden)" - } - fmt.Fprintf(out, "%-6d %-4d %-10s %s\n", n.RSSI, n.Channel, n.Auth, ssid) - } - fmt.Fprintf(os.Stderr, "%d networks\n", len(nets)) - return nil - }, - } -} - -// scanWifiUnsupported answers scan-wifi on firmware that cannot scan: not an error when the pod -// has built-in Wi-Fi (it can still join a network), an error when it has no Wi-Fi at all. -func scanWifiUnsupported(ctx context.Context, console *serialconsole.Console) error { - st, err := console.WifiShow(ctx) - if err != nil || st.State == "" { - return errors.New("scan-wifi: this pod has no Wi-Fi") - } - fmt.Println("This pod has built-in Wi-Fi, but its firmware cannot scan for networks:" + - " scanning needs firmware 3.9.4 or later (update with `benchpod flash-self`).") - fmt.Println("To join a network now: benchpod set-wifi --ssid ") - return nil -} - -// ── clear-wifi ─────────────────────────────────────────────────────────────── - -// clearWifiTimeout covers the C3 NVS erase that wifi-clear runs before it answers. 10 s was too -// short: the CLI gave up on pods that were still erasing (2026-10-15). -const clearWifiTimeout = 60 * time.Second - -func newClearWifiCmd(g *globalFlags) *cobra.Command { - return &cobra.Command{ - Use: "clear-wifi", - Short: "Erase the stored Wi-Fi credentials (Wi-Fi goes down at once)", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("clear-wifi") - if err != nil { - return err - } - // The pod answers once it has also erased the ESP32-C3's NVS over the C3's ROM - // loader: about 3 s, and up to half a minute when the C3 is slow to answer. - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(clearWifiTimeout)) - if err != nil { - return err - } - defer cancel() - defer console.Close() - - if err := console.WifiClear(ctx); err != nil { - return fmt.Errorf("clear-wifi: %w", err) - } - fmt.Fprintln(os.Stderr, "Erased the stored Wi-Fi credentials. Wi-Fi is off; no reboot needed. "+ - "USB networking is on again (firmware 3.9.0+).") - return nil - }, - } -} +// The commands in this file always use the firmware's USB serial console: the +// bootloader cannot be reached over the network. They ignore a network choice +// of --connection and only honor an explicit device path from it +// (g.serialDevice()), falling back to auto-detection otherwise. // ── bootsel ────────────────────────────────────────────────────────────────── @@ -427,3 +97,10 @@ func newDfuCmd(g *globalFlags) *cobra.Command { cmd.Flags().BoolVar(&yes, "yes", false, "skip the confirmation prompt") return cmd } + +// confirmYes asks on stderr and reads stdin; only "yes" goes ahead. +func confirmYes(prompt string) bool { + fmt.Fprint(os.Stderr, prompt) + line, _ := bufio.NewReader(os.Stdin).ReadString('\n') + return strings.TrimSpace(line) == "yes" +} diff --git a/cmd/benchpod-cli/root.go b/cmd/benchpod-cli/root.go index 3de5d12..491095c 100644 --- a/cmd/benchpod-cli/root.go +++ b/cmd/benchpod-cli/root.go @@ -139,7 +139,7 @@ func newRootCmd() *cobra.Command { }{ {"setup", "Setup:", []*cobra.Command{ newSetupCmd(g), newDiscoverCmd(g), newSetConnectionCmd(g), - newSetWifiCmd(g), newShowNetworkCmd(g), newScanWifiCmd(g), newClearWifiCmd(g), + newSetWifiCmd(g), newShowNetworkCmd(g), newScanWifiCmd(g), newClearWifiCmd(g), newNetResetCmd(g), newUSBBridgeCmd(g), newUSBReattachCmd(g), }}, {"pod", "The pod:", []*cobra.Command{ diff --git a/cmd/benchpod-cli/usbnet.go b/cmd/benchpod-cli/usbnet.go index e811097..640dc4b 100644 --- a/cmd/benchpod-cli/usbnet.go +++ b/cmd/benchpod-cli/usbnet.go @@ -7,6 +7,7 @@ import ( "io" "net" "os" + "strings" "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" @@ -180,6 +181,42 @@ func (g *globalFlags) networkTarget(cmd string) (ConnSpec, error) { if err != nil || !spec.IsSerial() { return spec, err } + return g.networkTargetFor(spec, cmd) +} + +// usbNetworkTarget is the pod's API for the commands that used to run on the USB console and now +// send JSON over the pod's USB network adapter (set-wifi, show-network, identity wipe, ...): an +// explicit network or embeddedci.com --connection is used as given; otherwise the pod on USB (a +// saved network default falls through to USB, as these commands always did), its USB network +// adapter, else its network address when that answers. +func (g *globalFlags) usbNetworkTarget(cmd string) (ConnSpec, error) { + if raw := strings.TrimSpace(g.connection); raw != "" { + if spec, err := parseTarget(raw); err == nil && !spec.IsSerial() { + return spec, nil + } + } + spec := ConnSpec{Kind: connSerial, Device: g.serialDevice(), Pod: g.usbPodName()} + return g.networkTargetFor(spec, cmd) +} + +// usbNetworkClient is podClient for usbNetworkTarget. +func (g *globalFlags) usbNetworkClient(cmd string, def time.Duration) (context.Context, context.CancelFunc, *podTarget, error) { + spec, err := g.usbNetworkTarget(cmd) + if err != nil { + return nil, func() {}, nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(def)) + cancel = withSignalCleanup(cancel, installSignalHandler(ctx, cancel)) + t, err := openPodTarget(ctx, spec) + if err != nil { + cancel() + return nil, func() {}, nil, fmt.Errorf("%s: %w", cmd, err) + } + return ctx, cancel, t, nil +} + +// networkTargetFor is networkTarget for a USB spec. +func (g *globalFlags) networkTargetFor(spec ConnSpec, cmd string) (ConnSpec, error) { if g.usbAddr != "" { return ConnSpec{Kind: connNetwork, Addr: g.usbAddr}, nil } diff --git a/cmd/benchpod-cli/wifi.go b/cmd/benchpod-cli/wifi.go new file mode 100644 index 0000000..d701807 --- /dev/null +++ b/cmd/benchpod-cli/wifi.go @@ -0,0 +1,517 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "strconv" + "strings" + "time" + + "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" + "github.com/spf13/cobra" +) + +// ── Wi-Fi over JSON ───────────────────────────────────────────────────────── +// +// set-wifi, show-network, scan-wifi and clear-wifi send the pod's JSON commands (wifi_set, +// wifi_status, wifi_scan, wifi_clear) over its USB network adapter (usbNetworkTarget): firmware +// 4.0 has no Wi-Fi commands on its console. Wi-Fi and USB networking are one or the other on the +// pod: wifi_set turns USB networking off (its reply still goes out over it), wifi_clear turns it +// back on. When no network reaches the pod at all, the console's `net-reset` (benchpod net-reset) +// forgets the Wi-Fi. + +// wifiState is the part of the pod's wifi_status reply the CLI reads. +type wifiState struct { + State string `json:"state"` + Configured bool `json:"configured"` + Connected bool `json:"connected"` + SSID string `json:"ssid"` + Via string `json:"via"` // "wifi-bridge" when a Wi-Fi bridge on the Ethernet port carries Wi-Fi + RSSI *int `json:"rssi_dbm"` + Bridge *struct { + Paired bool `json:"paired"` + Problem *string `json:"problem"` + RSSI *int `json:"rssi_dbm"` + } `json:"bridge"` +} + +func (s wifiState) viaBridge() bool { return s.Via == "wifi-bridge" } + +// rssi is the signal of the link that carries Wi-Fi ("" when not joined). +func (s wifiState) rssi() string { + r := s.RSSI + if s.viaBridge() && s.Bridge != nil { + r = s.Bridge.RSSI + } + if r == nil { + return "" + } + return strconv.Itoa(*r) + " dBm" +} + +// problem is what the pod sees wrong with its Wi-Fi bridge, "" if nothing. +func (s wifiState) problem() string { + if s.Bridge != nil && s.Bridge.Problem != nil { + return *s.Bridge.Problem + } + return "" +} + +// bridgeJoinFailure is why the bridge cannot join, "" while it is joining or has joined. +func (s wifiState) bridgeJoinFailure() string { + switch s.State { + case "auth-failed": + return "the Wi-Fi bridge could not join: wrong password (or the network refused it)" + case "no-ap": + return "the Wi-Fi bridge could not join: it does not see that network" + } + return "" +} + +// joined says the pod (or its bridge) is joined to ssid. +func (s wifiState) joined(ssid string) bool { + return (s.Connected || s.State == "connected") && strings.TrimSpace(s.SSID) == strings.TrimSpace(ssid) +} + +func readWifi(ctx context.Context, c podCommander) (wifiState, error) { + var st wifiState + raw, err := c.Command(ctx, map[string]any{"cmd": "wifi_status"}) + if err != nil { + return st, err + } + if err := json.Unmarshal(raw, &st); err != nil { + return st, fmt.Errorf("wifi_status: unexpected reply %s", strings.TrimSpace(string(raw))) + } + return st, nil +} + +// podIP is the pod's Ethernet (else Wi-Fi) address from its status, "" when it has none. +func podIP(ctx context.Context, c podCommander) string { + raw, err := c.Command(ctx, map[string]any{"cmd": "status", "caps": false}) + if err != nil { + return "" + } + var st struct { + IP string `json:"ip"` + } + if json.Unmarshal(raw, &st) != nil { + return "" + } + return usableIP(st.IP) +} + +func usableIP(ip string) string { + ip = strings.TrimSpace(ip) + if p := net.ParseIP(ip); p == nil || p.IsUnspecified() { + return "" + } + return ip +} + +// ── set-wifi ───────────────────────────────────────────────────────────────── + +func newSetWifiCmd(g *globalFlags) *cobra.Command { + var ssid, password string + var passwordStdin, skipBlobs bool + cmd := &cobra.Command{ + Use: "set-wifi", + Short: "Save Wi-Fi credentials and join (over the pod's USB network adapter)", + Long: "Save Wi-Fi credentials on the pod and wait for it to join. The CLI sends them\n" + + "over the pod's USB network adapter (wifi_set). Wi-Fi and USB networking are one or\n" + + "the other on the pod: once the credentials are stored, USB networking turns off\n" + + "(`benchpod clear-wifi` over the pod's network address, or `benchpod net-reset`\n" + + "over USB, turns it back on). With a Wi-Fi bridge on the pod's Ethernet port the\n" + + "bridge keeps them and USB networking stays on.\n\n" + + "USB networking off: `benchpod usb-network on --connection usb` (the pod's\n" + + "console `usb-network on`).", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + if strings.TrimSpace(ssid) == "" { + return usageErrorf("--ssid is required") + } + pw, err := resolveWifiPassword(password, passwordStdin) + if err != nil { + return fmt.Errorf("set-wifi: %w", err) + } + _, err = runSetWifi(g, ssid, pw, skipBlobs) + return err + }, + } + cmd.Flags().StringVar(&ssid, "ssid", "", "Wi-Fi SSID (required)") + cmd.Flags().StringVar(&password, "password", "", "Wi-Fi password (insecure: visible in shell history); omit to be prompted") + cmd.Flags().BoolVar(&passwordStdin, "password-stdin", false, "read the Wi-Fi password from the first line of stdin") + cmd.Flags().BoolVar(&skipBlobs, "skip-blobs", false, "do not install a missing ESP32-C3 image first (not needed through a Wi-Fi bridge)") + return cmd +} + +// wifiJoinWait bounds how long set-wifi waits for the pod (or its bridge) to join; wifiJoinPoll is +// how often it asks. Variables for the tests. +var ( + wifiJoinWait = 45 * time.Second + wifiJoinPoll = 3 * time.Second +) + +// runSetWifi saves Wi-Fi credentials over the pod's network API and waits for the join, returning +// the pod's address when the join is confirmed ("" when it is not). Shared by set-wifi and setup. +func runSetWifi(g *globalFlags, ssid, pw string, skipBlobs bool) (string, error) { + ctx, cancel, t, err := g.usbNetworkClient("set-wifi", 90*time.Second) + if err != nil { + return "", err + } + defer cancel() + + before, err := readWifi(ctx, t.client) + if err != nil { + return "", wifiError("set-wifi", err) + } + // Wi-Fi runs on the ESP32-C3, whose image the pod keeps in its W25Q: a pod without it (fresh + // board, no network) can only get it over USB. + if !before.viaBridge() && !skipBlobs && t.spec.IsNetwork() { + if err := ensureEspBlob(ctx, t.spec.Addr); err != nil { + return "", fmt.Errorf("set-wifi: %w", err) + } + } + raw, err := t.client.Command(ctx, map[string]any{"cmd": "wifi_set", "ssid": ssid, "password": pw}) + if err != nil { + return "", wifiError("set-wifi", err) + } + var rep struct { + Via string `json:"via"` + } + _ = json.Unmarshal(raw, &rep) + bridge := before.viaBridge() || rep.Via == "wifi-bridge" + if bridge { + fmt.Fprintf(os.Stderr, "Saved Wi-Fi credentials for SSID %q on the pod's Wi-Fi bridge via %s; waiting for it to join...\n", ssid, t.label) + } else { + fmt.Fprintf(os.Stderr, "Saved Wi-Fi credentials for SSID %q via %s; waiting for the pod to join "+ + "(USB networking turns off now)...\n", ssid, t.label) + } + return waitWifiJoin(ctx, g, t, ssid, bridge) +} + +// waitWifiJoin follows the join: over the connection the credentials went over while it still +// works (a bridge, the pod's Ethernet, embeddedci.com), else over the address the pod's console +// status reports once it has one. +func waitWifiJoin(ctx context.Context, g *globalFlags, t *podTarget, ssid string, bridge bool) (string, error) { + deadline := time.Now().Add(wifiJoinWait) + var st wifiState + for { + var c podCommander = t.client + s, err := readWifi(ctx, c) + if err != nil && !bridge { + // The USB link went down with wifi_set: find the pod's new address on its console. + if ip := consolePodIP(g); ip != "" { + c = &tcpclient.Client{Addr: net.JoinHostPort(ip, wifiPodPort), DialTimeout: 2 * time.Second} + s, err = readWifi(ctx, c) + } + } + if err == nil { + st = s + if st.joined(ssid) { + ip := podIP(ctx, c) + if bridge { + fmt.Fprintf(os.Stderr, "The Wi-Fi bridge joined %q (rssi %s), pod ip=%s\n", ssid, valueOrDash(st.rssi()), valueOrDash(ip)) + } else { + fmt.Fprintf(os.Stderr, "Joined %q, ip=%s\n", ssid, valueOrDash(ip)) + } + return ip, nil + } + if why := st.bridgeJoinFailure(); bridge && strings.TrimSpace(st.SSID) == ssid && why != "" { + return "", fmt.Errorf("set-wifi: %s (the credentials are saved on the bridge; run set-wifi again to change them)", why) + } + } + if time.Now().After(deadline) || ctx.Err() != nil { + break + } + select { + case <-ctx.Done(): + case <-time.After(wifiJoinPoll): + } + } + fmt.Fprintf(os.Stderr, "Credentials saved; join not confirmed yet (state %s; run `benchpod show-network`).\n", valueOrDash(st.State)) + return "", nil +} + +// wifiPodPort is the port set-wifi reaches the pod on at its new address (tests change it). +var wifiPodPort = tcpclient.PlainPort + +// consolePodIP is the pod's network address from its USB console's status, "" when it has none +// (or no console answers). A variable so tests can replace it. +var consolePodIP = func(g *globalFlags) string { + pods, _, err := serialconsole.ProbeSerial(g.serialDevice(), 2*time.Second) + if err != nil { + return "" + } + name := g.usbPodName() + for _, p := range pods { + if name != "" && !strings.Contains(p.Status, name) { + continue + } + if p.Addressed() && !usbLinkNet.Contains(net.ParseIP(p.IP)) { + return p.IP + } + } + return "" +} + +// wifiError words a failed Wi-Fi command; a pod without built-in Wi-Fi or a bridge says so itself. +func wifiError(what string, err error) error { + if pe, ok := tcpclient.AsPodError(err); ok { + return refusedError(what, pe) + } + return fmt.Errorf("%s: %w", what, err) +} + +// ensureEspBlob installs the blobs from the pod's firmware release when its ESP32-C3 slot is +// empty or holds a different image, so set-wifi works on a pod that has never had a network. +func ensureEspBlob(ctx context.Context, addr string) error { + ctx, cancel := context.WithTimeout(ctx, blobsInstallTimeout) + defer cancel() + lan, err := openLAN(ctx, addr) + if err != nil { + return fmt.Errorf("check the pod's ESP32-C3 image: %w (pass --skip-blobs to set Wi-Fi without the check)", err) + } + defer lan.s.Close() + target := lanBlobs{lan: lan, addr: addr} + slots, err := target.Blobs(ctx) + missing, err := espBlobMissing(slots, err) + if err != nil || !missing { + return err + } + fmt.Fprintln(os.Stderr, "set-wifi: the pod has no ESP32-C3 image for Wi-Fi yet; installing it over USB first") + return installBlobs(ctx, target, releaseBlobSource(target.Release(ctx)), false, nil) +} + +// espBlobMissing reads the pod's blob listing for set-wifi: whether the ESP32-C3 image needs +// installing. Firmware without blob slots keeps the image built in, which is fine; any other +// error reading the slots is reported, with --skip-blobs as the way past it. +func espBlobMissing(slots []serialconsole.BlobSlot, err error) (bool, error) { + if errors.Is(err, serialconsole.ErrNoBlobSlots) { + return false, nil + } + if err != nil { + return false, fmt.Errorf("check the pod's ESP32-C3 image: %w (pass --skip-blobs to set Wi-Fi without the check)", err) + } + for _, s := range slots { + if s.Name == "esp" && s.NeedsInstall() { + return true, nil + } + } + return false, nil +} + +// ── show-network ───────────────────────────────────────────────────────────── + +// newShowNetworkCmd reports the pod's network state. It is named for what it reports rather than +// for one of the interfaces it can report on: the IP is whichever address the pod is actually +// using, and the pod prefers its wired Ethernet lease, so on a cabled pod this prints an address +// and no SSID at all. +func newShowNetworkCmd(g *globalFlags) *cobra.Command { + return &cobra.Command{ + Use: "show-network", + Short: "Show the pod's network details: IP, plus stored SSID/state/RSSI (over the pod's USB network adapter)", + Long: "Report the pod's network state (status and wifi_status, over the pod's USB\n" + + "network adapter, or the --connection given).\n\n" + + "The IP is whichever address the pod is actually using: it prefers the wired\n" + + "Ethernet lease over Wi-Fi, so a pod on a cable reports an address here with no\n" + + "SSID at all. The SSID/state/RSSI fields describe the optional Wi-Fi interface.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + ctx, cancel, t, err := g.usbNetworkClient("show-network", 15*time.Second) + if err != nil { + return err + } + defer cancel() + st, err := readWifi(ctx, t.client) + if err != nil { + return wifiError("show-network", err) + } + out, closeOut, err := resolveOutput(g.outputFilename) + if err != nil { + return fmt.Errorf("show-network: open output: %w", err) + } + defer closeOut() + printNetwork(out, podIP(ctx, t.client), st) + return nil + }, + } +} + +func printNetwork(out io.Writer, ip string, st wifiState) { + // IP first: it is the field that matters on any pod, and it is populated on a wired pod that + // has no SSID at all. + fmt.Fprintf(out, "IP: %s\n", valueOrDash(ip)) + fmt.Fprintf(out, "SSID: %s\n", valueOrDash(st.SSID)) + fmt.Fprintf(out, "State: %s\n", valueOrDash(st.State)) + fmt.Fprintf(out, "RSSI: %s\n", valueOrDash(st.rssi())) + if st.Via != "" { + fmt.Fprintf(out, "Via: %s\n", st.Via) + } + if p := st.problem(); p != "" { + fmt.Fprintf(out, "Problem: %s\n", p) + } +} + +// ── scan-wifi ──────────────────────────────────────────────────────────────── + +// wifiScanPoll is how often scan-wifi reads a running scan. +var wifiScanPoll = 500 * time.Millisecond + +type wifiNetwork struct { + SSID string `json:"ssid"` + RSSI int `json:"rssi"` + Channel int `json:"channel"` + Auth string `json:"auth"` +} + +// newScanWifiCmd lists the networks the pod's Wi-Fi sees, to pick the SSID for set-wifi. +func newScanWifiCmd(g *globalFlags) *cobra.Command { + return &cobra.Command{ + Use: "scan-wifi", + Short: "List the Wi-Fi networks the pod sees (over the pod's USB network adapter)", + Long: "List the Wi-Fi networks the pod sees, strongest first, to pick the SSID for set-wifi\n" + + "(wifi_scan, over the pod's USB network adapter). The pod scans with its built-in\n" + + "Wi-Fi, or with a Wi-Fi bridge on its Ethernet port when one is plugged in. A scan\n" + + "takes a few seconds; a joined pod stays joined.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + // 45 s: a pod that is joining waits for the join to finish (up to 30 s) before it scans. + ctx, cancel, t, err := g.usbNetworkClient("scan-wifi", 45*time.Second) + if err != nil { + return err + } + defer cancel() + nets, truncated, err := scanWifi(ctx, t.client) + if err != nil { + return wifiError("scan-wifi", err) + } + out, closeOut, err := resolveOutput(g.outputFilename) + if err != nil { + return fmt.Errorf("scan-wifi: open output: %w", err) + } + defer closeOut() + fmt.Fprintf(out, "%-6s %-4s %-10s %s\n", "RSSI", "CH", "SECURITY", "SSID") + for _, n := range nets { + ssid := n.SSID + if ssid == "" { + ssid = "(hidden)" + } + fmt.Fprintf(out, "%-6d %-4d %-10s %s\n", n.RSSI, n.Channel, n.Auth, ssid) + } + msg := fmt.Sprintf("%d networks", len(nets)) + if truncated { + msg += " (weaker ones left out)" + } + fmt.Fprintln(os.Stderr, msg) + return nil + }, + } +} + +// scanWifi starts a scan and reads it until it is done. +func scanWifi(ctx context.Context, c podCommander) ([]wifiNetwork, bool, error) { + var rep struct { + State string `json:"state"` + ID int `json:"id"` + Networks []wifiNetwork `json:"networks"` + Truncated bool `json:"truncated"` + } + req := map[string]any{"cmd": "wifi_scan"} + for { + raw, err := c.Command(ctx, req) + if err != nil { + return nil, false, err + } + if err := json.Unmarshal(raw, &rep); err != nil { + return nil, false, fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(raw))) + } + if rep.State == "done" { + return rep.Networks, rep.Truncated, nil + } + req = map[string]any{"cmd": "wifi_scan", "id": rep.ID} + select { + case <-ctx.Done(): + return nil, false, ctx.Err() + case <-time.After(wifiScanPoll): + } + } +} + +// ── clear-wifi ─────────────────────────────────────────────────────────────── + +// clearWifiTimeout covers the reply; the pod erases the ESP32-C3's NVS after it. +const clearWifiTimeout = 60 * time.Second + +func newClearWifiCmd(g *globalFlags) *cobra.Command { + return &cobra.Command{ + Use: "clear-wifi", + Short: "Erase the stored Wi-Fi credentials (Wi-Fi goes down at once)", + Long: "Erase the pod's stored Wi-Fi credentials (wifi_clear): Wi-Fi goes down and USB\n" + + "networking comes back on. The CLI sends it over the pod's network: its USB network\n" + + "adapter, else (USB networking is off while Wi-Fi is set) its network address, or\n" + + "the --connection given. When no network reaches the pod, `benchpod net-reset`\n" + + "does it over the USB console.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + ctx, cancel, t, err := g.usbNetworkClient("clear-wifi", clearWifiTimeout) + if err != nil { + return fmt.Errorf("%w (without a network, `benchpod net-reset` clears the Wi-Fi over the USB console)", err) + } + defer cancel() + if _, err := t.client.Command(ctx, map[string]any{"cmd": "wifi_clear"}); err != nil { + return wifiError("clear-wifi", err) + } + fmt.Fprintln(os.Stderr, "Erased the stored Wi-Fi credentials. Wi-Fi is off; no reboot needed. USB networking is on again.") + return nil + }, + } +} + +// ── net-reset ──────────────────────────────────────────────────────────────── + +func newNetResetCmd(g *globalFlags) *cobra.Command { + var yes bool + cmd := &cobra.Command{ + Use: "net-reset", + Short: "Forget the Wi-Fi and reset Ethernet over the USB console, when no network reaches the pod", + Long: "Run the pod's console `net-reset` (firmware 4.0): the pod forgets its Wi-Fi\n" + + "credentials (its own flash and the ESP32-C3's, or the Wi-Fi bridge's), which turns\n" + + "USB networking back on, and puts Ethernet back to autonegotiation with a PHY reset\n" + + "and a new DHCP lease. The policies, the cloud settings and the device key stay.\n" + + "It is the way back to a pod that no network reaches; with a network, clear-wifi\n" + + "does the Wi-Fi part.", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + if !yes && !confirmYes("This forgets the pod's Wi-Fi and resets its Ethernet link. Type 'yes' to continue: ") { + return errors.New("aborted") + } + device, err := g.usbDevice("net-reset") + if err != nil { + return err + } + console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(clearWifiTimeout)) + if err != nil { + return err + } + defer cancel() + defer console.Close() + lines, err := console.NetReset(ctx) + for _, ln := range lines { + fmt.Fprintf(os.Stderr, " %s\n", ln) + } + if err != nil { + return fmt.Errorf("net-reset: %w", err) + } + fmt.Fprintln(os.Stderr, "Wi-Fi forgotten and Ethernet reset; USB networking is on again.") + return nil + }, + } + cmd.Flags().BoolVar(&yes, "yes", false, "skip the confirmation prompt") + return cmd +} diff --git a/cmd/benchpod-cli/wifi_test.go b/cmd/benchpod-cli/wifi_test.go new file mode 100644 index 0000000..86e0dac --- /dev/null +++ b/cmd/benchpod-cli/wifi_test.go @@ -0,0 +1,247 @@ +package main + +import ( + "bufio" + "encoding/json" + "net" + "os" + "strings" + "sync" + "testing" + "time" +) + +// jsonPod is a pod's JSON API that answers every line of every connection with handle. +type jsonPod struct { + mu sync.Mutex + reqs []map[string]any + handle func(req map[string]any) string +} + +func startJSONPod(t *testing.T, handle func(req map[string]any) string) (*jsonPod, string) { + t.Helper() + p := &jsonPod{handle: handle} + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(c net.Conn) { + defer c.Close() + r := bufio.NewReader(c) + for { + line, err := r.ReadString('\n') + if err != nil { + return + } + var req map[string]any + _ = json.Unmarshal([]byte(line), &req) + p.mu.Lock() + p.reqs = append(p.reqs, req) + p.mu.Unlock() + if _, err := c.Write([]byte(p.handle(req) + "\n")); err != nil { + return + } + } + }(conn) + } + }() + return p, ln.Addr().String() +} + +func (p *jsonPod) cmds() []string { + p.mu.Lock() + defer p.mu.Unlock() + var out []string + for _, r := range p.reqs { + c, _ := r["cmd"].(string) + out = append(out, c) + } + return out +} + +func (p *jsonPod) last(cmd string) map[string]any { + p.mu.Lock() + defer p.mu.Unlock() + for i := len(p.reqs) - 1; i >= 0; i-- { + if p.reqs[i]["cmd"] == cmd { + return p.reqs[i] + } + } + return nil +} + +func fastWifiJoin(t *testing.T) { + oldWait, oldPoll, oldScan, oldIP := wifiJoinWait, wifiJoinPoll, wifiScanPoll, consolePodIP + wifiJoinWait, wifiJoinPoll, wifiScanPoll = 2*time.Second, 20*time.Millisecond, 5*time.Millisecond + t.Cleanup(func() { wifiJoinWait, wifiJoinPoll, wifiScanPoll, consolePodIP = oldWait, oldPoll, oldScan, oldIP }) + consolePodIP = func(*globalFlags) string { return "" } +} + +// set-wifi: wifi_set over the USB network adapter, then wifi_status until the pod joined. +func TestSetWifiOverJSON(t *testing.T) { + fastWifiJoin(t) + var mu sync.Mutex + joined := false + pod, addr := startJSONPod(t, func(req map[string]any) string { + mu.Lock() + defer mu.Unlock() + switch req["cmd"] { + case "wifi_status": + if joined { + return okReply(map[string]any{"state": "connected", "connected": true, "configured": true, "ssid": "lab", "rssi_dbm": -60}) + } + return okReply(map[string]any{"state": "disabled", "connected": false, "configured": false, "ssid": ""}) + case "blob_status": + return okReply(map[string]any{"blobs": []any{map[string]any{"name": "esp", "state": "ok", "present": true}}}) + case "wifi_set": + joined = true + return okReply(map[string]any{"ssid": "lab"}) + case "status": + return okReply(map[string]any{"ip": "192.168.1.77", "api": 2, "min_client_api": 2}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + g := &globalFlags{connection: "usb", usbAddr: addr} + var ip string + var err error + out := captureStderr(t, func() { ip, err = runSetWifi(g, "lab", "s3cret", false) }) + if err != nil || ip != "192.168.1.77" { + t.Fatalf("ip %q, err %v\n%s", ip, err, out) + } + if set := pod.last("wifi_set"); set["ssid"] != "lab" || set["password"] != "s3cret" { + t.Fatalf("wifi_set %v", set) + } + if got := strings.Join(pod.cmds(), ","); !strings.HasPrefix(got, "wifi_status,blob_status,wifi_set,wifi_status") { + t.Fatalf("requests %s", got) + } + if !strings.Contains(out, `Joined "lab", ip=192.168.1.77`) || strings.Contains(out, "s3cret") { + t.Fatalf("stderr:\n%s", out) + } +} + +// When the USB link goes down with wifi_set, set-wifi follows the join on the address the +// console's status reports. +func TestSetWifiFollowsTheJoinOnTheNewAddress(t *testing.T) { + fastWifiJoin(t) + var mu sync.Mutex + set := false + _, usbAddr := startJSONPod(t, func(req map[string]any) string { + mu.Lock() + defer mu.Unlock() + switch req["cmd"] { + case "wifi_status": + if set { + return "the USB link is gone" // not a reply: the read fails + } + return okReply(map[string]any{"state": "disabled"}) + case "wifi_set": + set = true + return okReply(map[string]any{"ssid": "lab"}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + _, wifiAddr := startJSONPod(t, func(req map[string]any) string { + switch req["cmd"] { + case "wifi_status": + return okReply(map[string]any{"state": "connected", "connected": true, "ssid": "lab"}) + case "status": + return okReply(map[string]any{"ip": "127.0.0.1", "api": 2, "min_client_api": 2}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + g := &globalFlags{connection: "usb", usbAddr: usbAddr} + host, port, _ := net.SplitHostPort(wifiAddr) + oldPort := wifiPodPort + wifiPodPort = port + t.Cleanup(func() { wifiPodPort = oldPort }) + consolePodIP = func(*globalFlags) string { return host } + var ip string + var err error + captureStderr(t, func() { ip, err = runSetWifi(g, "lab", "", true) }) + if err != nil || ip != "127.0.0.1" { + t.Fatalf("ip %q, err %v", ip, err) + } +} + +// Through a Wi-Fi bridge: the bridge keeps the credentials; a wrong password is an error. +func TestSetWifiThroughABridge(t *testing.T) { + fastWifiJoin(t) + pod, addr := startJSONPod(t, func(req map[string]any) string { + switch req["cmd"] { + case "wifi_status": + return okReply(map[string]any{"state": "auth-failed", "ssid": "lab", "via": "wifi-bridge", + "bridge": map[string]any{"paired": true, "problem": nil}}) + case "wifi_set": + return okReply(map[string]any{"ssid": "lab", "via": "wifi-bridge"}) + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + var err error + captureStderr(t, func() { _, err = runSetWifi(&globalFlags{connection: "usb", usbAddr: addr}, "lab", "bad", false) }) + if err == nil || !strings.Contains(err.Error(), "wrong password") { + t.Fatalf("err = %v", err) + } + for _, c := range pod.cmds() { + if c == "blob_status" { + t.Fatal("checked the ESP32-C3 image through a bridge") + } + } +} + +func TestShowNetworkScanAndClearWifi(t *testing.T) { + fastWifiJoin(t) + scans := 0 + pod, addr := startJSONPod(t, func(req map[string]any) string { + switch req["cmd"] { + case "wifi_status": + return okReply(map[string]any{"state": "connected", "connected": true, "ssid": "lab", "rssi_dbm": -61}) + case "status": + return okReply(map[string]any{"ip": "192.168.1.77", "api": 2, "min_client_api": 2}) + case "wifi_scan": + scans++ + if scans < 3 { + return okReply(map[string]any{"state": "scanning", "id": 3}) + } + return okReply(map[string]any{"state": "done", "id": 3, "networks": []any{ + map[string]any{"ssid": "lab", "rssi": -48, "channel": 6, "auth": "wpa2/wpa3"}, + map[string]any{"ssid": "", "rssi": -80, "channel": 1, "auth": "open"}}}) + case "wifi_clear": + return okReply("cleared") + } + return codeReply("BP0002", map[string]any{"cmd": req["cmd"]}) + }) + out := t.TempDir() + "/out.txt" + read := func() string { b, _ := os.ReadFile(out); return string(b) } + if code := run([]string{"show-network", "--connection", addr, "--output-filename", out}); code != exitOK { + t.Fatalf("show-network: exit %d", code) + } + if got := read(); got != "IP: 192.168.1.77\nSSID: lab\nState: connected\nRSSI: -61 dBm\n" { + t.Fatalf("show-network:\n%s", got) + } + captureStderr(t, func() { + if code := run([]string{"scan-wifi", "--connection", addr, "--output-filename", out}); code != exitOK { + t.Fatalf("scan-wifi: exit %d", code) + } + }) + if got := read(); !strings.Contains(got, "-48 6 wpa2/wpa3 lab\n") || !strings.Contains(got, "(hidden)") { + t.Fatalf("scan-wifi:\n%s", got) + } + if r := pod.last("wifi_scan"); r["id"] != float64(3) { + t.Fatalf("poll %v", r) + } + captureStderr(t, func() { + if code := run([]string{"clear-wifi", "--connection", addr}); code != exitOK { + t.Fatalf("clear-wifi: exit %d", code) + } + }) + if pod.last("wifi_clear") == nil { + t.Fatal("no wifi_clear") + } +} diff --git a/internal/serialconsole/netreset.go b/internal/serialconsole/netreset.go new file mode 100644 index 0000000..5196445 --- /dev/null +++ b/internal/serialconsole/netreset.go @@ -0,0 +1,38 @@ +package serialconsole + +import ( + "context" + "errors" + "strings" +) + +// ErrNoNetReset is a console without `net-reset`: firmware before 4.0. +var ErrNoNetReset = errors.New("the pod's console has no net-reset (it needs firmware 4.0: `benchpod flash-self`)") + +// NetReset runs the console's `net-reset` (firmware 4.0): the pod forgets its Wi-Fi credentials +// (its flash and the ESP32-C3's NVS, or the Wi-Fi bridge's), which turns USB networking back on, +// and puts Ethernet back to autonegotiation with a PHY reset and a new DHCP lease. It returns +// the pod's `net-reset ...` lines: first the Ethernet one, then the Wi-Fi outcome. +func (c *Console) NetReset(ctx context.Context) ([]string, error) { + done := func(acc string) bool { return strings.Contains(acc, "net-reset wifi") || strings.Contains(acc, "net-reset error") } + out, err := c.sendCommandUntil(ctx, "net-reset", "net-reset", "", done) + var lines []string + for _, ln := range consoleLines(out) { + ln = strings.TrimSpace(ln) + if strings.HasPrefix(ln, "net-reset ") { + lines = append(lines, ln) + } + } + if strings.Contains(strings.ToLower(out), "unknown command") { + return nil, ErrNoNetReset + } + for _, ln := range lines { + if why, ok := strings.CutPrefix(ln, "net-reset error "); ok { + return lines, &CommandError{Cmd: "net-reset", Reason: why} + } + } + if err != nil { + return lines, err + } + return lines, nil +} From d3bdf8f1a63b260fcefc806e1f77890ed6b77f62 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:49:51 -0600 Subject: [PATCH 07/21] identity wipe: JSON identity_wipe over the USB network adapter Firmware 4.0 has no console identity-wipe. The CLI still reads the identity on the console, then sends identity_wipe with the confirm token over the pod's USB link; without the link it says how to turn USB networking on. BP0043 (not over the USB link) is worded from the catalog. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 ++++++--- cmd/benchpod-cli/identity.go | 41 +++++++++++++++++++++++++------ cmd/benchpod-cli/identity_test.go | 38 +++++++++++++++++++++++----- 3 files changed, 72 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index f37aceb..4e85cd2 100644 --- a/README.md +++ b/README.md @@ -388,7 +388,7 @@ benchpod lan-policy set locked --device-name benchpod-baea06 benchpod sig-policy --connection usb # show benchpod sig-policy set permissive --connection usb -# Device identity (USB console only): +# Device identity (USB only): benchpod identity --connection usb # show benchpod identity wipe --connection usb # erase the key, make a new one @@ -525,8 +525,10 @@ The pod stays offline without an identity. Recover it with: benchpod identity wi ``` `benchpod identity wipe` erases the key and makes a new one. It works only over -the pod's USB console (`--connection usb` or a serial device path): the pod -refuses it over the LAN and the cloud, so it needs someone at the pod. The CLI +USB (`--connection usb` or a serial device path): the CLI reads the identity on the +pod's console and sends the wipe (`identity_wipe`) over its USB network adapter; the +pod refuses it over the LAN and the cloud (`BP0043`), so it needs someone at the pod. +With USB networking off, `benchpod usb-network on --connection usb` turns it on. The CLI shows the current identity and asks before it wipes (`--yes` skips the question for scripts); the pod also checks a confirmation token (the current short id, or `unknown`), so a stray command cannot wipe a key. @@ -2346,7 +2348,8 @@ Same as `benchpod identity`. ### `benchpod identity wipe` -Erase the pod's device key and make a new one (USB only). The pod then needs to be +Erase the pod's device key and make a new one (USB only: the console shows the +identity, the wipe goes over the pod's USB network adapter). The pod then needs to be registered again. | Flag | Default | Purpose | diff --git a/cmd/benchpod-cli/identity.go b/cmd/benchpod-cli/identity.go index fc767b8..daaf6e5 100644 --- a/cmd/benchpod-cli/identity.go +++ b/cmd/benchpod-cli/identity.go @@ -3,6 +3,7 @@ package main import ( "bufio" "context" + "encoding/json" "errors" "fmt" "io" @@ -20,8 +21,10 @@ import ( // // The pod's device identity is an Ed25519 key in its own flash sector. The firmware generates it // once, on a blank sector, and never writes over a record it does not recognize: such a pod stays -// offline and says why. `identity wipe` is the deliberate way back. It runs on the USB console -// only (physical presence); the pod refuses it over the LAN and the cloud. +// offline and says why. `identity wipe` is the deliberate way back. The state comes from the USB +// console's `identity`; the wipe is the JSON identity_wipe over the pod's USB network adapter +// (physical presence; firmware 4.0 has no console identity-wipe). The pod refuses it over the LAN +// and the cloud (BP0043). // // embeddedci.com knows a pod by its public key, so after a wipe the pod is a new pod there: the old // device record keeps its data and its login state, and the pod is registered again as a new @@ -33,10 +36,30 @@ const identityMissing = "this firmware has no identity commands; update the pod' // identityConsole is the part of the USB console the identity commands use. type identityConsole interface { Identity(ctx context.Context) (serialconsole.IdentityState, error) - IdentityWipe(ctx context.Context, token string) (string, error) Close() error } +// wipeIdentity sends identity_wipe with the confirm token over the pod's USB network adapter and +// returns the new short id. A variable so tests can replace it. +var wipeIdentity = func(ctx context.Context, g *globalFlags, device, token string) (string, error) { + addr := g.usbLinkAddr(device, g.usbPodName()) + if addr == "" { + return "", errors.New("the pod's USB network adapter is not up: the pod wipes its identity only over its USB link. " + + usbNetworkOffHint) + } + raw, err := (&tcpclient.Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "identity_wipe", "confirm": token}) + if err != nil { + return "", err + } + var rep struct { + ShortID string `json:"short_id"` + } + if json.Unmarshal(raw, &rep) != nil || rep.ShortID == "" { + return "", fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(raw))) + } + return rep.ShortID, nil +} + // openIdentityConsole opens the pod's USB console; tests replace it with a fake. var openIdentityConsole = func(g *globalFlags, device string, timeout time.Duration) (identityConsole, string, context.Context, context.CancelFunc, error) { console, path, ctx, cancel, err := g.openSerialConsole(device, timeout) @@ -79,10 +102,12 @@ func newIdentityCmd(g *globalFlags) *cobra.Command { var yes bool wipe := &cobra.Command{ Use: "wipe", - Short: "Erase the pod's identity key and make a new one (USB console only)", - Long: "Erase the pod's identity and generate a fresh key, over the pod's USB\n" + - "console (--connection usb or a serial device path). The pod refuses this over the\n" + - "LAN and the cloud: it needs someone at the pod.\n\n" + + Short: "Erase the pod's identity key and make a new one (over USB only)", + Long: "Erase the pod's identity and generate a fresh key, over USB (--connection usb or a\n" + + "serial device path): the CLI reads the identity on the pod's console and sends the\n" + + "wipe over its USB network adapter. The pod refuses this over the LAN and the cloud:\n" + + "it needs someone at the pod. USB networking off: `benchpod usb-network on\n" + + "--connection usb` (the pod's console `usb-network on`).\n\n" + "Use it to recover a pod that reports an unknown identity record, or to retire a\n" + "key. The pod is a NEW pod to embeddedci.com afterwards: deregister the old record\n" + "and register the pod again (the command prints the steps).\n\n" + @@ -193,7 +218,7 @@ func runIdentityWipe(g *globalFlags, yes bool, in io.Reader, out io.Writer) erro return errors.New("identity wipe: cancelled, nothing changed") } } - newID, err := console.IdentityWipe(ctx, st.ConfirmToken()) + newID, err := wipeIdentity(ctx, g, device, st.ConfirmToken()) if err != nil { return identityErr("identity wipe", err) } diff --git a/cmd/benchpod-cli/identity_test.go b/cmd/benchpod-cli/identity_test.go index 1c0a5a8..0e83142 100644 --- a/cmd/benchpod-cli/identity_test.go +++ b/cmd/benchpod-cli/identity_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // fakeIdentityConsole stands in for the pod's USB console. @@ -43,7 +44,9 @@ func withFakeIdentityConsole(t *testing.T, fc *fakeIdentityConsole, tty bool) { return fc, device, context.Background(), func() {}, nil } stdinIsTerminal = func() bool { return tty } - t.Cleanup(func() { openIdentityConsole, stdinIsTerminal = saved, savedTTY }) + savedWipe := wipeIdentity + wipeIdentity = func(ctx context.Context, _ *globalFlags, _, token string) (string, error) { return fc.IdentityWipe(ctx, token) } + t.Cleanup(func() { openIdentityConsole, stdinIsTerminal, wipeIdentity = saved, savedTTY, savedWipe }) } func TestIdentityWipeOnlyOverUSB(t *testing.T) { @@ -126,16 +129,39 @@ func TestIdentityWipeNeedsTerminalOrYes(t *testing.T) { func TestIdentityWipeRefusalAndOldFirmware(t *testing.T) { fc := &fakeIdentityConsole{state: serialconsole.IdentityState{ShortID: "a1b2c3"}, - wipeErr: &serialconsole.IdentityError{Cmd: "identity-wipe", Reason: "hardware RNG failed; nothing was erased"}} + wipeErr: &tcpclient.PodError{Reason: "identity_wipe: hardware RNG failed; nothing was erased"}} withFakeIdentityConsole(t, fc, true) err := runIdentityWipe(&globalFlags{connection: "usb"}, true, nil, &bytes.Buffer{}) - if err == nil || err.Error() != "identity wipe: the pod refused: hardware RNG failed; nothing was erased" { + if err == nil || err.Error() != "identity wipe: the pod refused: identity_wipe: hardware RNG failed; nothing was erased" { t.Fatalf("err = %v", err) } - fc.wipeErr = serialconsole.ErrIdentityUnsupported + // Not over the USB link: BP0043. + fc.wipeErr = tcpclient.RefusalError("", "BP0043", map[string]any{"setting": "identity_wipe"}) err = runIdentityWipe(&globalFlags{connection: "usb"}, true, nil, &bytes.Buffer{}) - if err == nil || err.Error() != identityMissing { - t.Fatalf("old firmware: err = %v", err) + if err == nil || !strings.Contains(err.Error(), "BP0043: identity_wipe can only be changed on the device") || exitCode(err) != exitRefused { + t.Fatalf("BP0043: err = %v", err) + } +} + +// The real wipe sends identity_wipe with the confirm token over the USB link. +func TestIdentityWipeSendsJSON(t *testing.T) { + pod, addr := startJSONPod(t, func(req map[string]any) string { + return okReply(map[string]any{"short_id": "d4e5f6"}) + }) + old := localUSBPod + localUSBPod = func(string) string { return addr } + t.Cleanup(func() { localUSBPod = old }) + id, err := wipeIdentity(context.Background(), &globalFlags{connection: "usb"}, "", "a1b2c3") + if err != nil || id != "d4e5f6" { + t.Fatalf("id %q, err %v", id, err) + } + if r := pod.last("identity_wipe"); r["confirm"] != "a1b2c3" { + t.Fatalf("sent %v", r) + } + // No USB link: says how to turn USB networking on. + localUSBPod = func(string) string { return "" } + if _, err := wipeIdentity(context.Background(), &globalFlags{connection: "usb"}, "", "a1b2c3"); err == nil || !strings.Contains(err.Error(), "usb-network on") { + t.Fatalf("no link: err = %v", err) } } From 76bbbb051d339a8fa5be393dff68541a54a15d34 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:51:32 -0600 Subject: [PATCH 08/21] sig-policy: show only, over the USB network adapter Firmware 4.0 always requires signatures (BP0074 for loosening), so sig-policy has no set any more and its values are just required. Over USB it reads sig_policy over the pod's USB network adapter (no console sig-policy in 4.0); lan-policy set stays on the console. The root help describes the 0.10 transports. Co-Authored-By: Claude Opus 5.5 --- README.md | 34 +++++++---------- cmd/benchpod-cli/policy.go | 63 +++++++++++++++++------------- cmd/benchpod-cli/policy_test.go | 68 +++++++++++++++++---------------- cmd/benchpod-cli/root.go | 30 ++++++++------- 4 files changed, 102 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 4e85cd2..3ca5009 100644 --- a/README.md +++ b/README.md @@ -385,8 +385,7 @@ benchpod logout # Pod policies (cloud with --device-name, or USB): benchpod lan-policy --device-name benchpod-baea06 # show benchpod lan-policy set locked --device-name benchpod-baea06 -benchpod sig-policy --connection usb # show -benchpod sig-policy set permissive --connection usb +benchpod sig-policy --connection usb # show (always required) # Device identity (USB only): benchpod identity --connection usb # show @@ -439,16 +438,16 @@ Two settings the pod keeps in its config flash: | `locked` | read and instrument control only; config and firmware need cloud or USB | | `off` | nothing: no LAN listener, no mDNS. The cloud and USB keep working | -| `sig-policy` | How firmware and blob signatures are treated | -|--------------|---------------------------------------------------------------------------| -| `audit` | every image is accepted; signatures are only reported | -| `permissive` | unsigned images are accepted, a bad signature is refused | -| `required` | unsigned images are refused | +`sig-policy` (how firmware and blob signatures are treated) is always `required` from +firmware 4.0: the pod installs only signed images on every path, and the policy cannot be +loosened (`BP0074`). Install firmware you built yourself over USB DFU (`benchpod flash-self +./fw.bin`). -`benchpod lan-policy` and `benchpod sig-policy` show the policy; `... set ` -changes it. Pick the pod with `--device-name` / `--device-id` (through -embeddedci.com, like `deregister`) or with `--connection usb`. Over the LAN the -commands can only show the policy: the pod refuses changes from the LAN. +`benchpod lan-policy` and `benchpod sig-policy` show the policy; `lan-policy set ` +changes the LAN policy. Pick the pod with `--device-name` / `--device-id` (through +embeddedci.com, like `deregister`) or with `--connection usb` (`sig-policy` over the pod's +USB network adapter, `lan-policy set` over its console). Over the LAN the commands can only +show the policy: the pod refuses changes from the LAN. ``` $ benchpod lan-policy --device-name benchpod-baea06 @@ -457,9 +456,6 @@ LAN policy of benchpod-baea06: locked (read and instrument control only on the L - Over the cloud a change needs an organization owner or admin (an API key needs the `benchpod:admin` scope). -- The cloud can only make `sig-policy` stricter. Only the USB console can loosen - it (`benchpod sig-policy set permissive --connection usb`); the CLI says so when - the pod refuses. - With `lan-policy off`, LAN tools stop working until it is set back: SCPI/VISA, hwe2e `TestHW` and LAN `discover`. Set it back over the cloud or USB. - Firmware without these commands gets "this firmware has no LAN policy; update @@ -2318,9 +2314,9 @@ benchpod log-level debug ### `benchpod sig-policy` -Show the pod's signature policy: `audit`, `permissive` or `required`. Same -transports as `lan-policy`; the cloud can only make it stricter. These flags apply -to `show` and `set` too. +Show the pod's signature policy (always `required` from firmware 4.0) and how many release +keys it trusts. Over embeddedci.com, the pod's USB network adapter or the LAN. There is no +`set`: CLI 0.10 dropped the loosening. These flags apply to `show` too. | Flag | Default | Purpose | |-----------------|------------------------------|----------------------------------------------------------| @@ -2333,10 +2329,6 @@ to `show` and `set` too. Same as `benchpod sig-policy`. -### `benchpod sig-policy set ` - -Set the signature policy. Loosening it needs the USB console. - ### `benchpod identity` Show the pod's device identity (USB). See diff --git a/cmd/benchpod-cli/policy.go b/cmd/benchpod-cli/policy.go index 99f1ca4..0ee5c37 100644 --- a/cmd/benchpod-cli/policy.go +++ b/cmd/benchpod-cli/policy.go @@ -23,8 +23,8 @@ import ( // // - lan-policy: open | locked | off. Settable from the cloud and the USB console, never from // the LAN itself. -// - sig-policy: audit < permissive < required. The cloud may only make it stricter; the USB -// console may set anything. The LAN can never change it. +// - sig-policy: always required from firmware 4.0 (signatures cannot be loosened; BP0074), so +// the CLI only shows it (with the number of trusted keys). // // The target follows the CLI's conventions: --device-name / --device-id or --connection // embeddedci: go through embeddedci.com (like deregister), otherwise --connection picks the @@ -36,11 +36,14 @@ type podPolicy struct { jsonCmd string // the pod's JSON verb, e.g. "lan_policy" title string // "LAN policy", starts a sentence noun string // "LAN policy", inside a sentence - values []string // in order of strictness for sig-policy + values []string // the values set takes; none: show only meaning map[string]string // one-line explanation of each value missing string // what to say when the pod's firmware lacks the policy } +// settable says the policy has a set subcommand. +func (p podPolicy) settable() bool { return len(p.values) > 1 } + var lanPolicy = podPolicy{ cmd: "lan-policy", jsonCmd: "lan_policy", @@ -60,11 +63,9 @@ var sigPolicy = podPolicy{ jsonCmd: "sig_policy", title: "Signature policy", noun: "signature policy", - values: []string{"audit", "permissive", "required"}, + values: []string{"required"}, meaning: map[string]string{ - "audit": "every image is accepted; signatures are only reported", - "permissive": "unsigned images are accepted, a bad signature is refused", - "required": "unsigned images are refused", + "required": "only signed images are installed", }, missing: "this firmware has no signature policy; update the pod's firmware", } @@ -114,15 +115,14 @@ func newLanPolicyCmd(g *globalFlags) *cobra.Command { func newSigPolicyCmd(g *globalFlags) *cobra.Command { return newPolicyCmd(g, sigPolicy, - "Show or set the pod's signature policy (audit, permissive, required)", - "Show or set how the pod treats firmware and blob signatures.\n\n"+ - " audit every image is accepted; signatures are only reported\n"+ - " permissive unsigned images are accepted, a bad signature is refused\n"+ - " required unsigned images are refused\n\n"+ - "Over the cloud (--device-name, --device-id or --connection embeddedci:)\n"+ - "the policy can only be made stricter, and only by an organization owner or\n"+ - "admin. Only the USB console (--connection usb) can loosen it. The LAN can only\n"+ - "show it.") + "Show the pod's signature policy (always required)", + "Show how the pod treats firmware and blob signatures, and how many release keys\n"+ + "it trusts. Firmware 4.0 installs only signed images on every path (LAN, USB and\n"+ + "the cloud): the policy is always required and cannot be loosened (BP0074).\n"+ + "Install firmware you built yourself over USB DFU (`benchpod flash-self` with a\n"+ + "local .bin).\n\n"+ + "Over the cloud (--device-name, --device-id or --connection embeddedci:), over\n"+ + "USB (the pod's USB network adapter) or over the LAN.") } func newPolicyCmd(g *globalFlags, p podPolicy, short, long string) *cobra.Command { @@ -149,13 +149,16 @@ func newPolicyCmd(g *globalFlags, p podPolicy, short, long string) *cobra.Comman Short: "Show the pod's " + p.noun, Args: cobra.NoArgs, RunE: show, - }, &cobra.Command{ - Use: "set <" + strings.Join(p.values, "|") + ">", - Short: "Set the pod's " + p.noun, - Args: cobra.ExactArgs(1), - ValidArgs: p.values, - RunE: func(_ *cobra.Command, args []string) error { return run(args[0]) }, }) + if p.settable() { + root.AddCommand(&cobra.Command{ + Use: "set <" + strings.Join(p.values, "|") + ">", + Short: "Set the pod's " + p.noun, + Args: cobra.ExactArgs(1), + ValidArgs: p.values, + RunE: func(_ *cobra.Command, args []string) error { return run(args[0]) }, + }) + } pf := root.PersistentFlags() pf.StringVar(&t.serverURL, "server-url", "https://www.embeddedci.com", "embeddedci-server base URL") pf.StringVar(&t.tokenFile, "token-file", "", "path to token cache (default: ~/.config/benchpod-cli/token.json)") @@ -170,8 +173,8 @@ func runPolicy(g *globalFlags, p podPolicy, t policyTarget, set string, out, war t.deviceName = strings.TrimSpace(t.deviceName) t.deviceID = strings.TrimSpace(t.deviceID) set = strings.ToLower(strings.TrimSpace(set)) - if set != "" && !p.valid(set) { - return fmt.Errorf("%s set: %q is not a policy; use one of %s", p.cmd, set, strings.Join(p.values, ", ")) + if set != "" && (!p.settable() || !p.valid(set)) { + return usageErrorf("%s set: %q is not a policy; use one of %s", p.cmd, set, strings.Join(p.values, ", ")) } if t.deviceName != "" && t.deviceID != "" { return errors.New("pass only one of --device-name or --device-id") @@ -196,14 +199,22 @@ func runPolicy(g *globalFlags, p podPolicy, t policyTarget, set string, out, war return runPolicyCloud(g, p, t, set, out, warn) } if spec.IsSerial() { - // Showing is a read the pod's USB network link answers (firmware 3.9.0+), with no - // console: a Linux user outside the dialout group cannot open it. Changes stay on the + // Showing is a read the pod's USB network link answers, with no console: a Linux user + // outside the dialout group cannot open it. The signature policy is on the network API + // only (firmware 4.0 has no console sig-policy). Changing the LAN policy stays on the // console (physical presence). if set == "" && spec.Device == "" { if addr := localUSBPod(spec.Pod); addr != "" { return runPolicyLAN(g, p, addr, out) } } + if p.cmd == sigPolicy.cmd { + nt, err := g.networkTarget(p.cmd) + if err != nil { + return err + } + return runPolicyLAN(g, p, nt.Addr, out) + } return runPolicyUSB(g, p, spec.Device, set, out, warn) } if set != "" { diff --git a/cmd/benchpod-cli/policy_test.go b/cmd/benchpod-cli/policy_test.go index 44f3a57..24f8e83 100644 --- a/cmd/benchpod-cli/policy_test.go +++ b/cmd/benchpod-cli/policy_test.go @@ -81,7 +81,7 @@ func runPolicyCapture(t *testing.T, g *globalFlags, p podPolicy, target policyTa } func TestPolicyCloudShowAndSet(t *testing.T) { - srv := &policyServer{t: t, supported: true, policy: map[string]string{"lan-policy": "open", "sig-policy": "audit"}} + srv := &policyServer{t: t, supported: true, policy: map[string]string{"lan-policy": "open", "sig-policy": "required"}} target := cloudTarget(t, srv.start().URL) out, _, err := runPolicyCapture(t, &globalFlags{}, lanPolicy, target, "") @@ -108,11 +108,15 @@ func TestPolicyCloudShowAndSet(t *testing.T) { t.Fatalf("set off: err %v, warning %q", err, warn) } - out, _, err = runPolicyCapture(t, &globalFlags{}, sigPolicy, target, "required") - if err != nil || !strings.HasPrefix(out, "Signature policy of benchpod-baea06 is now required (") { - t.Fatalf("sig set = %q, %v", out, err) + out, _, err = runPolicyCapture(t, &globalFlags{}, sigPolicy, target, "") + if err != nil || out != "Signature policy of benchpod-baea06: required (only signed images are installed)\n" { + t.Fatalf("sig show = %q, %v", out, err) + } + // The signature policy has no set: it is always required. + if _, _, err = runPolicyCapture(t, &globalFlags{}, sigPolicy, target, "permissive"); exitCode(err) != exitUsage { + t.Fatalf("sig set: %v", err) } - if got := strings.Join(srv.puts, ","); got != "lan-policy=locked,lan-policy=off,sig-policy=required" { + if got := strings.Join(srv.puts, ","); got != "lan-policy=locked,lan-policy=off" { t.Fatalf("puts = %s", got) } } @@ -150,17 +154,21 @@ func TestPolicyCloudForbidden(t *testing.T) { } } -func TestPolicyCloudRefusedLoosening(t *testing.T) { - srv := &policyServer{t: t, supported: true, policy: map[string]string{"sig-policy": "required"}, - put: func(w http.ResponseWriter, _, _ string) bool { - w.WriteHeader(http.StatusConflict) - _, _ = w.Write([]byte(`{"error":"BP0074","code":"BP0074"}`)) - return true - }} - _, _, err := runPolicyCapture(t, &globalFlags{}, sigPolicy, cloudTarget(t, srv.start().URL), "permissive") - want := "sig-policy set: the pod refused: BP0074: " - if err == nil || !strings.HasPrefix(err.Error(), want) || exitCode(err) != exitRefused { - t.Fatalf("err = %v\nwant %q", err, want) +// sig-policy has no set subcommand any more; a relayed BP0074 is worded from the catalog. +func TestSigPolicyCannotBeLoosened(t *testing.T) { + g := &globalFlags{} + cmd := newSigPolicyCmd(g) + for _, c := range cmd.Commands() { + if c.Name() == "set" { + t.Fatal("sig-policy still has set") + } + } + if code := run([]string{"sig-policy", "set", "audit"}); code != exitUsage { + t.Fatalf("sig-policy set: exit %d", code) + } + err := cloudPolicyError(lanPolicy, "off", &serverapi.APIError{Status: http.StatusConflict, Code: "BP0074", Message: "BP0074"}) + if err == nil || !strings.Contains(err.Error(), "BP0074: ") || !strings.Contains(err.Error(), "this firmware installs only signed images") { + t.Fatalf("err = %v", err) } } @@ -208,25 +216,21 @@ func withFakeConsole(t *testing.T, fc *fakePolicyConsole) { } func TestPolicyUSBShowAndSet(t *testing.T) { - fc := &fakePolicyConsole{rep: serialconsole.PolicyReply{Policy: "required", Keys: 3}} + fc := &fakePolicyConsole{rep: serialconsole.PolicyReply{Policy: "open", Keys: -1}} withFakeConsole(t, fc) - g := &globalFlags{connection: "usb"} - - out, _, err := runPolicyCapture(t, g, sigPolicy, policyTarget{}, "") + // The signature policy goes over the pod's USB network adapter, not the console. + addr, got := fakeLANPod(t, `{"status":"ok","data":{"policy":"required","keys":3}}`) + out, _, err := runPolicyCapture(t, &globalFlags{connection: "usb", usbAddr: addr}, sigPolicy, policyTarget{}, "") if err != nil { t.Fatalf("show: %v", err) } - if want := "Signature policy of the pod on /dev/cu.usbmodem1101: required (unsigned images are refused), 3 trusted keys\n"; out != want { + if want := "Signature policy of " + addr + ": required (only signed images are installed), 3 trusted keys\n"; out != want { t.Fatalf("show = %q, want %q", out, want) } - - // The USB console may loosen the policy. - out, _, err = runPolicyCapture(t, g, sigPolicy, policyTarget{}, "audit") - if err != nil || !strings.HasPrefix(out, "Signature policy of the pod on /dev/cu.usbmodem1101 is now audit (") { - t.Fatalf("set = %q, %v", out, err) + if req := <-got; req != `{"cmd":"sig_policy"}` { + t.Fatalf("request %s", req) } - fc.rep = serialconsole.PolicyReply{Policy: "open", Keys: -1} out, warn, err := runPolicyCapture(t, &globalFlags{connection: "/dev/cu.usbmodem9"}, lanPolicy, policyTarget{}, "off") if err != nil { t.Fatalf("lan set: %v", err) @@ -239,7 +243,7 @@ func TestPolicyUSBShowAndSet(t *testing.T) { t.Fatalf("warning %q does not mention %q", warn, w) } } - if got := strings.Join(fc.calls, ","); got != "sig-policy,sig-policy audit,lan-policy off" { + if got := strings.Join(fc.calls, ","); got != "lan-policy off" { t.Fatalf("console calls = %s", got) } } @@ -249,8 +253,8 @@ func TestPolicyUSBOldFirmwareAndRefusal(t *testing.T) { withFakeConsole(t, fc) g := &globalFlags{connection: "usb"} - _, _, err := runPolicyCapture(t, g, sigPolicy, policyTarget{}, "") - if err == nil || err.Error() != "this firmware has no signature policy; update the pod's firmware" { + _, _, err := runPolicyCapture(t, g, lanPolicy, policyTarget{}, "") + if err == nil || err.Error() != "this firmware has no LAN policy; update the pod's firmware" { t.Fatalf("old firmware: err = %v", err) } @@ -286,14 +290,14 @@ func fakeLANPod(t *testing.T, reply string) (addr string, got chan string) { } func TestPolicyLANShowOnly(t *testing.T) { - addr, got := fakeLANPod(t, `{"status":"ok","data":{"policy":"audit","enforces":true,"keys":1}}`) + addr, got := fakeLANPod(t, `{"status":"ok","data":{"policy":"required","enforces":true,"keys":1}}`) g := &globalFlags{connection: addr} out, _, err := runPolicyCapture(t, g, sigPolicy, policyTarget{}, "") if err != nil { t.Fatalf("show: %v", err) } - if want := "Signature policy of " + addr + ": audit (every image is accepted; signatures are only reported), 1 trusted key\n"; out != want { + if want := "Signature policy of " + addr + ": required (only signed images are installed), 1 trusted key\n"; out != want { t.Fatalf("show = %q, want %q", out, want) } if req := <-got; req != `{"cmd":"sig_policy"}` { diff --git a/cmd/benchpod-cli/root.go b/cmd/benchpod-cli/root.go index 491095c..f948098 100644 --- a/cmd/benchpod-cli/root.go +++ b/cmd/benchpod-cli/root.go @@ -62,24 +62,26 @@ func newRootCmd() *cobra.Command { "New pod? Run `benchpod setup`: it finds the pod, gets it on the network, sets\n" + "the board I/O voltage, registers it with embeddedci.com and saves the connection.\n\n" + "--connection says where and how to reach the pod; the transport follows from\n" + - "its value. An address (192.168.1.5[:8080]) uses the pod's network (TCP/JSON) API;\n" + - "a device path (/dev/tty..., COM3) or `usb` uses the pod's USB console, and its\n" + - "USB network adapter for the network commands (firmware 3.9.0+, no Wi-Fi set);\n" + - "embeddedci: goes through embeddedci.com to the pod with that name on your\n" + - "account (signed in with `benchpod login`, or BENCHPOD_API_KEY). Omit --connection\n" + - "to use the default saved by `benchpod discover --save` or `benchpod set-connection`.\n" + + "its value. An address (192.168.1.5) uses the pod's network API (TLS on 8443,\n" + + "pinned on first use); a device path (/dev/tty..., COM3) or `usb` uses the pod's\n" + + "USB network adapter; embeddedci: goes through embeddedci.com to the pod\n" + + "with that name on your account (signed in with `benchpod login`, or\n" + + "BENCHPOD_API_KEY). Omit --connection to use the default saved by\n" + + "`benchpod discover --save` or `benchpod set-connection`.\n" + "--org (or BENCHPOD_ORG) picks which of your embeddedci.com organizations cloud\n" + "calls act in, by id, slug or name; the default is the one active in the web app.\n\n" + - "Over the network: every pod command but the USB-only ones below. Over the USB\n" + - "console: status, la voltage, flash (SWD), lan-policy, sig-policy, cloud ca and\n" + - "cloud proxy; the rest over the pod's USB network adapter when it is up.\n" + + "This CLI drives firmware 4.0. Against firmware 3.x only status, flash-self,\n" + + "install-blobs, dfu, bootsel, discover and identity run (exit code 7 otherwise:\n" + + "update the pod with `benchpod flash-self`).\n\n" + + "Over USB every pod command sends JSON over the pod's USB network adapter; the\n" + + "USB console is only for status, dfu, bootsel, identity, lan-policy, usb-network\n" + + "and net-reset. USB networking off: `benchpod usb-network on --connection usb`.\n" + "Through embeddedci.com: status, ping, la voltage, la pull, la pullup, la status, la step,\n" + "la pins, la dir, i2c, generate, sensor, lan-policy, sig-policy, cloud ca\n" + - "show/clear, cloud proxy, deregister and flash-self (embeddedci.com runs the update).\n" + - "Always over the USB console: set-wifi, show-network, clear-wifi, identity,\n" + - "install-blobs, bootsel, dfu, usb-bridge and usb-reattach; flash-self reflashes\n" + - "the pod over USB DFU unless --network or an embeddedci: connection. A command\n" + - "that cannot use the connection says so and names what to use instead.\n\n" + + "show/clear, cloud proxy, the Wi-Fi commands, deregister and flash-self\n" + + "(embeddedci.com runs the update). flash-self reflashes the pod over USB DFU\n" + + "unless --network or an embeddedci: connection. A command that cannot use the\n" + + "connection says so and names what to use instead.\n\n" + "flash and spi-flash over the network take the pins you leave out from the pod's\n" + "wiring profile on embeddedci.com when you are signed in and the pod is on your\n" + "account.\n\n" + From 3b641b52bd472d4ddab46c797b966a95a50908ce Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:53:10 -0600 Subject: [PATCH 09/21] usb-reattach, la voltage, flash over USB: JSON only, no console usb-reattach sends usb_reattach (over the USB link when it is up, else the pod's network address). la voltage and flash (dap_start, target power) over USB use the pod's USB network adapter; the console paths for firmware before 3.9.0 are gone, and without the adapter the error says how to turn it on. Co-Authored-By: Claude Opus 5.5 --- README.md | 15 ++++---- cmd/benchpod-cli/cloudcfg.go | 2 +- cmd/benchpod-cli/flash.go | 49 ++++------------------- cmd/benchpod-cli/flash_self_test.go | 1 - cmd/benchpod-cli/identity_test.go | 4 +- cmd/benchpod-cli/lantls.go | 32 +++++++-------- cmd/benchpod-cli/lavoltage.go | 52 +------------------------ cmd/benchpod-cli/lavoltage_test.go | 60 ++++++++--------------------- cmd/benchpod-cli/usbbridge.go | 23 +++++------ internal/serialconsole/netreset.go | 4 +- 10 files changed, 68 insertions(+), 174 deletions(-) diff --git a/README.md b/README.md index 3ca5009..51f6529 100644 --- a/README.md +++ b/README.md @@ -601,8 +601,8 @@ intelligence and OpenOCD's exit code is the verdict. The pod runs a CMSIS-DAP processor locally and OpenOCD's `cmsis-dap` **TCP backend** ships whole DAP transfers (`DAP_Transfer`/`DAP_TransferBlock`), so a flash is one round-trip per DAP command instead of thousands of per-bit round-trips — fast even over the -network. Works on **TCP** (`dap_start`) and **USB** (the console `dap-start` -command). It needs a **recent OpenOCD with the `cmsis_dap_tcp` backend** +network. Works on **TCP** (`dap_start`), over the network or over USB on the pod's +USB network adapter (firmware 4.0 has no probe on its console). It needs a **recent OpenOCD with the `cmsis_dap_tcp` backend** (post-0.12.0; e.g. `brew install --HEAD open-ocd`); the CLI checks for the backend up front and fails with clear advice if it is missing. @@ -2014,11 +2014,12 @@ Show whether the background service is installed and running. No flags. ### `benchpod usb-reattach` -Make the pod drop off the USB bus for half a second and connect again (USB). The -computer then sets up the console and the USB network adapter anew, as after -replugging the cable. macOS ignores a new network adapter while the screen is -locked: run this after unlocking when the pod was plugged in or rebooted meanwhile. -Needs firmware 3.9.0 or later. No flags. +Make the pod drop off the USB bus for half a second and connect again (`usb_reattach`). The +computer then sets up the console and the USB network adapter anew, as after replugging the +cable. macOS ignores a new network adapter while the screen is locked: run this after +unlocking when the pod was plugged in or rebooted meanwhile. The CLI sends it over the pod's +USB network adapter when that is up, else over the pod's network address from its console +`status` (or the `--connection` given); with neither, replug the cable. No flags. ### `benchpod login` diff --git a/cmd/benchpod-cli/cloudcfg.go b/cmd/benchpod-cli/cloudcfg.go index 82d9de8..4296be7 100644 --- a/cmd/benchpod-cli/cloudcfg.go +++ b/cmd/benchpod-cli/cloudcfg.go @@ -468,7 +468,7 @@ func openLAN(ctx context.Context, addr string) (lanSession, error) { } type caReply struct { - Present bool `json:"present"` + Present bool `json:"present"` Certs []podCACert `json:"certs"` } diff --git a/cmd/benchpod-cli/flash.go b/cmd/benchpod-cli/flash.go index 0e1aed4..1206a9f 100644 --- a/cmd/benchpod-cli/flash.go +++ b/cmd/benchpod-cli/flash.go @@ -12,7 +12,6 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/openocd" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/embeddedci-com/benchpod-cli/internal/serverapi" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" @@ -361,16 +360,16 @@ func printTargetUnreachableHint(f *flashFlags) { } } -// openDAP optionally powers the target, then arms the pod's CMSIS-DAP probe over -// the selected transport (dap_start over the network, the dap-start console command -// over USB) and returns the length-framed DAP stream to bridge to OpenOCD. +// openDAP optionally powers the target, then arms the pod's CMSIS-DAP probe (dap_start over +// the network, or over USB on the pod's USB network adapter) and returns the length-framed DAP +// stream to bridge to OpenOCD. // powerEfuse 0 leaves target power untouched; 1/2 enables that eFuse first. func openDAP(ctx context.Context, g *globalFlags, swclk, swdio int, powerEfuse int) (io.ReadWriteCloser, bool, error) { spec, err := g.resolveConnection() if err != nil { return nil, false, err } - spec = g.preferUSBNetwork(spec, "flash") // the probe over the USB network is much faster + spec = g.preferUSBNetwork(spec, "flash") if spec.IsNetwork() { client := &tcpclient.Client{Addr: spec.Addr} // Ask the pod whether it has the dedicated reset pin BEFORE arming the @@ -395,43 +394,9 @@ func openDAP(ctx context.Context, g *globalFlags, swclk, swdio int, powerEfuse i return conn, hasNRST, nil } - // Serial transport: open the console, optionally power the target, perform - // the dap-start handshake, and hand back the framed stream. DAPStart's - // returned closer owns the port (its Close sends a leave frame and closes it), - // so we only close the console explicitly when we bail out before the - // handshake succeeds. Same auto-detect as the other serial commands: explicit - // device verbatim, else probe USB serial ports for the bench-pod identifier. - console, path, err := g.openBenchpodSerial(spec.Device, 2*time.Second) - if err != nil { - return nil, false, err - } - // Same probe as the network path, on the console this time — and for the same - // reason it has to happen before dap-start: the console stops taking text - // commands once the probe is armed. The port is already open, so this costs - // one `status` round-trip and no extra connection. - hasNRST := true - if v, err := console.HasNRSTPin(ctx); err == nil { - hasNRST = v - } - if powerEfuse != 0 { - if err := console.TargetPower(ctx, powerEfuse, true); err != nil { - console.Close() - if errors.Is(err, serialconsole.ErrMovedToNetwork) || errors.Is(err, serialconsole.ErrUnknownCommand) { - return nil, false, fmt.Errorf("flash: this pod's console has no power command (firmware 3.9.0+ switches " + - "target power over the network API) and its USB network is not usable; drop --target-power, " + - "or connect over the network") - } - return nil, false, fmt.Errorf("flash: enable target-power eFuse %d over %s: %w", powerEfuse, path, err) - } - fmt.Fprintf(os.Stderr, "flash: target-power eFuse %d on\n", powerEfuse) - settle(ctx, targetPowerSettle) - } - conn, err := console.DAPStart(ctx, swclk, swdio) - if err != nil { - console.Close() - return nil, false, fmt.Errorf("flash: dap-start over %s: %w", path, err) - } - return conn, hasNRST, nil + // USB without a usable USB network adapter: firmware 4.0 has no probe on its console. + _, err = g.networkTarget("flash") + return nil, false, err } // settle waits for d or until ctx is cancelled, whichever comes first, so the diff --git a/cmd/benchpod-cli/flash_self_test.go b/cmd/benchpod-cli/flash_self_test.go index ae3bc5b..54fdfaa 100644 --- a/cmd/benchpod-cli/flash_self_test.go +++ b/cmd/benchpod-cli/flash_self_test.go @@ -113,4 +113,3 @@ func TestInstallBlobsAfterFlashFailsWhenTheConsoleNeverReturns(t *testing.T) { t.Fatalf("err = %v, want an error naming install-blobs", err) } } - diff --git a/cmd/benchpod-cli/identity_test.go b/cmd/benchpod-cli/identity_test.go index 0e83142..040fe0a 100644 --- a/cmd/benchpod-cli/identity_test.go +++ b/cmd/benchpod-cli/identity_test.go @@ -45,7 +45,9 @@ func withFakeIdentityConsole(t *testing.T, fc *fakeIdentityConsole, tty bool) { } stdinIsTerminal = func() bool { return tty } savedWipe := wipeIdentity - wipeIdentity = func(ctx context.Context, _ *globalFlags, _, token string) (string, error) { return fc.IdentityWipe(ctx, token) } + wipeIdentity = func(ctx context.Context, _ *globalFlags, _, token string) (string, error) { + return fc.IdentityWipe(ctx, token) + } t.Cleanup(func() { openIdentityConsole, stdinIsTerminal, wipeIdentity = saved, savedTTY, savedWipe }) } diff --git a/cmd/benchpod-cli/lantls.go b/cmd/benchpod-cli/lantls.go index 74ca8b3..bef5f07 100644 --- a/cmd/benchpod-cli/lantls.go +++ b/cmd/benchpod-cli/lantls.go @@ -140,22 +140,22 @@ func newLanTLSCmd(g *globalFlags) *cobra.Command { onOffCmd("https-only", "https_only", "Take only TLS on Ethernet and Wi-Fi (on, the default) or plaintext 8080 too (off)"), onOffCmd("scpi", "scpi", "Turn SCPI on the pod's TCP ports on or off (off by default)"), &cobra.Command{ - Use: "regenerate", - Short: "Make a new key and self-signed certificate on the pod", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - return run(func(out, warn io.Writer) error { - return runLanTLS(g, map[string]any{"regenerate": true}, out, warn) - }) - }, - }, setCert, trust, &cobra.Command{ - Use: "forget", - Short: "Drop this computer's pin for the pod", - Args: cobra.NoArgs, - RunE: func(_ *cobra.Command, _ []string) error { - return run(func(out, _ io.Writer) error { return runLanTLSForget(g, out) }) - }, - }) + Use: "regenerate", + Short: "Make a new key and self-signed certificate on the pod", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + return run(func(out, warn io.Writer) error { + return runLanTLS(g, map[string]any{"regenerate": true}, out, warn) + }) + }, + }, setCert, trust, &cobra.Command{ + Use: "forget", + Short: "Drop this computer's pin for the pod", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + return run(func(out, _ io.Writer) error { return runLanTLSForget(g, out) }) + }, + }) return root } diff --git a/cmd/benchpod-cli/lavoltage.go b/cmd/benchpod-cli/lavoltage.go index 9a7b1bb..676ee29 100644 --- a/cmd/benchpod-cli/lavoltage.go +++ b/cmd/benchpod-cli/lavoltage.go @@ -10,7 +10,6 @@ import ( "strings" "time" - "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" ) @@ -65,21 +64,6 @@ func newLAVoltageCmd(g *globalFlags) *cobra.Command { } } -// laVoltageConsole is the part of the USB console la voltage uses. -type laVoltageConsole interface { - LAVoltage(ctx context.Context, mv int) (int, error) - Close() error -} - -// openLAVoltageConsole opens the pod's USB console; tests replace it with a fake. -var openLAVoltageConsole = func(g *globalFlags, device string, timeout time.Duration) (laVoltageConsole, string, context.Context, context.CancelFunc, error) { - console, path, ctx, cancel, err := g.openSerialConsole(device, timeout) - if err != nil { - return nil, "", nil, cancel, err - } - return console, path, ctx, cancel, nil -} - // laVoltageReply is the pod's JSON answer to la_voltage. type laVoltageReply struct { MV int `json:"mv"` @@ -208,28 +192,12 @@ func laVoltageDo(g *globalFlags, mv int) (string, laVoltageReply, error) { if err != nil { return "", laVoltageReply{}, err } - spec = g.preferUSBNetwork(spec, what) var rep laVoltageReply if spec.IsSerial() { - console, path, ctx, cancel, err := openLAVoltageConsole(g, spec.Device, g.effectiveTimeout(15*time.Second)) - if err != nil { + // Over USB: the pod's USB network adapter (podClient says why when it is not usable). + if _, err := g.networkTarget(what); err != nil { return "", rep, err } - defer cancel() - defer console.Close() - rep.MV, err = console.LAVoltage(ctx, mv) - if errors.Is(err, serialconsole.ErrMovedToNetwork) || - (errors.Is(err, serialconsole.ErrUnknownCommand) && consoleHasUSBNet(ctx, console)) { - // Firmware 3.9.0+ moved la-voltage from the console to the JSON API; preferUSBNetwork - // already found the USB network unusable, so say why. - _, nerr := g.networkTarget(what) - return "", rep, fmt.Errorf("%s: this pod's console has no la-voltage (firmware 3.9.0+ sets it over the "+ - "network API) and its USB network is not usable: %v", what, nerr) - } - if err != nil { - return "", rep, laVoltageError(what, err) - } - return "the pod on " + path, rep, nil } ctx, cancel, pod, err := g.podClient(what, 15*time.Second) if err != nil { @@ -262,9 +230,6 @@ func laVoltageLAN(ctx context.Context, client podCommander, mv int) (laVoltageRe // laVoltageError says when the firmware is too old, and leaves other refusals to the pod. func laVoltageError(what string, err error) error { - if errors.Is(err, serialconsole.ErrUnknownCommand) { - return errors.New(laVoltageMissing) - } if pe, ok := tcpclient.AsPodError(err); ok { if isUnknownCommand(err) { return errors.New(laVoltageMissing) @@ -274,19 +239,6 @@ func laVoltageError(what string, err error) error { return fmt.Errorf("%s: %w", what, err) } -// consoleHasUSBNet: the pod's console reports a USB network adapter (firmware 3.9.0+), which -// tells a console that moved a command to the JSON API from one too old to have it. -func consoleHasUSBNet(ctx context.Context, c laVoltageConsole) bool { - u, ok := c.(interface { - USBNetwork(context.Context) (serialconsole.USBNet, error) - }) - if !ok { - return false - } - _, err := u.USBNetwork(ctx) - return err == nil -} - // formatMV is 3300 -> "3.3 V". func formatMV(mv int) string { return strings.TrimSuffix(strings.TrimRight(fmt.Sprintf("%.3f", float64(mv)/1000), "0"), ".") + " V" diff --git a/cmd/benchpod-cli/lavoltage_test.go b/cmd/benchpod-cli/lavoltage_test.go index a0ab249..879150e 100644 --- a/cmd/benchpod-cli/lavoltage_test.go +++ b/cmd/benchpod-cli/lavoltage_test.go @@ -2,11 +2,9 @@ package main import ( "bytes" - "context" "errors" "strings" "testing" - "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" ) @@ -113,54 +111,28 @@ func TestLAVoltageLANRefusals(t *testing.T) { } } -type fakeLAVoltageConsole struct { - mv int - err error - set []int -} - -func (f *fakeLAVoltageConsole) LAVoltage(_ context.Context, mv int) (int, error) { - f.set = append(f.set, mv) - if f.err != nil { - return 0, f.err - } - if mv != 0 { - f.mv = mv - } - return f.mv, nil -} -func (f *fakeLAVoltageConsole) Close() error { return nil } - +// Over USB la voltage goes over the pod's USB network adapter; without it, it says why. func TestLAVoltageUSB(t *testing.T) { stubLAVoltageProfile(t, "", false, nil) - fc := &fakeLAVoltageConsole{} - saved := openLAVoltageConsole - t.Cleanup(func() { openLAVoltageConsole = saved }) - openLAVoltageConsole = func(_ *globalFlags, device string, _ time.Duration) (laVoltageConsole, string, context.Context, context.CancelFunc, error) { - return fc, "/dev/cu.usbmodem1", context.Background(), func() {}, nil - } + addr, got := fakeLANPod(t, `{"status":"ok","data":{"mv":1800,"st":1,"readback_mv":1800}}`) var out bytes.Buffer - if err := runLAVoltage(&globalFlags{connection: "usb"}, 1800, &out, &bytes.Buffer{}); err != nil { + if err := runLAVoltage(&globalFlags{connection: "usb", usbAddr: addr}, 1800, &out, &bytes.Buffer{}); err != nil { t.Fatal(err) } - if out.String() != "LA voltage of the pod on /dev/cu.usbmodem1 is now 1.8 V\n" || len(fc.set) != 1 || fc.set[0] != 1800 { - t.Fatalf("out = %q, set = %v", out.String(), fc.set) + if out.String() != "LA voltage of "+addr+" is now 1.8 V\n" { + t.Fatalf("out = %q", out.String()) } - - fc.err = &serialconsole.CommandError{Cmd: "la-voltage", Reason: "1.8 V needs a v3 pod; this board is v2 (its TPS2116 has no 1.8 V setting)"} - err := runLAVoltage(&globalFlags{connection: "usb"}, 1800, &bytes.Buffer{}, &bytes.Buffer{}) - if err == nil || err.Error() != "la voltage: the pod refused: "+fc.err.(*serialconsole.CommandError).Reason { - t.Fatalf("refusal: %v", err) - } - fc.err = serialconsole.ErrUnknownCommand - if err := runLAVoltage(&globalFlags{connection: "usb"}, 0, &bytes.Buffer{}, &bytes.Buffer{}); err == nil || err.Error() != laVoltageMissing { - t.Fatalf("old firmware: %v", err) - } - // A 3.9.0 console moved la-voltage to the network API, and the USB network was not usable. - fc.err = serialconsole.ErrMovedToNetwork - if err := runLAVoltage(&globalFlags{connection: "usb"}, 0, &bytes.Buffer{}, &bytes.Buffer{}); err == nil || - !strings.Contains(err.Error(), "network API") || !strings.Contains(err.Error(), "USB network is not usable") { - t.Fatalf("3.9.0 console without a usable USB network: %v", err) + if req := <-got; !strings.Contains(req, `"cmd":"la_voltage"`) || !strings.Contains(req, `"mv":1800`) { + t.Fatalf("request %s", req) + } + old := usbNetwork + usbNetwork = func(*globalFlags, string) (serialconsole.USBNet, error) { + return serialconsole.USBNet{PodIP: "10.237.8.85", HostIP: "10.237.8.86", OffBySetting: true}, nil + } + t.Cleanup(func() { usbNetwork = old }) + err := runLAVoltage(&globalFlags{connection: "usb"}, 0, &bytes.Buffer{}, &bytes.Buffer{}) + if err == nil || !strings.Contains(err.Error(), "usb-network on") { + t.Fatalf("no USB network: %v", err) } } diff --git a/cmd/benchpod-cli/usbbridge.go b/cmd/benchpod-cli/usbbridge.go index 19c2868..f9ddef0 100644 --- a/cmd/benchpod-cli/usbbridge.go +++ b/cmd/benchpod-cli/usbbridge.go @@ -14,6 +14,7 @@ import ( "time" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" "github.com/spf13/cobra" ) @@ -226,25 +227,25 @@ func newUSBReattachCmd(g *globalFlags) *cobra.Command { return &cobra.Command{ Use: "usb-reattach", Short: "Make the pod reconnect on USB, so this computer sets up its USB network adapter again", - Long: "Make the pod drop off the USB bus for half a second and connect again (USB console).\n" + + Long: "Make the pod drop off the USB bus for half a second and connect again (usb_reattach).\n" + "This computer then enumerates the console and the USB network adapter anew, as after\n" + "replugging the cable. macOS ignores a new network adapter while the screen is locked,\n" + "so run this after unlocking when the pod was plugged in or rebooted meanwhile.\n" + - "Needs firmware 3.9.0 or later.", + "The CLI sends it over the pod's USB network adapter when that is up, else over the\n" + + "pod's network address from its console status (or the --connection given); with\n" + + "neither, unplug the USB cable and plug it back in.", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error { - device, err := g.usbDevice("usb-reattach") + ctx, cancel, t, err := g.usbNetworkClient("usb-reattach", 10*time.Second) if err != nil { - return err - } - console, _, ctx, cancel, err := g.openSerialConsole(device, g.effectiveTimeout(10*time.Second)) - if err != nil { - return err + return fmt.Errorf("%w (or unplug the USB cable and plug it back in)", err) } defer cancel() - defer console.Close() - if err := console.USBReattach(ctx); err != nil { - return fmt.Errorf("usb-reattach: %w", err) + if _, err := t.client.Command(ctx, map[string]any{"cmd": "usb_reattach"}); err != nil { + // Over the USB link itself the connection drops with the re-enumeration. + if _, refused := tcpclient.AsPodError(err); refused || !t.spec.IsNetwork() || !tcpclient.IsUSBLinkAddr(hostOf(t.spec.Addr)) { + return wifiError("usb-reattach", err) + } } fmt.Fprintln(os.Stderr, "The pod reconnected on USB; its network adapter (unless turned off with `benchpod usb-network off`) is back in a few seconds.") return nil diff --git a/internal/serialconsole/netreset.go b/internal/serialconsole/netreset.go index 5196445..8e1b188 100644 --- a/internal/serialconsole/netreset.go +++ b/internal/serialconsole/netreset.go @@ -14,7 +14,9 @@ var ErrNoNetReset = errors.New("the pod's console has no net-reset (it needs fir // and puts Ethernet back to autonegotiation with a PHY reset and a new DHCP lease. It returns // the pod's `net-reset ...` lines: first the Ethernet one, then the Wi-Fi outcome. func (c *Console) NetReset(ctx context.Context) ([]string, error) { - done := func(acc string) bool { return strings.Contains(acc, "net-reset wifi") || strings.Contains(acc, "net-reset error") } + done := func(acc string) bool { + return strings.Contains(acc, "net-reset wifi") || strings.Contains(acc, "net-reset error") + } out, err := c.sendCommandUntil(ctx, "net-reset", "net-reset", "", done) var lines []string for _, ln := range consoleLines(out) { From d5777e2bf92059dee5846d8235c1626cbf1119b8 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Thu, 19 Nov 2026 21:55:23 -0600 Subject: [PATCH 10/21] serialconsole: keep only the console commands firmware 4.0 has Drop the console Wi-Fi, CA, proxy, upload, blobs, la-voltage, power, dap-start, identity-wipe and usb-reattach code and their tests: the CLI sends JSON over the USB network adapter for all of them. Add net-reset. Co-Authored-By: Claude Opus 5.5 --- internal/serialconsole/cloudcfg.go | 268 ---------- internal/serialconsole/cloudcfg_test.go | 207 -------- internal/serialconsole/identity.go | 32 -- internal/serialconsole/identity_test.go | 26 - internal/serialconsole/lavoltage.go | 75 --- internal/serialconsole/lavoltage_test.go | 95 ---- internal/serialconsole/netreset_test.go | 35 ++ internal/serialconsole/power_test.go | 80 --- internal/serialconsole/replies.go | 59 +++ internal/serialconsole/serialconsole.go | 205 +------- internal/serialconsole/serialconsole_test.go | 385 -------------- internal/serialconsole/upload.go | 340 +----------- internal/serialconsole/upload_test.go | 514 ------------------- internal/serialconsole/usbnet.go | 15 - internal/serialconsole/wifi.go | 302 ----------- internal/serialconsole/wifi_bridge_test.go | 127 ----- 16 files changed, 107 insertions(+), 2658 deletions(-) delete mode 100644 internal/serialconsole/cloudcfg.go delete mode 100644 internal/serialconsole/cloudcfg_test.go delete mode 100644 internal/serialconsole/lavoltage.go delete mode 100644 internal/serialconsole/lavoltage_test.go create mode 100644 internal/serialconsole/netreset_test.go delete mode 100644 internal/serialconsole/power_test.go create mode 100644 internal/serialconsole/replies.go delete mode 100644 internal/serialconsole/upload_test.go delete mode 100644 internal/serialconsole/wifi.go delete mode 100644 internal/serialconsole/wifi_bridge_test.go diff --git a/internal/serialconsole/cloudcfg.go b/internal/serialconsole/cloudcfg.go deleted file mode 100644 index 77dfed4..0000000 --- a/internal/serialconsole/cloudcfg.go +++ /dev/null @@ -1,268 +0,0 @@ -package serialconsole - -import ( - "context" - "errors" - "fmt" - "strings" - - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// The pod's company CA certificate and HTTP proxy over the console (firmware -// docs/design/cloud-hardening.md, section 3): -// -// ca -> ca (one line per certificate) | ca none -// ca-clear -> ca-clear ok | ca-clear error -// proxy -> proxy auth|noauth | proxy none -// proxy-set [user pw] -> proxy auth|noauth | proxy error -// proxy-clear -> proxy none -// -// Any command may also answer " error ". The CA itself is uploaded with the regular -// upload path (Upload with target "ca"). Older firmware answers "unknown command". - -// ErrUnknownCommand is older firmware's answer to a console command it does not have. It is the -// same value as ErrPolicyUnsupported, so either name matches with errors.Is. -var ErrUnknownCommand = ErrPolicyUnsupported - -// ConsoleLineMax is the longest command line the firmware's line editor takes (CONSOLE_LINE_MAX -// is 128 including the terminating NUL). -const ConsoleLineMax = 127 - -// CommandError is the pod refusing a console command (" error "). It is the CLI's one -// refusal type, tcpclient.PodError, with Cmd set. -type CommandError = tcpclient.PodError - -// CACert is one certificate of the pod's company CA, as the pod reports it. -type CACert struct { - Subject string `json:"subject"` - SHA256 string `json:"sha256"` // hex SHA-256 of the DER certificate -} - -// ProxyConfig is the pod's HTTP proxy. Addr is "" when no proxy is set. -type ProxyConfig struct { - Addr string // host:port - Auth bool // a user and password are stored (the pod never reports the password) -} - -// CloudCA lists the company CA certificates the pod holds (none: an empty list). -func (c *Console) CloudCA(ctx context.Context) ([]CACert, error) { - out, err := c.cfgCommand(ctx, "ca", "ca", "", parseCAComplete) - if err != nil { - return nil, err - } - certs, err := parseCA(out) - if errors.Is(err, errNoCAReply) { - return nil, fmt.Errorf("ca: no reply from the pod (got: %q)", tail([]byte(out), 200)) - } - return certs, err -} - -// CloudCAClear removes the pod's company CA. -func (c *Console) CloudCAClear(ctx context.Context) error { - out, err := c.cfgCommand(ctx, "ca-clear", "ca-clear", "", func(s string) bool { - _, ok := lastReply(s, "ca-clear", "ca-clear") - return ok - }) - if err != nil { - return err - } - rest, ok := lastReply(out, "ca-clear", "ca-clear") - if !ok { - return fmt.Errorf("ca-clear: no reply from the pod (got: %q)", tail([]byte(out), 200)) - } - if why, isErr := replyError(rest); isErr { - return &CommandError{Cmd: "ca-clear", Reason: why} - } - return nil -} - -// CloudProxy reports the pod's HTTP proxy. -func (c *Console) CloudProxy(ctx context.Context) (ProxyConfig, error) { - return c.proxyCommand(ctx, "proxy", "proxy", "") -} - -// CloudProxyClear removes the pod's HTTP proxy and returns what the pod reports afterwards. -func (c *Console) CloudProxyClear(ctx context.Context) (ProxyConfig, error) { - return c.proxyCommand(ctx, "proxy-clear", "proxy-clear", "") -} - -// CloudProxySet sets the pod's HTTP proxy to addr (host:port), with a user and password when -// user is not empty. The password never reaches a log line or an error message. -func (c *Console) CloudProxySet(ctx context.Context, addr, user, password string) (ProxyConfig, error) { - addr = strings.TrimSpace(addr) - if addr == "" || strings.ContainsAny(addr, " \t\r\n") { - return ProxyConfig{}, fmt.Errorf("proxy-set: bad address %q", addr) - } - if (user == "") != (password == "") { - return ProxyConfig{}, errors.New("proxy-set: pass both a user and a password, or neither") - } - if strings.ContainsAny(user, " \t\r\n") || strings.ContainsAny(password, " \t\r\n") { - return ProxyConfig{}, errors.New("proxy-set: the USB console cannot carry a user or password with spaces; set it over the LAN") - } - line, display := "proxy-set "+addr, "proxy-set "+addr - if user != "" { - line += " " + user + " " + password - display += " " + user + " ***" - } - if len(line) > ConsoleLineMax { - return ProxyConfig{}, fmt.Errorf("proxy-set: the command is %d characters, the USB console takes %d; use a shorter host, user or password, or set it over the LAN", - len(line), ConsoleLineMax) - } - return c.proxyCommand(ctx, line, display, password) -} - -func (c *Console) proxyCommand(ctx context.Context, line, display, secret string) (ProxyConfig, error) { - cmd := strings.Fields(line)[0] - done := func(s string) bool { - _, ok := proxyReply(s, cmd, line) - return ok - } - out, err := c.cfgCommand(ctx, line, display, secret, done) - if err != nil { - return ProxyConfig{}, err - } - rest, ok := proxyReply(out, cmd, line) - if !ok { - return ProxyConfig{}, fmt.Errorf("%s: no reply from the pod (got: %q)", cmd, maskPassword(tail([]byte(out), 200), secret)) - } - if why, isErr := replyError(rest); isErr { - return ProxyConfig{}, &CommandError{Cmd: cmd, Reason: maskPassword(why, secret)} - } - f := strings.Fields(rest) - if f[0] == "none" { - return ProxyConfig{}, nil - } - p := ProxyConfig{Addr: f[0]} - if len(f) > 1 { - p.Auth = f[1] == "auth" - } - return p, nil -} - -// proxyReply is the pod's answer to a proxy command: a "proxy ..." line, or " error ...". -func proxyReply(raw, cmd, line string) (string, bool) { - if cmd != "proxy" { - if rest, ok := lastReply(raw, cmd, line); ok { - if _, isErr := replyError(rest); isErr { - return rest, true - } - } - } - return lastReply(raw, "proxy", line) -} - -// cfgCommand sends line (shown as display, with secret masked) and reads until complete reports -// the reply is in (or the prompt and a short grace passed). An "unknown command" answer is -// ErrUnknownCommand. -func (c *Console) cfgCommand(ctx context.Context, line, display, secret string, complete func(string) bool) (string, error) { - cmd := strings.Fields(line)[0] - unknownOrDone := func(s string) bool { return strings.Contains(s, "unknown command") || complete(s) } - out, err := c.sendCommandUntil(ctx, line, display, secret, unknownOrDone) - if strings.Contains(out, "unknown command") { - return "", ErrUnknownCommand - } - if err != nil && !complete(out) { - return "", fmt.Errorf("%s: %w", cmd, err) - } - return out, nil -} - -// consoleLines splits raw console output into trimmed lines, dropping prompts and backspaces. -func consoleLines(raw string) []string { - s := strings.ReplaceAll(raw, "\r\n", "\n") - s = strings.ReplaceAll(s, "\r", "\n") - var lines []string - for _, ln := range strings.Split(s, "\n") { - ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) - if ln != "" { - lines = append(lines, ln) - } - } - return lines -} - -// lastReply returns what follows " " on the last line that starts with it, skipping the -// first copy of the echoed command line. -func lastReply(raw, word, line string) (string, bool) { - echoSeen := false - var rest string - found := false - for _, ln := range consoleLines(raw) { - if !echoSeen && ln == line { - echoSeen = true - continue - } - if strings.HasPrefix(ln, word+" ") { - rest, found = strings.TrimSpace(ln[len(word)+1:]), true - } - } - return rest, found && rest != "" -} - -// replyError reports whether a reply is "error ", and the why. -func replyError(rest string) (string, bool) { - if rest != "error" && !strings.HasPrefix(rest, "error ") { - return "", false - } - why := strings.TrimSpace(strings.TrimPrefix(rest, "error")) - if why == "" { - why = "refused" - } - return why, true -} - -// parseCAComplete reports whether the reply to `ca` is in: "ca none", an error, or at least one -// certificate line. More certificate lines may follow; the prompt ends the read. -func parseCAComplete(raw string) bool { - _, err := parseCA(raw) - return err == nil || !errors.Is(err, errNoCAReply) -} - -var errNoCAReply = errors.New("no ca reply yet") - -// parseCA reads "ca " lines (the subject may hold spaces; the hash is the -// last field), "ca none", or "ca error ". -func parseCA(raw string) ([]CACert, error) { - var certs []CACert - none := false - for _, ln := range consoleLines(raw) { - rest, ok := strings.CutPrefix(ln, "ca ") - if !ok { - continue - } - rest = strings.TrimSpace(rest) - if why, isErr := replyError(rest); isErr { - return nil, &CommandError{Cmd: "ca", Reason: why} - } - if rest == "none" { - none = true - continue - } - i := strings.LastIndexAny(rest, " \t") - if i < 0 { - continue - } - sha := strings.ToLower(rest[i+1:]) - if !isHex64(sha) { - continue - } - certs = append(certs, CACert{Subject: strings.TrimSpace(rest[:i]), SHA256: sha}) - } - if len(certs) == 0 && !none { - return nil, errNoCAReply - } - return certs, nil -} - -func isHex64(s string) bool { - if len(s) != 64 { - return false - } - for _, r := range s { - if !(r >= '0' && r <= '9' || r >= 'a' && r <= 'f') { - return false - } - } - return true -} diff --git a/internal/serialconsole/cloudcfg_test.go b/internal/serialconsole/cloudcfg_test.go deleted file mode 100644 index 2e033d0..0000000 --- a/internal/serialconsole/cloudcfg_test.go +++ /dev/null @@ -1,207 +0,0 @@ -package serialconsole - -import ( - "bytes" - "context" - "errors" - "fmt" - "strings" - "testing" -) - -const ( - shaA = "8f2a6e0a3c5b0f1e9d7c6b5a4938271605f4e3d2c1b0a9988776655443322110" - shaB = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" -) - -// cfgPod answers ca, ca-clear, proxy, proxy-set and proxy-clear like the firmware's console: -// the line is echoed, a log line may interleave, then the reply and the prompt. old makes it -// answer like firmware without the commands. -type cfgPod struct { - certs []CACert - proxy string - auth bool - old bool - failNext string // the next ca-clear or proxy-set answers " error " - lines []string -} - -func (p *cfgPod) console() *Console { - fc := &fakeConsole{onWrite: func(line string, out *bytes.Buffer) { - p.lines = append(p.lines, line) - out.WriteString(line + "\r\n") - out.WriteString("[cloud] reconnect in 5 s\r\n") - f := strings.Fields(line) - switch { - case p.old: - fmt.Fprintf(out, " unknown command '%s' (try 'help')\r\n", f[0]) - case f[0] == "ca": - if len(p.certs) == 0 { - out.WriteString("ca none\r\n") - } - for _, c := range p.certs { - fmt.Fprintf(out, "ca %s %s\r\n", c.Subject, c.SHA256) - } - case f[0] == "ca-clear" && p.failNext != "": - fmt.Fprintf(out, "ca-clear error %s\r\n", p.failNext) - p.failNext = "" - case f[0] == "ca-clear": - p.certs = nil - out.WriteString("ca-clear ok\r\n") - case f[0] == "proxy-set" && p.failNext != "": - fmt.Fprintf(out, "proxy error %s\r\n", p.failNext) - p.failNext = "" - case f[0] == "proxy-set": - p.proxy, p.auth = f[1], len(f) == 4 - fallthrough - case f[0] == "proxy": - if p.proxy == "" { - out.WriteString("proxy none\r\n") - } else if p.auth { - fmt.Fprintf(out, "proxy %s auth\r\n", p.proxy) - } else { - fmt.Fprintf(out, "proxy %s noauth\r\n", p.proxy) - } - case f[0] == "proxy-clear": - p.proxy, p.auth = "", false - out.WriteString("proxy none\r\n") - } - out.WriteString("> ") - }} - return newConsole(fc) -} - -func TestCloudCAShowAndClear(t *testing.T) { - pod := &cfgPod{certs: []CACert{{"CN=Acme Root CA, O=Acme Corp", shaA}, {"CN=Acme Issuing CA 2", shaB}}} - c := pod.console() - - certs, err := c.CloudCA(testContext(t)) - if err != nil { - t.Fatalf("ca: %v", err) - } - if len(certs) != 2 || certs[0] != pod.certs[0] || certs[1] != pod.certs[1] { - t.Fatalf("ca = %+v", certs) - } - - if err := c.CloudCAClear(testContext(t)); err != nil { - t.Fatalf("ca-clear: %v", err) - } - certs, err = c.CloudCA(testContext(t)) - if err != nil || len(certs) != 0 { - t.Fatalf("ca after clear = %+v, %v", certs, err) - } - - pod.failNext = "w25q write failed" - err = c.CloudCAClear(testContext(t)) - var ce *CommandError - if !errors.As(err, &ce) || ce.Reason != "w25q write failed" { - t.Fatalf("ca-clear refusal = %v", err) - } -} - -func TestCloudProxySetShowClear(t *testing.T) { - pod := &cfgPod{} - c := pod.console() - var logs bytes.Buffer - c.logf = func(format string, a ...any) { fmt.Fprintf(&logs, format+"\n", a...) } - - p, err := c.CloudProxy(testContext(t)) - if err != nil || p.Addr != "" { - t.Fatalf("proxy = %+v, %v", p, err) - } - p, err = c.CloudProxySet(testContext(t), "proxy.corp:3128", "alice", "s3cret") - if err != nil || p.Addr != "proxy.corp:3128" || !p.Auth { - t.Fatalf("proxy-set = %+v, %v", p, err) - } - if got := pod.lines[len(pod.lines)-1]; got != "proxy-set proxy.corp:3128 alice s3cret" { - t.Fatalf("sent %q", got) - } - if strings.Contains(logs.String(), "s3cret") { - t.Fatalf("the password reached the log:\n%s", logs.String()) - } - p, err = c.CloudProxySet(testContext(t), "10.0.0.1:8080", "", "") - if err != nil || p.Addr != "10.0.0.1:8080" || p.Auth { - t.Fatalf("proxy-set noauth = %+v, %v", p, err) - } - p, err = c.CloudProxyClear(testContext(t)) - if err != nil || p.Addr != "" { - t.Fatalf("proxy-clear = %+v, %v", p, err) - } - - pod.failNext = "cannot resolve host" - _, err = c.CloudProxySet(testContext(t), "nowhere:1", "", "") - var ce *CommandError - if !errors.As(err, &ce) || ce.Cmd != "proxy-set" || ce.Reason != "cannot resolve host" { - t.Fatalf("proxy-set refusal = %v", err) - } -} - -func TestCloudProxySetLocalChecks(t *testing.T) { - pod := &cfgPod{} - c := pod.console() - for _, tc := range []struct{ addr, user, pass, want string }{ - {"a b:1", "", "", "bad address"}, - {"p:1", "u", "", "both a user and a password"}, - {"p:1", "u", "pa ss", "spaces"}, - {"p:1", "u", strings.Repeat("x", 120), "the USB console takes 127"}, - } { - _, err := c.CloudProxySet(context.Background(), tc.addr, tc.user, tc.pass) - if err == nil || !strings.Contains(err.Error(), tc.want) { - t.Errorf("%+v: err = %v, want %q", tc, err, tc.want) - } - if err != nil && tc.pass != "" && strings.Contains(err.Error(), tc.pass) { - t.Errorf("the password is in the error: %v", err) - } - } - if len(pod.lines) != 0 { - t.Fatalf("a refused value reached the pod: %v", pod.lines) - } -} - -func TestCloudConfigOldFirmware(t *testing.T) { - c := (&cfgPod{old: true}).console() - if _, err := c.CloudCA(testContext(t)); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("ca: %v", err) - } - if err := c.CloudCAClear(testContext(t)); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("ca-clear: %v", err) - } - if _, err := c.CloudProxy(testContext(t)); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("proxy: %v", err) - } - if _, err := c.CloudProxySet(testContext(t), "p:1", "u", "pw"); !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("proxy-set: %v", err) - } -} - -func TestParseCA(t *testing.T) { - raw := "ca\r\n[log] x\r\nca CN=Root With Spaces " + strings.ToUpper(shaA) + "\r\nca garbage\r\n> " - certs, err := parseCA(raw) - if err != nil || len(certs) != 1 || certs[0].Subject != "CN=Root With Spaces" || certs[0].SHA256 != shaA { - t.Fatalf("parseCA = %+v, %v", certs, err) - } - if _, err := parseCA("ca\r\n> "); !errors.Is(err, errNoCAReply) { - t.Fatalf("echo only: %v", err) - } - var ce *CommandError - if _, err := parseCA("ca\r\nca error w25q read failed\r\n> "); !errors.As(err, &ce) || ce.Reason != "w25q read failed" { - t.Fatalf("error reply: %v", err) - } -} - -func TestUploadCATarget(t *testing.T) { - sim := newPodUploadSim() - c := newConsole(sim) - pem := []byte("-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n") - if err := c.Upload(context.Background(), "ca", pem, 0, nil); err != nil { - t.Fatalf("upload ca: %v", err) - } - if !bytes.Equal(sim.committed["ca"], pem) { - t.Fatalf("committed %q", sim.committed["ca"]) - } - for _, cmd := range sim.commands { - if strings.HasPrefix(cmd, "upload-sig") { - t.Fatalf("a CA upload sent %q", cmd) - } - } -} diff --git a/internal/serialconsole/identity.go b/internal/serialconsole/identity.go index 71468c6..2a6046c 100644 --- a/internal/serialconsole/identity.go +++ b/internal/serialconsole/identity.go @@ -88,38 +88,6 @@ func parseIdentityState(reply string) (IdentityState, error) { return IdentityState{ShortID: f[0], PublicKey: f[1]}, nil } -// IdentityWipe erases the pod's device key and makes a new one, confirming with token (the -// current short id, or "unknown"). It returns the new short id. -func (c *Console) IdentityWipe(ctx context.Context, token string) (string, error) { - token = strings.TrimSpace(token) - if token == "" || strings.ContainsAny(token, " \t\r\n") { - return "", fmt.Errorf("identity-wipe: bad confirmation token %q", token) - } - line := "identity-wipe " + token - complete := func(acc string) bool { - _, _, err := parseConsoleReply(acc, "identity-wipe", line) - return !errors.Is(err, errNoConsoleReply) - } - out, err := c.sendCommandUntil(ctx, line, line, "", complete) - reply, refused, perr := parseConsoleReply(out, "identity-wipe", line) - switch { - case perr == nil && refused: - return "", &IdentityError{Cmd: "identity-wipe", Reason: reply} - case perr == nil: - f := strings.Fields(reply) - if len(f) < 2 || f[0] != "ok" { - return "", fmt.Errorf("identity-wipe: unexpected reply %q", reply) - } - return f[1], nil - case !errors.Is(perr, errNoConsoleReply): - return "", perr - case err != nil: - return "", fmt.Errorf("identity-wipe: %w", err) - default: - return "", fmt.Errorf("identity-wipe: no reply from the pod (got: %q)", tail([]byte(out), 200)) - } -} - var errNoConsoleReply = errors.New("no reply yet") // parseConsoleReply finds " " in raw console output, skipping the line editor's echo diff --git a/internal/serialconsole/identity_test.go b/internal/serialconsole/identity_test.go index cd981b3..b5fe57f 100644 --- a/internal/serialconsole/identity_test.go +++ b/internal/serialconsole/identity_test.go @@ -64,35 +64,9 @@ func TestIdentityShow(t *testing.T) { } } -func TestIdentityWipe(t *testing.T) { - pod := &identityPod{problem: "unknown identity record", newID: "ed6313"} - c, fc := pod.console() - if _, err := c.IdentityWipe(testContext(t), "a1b2c3"); err == nil { - t.Fatal("a wrong token was accepted") - } else { - var ie *IdentityError - if !errors.As(err, &ie) || !strings.Contains(ie.Reason, "identity-wipe unknown") { - t.Fatalf("err = %v", err) - } - } - id, err := c.IdentityWipe(testContext(t), "unknown") - if err != nil || id != "ed6313" { - t.Fatalf("wipe = %q, %v", id, err) - } - if got := fc.written.String(); got != "identity-wipe a1b2c3\nidentity-wipe unknown\n" { - t.Fatalf("written = %q", got) - } - if _, err := c.IdentityWipe(testContext(t), "two words"); err == nil { - t.Fatal("a token with a space was sent") - } -} - func TestIdentityOldFirmware(t *testing.T) { c, _ := (&identityPod{old: true}).console() if _, err := c.Identity(testContext(t)); !errors.Is(err, ErrIdentityUnsupported) { t.Fatalf("identity err = %v", err) } - if _, err := c.IdentityWipe(testContext(t), "unknown"); !errors.Is(err, ErrIdentityUnsupported) { - t.Fatalf("wipe err = %v", err) - } } diff --git a/internal/serialconsole/lavoltage.go b/internal/serialconsole/lavoltage.go deleted file mode 100644 index 8578c8e..0000000 --- a/internal/serialconsole/lavoltage.go +++ /dev/null @@ -1,75 +0,0 @@ -package serialconsole - -import ( - "context" - "errors" - "fmt" - "regexp" - "strconv" - "strings" -) - -// The LA bank voltage over the console (firmware console.c, "la-voltage"): -// -// la-voltage -> LA VCCIO = 3300 mV (st=1) | LA VCCIO = UNSET (st=0) -// la-voltage 1800|3300 -> LA VCCIO = 1800 mV (st=0) -// | 1.8 V needs a v3 pod; this board is ... -// | la voltage can't change while pins are in use: ... -// | usage: la-voltage <1800|3300> - -var laVCCIOLine = regexp.MustCompile(`LA VCCIO = (UNSET|\d+ mV)`) - -// laVoltageRefusals start the console's refusal lines. -var laVoltageRefusals = []string{"1.8 V needs", "la voltage ", "usage: la-voltage"} - -var errNoLAVoltageReply = errors.New("no la-voltage reply yet") - -// LAVoltage sets the LA bank voltage to mv (1800 or 3300), or only reads it when mv is 0, and -// returns the selection the pod reports afterwards in millivolts (0: not set yet). -func (c *Console) LAVoltage(ctx context.Context, mv int) (int, error) { - line := "la-voltage" - if mv != 0 { - line += " " + strconv.Itoa(mv) - } - complete := func(acc string) bool { - _, err := parseLAVoltageReply(acc) - return !errors.Is(err, errNoLAVoltageReply) - } - out, err := c.sendCommandUntil(ctx, line, line, "", complete) - got, perr := parseLAVoltageReply(out) - if perr == nil || !errors.Is(perr, errNoLAVoltageReply) { - return got, perr - } - if err != nil { - return 0, err - } - return 0, fmt.Errorf("la-voltage: no reply from the pod (got: %q)", tail([]byte(out), 200)) -} - -// parseLAVoltageReply finds the reply in raw console output; log lines interleave freely. -func parseLAVoltageReply(raw string) (int, error) { - s := strings.ReplaceAll(raw, "\r\n", "\n") - s = strings.ReplaceAll(s, "\r", "\n") - for _, ln := range strings.Split(s, "\n") { - ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) - if strings.Contains(ln, movedLine) { - return 0, ErrMovedToNetwork - } - if strings.Contains(ln, "unknown command") { - return 0, ErrUnknownCommand - } - if m := laVCCIOLine.FindStringSubmatch(ln); m != nil { - if m[1] == "UNSET" { - return 0, nil - } - n, _ := strconv.Atoi(strings.TrimSuffix(m[1], " mV")) - return n, nil - } - for _, p := range laVoltageRefusals { - if strings.HasPrefix(ln, p) { - return 0, &CommandError{Cmd: "la-voltage", Reason: ln} - } - } - } - return 0, errNoLAVoltageReply -} diff --git a/internal/serialconsole/lavoltage_test.go b/internal/serialconsole/lavoltage_test.go deleted file mode 100644 index c2feb2f..0000000 --- a/internal/serialconsole/lavoltage_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package serialconsole - -import ( - "bytes" - "errors" - "fmt" - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// laVoltagePod answers la-voltage like the firmware's console (console.c). -type laVoltagePod struct { - mv int - v2 bool // a v2 board: no 1.8 V - inUse string // pins in use: a change is refused - old bool - moved bool // firmware 3.9.0+: la-voltage moved to the JSON API - writes []string -} - -func (p *laVoltagePod) console() *Console { - return newConsole(&fakeConsole{onWrite: func(line string, out *bytes.Buffer) { - p.writes = append(p.writes, line) - out.WriteString(line + "\r\n[net] dhcp renew\r\n") - f := strings.Fields(line) - switch { - case p.old: - fmt.Fprintf(out, " unknown command '%s' (try 'help')\r\n", f[0]) - case p.moved: - fmt.Fprintf(out, "%s: moved to the network API (JSON la_voltage) in firmware 3.9.0; update the benchpod CLI to 0.6.0 or later (or embeddedci to 2.12.0), which uses it over USB\r\n", f[0]) - case len(f) == 1 && p.mv == 0: - out.WriteString(" LA VCCIO = UNSET (st=0)\r\n") - case len(f) == 1: - fmt.Fprintf(out, " LA VCCIO = %d mV (st=1)\r\n", p.mv) - case p.inUse != "" && f[1] != fmt.Sprint(p.mv): - fmt.Fprintf(out, " la voltage can't change while pins are in use: %s; stop them first\r\n", p.inUse) - case f[1] == "1800" && p.v2: - out.WriteString(" 1.8 V needs a v3 pod; this board is v2 (its TPS2116 has no 1.8 V setting)\r\n") - case f[1] == "1800" || f[1] == "3300": - fmt.Sscan(f[1], &p.mv) - fmt.Fprintf(out, " LA VCCIO = %d mV (st=1)\r\n", p.mv) - default: - out.WriteString(" usage: la-voltage <1800|3300>\r\n") - } - out.WriteString("> ") - }}) -} - -func TestLAVoltageShowAndSet(t *testing.T) { - pod := &laVoltagePod{} - c := pod.console() - if mv, err := c.LAVoltage(testContext(t), 0); err != nil || mv != 0 { - t.Fatalf("unset = %d, %v", mv, err) - } - if mv, err := c.LAVoltage(testContext(t), 3300); err != nil || mv != 3300 || pod.mv != 3300 { - t.Fatalf("set = %d, %v", mv, err) - } - if mv, err := c.LAVoltage(testContext(t), 0); err != nil || mv != 3300 { - t.Fatalf("show = %d, %v", mv, err) - } - if got := strings.Join(pod.writes, "|"); got != "la-voltage|la-voltage 3300|la-voltage" { - t.Fatalf("writes = %s", got) - } -} - -func TestLAVoltageRefusals(t *testing.T) { - for _, pod := range []*laVoltagePod{ - {mv: 3300, v2: true}, - {mv: 3300, inUse: "LA3 (uart_rx), LA4 (uart_tx)"}, - } { - _, err := pod.console().LAVoltage(testContext(t), 1800) - pe, ok := tcpclient.AsPodError(err) - if !ok || pe.Cmd != "la-voltage" || pe.Reason == "" || strings.HasPrefix(pe.Reason, " ") { - t.Fatalf("err = %#v", err) - } - } - _, err := (&laVoltagePod{old: true}).console().LAVoltage(testContext(t), 0) - if !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("old firmware: %v", err) - } -} - -// Firmware 3.9.0 answers la-voltage with the moved line; firmware before it runs the command. -func TestLAVoltageAcrossFirmwareGenerations(t *testing.T) { - _, err := (&laVoltagePod{moved: true}).console().LAVoltage(testContext(t), 3300) - if !errors.Is(err, ErrMovedToNetwork) { - t.Fatalf("3.9.0 console: err = %v, want ErrMovedToNetwork", err) - } - got, err := (&laVoltagePod{}).console().LAVoltage(testContext(t), 3300) - if err != nil || got != 3300 { - t.Fatalf("older firmware: %d, %v", got, err) - } -} diff --git a/internal/serialconsole/netreset_test.go b/internal/serialconsole/netreset_test.go new file mode 100644 index 0000000..5f1f57a --- /dev/null +++ b/internal/serialconsole/netreset_test.go @@ -0,0 +1,35 @@ +package serialconsole + +import ( + "bytes" + "errors" + "reflect" + "testing" +) + +func netResetConsole(reply string) *Console { + return newConsole(&fakeConsole{onWrite: func(line string, out *bytes.Buffer) { + out.WriteString(line + "\r\n") + out.WriteString("[eth] link down\r\n") + out.WriteString(reply) + out.WriteString("> ") + }}) +} + +func TestNetReset(t *testing.T) { + c := netResetConsole("net-reset eth autonegotiation, link and DHCP again\r\n" + + "net-reset wifi cleared (pod flash and the ESP32-C3's NVS)\r\n") + lines, err := c.NetReset(testContext(t)) + want := []string{"net-reset eth autonegotiation, link and DHCP again", "net-reset wifi cleared (pod flash and the ESP32-C3's NVS)"} + if err != nil || !reflect.DeepEqual(lines, want) { + t.Fatalf("lines %q, err %v", lines, err) + } + c = netResetConsole(" unknown command 'net-reset' (try 'help')\r\n") + if _, err := c.NetReset(testContext(t)); !errors.Is(err, ErrNoNetReset) { + t.Fatalf("old firmware: %v", err) + } + c = netResetConsole("net-reset error busy: a capture is running\r\n") + if _, err := c.NetReset(testContext(t)); err == nil || err.Error() != "net-reset: busy: a capture is running" { + t.Fatalf("refusal: %v", err) + } +} diff --git a/internal/serialconsole/power_test.go b/internal/serialconsole/power_test.go deleted file mode 100644 index a0a7a6d..0000000 --- a/internal/serialconsole/power_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package serialconsole - -import ( - "bytes" - "errors" - "fmt" - "strings" - "testing" - - "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" -) - -// powerPod answers `power` like the firmware's console (console.c). -type powerPod struct { - old bool - moved bool // firmware 3.9.0+: power moved to the JSON API - on [3]bool - writes []string -} - -func (p *powerPod) console() *Console { - return newConsole(&fakeConsole{onWrite: func(line string, out *bytes.Buffer) { - p.writes = append(p.writes, line) - out.WriteString(line + "\r\n[net] dhcp renew\r\n") - f := strings.Fields(line) - switch { - case p.moved: - fmt.Fprintf(out, "%s: moved to the network API (JSON target_power) in firmware 3.9.0; update the benchpod CLI to 0.6.0 or later (or embeddedci to 2.12.0), which uses it over USB\r\n", f[0]) - case p.old || f[0] != "power" || len(f) < 3: - fmt.Fprintf(out, " unknown command '%s' (try 'help')\r\n", f[0]) - case f[1] != "1" && f[1] != "2": - out.WriteString(" bad eFuse index\r\n") - default: - var e int - fmt.Sscan(f[1], &e) - p.on[e] = f[2] == "on" - state := "OFF" - if p.on[e] { - state = "ON" - } - fmt.Fprintf(out, " eFuse%d %s\r\n", e, state) - } - out.WriteString("> ") - }}) -} - -func TestTargetPowerOnOff(t *testing.T) { - pod := &powerPod{} - c := pod.console() - if err := c.TargetPower(testContext(t), 1, true); err != nil || !pod.on[1] { - t.Fatalf("on: %v (on=%v)", err, pod.on[1]) - } - if err := c.TargetPower(testContext(t), 1, false); err != nil || pod.on[1] { - t.Fatalf("off: %v (on=%v)", err, pod.on[1]) - } - if got := strings.Join(pod.writes, "|"); got != "power 1 on|power 1 off" { - t.Fatalf("writes = %s", got) - } -} - -func TestTargetPowerRefusals(t *testing.T) { - err := (&powerPod{}).console().TargetPower(testContext(t), 3, true) - if pe, ok := tcpclient.AsPodError(err); !ok || pe.Cmd != "power" || pe.Reason != "bad eFuse index" { - t.Fatalf("bad index: %#v", err) - } - // A console without the command must fail, not pass for a powered target. - err = (&powerPod{old: true}).console().TargetPower(testContext(t), 1, true) - if !errors.Is(err, ErrUnknownCommand) { - t.Fatalf("old firmware: %v", err) - } -} - -func TestTargetPowerAcrossFirmwareGenerations(t *testing.T) { - if err := (&powerPod{moved: true}).console().TargetPower(testContext(t), 1, true); !errors.Is(err, ErrMovedToNetwork) { - t.Fatalf("3.9.0 console: err = %v, want ErrMovedToNetwork", err) - } - if err := (&powerPod{}).console().TargetPower(testContext(t), 1, true); err != nil { - t.Fatalf("older firmware: %v", err) - } -} diff --git a/internal/serialconsole/replies.go b/internal/serialconsole/replies.go new file mode 100644 index 0000000..1eab578 --- /dev/null +++ b/internal/serialconsole/replies.go @@ -0,0 +1,59 @@ +package serialconsole + +import ( + "strings" + + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" +) + +// ErrUnknownCommand is older firmware's answer to a console command it does not have. It is the +// same value as ErrPolicyUnsupported, so either name matches with errors.Is. +var ErrUnknownCommand = ErrPolicyUnsupported + +// CommandError is the pod refusing a console command (" error "). It is the CLI's one +// refusal type, tcpclient.PodError, with Cmd set. +type CommandError = tcpclient.PodError + +// consoleLines splits raw console output into trimmed lines, dropping prompts and backspaces. +func consoleLines(raw string) []string { + s := strings.ReplaceAll(raw, "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") + var lines []string + for _, ln := range strings.Split(s, "\n") { + ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) + if ln != "" { + lines = append(lines, ln) + } + } + return lines +} + +// lastReply returns what follows " " on the last line that starts with it, skipping the +// first copy of the echoed command line. +func lastReply(raw, word, line string) (string, bool) { + echoSeen := false + var rest string + found := false + for _, ln := range consoleLines(raw) { + if !echoSeen && ln == line { + echoSeen = true + continue + } + if strings.HasPrefix(ln, word+" ") { + rest, found = strings.TrimSpace(ln[len(word)+1:]), true + } + } + return rest, found && rest != "" +} + +// replyError reports whether a reply is "error ", and the why. +func replyError(rest string) (string, bool) { + if rest != "error" && !strings.HasPrefix(rest, "error ") { + return "", false + } + why := strings.TrimSpace(strings.TrimPrefix(rest, "error")) + if why == "" { + why = "refused" + } + return why, true +} diff --git a/internal/serialconsole/serialconsole.go b/internal/serialconsole/serialconsole.go index 22b63de..c0a708b 100644 --- a/internal/serialconsole/serialconsole.go +++ b/internal/serialconsole/serialconsole.go @@ -20,7 +20,6 @@ import ( "path/filepath" "sort" "strings" - "sync" "time" "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" @@ -90,11 +89,6 @@ const perReadTimeout = 250 * time.Millisecond // exactly this; any "ERROR:"/"usage:" line before it is a handshake failure. const dapReadySentinel = "dap ready" -// dapFlushDelay gives the final leave frame time to reach the firmware over USB -// before the port is closed, so the probe is disarmed promptly rather than only -// by the firmware's 60s inactivity watchdog. -const dapFlushDelay = 50 * time.Millisecond - // errPortVanished is returned by sendCommand when the port reaches EOF before a // prompt. For most commands that is a failure; for Bootsel it is the expected // success signal (the device reboots into the UF2 bootloader and the CDC-ACM @@ -553,55 +547,8 @@ func (c *Console) sendCommandWait(ctx context.Context, line, display, secret str } } -// TargetPower enables (on) or disables a target power eFuse over the console -// (firmware console.c: `power <1|2> `, which answers "eFuse1 ON", -// "eFuse1 OFF" or "bad eFuse index"). efuse is 1 (internal 5V) or 2 (external). -// Anything but the matching eFuse line is reported as an error, so a console -// that does not know the command can no longer pass for a powered target. -func (c *Console) TargetPower(ctx context.Context, efuse int, on bool) error { - state, want := "off", "OFF" - if on { - state, want = "on", "ON" - } - line := fmt.Sprintf("power %d %s", efuse, state) - complete := func(acc string) bool { - return !errors.Is(parsePowerReply(acc, efuse, want), errNoPowerReply) - } - out, err := c.sendCommandUntil(ctx, line, line, "", complete) - perr := parsePowerReply(out, efuse, want) - if !errors.Is(perr, errNoPowerReply) { - return perr - } - if err != nil { - return err - } - return fmt.Errorf("power: no reply from the pod (got: %q)", tail([]byte(out), 200)) -} - var errNoPowerReply = errors.New("no power reply yet") -// parsePowerReply finds the `power` reply in raw console output; log lines -// interleave freely. -func parsePowerReply(raw string, efuse int, want string) error { - ok := fmt.Sprintf("eFuse%d %s", efuse, want) - s := strings.ReplaceAll(raw, "\r\n", "\n") - s = strings.ReplaceAll(s, "\r", "\n") - for _, ln := range strings.Split(s, "\n") { - ln = strings.TrimSpace(strings.TrimLeft(ln, "> \t\x08")) - switch { - case strings.Contains(ln, movedLine): - return ErrMovedToNetwork - case strings.Contains(ln, "unknown command"): - return ErrUnknownCommand - case ln == ok: - return nil - case strings.HasPrefix(ln, "bad eFuse"), strings.HasPrefix(ln, "ERROR:"): - return &CommandError{Cmd: "power", Reason: ln} - } - } - return errNoPowerReply -} - // Status runs the firmware's `status` console command and returns its output as // presentable text (the console prints human-readable lines, not JSON). The // echoed command and the trailing prompt are stripped; interleaved async log @@ -679,70 +626,6 @@ func (c *Console) Dfu(ctx context.Context) error { return errors.New("device did not acknowledge dfu (RP2350 pods use `bootsel` instead)") } -// DAPStart enters the firmware's length-framed CMSIS-DAP probe mode over the -// console. It sends `dap-start `, then reads console -// lines until the firmware prints the `dap ready` sentinel; any `ERROR:`/`usage:` -// line before it is a handshake failure. On success the port is switched to -// blocking reads and an io.ReadWriteCloser carrying the raw framed DAP stream is -// returned — ready to hand to openocd.BridgeDAP. Its Close sends a zero-length -// frame to disarm the probe and return the console to its prompt, mirroring how -// closing the TCP connection returns the pod to a safe state. The firmware's 60s -// inactivity watchdog is the backstop if Close never runs. -// -// swclk/swdio are LA pin numbers (1-14); the caller is responsible for -// parsing/validating them (see parseLAPin in the CLI). Target reset is not a -// parameter: since pod rev3 nRESET is the pod's own pin on J1 pin 22, driven by -// the firmware behind CMSIS-DAP SWJ_PINS. -// -// If the firmware never reports "dap ready" before ctx expires (or emits an -// error line), no connection is returned and the error carries the full console -// transcript captured during the handshake, so the caller can show what the pod -// actually said instead of launching OpenOCD against a link that isn't armed. -func (c *Console) DAPStart(ctx context.Context, swclk, swdio int) (io.ReadWriteCloser, error) { - cmd := fmt.Sprintf("dap-start %d %d", swclk, swdio) - if err := c.writeLine(cmd); err != nil { - return nil, fmt.Errorf("write dap-start: %w", err) - } - if rt, ok := c.rw.(readTimeoutSetter); ok { - _ = rt.SetReadTimeout(perReadTimeout) - } - - // Accumulate every line so a handshake failure can report the firmware's - // actual output rather than just the last partial read. - var transcript strings.Builder - record := func(line string) { - transcript.WriteString(line) - transcript.WriteByte('\n') - } - - for { - line, err := c.readLine(ctx) - if err != nil { - if line != "" { - record(line) - } - return nil, fmt.Errorf("dap-start: pod never reported %q (%w)%s", - dapReadySentinel, err, transcriptSuffix(transcript.String())) - } - record(line) - trimmed := strings.TrimSpace(line) - switch { - case trimmed == dapReadySentinel: - // Raw DAP mode is open for the whole flash session, which can outlast - // any per-read timeout — switch to blocking reads so the bridge's - // pumps block until data/close rather than spinning. - if rt, ok := c.rw.(readTimeoutSetter); ok { - _ = rt.SetReadTimeout(serial.NoTimeout) - } - return &dapConn{rw: c.rw}, nil - case strings.HasPrefix(trimmed, "ERROR:"), strings.HasPrefix(trimmed, "usage:"): - return nil, fmt.Errorf("dap-start rejected by firmware: %s%s", - trimmed, transcriptSuffix(transcript.String())) - } - // Otherwise: the command echo or an async log line — keep reading. - } -} - // transcriptSuffix formats captured console output for a handshake error, // returning "" when there is nothing to show. func transcriptSuffix(t string) string { @@ -782,86 +665,6 @@ func (c *Console) readLine(ctx context.Context) (string, error) { } } -// dapConn is the raw framed CMSIS-DAP stream returned by DAPStart. Read/Write -// pass straight through to the serial port; Close (idempotent) sends a -// zero-length frame to disarm the probe, then closes the port. It deliberately -// does NOT read after the leave frame: openocd.BridgeDAP closes this connection -// while its own pump goroutine is still reading the same port, so a concurrent -// read here would race it. Closing the port unblocks that goroutine, and the -// leave frame (with the 60s watchdog as a backstop) is enough to leave the -// firmware in a safe state. -type dapConn struct { - rw io.ReadWriteCloser - closeOnce sync.Once - closeErr error -} - -func (s *dapConn) Read(p []byte) (int, error) { return s.rw.Read(p) } -func (s *dapConn) Write(p []byte) (int, error) { return s.rw.Write(p) } - -func (s *dapConn) Close() error { - s.closeOnce.Do(func() { - if _, err := s.rw.Write([]byte{0x00, 0x00}); err == nil { - // Let the zero-length leave frame flush over USB before dropping the port. - time.Sleep(dapFlushDelay) - } - s.closeErr = s.rw.Close() - }) - return s.closeErr -} - -// quoteArg double-quotes an argument for the firmware shell. Embedded double -// quotes are not currently supported by the firmware parser, so we reject them -// with a clear error rather than guess at an escaping scheme. -func quoteArg(s string) (string, error) { - if strings.Contains(s, `"`) { - return "", errors.New(`value may not contain a double-quote (") character`) - } - return `"` + s + `"`, nil -} - -// maskPassword replaces occurrences of the cleartext password in captured -// output with "***" so it is never logged. No-op for empty passwords. -func maskPassword(out, password string) string { - if password == "" { - return out - } - return strings.ReplaceAll(out, password, "***") -} - -// parseIPAfter returns the value of an "ip=" token appearing after the -// given marker in s, or "" if none is found. -func parseIPAfter(s, marker string) string { - i := strings.Index(s, marker) - if i < 0 { - return "" - } - rest := s[i+len(marker):] - j := strings.Index(rest, "ip=") - if j < 0 { - return "" - } - return firstToken(rest[j+len("ip="):]) -} - -// fieldValue scans s line-by-line for a "