From a1374ccf7dd7bf3245aeb593e4b132d1c28400df Mon Sep 17 00:00:00 2001 From: BFNOC <15773134+BFNOC@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:58:39 +0800 Subject: [PATCH] fix(esim): abort a switch to Lebara UK when the radio cannot be turned off - Return the radio release error from releaseRadioBeforeSwitch - Report the mode read back after a failed release - Abort the switch to a Lebara UK or unclassified target when the radio stays on - Keep a failed RadioCycle release of other cards logged and switching --- internal/device/pool_esim_switch.go | 80 ++++-- .../pool_esim_switch_lebara_radio_test.go | 243 ++++++++++++++++++ 2 files changed, 300 insertions(+), 23 deletions(-) create mode 100644 internal/device/pool_esim_switch_lebara_radio_test.go diff --git a/internal/device/pool_esim_switch.go b/internal/device/pool_esim_switch.go index cc41874a..c5633512 100644 --- a/internal/device/pool_esim_switch.go +++ b/internal/device/pool_esim_switch.go @@ -18,6 +18,11 @@ import ( // stop within voWiFiStopWaitTimeout; VoWiFi has been stopped and is not restored. var ErrSwitchVoWiFiNotStopped = errors.New("已请求停止 VoWiFi,但旧任务尚未确认退出,未切换 profile") +// ErrSwitchRadioNotReleased aborts a switch to a Lebara UK target (or one that +// could not be classified) whose radio could not be turned off first: with the +// radio on, the new profile could attach and move the card to another IMSI. +var ErrSwitchRadioNotReleased = errors.New("切入 Lebara UK 或无法识别的目标前关闭射频失败") + var postSwitchSIMAuthRecoveryDelays = []time.Duration{ 500 * time.Millisecond, 500 * time.Millisecond, @@ -323,25 +328,56 @@ func (p *Pool) applyNetworkPreferenceForSwitchSnapshot(worker *Worker, snapshot return worker.StopNetwork() } -func releaseRadioBeforeSwitch(deviceID string, worker *Worker) { +func releaseRadioBeforeSwitch(deviceID string, worker *Worker) error { if worker == nil || worker.Backend == nil || resolvedBackendMode(worker.Config) == backend.BackendPCSC { - return + return nil } controller, ok := worker.Backend.(backend.OperatingModeController) if !ok { - return + return nil } ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - if err := controller.SetOperatingMode(ctx, backend.ModeLowPower); err != nil { - logger.Warn("eSIM 切卡前释放 radio 失败,继续切卡", - "device", deviceID, - "err", err) - return + err := controller.SetOperatingMode(ctx, backend.ModeLowPower) + cancel() + if err != nil { + // The mode is read back only to report it. A failed release stays a + // failure even when the mode reads back as off: the QMI backend passes + // a reset in progress (ModeReset, 4) through unchanged, the same value + // it maps persistent flight (ModePersistLow, 6) to. + readCtx, cancelRead := context.WithTimeout(context.Background(), 2*time.Second) + mode, readErr := controller.GetOperatingMode(readCtx) + cancelRead() + if readErr != nil { + return fmt.Errorf("%w(读回射频模式失败: %v)", err, readErr) + } + return fmt.Errorf("%w(读回射频模式 %d)", err, mode) } logger.Info("eSIM 切卡前已释放 radio", "device", deviceID, "mode", backend.ModeLowPower) + return nil +} + +// releaseRadioForSwitchTarget turns the radio off before the profile changes. +// Only a Lebara UK target (or an unclassified one) aborts the switch when that +// fails; the RadioCycle release of other cards keeps going as before. +func (p *Pool) releaseRadioForSwitchTarget(worker *Worker, snapshot esimSwitchContext) error { + if snapshot.TargetLebaraCandidate || snapshot.TargetClassifyFailed { + if err := p.holdRadioOffForLebaraSwitchTarget(worker); err != nil { + logger.Error("切入受保护目标前关闭射频失败,中止切卡", + "device", worker.ID, "switch_token", snapshot.SwitchToken, "target_iccid", snapshot.TargetICCID, + "target_lebara_uk", snapshot.TargetLebaraCandidate, "target_classify_failed", snapshot.TargetClassifyFailed, + "err", err) + return fmt.Errorf("%w: %w", ErrSwitchRadioNotReleased, err) + } + return nil + } + if worker.Config.ESIMSwitch.RadioCycle { + if err := releaseRadioBeforeSwitch(worker.ID, worker); err != nil { + logger.Warn("eSIM 切卡前释放 radio 失败,继续切卡", "device", worker.ID, "err", err) + } + } + return nil } func (p *Pool) bringRadioOnlineAfterSwitch(deviceID string, worker *Worker, snapshot esimSwitchContext, attachTimeout time.Duration) { @@ -407,13 +443,15 @@ func (p *Pool) handleESIMSwitchBeforeSnapshot(deviceID string, snapshot esimSwit return token } -// prepareESIMSwitch returns an error when the old VoWiFi task has not stopped; -// the switch is then aborted before any radio, data or profile change. +// prepareESIMSwitch returns an error when the old VoWiFi task has not stopped +// (the switch is then aborted before any radio, data or profile change), or +// when the radio could not be turned off for a Lebara UK target or one that +// could not be classified (the switch is then aborted before any profile +// change and the failure path restores the snapshot). func (p *Pool) prepareESIMSwitch(deviceID string, snapshot esimSwitchContext) (uint64, error) { if snapshot.SwitchToken == 0 { return 0, nil } - holdTargetRadio := snapshot.TargetLebaraCandidate || snapshot.TargetClassifyFailed // Stop the old VoWiFi task first: until it has exited, nothing about the // SIM, its identity or the radio changes, so an abort leaves nothing to undo. if snapshot.VoWiFiActiveBefore { @@ -448,10 +486,8 @@ func (p *Pool) prepareESIMSwitch(deviceID string, snapshot esimSwitchContext) (u } } if worker := p.GetWorker(deviceID); worker != nil && worker.QMICore != nil { - if holdTargetRadio { - p.holdRadioOffForLebaraSwitchTarget(worker) - } else if worker.Config.ESIMSwitch.RadioCycle { - releaseRadioBeforeSwitch(deviceID, worker) + if err := p.releaseRadioForSwitchTarget(worker, snapshot); err != nil { + return snapshot.SwitchToken, err } worker.QMICore.ReleaseAPDULeasesForSwitchTeardown() // 切卡前主动清空 DeviceSnapshot 中缓存的 ICCID/IMSI, @@ -460,18 +496,16 @@ func (p *Pool) prepareESIMSwitch(deviceID string, snapshot esimSwitchContext) (u snap.ResetIdentities(false) } } else if worker := p.GetWorker(deviceID); worker != nil { - if holdTargetRadio { - p.holdRadioOffForLebaraSwitchTarget(worker) - } else if worker.Config.ESIMSwitch.RadioCycle { - releaseRadioBeforeSwitch(deviceID, worker) + if err := p.releaseRadioForSwitchTarget(worker, snapshot); err != nil { + return snapshot.SwitchToken, err } } return snapshot.SwitchToken, nil } -func (p *Pool) holdRadioOffForLebaraSwitchTarget(worker *Worker) { +func (p *Pool) holdRadioOffForLebaraSwitchTarget(worker *Worker) error { if worker == nil { - return + return nil } worker.setCellularRadioSuppressed(true) if nc := worker.NetworkController(); nc != nil && nc.IsConnected() { @@ -479,7 +513,7 @@ func (p *Pool) holdRadioOffForLebaraSwitchTarget(worker *Worker) { logger.Warn("切换 Lebara UK 前关闭数据连接失败", "device", worker.ID, "err", err) } } - releaseRadioBeforeSwitch(worker.ID, worker) + return releaseRadioBeforeSwitch(worker.ID, worker) } func (p *Pool) refreshPostSwitchIdentity(deviceID string, worker *Worker, snapshot esimSwitchContext) (bool, error) { diff --git a/internal/device/pool_esim_switch_lebara_radio_test.go b/internal/device/pool_esim_switch_lebara_radio_test.go new file mode 100644 index 00000000..30e678d7 --- /dev/null +++ b/internal/device/pool_esim_switch_lebara_radio_test.go @@ -0,0 +1,243 @@ +package device + +import ( + "context" + "errors" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/yibaiba/hideck/internal/backend" + "github.com/yibaiba/hideck/internal/config" + "github.com/yibaiba/hideck/internal/db" + qmicore "github.com/yibaiba/hideck/internal/qmi" +) + +var errLowPowerRejected = errors.New("set operating mode rejected") + +// lowPowerFailingBackend fails every request for the low power mode; the mode +// read back is whatever the stub reports, or readErr when set. +type lowPowerFailingBackend struct { + *esimSwitchRestoreBackendStub + readErr error +} + +func (b lowPowerFailingBackend) GetOperatingMode(ctx context.Context) (backend.OperatingMode, error) { + if b.readErr != nil { + return backend.ModeLowPower, b.readErr + } + return b.esimSwitchRestoreBackendStub.GetOperatingMode(ctx) +} + +func (b lowPowerFailingBackend) SetOperatingMode(ctx context.Context, mode backend.OperatingMode) error { + _ = b.esimSwitchRestoreBackendStub.SetOperatingMode(ctx, mode) + if mode == backend.ModeLowPower { + return errLowPowerRejected + } + return nil +} + +const ( + lebaraTargetICCID = "8944000000000000087" + plainTargetICCID = "8986000000000000095" +) + +func initSwitchTargetDB(t *testing.T) { + t.Helper() + if err := db.Init(filepath.Join(t.TempDir(), "lebara-radio.db")); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if db.DB != nil { + if sqlDB, err := db.DB.DB(); err == nil { + _ = sqlDB.Close() + } + db.DB = nil + } + }) + if err := db.UpsertSIMCard(lebaraTargetICCID, "234870000000001", "", "Lebara", nil); err != nil { + t.Fatal(err) + } + if err := db.UpsertSIMCard(plainTargetICCID, "460001234567891", "", "CMCC", nil); err != nil { + t.Fatal(err) + } +} + +func setCurrentSIMIdentity(w *Worker, iccid, imsi string) { + w.cacheMu.Lock() + w.state.Identity.ICCID = iccid + w.state.Identity.IMSI = imsi + w.state.Identity.Ready = true + w.state.Identity.Phase = simIdentityPhaseReady + w.cacheMu.Unlock() +} + +func hasOperatingMode(calls []backend.OperatingMode, mode backend.OperatingMode) bool { + for _, call := range calls { + if call == mode { + return true + } + } + return false +} + +// A Lebara UK target, or one that could not be classified, must not see the +// radio on while its profile is enabled: when the radio cannot be turned off +// first, the switch is aborted before any profile APDU, and the failure path +// never turns the radio on for a current card that is or may be Lebara UK. +func TestESIMSwitchToProtectedTargetAbortsWhenRadioStaysOn(t *testing.T) { + for _, tc := range []struct { + name string + currentIMSI string + classifyFails bool + currentKnownLebara bool + withQMICore bool + wantOnlineAfter bool + wantIMSIRestored string + }{ + {name: "plain current card", currentIMSI: "460001234567890", wantOnlineAfter: true, wantIMSIRestored: "460001234567890"}, + {name: "current card is Lebara UK", currentIMSI: "234870000000009"}, + {name: "current Lebara UK flipped to 20404", currentIMSI: "204040000000009", currentKnownLebara: true}, + {name: "current IMSI 20404 without Lebara history", currentIMSI: "204040000000009"}, + {name: "current identity unknown"}, + {name: "target not classified", currentIMSI: "460001234567890", classifyFails: true, wantOnlineAfter: true}, + {name: "QMI core branch", currentIMSI: "234870000000009", withQMICore: true}, + } { + t.Run(tc.name, func(t *testing.T) { + initSwitchTargetDB(t) + p := NewPool(&config.Config{}) + defer p.cancel() + stub := &esimSwitchRestoreBackendStub{mode: backend.BackendQMI, getMode: backend.ModeOnline} + w := &Worker{ID: "dev-1", Backend: lowPowerFailingBackend{esimSwitchRestoreBackendStub: stub}, Config: config.DeviceConfig{ID: "dev-1"}} + const currentICCID = "8986000000000000011" + if tc.currentKnownLebara { + // The card was seen as Lebara UK (23487) before it flipped to 20404. + if err := db.UpsertSIMCard(currentICCID, "234870000000009", "", "Lebara", nil); err != nil { + t.Fatal(err) + } + if class, err := ClassifyLebaraUKForICCID(currentICCID, ""); err != nil || !class.IsLebara { + t.Fatalf("current card classification = (%+v, %v), want Lebara UK from its history", class, err) + } + } + if tc.currentIMSI != "" { + setCurrentSIMIdentity(w, currentICCID, tc.currentIMSI) + } + var qmiMgr *qmicore.Manager + if tc.withQMICore { + qmiMgr = &qmicore.Manager{} + setPrivateMapFieldSwitchRestore(t, qmiMgr, "apduSessions", byte(1), func(elemType reflect.Type) reflect.Value { + elem := reflect.New(elemType).Elem() + elem.FieldByName("Channel").SetUint(1) + elem.FieldByName("Owner").SetString("test") + elem.FieldByName("OpenedAt").Set(reflect.ValueOf(time.Now())) + return elem + }) + w.QMICore = qmiMgr + } + p.workers[w.ID] = w + if tc.classifyFails { + sqlDB, err := db.DB.DB() + if err != nil { + t.Fatal(err) + } + _ = sqlDB.Close() + } + + snapshot := p.beginESIMSwitchForWorker(w.ID, lebaraTargetICCID, w) + if snapshot.TargetLebaraCandidate == tc.classifyFails || snapshot.TargetClassifyFailed != tc.classifyFails { + t.Fatalf("target classification = (lebara %v, failed %v), test setup is wrong", + snapshot.TargetLebaraCandidate, snapshot.TargetClassifyFailed) + } + token, err := p.prepareESIMSwitch(w.ID, snapshot) + if !errors.Is(err, ErrSwitchRadioNotReleased) || !errors.Is(err, errLowPowerRejected) { + t.Fatalf("prepareESIMSwitch err = %v, want ErrSwitchRadioNotReleased wrapping the backend error", err) + } + if token == 0 { + t.Fatal("aborted switch must return its token so the failure callback can clear it") + } + if len(stub.setCalls) != 1 || stub.setCalls[0] != backend.ModeLowPower { + t.Fatalf("setCalls before the failure callback = %v, want one low power request", stub.setCalls) + } + if qmiMgr != nil { + if got := privateMapLenSwitchRestore(t, qmiMgr, "apduSessions"); got != 1 { + t.Fatalf("apduSessions len = %d, want the current card's session kept", got) + } + } + + p.handleESIMSwitchFailedWithError(w.ID, token, err) + if p.IsESIMSwitching(w.ID) { + t.Fatal("aborted switch left the device in the switching state") + } + if got := hasOperatingMode(stub.setCalls, backend.ModeOnline); got != tc.wantOnlineAfter { + t.Fatalf("setCalls after the failure callback = %v, radio online = %v, want %v", + stub.setCalls, got, tc.wantOnlineAfter) + } + if tc.wantIMSIRestored != "" { + status := w.ProjectDeviceStatus() + if status.IMSI != tc.wantIMSIRestored || status.ICCID != currentICCID || w.CurrentICCID() != currentICCID { + t.Fatalf("restored identity = (%q, %q, current %q), want (%q, %q)", + status.ICCID, status.IMSI, w.CurrentICCID(), currentICCID, tc.wantIMSIRestored) + } + } + }) + } +} + +// A failed release aborts the switch even when the mode reads back as off (the +// QMI backend passes a reset in progress through as 4, the persistent flight +// value) or cannot be read back; the read back is only reported in the error. +func TestESIMSwitchToLebaraAbortsWhateverTheModeReadsBack(t *testing.T) { + for _, tc := range []struct { + name string + getMode backend.OperatingMode + readErr error + wantText string + }{ + {name: "reads back as flight", getMode: backend.ModeRFOff, wantText: "读回射频模式 4"}, + {name: "reads back as low power", getMode: backend.ModeLowPower, wantText: "读回射频模式 0"}, + {name: "read back fails", readErr: errors.New("dms timeout"), wantText: "读回射频模式失败: dms timeout"}, + } { + t.Run(tc.name, func(t *testing.T) { + initSwitchTargetDB(t) + p := NewPool(&config.Config{}) + defer p.cancel() + stub := &esimSwitchRestoreBackendStub{mode: backend.BackendQMI, getMode: tc.getMode} + w := &Worker{ID: "dev-1", Backend: lowPowerFailingBackend{stub, tc.readErr}, Config: config.DeviceConfig{ID: "dev-1"}} + p.workers[w.ID] = w + + token, err := p.prepareESIMSwitch(w.ID, p.beginESIMSwitchForWorker(w.ID, lebaraTargetICCID, w)) + if !errors.Is(err, ErrSwitchRadioNotReleased) || !strings.Contains(err.Error(), tc.wantText) { + t.Fatalf("prepareESIMSwitch err = %v, want ErrSwitchRadioNotReleased reporting %q", err, tc.wantText) + } + p.handleESIMSwitchFailedWithError(w.ID, token, err) + }) + } +} + +// Other cards keep the existing RadioCycle behaviour: a failed release is only +// logged and the switch goes on. +func TestESIMSwitchRadioCycleReleaseFailureStillSwitchesOtherCards(t *testing.T) { + initSwitchTargetDB(t) + p := NewPool(&config.Config{}) + defer p.cancel() + stub := &esimSwitchRestoreBackendStub{mode: backend.BackendQMI, getMode: backend.ModeOnline} + w := &Worker{ID: "dev-1", Backend: lowPowerFailingBackend{esimSwitchRestoreBackendStub: stub}, Config: config.DeviceConfig{ + ID: "dev-1", ESIMSwitch: config.ESIMSwitchConfig{RadioCycle: true}, + }} + p.workers[w.ID] = w + + snapshot := p.beginESIMSwitchForWorker(w.ID, plainTargetICCID, w) + if snapshot.TargetLebaraCandidate || snapshot.TargetClassifyFailed { + t.Fatalf("plain target classified as protected: %+v", snapshot) + } + token, err := p.prepareESIMSwitch(w.ID, snapshot) + if err != nil || token == 0 { + t.Fatalf("prepareESIMSwitch = (%d, %v), want the switch to go on", token, err) + } + if len(stub.setCalls) != 1 || stub.setCalls[0] != backend.ModeLowPower { + t.Fatalf("setCalls = %v, want one low power request", stub.setCalls) + } + p.handleESIMSwitchFailed(w.ID, token) +}