From bf1f94b10709d67fe8afef0d45f6b35c8dd070f4 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 21:21:46 -0600 Subject: [PATCH] LAN-only-over-USB changes go over the pod's USB link; LAN address shown as used lan-pairing, lan-tls changes (https-only, scpi, regenerate, set-cert) and cloud ca/proxy changes given a LAN address now go over the pod's own USB link when its USB-C cable is in this computer, as lan-clients does since #84 (same helpers: readLanPodState, reachUSBLink). A computer that is not paired reads lan-pairing, lan-tls and cloud ca/proxy over the link too. A BP0081 refusal from a pod plugged into this computer now says to pair it now with `benchpod lan-clients add`, instead of to plug it in. Messages name a LAN pod by the address the connection used (host:8443 over TLS), or by the host alone before one: status, setup, discover and every command's label no longer show the plaintext 8080. Co-Authored-By: Claude Opus 5.5 --- README.md | 11 ++- cmd/benchpod-cli/adcrange.go | 2 +- cmd/benchpod-cli/cloudcfg.go | 33 +++++-- cmd/benchpod-cli/cloudcfg_test.go | 26 +++++- cmd/benchpod-cli/commands_discover.go | 4 +- cmd/benchpod-cli/errors.go | 31 +++++++ cmd/benchpod-cli/lanclients.go | 20 +++- cmd/benchpod-cli/lantls.go | 27 ++++-- cmd/benchpod-cli/lantls_test.go | 4 + cmd/benchpod-cli/lavoltage.go | 2 +- cmd/benchpod-cli/loglevel.go | 4 +- cmd/benchpod-cli/pair_usblink.go | 53 ++++++++++- cmd/benchpod-cli/pair_usblink_test.go | 128 ++++++++++++++++++++++++++ cmd/benchpod-cli/podclient.go | 16 +++- cmd/benchpod-cli/sensor.go | 10 +- cmd/benchpod-cli/setup.go | 11 ++- cmd/benchpod-cli/setup_test.go | 5 +- cmd/benchpod-cli/status.go | 6 +- cmd/benchpod-cli/usbnetwork.go | 2 +- cmd/benchpod-cli/wifi.go | 4 +- internal/tcpclient/client.go | 9 +- internal/tcpclient/errors.go | 12 +++ internal/tcpclient/session.go | 5 +- internal/tcpclient/shownaddr_test.go | 26 ++++++ internal/tcpclient/tls.go | 27 +++++- 25 files changed, 416 insertions(+), 62 deletions(-) create mode 100644 internal/tcpclient/shownaddr_test.go diff --git a/README.md b/README.md index 5b831e0..f0bdc7a 100644 --- a/README.md +++ b/README.md @@ -249,7 +249,7 @@ Which command works over which connection: | Connection | Commands | |---------------------|----------| -| 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. | +| Network address | Every pod command except the USB console ones below. Settings the pod changes only over USB or the cloud (`lan-pairing`, `lan-clients` changes, `lan-tls` switches, `cloud ca`/`proxy` changes) go over the pod's own USB link when its USB-C cable is in this computer; otherwise they are refused with their code, as are `identity wipe` and `usb-network`. | | 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 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. | @@ -531,8 +531,9 @@ LAN TLS of 192.168.1.220:8080 (connected over TLS) - `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`). + TLS or not (`BP0042`). Given the pod's network address while its USB-C cable is in + this computer, `benchpod` sends them over that pod's own USB link. 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). @@ -2324,7 +2325,9 @@ Given the pod's network address or name (`--connection 192.168.1.164`, pod's USB-C cable is in this computer, pairs over that pod's own USB link: no need to pick it among several pods on USB. Otherwise it says to plug the pod in over USB-C, or to use `--connection embeddedci:`. A computer that is paired already is told so. `remove`, -`clear` and `benchpod setup` take the USB link the same way. +`clear` and `benchpod setup` take the USB link the same way, and so do `benchpod lan-pairing` +and the `lan-tls` changes. A command refused with `BP0081` (this computer is not paired) from a +pod whose USB-C cable is in this computer says to pair it now with `benchpod lan-clients add`. | Flag | Default | Purpose | |-------------|-----------------|----------------------------------------------------------------------| diff --git a/cmd/benchpod-cli/adcrange.go b/cmd/benchpod-cli/adcrange.go index 9553c7f..26c0557 100644 --- a/cmd/benchpod-cli/adcrange.go +++ b/cmd/benchpod-cli/adcrange.go @@ -82,7 +82,7 @@ func runADCRange(g *globalFlags, action string, out io.Writer) error { return err } defer cancel() - return adcRange(ctx, t.client, t.label, action, what, out) + return adcRange(ctx, t.client, t.where(), action, what, out) } func adcRange(ctx context.Context, c podCommander, via, action, what string, out io.Writer) error { diff --git a/cmd/benchpod-cli/cloudcfg.go b/cmd/benchpod-cli/cloudcfg.go index a3ec1c8..7c8da6a 100644 --- a/cmd/benchpod-cli/cloudcfg.go +++ b/cmd/benchpod-cli/cloudcfg.go @@ -204,6 +204,19 @@ func cloudCfgTarget(g *globalFlags, what string) (spec ConnSpec, err error) { return parseTarget(raw) } +// cloudCfgOverUSBLink is where a cloud ca / cloud proxy command for the LAN address addr goes: a +// change (or a computer that is not paired) over the pod's USB link when it is plugged into this +// computer, since the pod refuses those from the LAN. +func cloudCfgOverUSBLink(g *globalFlags, addr, action string) (dial, label string, err error) { + ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(15*time.Second)) + defer cancel() + need := notPairedHere + if action != "show" { + need = nil + } + return overUSBLink(ctx, addr, need) +} + // cloudCfgPod runs one cloud_ca / cloud_proxy JSON command through embeddedci.com and decodes the // reply into out (nil to skip). func cloudCfgPod(g *globalFlags, spec ConnSpec, def time.Duration, req map[string]any, out any) (string, error) { @@ -216,14 +229,14 @@ func cloudCfgPod(g *globalFlags, spec ConnSpec, def time.Duration, req map[strin } data, err := pod.client.Command(ctx, req) if err != nil { - return pod.label, err + return pod.where(), err } if out != nil { if err := json.Unmarshal(data, out); err != nil { - return pod.label, fmt.Errorf("unexpected reply to %v: %s", req["cmd"], strings.TrimSpace(string(data))) + return pod.where(), fmt.Errorf("unexpected reply to %v: %s", req["cmd"], strings.TrimSpace(string(data))) } } - return pod.label, nil + return pod.where(), nil } // ── CA certificate checks ─────────────────────────────────────────────────── @@ -352,8 +365,11 @@ func runCloudCA(g *globalFlags, action, file string, out, warn io.Writer) error 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) + var dial string + if dial, label, err = cloudCfgOverUSBLink(g, spec.Addr, action); err != nil { + return fmt.Errorf("%s: %w", what, err) + } + certs, err = cloudCALAN(g, dial, action, upload, warn) } if err != nil { return cloudCfgError(what, err) @@ -625,8 +641,11 @@ func runCloudProxy(g *globalFlags, action, addr, user, password string, out, war 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) + var dial string + if dial, label, err = cloudCfgOverUSBLink(g, spec.Addr, action); err != nil { + return fmt.Errorf("%s: %w", what, err) + } + p, err = cloudProxyLAN(g, dial, action, addr, user, password) } if err != nil { err = cloudCfgError(what, err) diff --git a/cmd/benchpod-cli/cloudcfg_test.go b/cmd/benchpod-cli/cloudcfg_test.go index eea9cb4..f1f9089 100644 --- a/cmd/benchpod-cli/cloudcfg_test.go +++ b/cmd/benchpod-cli/cloudcfg_test.go @@ -395,7 +395,8 @@ func TestCloudCALAN(t *testing.T) { t.Fatalf("set = %q", out) } nChunks := (len(pemData) + caLANChunk - 1) / caLANChunk - want := "cloud_ca,ota_begin" + strings.Repeat(",ota_data", nChunks) + ",ota_end,ota_commit,cloud_ca" + // status first: whether the pod's USB link answers here (the change would go over it). + want := "status,cloud_ca,ota_begin" + strings.Repeat(",ota_data", nChunks) + ",ota_end,ota_commit,cloud_ca" if got := pod.cmds(); got != want { t.Fatalf("requests = %s\nwant %s", got, want) } @@ -486,7 +487,13 @@ func TestCloudProxyLAN(t *testing.T) { warn != "The pod reconnects to the cloud through proxy.corp:3128.\n" { t.Fatalf("set = %q, %q, %v", out, warn, err) } - set := pod.reqs[1] + var set map[string]any // each command reads status first (is the pod's USB link here?) + for _, r := range pod.reqs { + if _, ok := r["set"]; ok { + set = r + break + } + } if set["set"] != "proxy.corp:3128" || set["user"] != "alice" || set["password"] != "pa ss" { t.Fatalf("set request = %v", set) } @@ -494,8 +501,8 @@ func TestCloudProxyLAN(t *testing.T) { if err != nil || !strings.HasSuffix(out, "is now 10.1.2.3:8080 (no authentication)\n") { t.Fatalf("set noauth = %q, %v", out, err) } - if _, ok := pod.reqs[3]["password"]; ok { - t.Fatalf("a password went out without --user: %v", pod.reqs[3]) + if last := lastSet(pod.reqs); last["password"] != nil { + t.Fatalf("a password went out without --user: %v", last) } out, _, err = runProxyCapture(g, "clear", "", "", "") if err != nil || !strings.HasSuffix(out, "is now none (the pod connects to the cloud directly)\n") { @@ -503,6 +510,17 @@ func TestCloudProxyLAN(t *testing.T) { } } +// lastSet is the last cloud_proxy set request. +func lastSet(reqs []map[string]any) map[string]any { + var last map[string]any + for _, r := range reqs { + if _, ok := r["set"]; ok { + last = r + } + } + return last +} + func TestCloudCfgNeedsATarget(t *testing.T) { g := &globalFlags{configFile: filepath.Join(t.TempDir(), "none.yaml")} if _, _, err := runProxyCapture(g, "show", "", "", ""); err == nil || !strings.Contains(err.Error(), "--connection usb") { diff --git a/cmd/benchpod-cli/commands_discover.go b/cmd/benchpod-cli/commands_discover.go index f329e07..cf7baaf 100644 --- a/cmd/benchpod-cli/commands_discover.go +++ b/cmd/benchpod-cli/commands_discover.go @@ -489,7 +489,7 @@ func printReport(in reportInput) { w := tabwriter.NewWriter(out, 0, 2, 2, ' ', 0) fmt.Fprintln(w, " INSTANCE\tADDRESS\tHOSTNAME\tID") for _, p := range in.netPods { - fmt.Fprintf(w, " %s\t%s\t%s\t%s\n", p.instance, p.addr, p.hostname, shortID(p.id)) + fmt.Fprintf(w, " %s\t%s\t%s\t%s\n", p.instance, tcpclient.ShownAddr(p.addr), p.hostname, shortID(p.id)) } _ = w.Flush() for _, p := range in.netPods { @@ -540,7 +540,7 @@ func printVerdict(out *os.File, in reportInput) { if !p.reachable { fmt.Fprintf(out, "\n%s advertises itself but does not answer its API on %s.\n"+ "The record may be stale (a pod that has since rebooted or moved), or a firewall\n"+ - "may be blocking port 8080.\n", p.instance, p.addr) + "may be blocking ports 8443 (TLS) and 8080.\n", p.instance, tcpclient.ShownAddr(p.addr)) } } diff --git a/cmd/benchpod-cli/errors.go b/cmd/benchpod-cli/errors.go index eef2f92..81cdb4a 100644 --- a/cmd/benchpod-cli/errors.go +++ b/cmd/benchpod-cli/errors.go @@ -1,9 +1,11 @@ package main import ( + "context" "errors" "fmt" "strings" + "time" "github.com/embeddedci-com/benchpod-cli/internal/cloudpod" "github.com/embeddedci-com/benchpod-cli/internal/errcatalog" @@ -209,8 +211,37 @@ func codedRefusal(pe *tcpclient.PodError) (string, bool) { if pe == nil || pe.Code == "" { return "", false } + if fix := pairHereFix(pe); fix != "" { + e, _ := errcatalog.Lookup(pe.Code) + code := strings.ToUpper(strings.TrimSpace(pe.Code)) + return fmt.Sprintf("%s: %s; %s (%s)", code, errcatalog.Fill(e.Message, pe.Args), fix, errcatalog.DocsURL(code)), true + } if text, ok := errcatalog.Render(pe.Code, pe.Args, "cli"); ok { return text, true } return fmt.Sprintf("%s: %s (%s)", strings.ToUpper(pe.Code), strings.TrimSpace(pe.Reason), errcatalog.DocsURL(pe.Code)), true } + +// pairHereFix is the fix for a computer that is not paired (BP0081) with a pod it reached on the +// LAN when that pod's USB-C cable is in this very computer (its status shows the USB link, and +// the link answers from here): pair now, no plugging in. "" otherwise, and the catalog's fix +// stands. +func pairHereFix(pe *tcpclient.PodError) string { + if !strings.EqualFold(strings.TrimSpace(pe.Code), "BP0081") || pe.Addr == "" || isUSBLinkAddr(pe.Addr) { + return "" + } + fix, ok := pairHereFixes[pe.Addr] + if !ok { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + if usb, err := reachUSBLink(ctx, pe.Addr, readLanPodState(ctx, pe.Addr).usbIP); err == nil && usb != "" { + fix = "the pod is plugged into this computer over USB, so pair this computer now with " + + "`benchpod lan-clients add --connection " + tcpclient.ShownAddr(pe.Addr) + "`, then run this again" + } + pairHereFixes[pe.Addr] = fix + } + return fix +} + +// pairHereFixes keeps pairHereFix's answer per address for the run (a refusal is worded more than once). +var pairHereFixes = map[string]string{} diff --git a/cmd/benchpod-cli/lanclients.go b/cmd/benchpod-cli/lanclients.go index 75b086e..0fe4b2f 100644 --- a/cmd/benchpod-cli/lanclients.go +++ b/cmd/benchpod-cli/lanclients.go @@ -231,7 +231,7 @@ func lanClientsNetwork(g *globalFlags, o lanClientsOp, key string) (lanClientsVi if err != nil { return lanClientsView{}, "", fmt.Errorf("lan-clients: %w", err) } - return v, t.label, errAlreadyPaired + return v, t.where(), errAlreadyPaired } if err != nil { return lanClientsView{}, "", err @@ -239,7 +239,7 @@ func lanClientsNetwork(g *globalFlags, o lanClientsOp, key string) (lanClientsVi if usb != "" { lanAddr = t.spec.Addr t = &podTarget{spec: ConnSpec{Kind: connNetwork, Addr: usb}, client: &tcpclient.Client{Addr: usb}, - label: t.spec.Addr + " (over its USB link " + hostOf(usb) + ")"} + label: usbLinkLabel(t.spec.Addr, usb)} } } req := map[string]any{"cmd": "lan_clients"} @@ -261,7 +261,7 @@ func lanClientsNetwork(g *globalFlags, o lanClientsOp, key string) (lanClientsVi if lanAddr != "" && o.op == "add" { pinLanCertOverUSBLink(ctx, t.spec.Addr, lanAddr) } - return v, t.label, nil + return v, t.where(), nil } // lanClientsAll runs req and reads every page of the list (the pod sends 12 a reply). @@ -384,7 +384,8 @@ func newLanPairingCmd(g *globalFlags) *cobra.Command { Long: "Show or set LAN pairing (firmware 4.0.1+). on (the default): a computer on Ethernet or\n" + "Wi-Fi drives the pod only once it is paired (`benchpod setup`, `benchpod lan-clients`).\n" + "off: every computer on the network may, as before 4.0.1; then keep the pod on a trusted\n" + - "lab network. Changed over USB (the console or --connection usb) or embeddedci.com.", + "lab network. Changed over USB (the console or --connection usb) or embeddedci.com; given\n" + + "the pod's network address, over that pod's own USB link when it is plugged in here.", Args: cobra.MaximumNArgs(1), ValidArgs: []string{"on", "off"}, RunE: func(_ *cobra.Command, args []string) error { @@ -429,6 +430,15 @@ func runLanPairing(g *globalFlags, set string, out io.Writer) error { return err } defer cancel() + // A LAN address: a change, and a read this computer may not make while it is not paired, + // go over the pod's USB link when it is plugged into this computer. + var need func(lanPodState) bool + if set == "" { + need = notPairedHere + } + if t, _, err = targetOverUSBLink(ctx, t, need); err != nil { + return fmt.Errorf("lan-pairing: %w", err) + } req := map[string]any{"cmd": "lan_policy"} if set != "" { req["pairing"] = set == "on" @@ -443,7 +453,7 @@ func runLanPairing(g *globalFlags, set string, out io.Writer) error { if json.Unmarshal(data, &rep) != nil || rep.Pairing == nil { return errors.New(lanClientsMissing) } - on, label = *rep.Pairing, t.label + on, label = *rep.Pairing, t.where() } state := map[bool]string{true: "on: computers on Ethernet and Wi-Fi must be paired", false: "off: every computer on the network may use the pod"}[on] if set != "" { diff --git a/cmd/benchpod-cli/lantls.go b/cmd/benchpod-cli/lantls.go index bef5f07..f034d1d 100644 --- a/cmd/benchpod-cli/lantls.go +++ b/cmd/benchpod-cli/lantls.go @@ -177,6 +177,17 @@ func runLanTLS(g *globalFlags, change map[string]any, out, warn io.Writer) error return err } defer cancel() + // A change over a LAN address goes over the pod's USB link when it is plugged into this + // computer (the pod takes changes over USB or the cloud only); so does showing it to a + // computer that is not paired. + need := notPairedHere + if len(change) > 0 { + need = nil + } + t, lanAddr, err := targetOverUSBLink(ctx, t, need) + if err != nil { + return fmt.Errorf("lan-tls: %w", err) + } req := map[string]any{"cmd": "lan_tls"} for k, v := range change { req[k] = v @@ -189,8 +200,8 @@ func runLanTLS(g *globalFlags, change map[string]any, out, warn io.Writer) error if err := json.Unmarshal(raw, &rep); err != nil { return fmt.Errorf("lan-tls: unexpected reply: %s", strings.TrimSpace(string(raw))) } - addr := "" - if !t.spec.IsCloud() { + addr := lanAddr + if addr == "" && !t.spec.IsCloud() { addr = t.spec.Addr } // This computer made the change: pin the new certificate for the address it used. @@ -199,7 +210,7 @@ func runLanTLS(g *globalFlags, change map[string]any, out, warn io.Writer) error fmt.Fprintf(warn, "Could not update the pin: %v\n", err) } } - printLanTLS(out, t.label, addr, rep, lastTLS(t)) + printLanTLS(out, t.where(), addr, rep, lastTLS(t)) 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.") } @@ -374,7 +385,11 @@ func runLanTLSSetCert(g *globalFlags, certFile, keyFile string, out, warn io.Wri defer cancel() defer installSignalHandler(ctx, cancel)() - lan, err := openLAN(ctx, addr) + dial, label, err := overUSBLink(ctx, addr, nil) + if err != nil { + return fmt.Errorf("lan-tls set-cert: %w", err) + } + lan, err := openLAN(ctx, dial) if err != nil { return fmt.Errorf("lan-tls set-cert: %w", err) } @@ -382,7 +397,7 @@ func runLanTLSSetCert(g *globalFlags, certFile, keyFile string, out, warn io.Wri if err := lan.cmd(ctx, map[string]any{"cmd": "lan_tls"}, &lanTLSReply{}); err != nil { return lanTLSError("lan-tls set-cert", err) } - fmt.Fprintf(warn, "Uploading %d bytes to %s ...\n", len(bundle), addr) + fmt.Fprintf(warn, "Uploading %d bytes to %s ...\n", len(bundle), label) if err := uploadOTALAN(ctx, lan, bundle, "tls"); err != nil { if !lan.s.Broken() { _ = lan.cmd(ctx, map[string]any{"cmd": "ota_abort"}, nil) @@ -401,6 +416,6 @@ func runLanTLSSetCert(g *globalFlags, certFile, keyFile string, out, warn io.Wri fmt.Fprintf(warn, "Could not update the pin: %v\n", err) } } - printLanTLS(out, addr, addr, rep, map[bool]string{true: "TLS", false: "plaintext"}[lan.s.TLS()]) + printLanTLS(out, label, addr, rep, map[bool]string{true: "TLS", false: "plaintext"}[lan.s.TLS()]) return nil } diff --git a/cmd/benchpod-cli/lantls_test.go b/cmd/benchpod-cli/lantls_test.go index 9669b9a..2569ea0 100644 --- a/cmd/benchpod-cli/lantls_test.go +++ b/cmd/benchpod-cli/lantls_test.go @@ -28,6 +28,10 @@ func TestLanTLSSwitches(t *testing.T) { } var req map[string]any _ = json.Unmarshal([]byte(<-got), &req) + if req["cmd"] == "status" { // whether the pod's USB link answers here + req = nil + _ = json.Unmarshal([]byte(<-got), &req) + } if len(req) != len(c.want) { t.Fatalf("%v: sent %v", c.args, req) } diff --git a/cmd/benchpod-cli/lavoltage.go b/cmd/benchpod-cli/lavoltage.go index 8f6decf..7529422 100644 --- a/cmd/benchpod-cli/lavoltage.go +++ b/cmd/benchpod-cli/lavoltage.go @@ -169,7 +169,7 @@ func laVoltageDo(g *globalFlags, mv int) (string, laVoltageReply, error) { if rep, err = laVoltageLAN(ctx, pod.client, mv); err != nil { return "", rep, laVoltageError(what, err) } - return pod.label, rep, nil + return pod.where(), rep, nil } // laVoltageLAN runs la_voltage as a JSON command, on the pod's network port or through diff --git a/cmd/benchpod-cli/loglevel.go b/cmd/benchpod-cli/loglevel.go index 0179862..b81ceca 100644 --- a/cmd/benchpod-cli/loglevel.go +++ b/cmd/benchpod-cli/loglevel.go @@ -69,9 +69,9 @@ func runLogLevel(g *globalFlags, set string, out io.Writer) error { return fmt.Errorf("log-level: %w", err) } if set == "" { - fmt.Fprintf(out, "Console log level of the pod at %s: %s\n", t.label, level) + fmt.Fprintf(out, "Console log level of the pod at %s: %s\n", t.where(), level) } else { - fmt.Fprintf(out, "Console log level of the pod at %s is now %s (stored on the pod).\n", t.label, level) + fmt.Fprintf(out, "Console log level of the pod at %s is now %s (stored on the pod).\n", t.where(), level) } return nil } diff --git a/cmd/benchpod-cli/pair_usblink.go b/cmd/benchpod-cli/pair_usblink.go index 7af2388..1bae548 100644 --- a/cmd/benchpod-cli/pair_usblink.go +++ b/cmd/benchpod-cli/pair_usblink.go @@ -44,10 +44,14 @@ func readLanPodState(ctx context.Context, addr string) lanPodState { IP string `json:"ip"` } `json:"usb"` } - if json.Unmarshal(data, &st) != nil || st.Pairing == nil { + if json.Unmarshal(data, &st) != nil { return lanPodState{} } - s := lanPodState{known: true, pairing: *st.Pairing, paired: st.Paired} + var s lanPodState + if st.Pairing != nil { + s = lanPodState{known: true, pairing: *st.Pairing, paired: st.Paired} + } + // The USB link is there on firmware without pairing too (LAN TLS changes go over it). if st.USB != nil && st.USB.Link && tcpclient.IsUSBLinkAddr(strings.TrimSpace(st.USB.IP)) { s.usbIP = strings.TrimSpace(st.USB.IP) } @@ -105,6 +109,49 @@ func pinLanCertOverUSBLink(ctx context.Context, usbAddr, lanAddr string) { } } +// overUSBLink is where a change the pod takes only over USB or the cloud (LAN pairing, LAN TLS, +// the cloud CA and proxy) goes when the connection is the LAN address lanAddr: the same pod's USB +// link when it answers from this computer, with a label that names both; else lanAddr itself, +// and the pod's refusal then says what to do. A USB link address stays as it is. need, when not +// nil, decides from the pod's status whether to go over the USB link at all. +func overUSBLink(ctx context.Context, lanAddr string, need func(lanPodState) bool) (dial, label string, err error) { + if isUSBLinkAddr(lanAddr) { + return lanAddr, tcpclient.ShownAddr(lanAddr), nil + } + st := readLanPodState(ctx, lanAddr) + if need != nil && !need(st) { + return lanAddr, tcpclient.ShownAddr(lanAddr), nil + } + usb, err := reachUSBLink(ctx, lanAddr, st.usbIP) + if err != nil || usb == "" { + return lanAddr, tcpclient.ShownAddr(lanAddr), err + } + return usb, usbLinkLabel(lanAddr, usb), nil +} + +func usbLinkLabel(lanAddr, usb string) string { + return tcpclient.ShownAddr(lanAddr) + " (over its USB link " + hostOf(usb) + ")" +} + +// notPairedHere says the pod has pairing on and this computer is not paired with it (it may +// only read status over the LAN). +func notPairedHere(st lanPodState) bool { + return st.known && st.pairing && st.paired != nil && !*st.paired +} + +// targetOverUSBLink is overUSBLink for a podClient target: a LAN target becomes the USB link's +// when it answers here. lanAddr is the LAN address it stands for ("" when t is unchanged). +func targetOverUSBLink(ctx context.Context, t *podTarget, need func(lanPodState) bool) (nt *podTarget, lanAddr string, err error) { + if !t.spec.IsNetwork() || isUSBLinkAddr(t.spec.Addr) { + return t, "", nil + } + dial, label, err := overUSBLink(ctx, t.spec.Addr, need) + if err != nil || dial == t.spec.Addr { + return t, "", err + } + return &podTarget{spec: ConnSpec{Kind: connNetwork, Addr: dial}, client: &tcpclient.Client{Addr: dial}, label: label}, t.spec.Addr, nil +} + // errNeedsUSBLink is what lan-clients says when a LAN connection cannot reach the pod's USB link. func errNeedsUSBLink(what, lanAddr string, notPaired bool) error { if notPaired { @@ -129,7 +176,7 @@ func lanClientsRoute(ctx context.Context, lanAddr string, o lanClientsOp) (strin if !st.known { return "", nil // no pairing on this firmware, or no answer: the command says so itself } - notPaired := st.pairing && st.paired != nil && !*st.paired + notPaired := notPairedHere(st) if o.op == "" && !notPaired { return "", nil // a paired computer lists over the LAN } diff --git a/cmd/benchpod-cli/pair_usblink_test.go b/cmd/benchpod-cli/pair_usblink_test.go index 3b8d40e..bb5d9ca 100644 --- a/cmd/benchpod-cli/pair_usblink_test.go +++ b/cmd/benchpod-cli/pair_usblink_test.go @@ -5,7 +5,9 @@ import ( "bytes" "encoding/json" "io" + "log" "net" + "os" "strings" "sync" "testing" @@ -215,3 +217,129 @@ func TestSetupPairsOverTheUSBLink(t *testing.T) { t.Errorf("USB link got %s", got) } } + +// usbLinkPod is the pod's own USB link: it answers ping, its LAN certificate, and records the rest. +func usbLinkPod(t *testing.T, replies map[string]string) *recordingPod { + t.Helper() + all := map[string]string{"ping": `{"status":"ok","data":"pong"}`, "lan_tls": `{"status":"ok","data":{"sha256":"abcd"}}`} + for k, v := range replies { + all[k] = v + } + return newRecordingPod(t, all) +} + +func sent(p *recordingPod, cmd string) bool { + for _, c := range p.cmds() { + if c == cmd { + return true + } + } + return false +} + +// lan-pairing off over a LAN address from a computer that is not paired: the pod is plugged into +// this computer, so the change goes over its USB link instead of failing with BP0081. +func TestLanPairingOverLANGoesThroughTheUSBLink(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(false, true), "": `{"status":"error","code":"BP0081","args":{"cmd":"lan_policy"}}`}) + usb := usbLinkPod(t, map[string]string{"lan_policy": `{"status":"ok","data":{"pairing":false}}`}) + withUSBLink(t, usb.addr) + + var out bytes.Buffer + if err := runLanPairing(&globalFlags{connection: lan.addr}, "off", &out); err != nil { + t.Fatalf("lan-pairing off: %v", err) + } + if want := "LAN pairing on " + lan.addr + " (over its USB link 127.0.0.1) is now off"; !strings.Contains(out.String(), want) { + t.Errorf("output:\n%s", out.String()) + } + if sent(lan, "lan_policy") || !sent(usb, "lan_policy") { + t.Errorf("LAN got %v, USB link got %v", lan.cmds(), usb.cmds()) + } + // Reading it as a computer that is not paired goes over the link too. + out.Reset() + if err := runLanPairing(&globalFlags{connection: lan.addr}, "", &out); err != nil || !strings.Contains(out.String(), "over its USB link") { + t.Errorf("show: %q, %v", out.String(), err) + } +} + +// A paired computer reads LAN pairing over the LAN; a change still goes over the USB link. +func TestLanPairingPairedReadStaysOnTheLAN(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(true, true), "lan_policy": `{"status":"ok","data":{"pairing":true}}`}) + usb := usbLinkPod(t, map[string]string{"lan_policy": `{"status":"ok","data":{"pairing":true}}`}) + withUSBLink(t, usb.addr) + if err := runLanPairing(&globalFlags{connection: lan.addr}, "", io.Discard); err != nil { + t.Fatal(err) + } + if !sent(lan, "lan_policy") || len(usb.cmds()) != 0 { + t.Errorf("LAN got %v, USB link got %v", lan.cmds(), usb.cmds()) + } + if err := runLanPairing(&globalFlags{connection: lan.addr}, "on", io.Discard); err != nil { + t.Fatal(err) + } + if !sent(usb, "lan_policy") { + t.Errorf("USB link got %v", usb.cmds()) + } +} + +// lan-tls switches over a LAN address go over the USB link; regenerate pins the new certificate +// for the LAN address, not the link. +func TestLanTLSChangesGoThroughTheUSBLink(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(true, true), "": `{"status":"error","code":"BP0042","args":{"setting":"lan_tls"}}`}) + usb := usbLinkPod(t, map[string]string{"lan_tls": `{"status":"ok","data":{"port":8443,"https_only":true,"scpi":true,"sha256":"beef","subject":"CN=benchpod-c2f662"}}`}) + withUSBLink(t, usb.addr) + for _, change := range []map[string]any{{"scpi": true}, {"https_only": true}, {"regenerate": true}} { + var out bytes.Buffer + if err := runLanTLS(&globalFlags{connection: lan.addr}, change, &out, io.Discard); err != nil { + t.Fatalf("%v: %v", change, err) + } + if !strings.Contains(out.String(), "LAN TLS of "+lan.addr+" (over its USB link 127.0.0.1)") { + t.Errorf("%v: output:\n%s", change, out.String()) + } + } + if sent(lan, "lan_tls") { + t.Errorf("a change went to the LAN: %v", lan.cmds()) + } + if pin, ok := tcpclient.GetPin(lan.addr); !ok || pin.SHA256 != "beef" { + t.Errorf("pin for the LAN address = %+v, %v", pin, ok) + } +} + +// Without the pod's USB link here, the change goes to the LAN and its refusal says what to do. +func TestLanTLSChangeWithoutTheUSBLinkIsRefused(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(true, false), "": `{"status":"error","code":"BP0042","args":{"setting":"lan_tls"}}`}) + withUSBLink(t, "") + err := runLanTLS(&globalFlags{connection: lan.addr}, map[string]any{"scpi": true}, io.Discard, io.Discard) + if err == nil || !strings.Contains(err.Error(), "BP0042") { + t.Fatalf("err = %v", err) + } +} + +// BP0081 from a pod whose USB-C cable is in this computer: the hint says to pair now, not to +// plug it in. +func TestNotPairedHintWhenThePodIsPluggedInHere(t *testing.T) { + refusal := `{"status":"error","code":"BP0081","args":{"cmd":"log_level"}}` + for _, link := range []bool{true, false} { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(false, link), "": refusal}) + usb := usbLinkPod(t, nil) + if link { + withUSBLink(t, usb.addr) + } else { + withUSBLink(t, "") + } + pairHereFixes = map[string]string{} + var logged strings.Builder + log.SetOutput(&logged) + code := run([]string{"log-level", "debug", "--connection", lan.addr}) + log.SetOutput(os.Stderr) + if code != exitRefused { + t.Fatalf("link=%v: exit %d", link, code) + } + got := logged.String() + pairNow := "pair this computer now with `benchpod lan-clients add --connection " + lan.addr + "`" + if link && (!strings.Contains(got, pairNow) || strings.Contains(got, "plug the pod into")) { + t.Errorf("link up: %s", got) + } + if !link && (strings.Contains(got, "pair this computer now") || !strings.Contains(got, "plug the pod into this computer's USB-C port")) { + t.Errorf("link down: %s", got) + } + } +} diff --git a/cmd/benchpod-cli/podclient.go b/cmd/benchpod-cli/podclient.go index f60257c..b56c7a4 100644 --- a/cmd/benchpod-cli/podclient.go +++ b/cmd/benchpod-cli/podclient.go @@ -38,10 +38,22 @@ var ( type podTarget struct { spec ConnSpec client podCommander - label string // how messages name the pod: "192.168.1.5:8080" or "benchpod-a1b2c3 on embeddedci.com" + label string // how messages name the pod when set: "benchpod-a1b2c3 on embeddedci.com"; "" for the address (where) deviceID string // the pod's id on embeddedci.com when the connection goes through it, else "" } +// where is how messages name the pod: its label, else the address the connection went to +// ("192.168.1.5:8443" over TLS; the host alone before the first command). +func (t *podTarget) where() string { + if t.label != "" { + return t.label + } + if c, ok := t.client.(*tcpclient.Client); ok { + return c.Shown() + } + return tcpclient.ShownAddr(t.spec.Addr) +} + // podClient resolves the connection for a single-reply JSON command: the pod's network address, // or embeddedci: through embeddedci.com. A USB connection gets the standard "needs the // network" error unless the pod's USB network adapter is up. It returns a deadline context (overridable by --timeout) with signal handling. @@ -69,7 +81,7 @@ func openPodTarget(ctx context.Context, spec ConnSpec) (*podTarget, error) { } return &podTarget{spec: spec, client: c, label: c.Label(), deviceID: c.DeviceID}, nil } - return &podTarget{spec: spec, client: &tcpclient.Client{Addr: spec.Addr}, label: spec.Addr}, nil + return &podTarget{spec: spec, client: &tcpclient.Client{Addr: spec.Addr}}, nil } // cloudServerURL is the embeddedci.com base URL the cloud connection uses: BENCHPOD_API_BASE (the diff --git a/cmd/benchpod-cli/sensor.go b/cmd/benchpod-cli/sensor.go index 3de7c97..fcb5daf 100644 --- a/cmd/benchpod-cli/sensor.go +++ b/cmd/benchpod-cli/sensor.go @@ -88,7 +88,7 @@ func newSensorImageCmd(g *globalFlags) *cobra.Command { verb = "switched to" } fmt.Fprintf(cmd.OutOrStdout(), "The pod on %s %s the %s FPGA image (image %v, gateware v%v)\n", - t.label, verb, valueOrUnknown(name), reply["image"], reply["version"]) + t.where(), verb, valueOrUnknown(name), reply["image"], reply["version"]) return nil }, } @@ -366,7 +366,7 @@ func runSensorValidate(g *globalFlags, src, version string, offline bool, stdin if err != nil { return err } - fmt.Fprintf(out, "%s: compiles on %s (%s sensor %s, %v program bytes)\n", src, t.label, doc.Kind(), doc.Name(), rep["program_bytes"]) + fmt.Fprintf(out, "%s: compiles on %s (%s sensor %s, %v program bytes)\n", src, t.where(), doc.Kind(), doc.Name(), rep["program_bytes"]) printParams(out, rep["params"]) return nil } @@ -484,7 +484,7 @@ func runSensorStart(g *globalFlags, src string, f sensorStartFlags, stdin io.Rea if err != nil { return err } - fmt.Fprintf(out, "Started %s (%s sensor %s) on %s, %s", instance, doc.Kind(), doc.Name(), t.label, formatPins(pins)) + fmt.Fprintf(out, "Started %s (%s sensor %s) on %s, %s", instance, doc.Kind(), doc.Name(), t.where(), formatPins(pins)) if slot, _ := started["slot"].(string); slot != "" { fmt.Fprintf(out, ", slot %s", slot) } @@ -705,7 +705,7 @@ func runStimulusLoad(g *globalFlags, src string, stdin io.Reader, out io.Writer) if _, err := uploadDocument(ctx, t, "sensor stimulus load", "sensor_stimulus", doc, "", false); err != nil { return err } - fmt.Fprintf(out, "Loaded stimulus %s on %s; play it with `benchpod sensor stimulus start`\n", doc.Name(), t.label) + fmt.Fprintf(out, "Loaded stimulus %s on %s; play it with `benchpod sensor stimulus start`\n", doc.Name(), t.where()) return nil } @@ -812,7 +812,7 @@ func newSensorStatusCmd(g *globalFlags) *cobra.Command { _, err := fmt.Fprintln(out, string(b)) return err } - printSensorStatus(out, t.label, st) + printSensorStatus(out, t.where(), st) return nil }, } diff --git a/cmd/benchpod-cli/setup.go b/cmd/benchpod-cli/setup.go index 4d40153..f211e35 100644 --- a/cmd/benchpod-cli/setup.go +++ b/cmd/benchpod-cli/setup.go @@ -13,6 +13,7 @@ import ( "github.com/embeddedci-com/benchpod-cli/internal/benchpodconfig" "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" ) // ── setup ──────────────────────────────────────────────────────────────────── @@ -242,7 +243,7 @@ func runSetup(env setupEnv, ui *setupUI, o setupOpts) error { step(2, "Network") switch { case p.lanAddr != "": - fmt.Fprintf(out, " Done: the pod is on the network at %s.\n", p.lanAddr) + fmt.Fprintf(out, " Done: the pod is on the network at %s.\n", tcpclient.ShownAddr(p.lanAddr)) case p.addr != "" && isUSBLinkAddr(p.addr): // Enough for this computer: the whole API runs over the USB cable. Other machines and CI // need Ethernet or Wi-Fi, which setup does not force on a pod that already works. @@ -250,7 +251,7 @@ func runSetup(env setupEnv, ui *setupUI, o setupOpts) error { fmt.Fprintln(out, " No Ethernet or Wi-Fi address was found. To use it from other machines or CI, plug in") fmt.Fprintln(out, " Ethernet (it takes a DHCP lease on its own) or join Wi-Fi with `benchpod set-wifi`.") case p.addr != "": - fmt.Fprintf(out, " Done: the pod is on the network at %s.\n", p.addr) + fmt.Fprintf(out, " Done: the pod is on the network at %s.\n", tcpclient.ShownAddr(p.addr)) default: if p.device == "" { return errors.New("the pod has no network address and is not on USB; connect it over USB and run setup again") @@ -263,7 +264,7 @@ func runSetup(env setupEnv, ui *setupUI, o setupOpts) error { if !isUSBLinkAddr(addr) { p.lanAddr = addr } - fmt.Fprintf(out, " The pod is on the network at %s.\n", p.addr) + fmt.Fprintf(out, " The pod is on the network at %s.\n", tcpclient.ShownAddr(p.addr)) } // 3. Board I/O voltage. @@ -313,10 +314,10 @@ func describeSetupPod(p setupPod) string { case p.addr != "" && isUSBLinkAddr(p.addr): parts = append(parts, "USB network "+p.addr) if p.lanAddr != "" { - parts = append(parts, "network "+p.lanAddr) + parts = append(parts, "network "+tcpclient.ShownAddr(p.lanAddr)) } case p.addr != "": - parts = append(parts, "network "+p.addr) + parts = append(parts, "network "+tcpclient.ShownAddr(p.addr)) default: parts = append(parts, "no network address yet") } diff --git a/cmd/benchpod-cli/setup_test.go b/cmd/benchpod-cli/setup_test.go index 82ecb4c..9ffdd62 100644 --- a/cmd/benchpod-cli/setup_test.go +++ b/cmd/benchpod-cli/setup_test.go @@ -471,8 +471,9 @@ func TestSetupSavesTheLANAddressOfAPodAlsoOnUSB(t *testing.T) { if env.saved != "192.168.1.220:8080" { t.Errorf("saved %q, want the LAN address", env.saved) } - for _, want := range []string{"USB network 10.237.8.85:8080, network 192.168.1.220:8080", - "on the network at 192.168.1.220:8080", "--benchpod-connection=192.168.1.220`"} { + // The LAN address without the plaintext port: on firmware 4.0 the LAN API is TLS on 8443. + for _, want := range []string{"USB network 10.237.8.85:8080, network 192.168.1.220,", + "on the network at 192.168.1.220.", "--benchpod-connection=192.168.1.220`"} { if !strings.Contains(out, want) { t.Errorf("output lacks %q:\n%s", want, out) } diff --git a/cmd/benchpod-cli/status.go b/cmd/benchpod-cli/status.go index 597c88e..5bd7240 100644 --- a/cmd/benchpod-cli/status.go +++ b/cmd/benchpod-cli/status.go @@ -74,7 +74,11 @@ func newStatusCmd(g *globalFlags) *cobra.Command { printJSON(out, data) // not the shape we know: show it as it is return nil } - sum := statusSummary{addr: pod.label, st: st, cloudID: pod.deviceID} + where := pod.where() + if c, ok := pod.client.(*tcpclient.Client); ok && c.LastDialTLS() { + where += " over TLS" + } + sum := statusSummary{addr: where, st: st, cloudID: pod.deviceID} gatherStatusExtras(ctx, pod.client, &sum) printStatusSummary(out, sum) return nil diff --git a/cmd/benchpod-cli/usbnetwork.go b/cmd/benchpod-cli/usbnetwork.go index d223d06..cac5ddc 100644 --- a/cmd/benchpod-cli/usbnetwork.go +++ b/cmd/benchpod-cli/usbnetwork.go @@ -77,7 +77,7 @@ func runUSBNetwork(g *globalFlags, set string, out io.Writer) error { if err != nil { return fmt.Errorf("%s: %w", what, err) } - printUSBNetwork(out, t.label, setting, "") + printUSBNetwork(out, t.where(), setting, "") return nil } // Reading and turning off work over the USB link itself when it is up (no console needed); diff --git a/cmd/benchpod-cli/wifi.go b/cmd/benchpod-cli/wifi.go index d701807..c05a426 100644 --- a/cmd/benchpod-cli/wifi.go +++ b/cmd/benchpod-cli/wifi.go @@ -187,10 +187,10 @@ func runSetWifi(g *globalFlags, ssid, pw string, skipBlobs bool) (string, error) _ = 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) + 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.where()) } 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) + "(USB networking turns off now)...\n", ssid, t.where()) } return waitWifiJoin(ctx, g, t, ssid, bridge) } diff --git a/internal/tcpclient/client.go b/internal/tcpclient/client.go index 00f4695..12dbc64 100644 --- a/internal/tcpclient/client.go +++ b/internal/tcpclient/client.go @@ -54,7 +54,8 @@ type Client struct { // commands themselves, and read-only probes of other pods). NoLeaseJoin bool - lastTLS bool // the last connection used TLS + lastTLS bool // the last connection used TLS + lastAddr string // where the last connection went (host:8443 for TLS), "" before one } // reply is one decoded response line from the firmware. @@ -91,7 +92,7 @@ func (c *Client) Command(ctx context.Context, req map[string]any) (json.RawMessa } return r.Data, nil case "error": - return nil, replyError(r) + return nil, replyErrorAt(r, c.Addr) default: return nil, fmt.Errorf("unexpected response status %q", r.Status) } @@ -134,7 +135,7 @@ func (c *Client) Samples(ctx context.Context, req map[string]any) ([]int, error) return out, nil } case "error": - return nil, replyError(r) + return nil, replyErrorAt(r, c.Addr) default: return nil, fmt.Errorf("unexpected response status %q", r.Status) } @@ -181,7 +182,7 @@ func (c *Client) Chunks(ctx context.Context, req map[string]any) ([]json.RawMess } switch head.Status { case "error": - return nil, replyError(&head) + return nil, replyErrorAt(&head, c.Addr) case "ok", "chunk": default: return nil, fmt.Errorf("unexpected response status %q", head.Status) diff --git a/internal/tcpclient/errors.go b/internal/tcpclient/errors.go index 8ff54fa..7b8ceff 100644 --- a/internal/tcpclient/errors.go +++ b/internal/tcpclient/errors.go @@ -23,6 +23,9 @@ type PodError struct { // (benchpod-firmware errors/catalog.toml); "" / nil for a refusal without a code. Code string Args map[string]any + // Addr is the network address (host:port as dialed from) that refused, for a refusal a Client + // or Session read; "" otherwise (the USB console, embeddedci.com). + Addr string } func (e *PodError) Error() string { @@ -210,6 +213,15 @@ func codedReason(code string, args map[string]any) string { // 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) } +// replyErrorAt is replyError for a reply from the pod at addr. +func replyErrorAt(r *reply, addr string) error { + err := replyError(r) + if pe, ok := err.(*PodError); ok { + pe.Addr = strings.TrimSpace(addr) + } + return err +} + // 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. A coded refusal's text comes from the catalog, never diff --git a/internal/tcpclient/session.go b/internal/tcpclient/session.go index 820a03d..bd8b5e0 100644 --- a/internal/tcpclient/session.go +++ b/internal/tcpclient/session.go @@ -27,6 +27,7 @@ type Session struct { mu sync.Mutex broken error + addr string // the Client's address, for refusals (PodError.Addr) } // Open dials the pod and returns a Session. The caller must Close it. @@ -49,7 +50,7 @@ func (c *Client) Open(ctx context.Context) (*Session, error) { if tc, ok := conn.(*net.TCPConn); ok { _ = tc.SetNoDelay(true) } - return &Session{conn: conn, reader: bufio.NewReader(conn)}, nil + return &Session{conn: conn, reader: bufio.NewReader(conn), addr: addr}, nil } // Command sends req and reads its one reply line, like Client.Command, on the @@ -89,7 +90,7 @@ func (s *Session) Command(ctx context.Context, req map[string]any) (json.RawMess } return r.Data, nil case "error": - return nil, replyError(r) + return nil, replyErrorAt(r, s.addr) default: return nil, fmt.Errorf("unexpected response status %q", r.Status) } diff --git a/internal/tcpclient/shownaddr_test.go b/internal/tcpclient/shownaddr_test.go new file mode 100644 index 0000000..54baab5 --- /dev/null +++ b/internal/tcpclient/shownaddr_test.go @@ -0,0 +1,26 @@ +package tcpclient + +import "testing" + +// Messages name a LAN pod by its host until a connection shows TLS 8443 or plaintext 8080. +func TestShownAddr(t *testing.T) { + for in, want := range map[string]string{ + "192.168.1.164:8080": "192.168.1.164", + "192.168.1.164:8443": "192.168.1.164:8443", + "192.168.1.164:9000": "192.168.1.164:9000", + "10.237.210.109:8080": "10.237.210.109:8080", // the USB link is plaintext 8080 + "benchpod.local:8080": "benchpod.local", + } { + if got := ShownAddr(in); got != want { + t.Errorf("ShownAddr(%q) = %q, want %q", in, got, want) + } + } + c := &Client{Addr: "192.168.1.164:8080"} + if got := c.Shown(); got != "192.168.1.164" { + t.Errorf("before a connection: %q", got) + } + c.lastTLS, c.lastAddr = true, "192.168.1.164:8443" + if got := c.Shown(); got != "192.168.1.164:8443" { + t.Errorf("after a TLS connection: %q", got) + } +} diff --git a/internal/tcpclient/tls.go b/internal/tcpclient/tls.go index 2a230fd..32aff30 100644 --- a/internal/tcpclient/tls.go +++ b/internal/tcpclient/tls.go @@ -137,7 +137,7 @@ func (c *Client) dial(ctx context.Context, budget time.Duration) (net.Conn, erro } } if p.tlsAddr == "" { - c.lastTLS = false + c.lastTLS, c.lastAddr = false, p.plainAddr return dialWithRetry(ctx, "tcp", p.plainAddr, budget, dialAttemptTimeout, dialRetryBackoff) } if p.fallback && !pinned(p.tlsAddr) { @@ -147,7 +147,7 @@ func (c *Client) dial(ctx context.Context, budget time.Duration) (net.Conn, erro if errors.Is(err, syscall.ECONNREFUSED) { noTLS.Store(p.plainAddr, true) } - c.lastTLS = false + c.lastTLS, c.lastAddr = false, p.plainAddr return dialWithRetry(ctx, "tcp", p.plainAddr, budget, dialAttemptTimeout, dialRetryBackoff) } return c.handshake(ctx, raw, p.tlsAddr) @@ -179,13 +179,34 @@ func (c *Client) handshake(ctx context.Context, raw net.Conn, addr string) (net. } return nil, &dialError{addr: addr, err: fmt.Errorf("TLS handshake: %w", err)} } - c.lastTLS = true + c.lastTLS, c.lastAddr = true, addr return conn, nil } // LastDialTLS reports whether the Client's most recent connection used TLS. func (c *Client) LastDialTLS() bool { return c.lastTLS } +// ShownAddr is how messages name the pod at addr before anything is sent to it: the host alone +// for the default port on the LAN (the client picks TLS on 8443, or plaintext 8080 on a pod +// without TLS), else addr as given. +func ShownAddr(addr string) string { + addr = strings.TrimSpace(addr) + host, port, err := net.SplitHostPort(addr) + if err != nil || port != PlainPort || IsUSBLinkAddr(host) || DefaultTLSMode == TLSOff { + return addr + } + return host +} + +// Shown is how messages name the pod: the address the last connection went to (host:8443 over +// TLS), else ShownAddr of c.Addr. +func (c *Client) Shown() string { + if c.lastAddr != "" { + return c.lastAddr + } + return ShownAddr(c.Addr) +} + // tlsConfig is the client configuration for addr (host:8443). pin: check (and on first use // record) the pin; false accepts any certificate (PeerCertificate, for showing and trusting). func tlsConfig(addr string, pin bool) (*tls.Config, error) {