Merge pull request #118 from ilazycat/ml307-support

Preserve the AT-only QMI capability check from #117 when validating phone mode policy, with regression coverage for rejected policy mutations.
This commit is contained in:
yibaiba committed 2026-11-23 18:37:06 +08:00
commit 8a1c29d85f
100 files changed
+5929 -424

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
package api
import (
"context"
"errors"
"testing"
"github.com/yibaiba/hideck/internal/automation"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/device"
"github.com/yibaiba/hideck/internal/modem"
)
func TestAutomaticCellularCallRejectsUnsupportedModemBeforePreparation(t *testing.T) {
cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: "at", ATPort: "/dev/test-ml307c"}
manager, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C)
if err != nil {
t.Fatal(err)
}
pool := device.NewPool(&config.Config{})
pool.AttachWorkerForTest(&device.Worker{ID: cfg.ID, Config: cfg, Modem: manager})
executor := &automaticTaskExecutor{server: &Server{pool: pool}}
_, err = executor.Execute(context.Background(), automation.Task{
DeviceID: cfg.ID, TaskType: automation.TaskTypeCall, Environment: automation.EnvironmentCellular,
ProfileICCID: "8944000000000000501", ProfileAID: "A0000005591010FFFFFFFF8900000100",
Payload: automation.Payload{Phone: "888"},
}, func(step string) error {
t.Fatalf("unsupported cellular call reached preparation: %s", step)
return nil
})
var unsupported *device.PhoneModeUnsupportedError
if !errors.As(err, &unsupported) || automation.IsRetryable(err) {
t.Fatalf("Execute() error = %v, want a permanent unsupported phone mode error", err)
}
}
+8 -2
View File
@@ -38,6 +38,11 @@ func (e *automaticTaskExecutor) Execute(
if worker == nil {
return "", fmt.Errorf("device %s is offline", task.DeviceID)
}
if task.TaskType == automation.TaskTypeCall && task.Environment == automation.EnvironmentCellular {
if err := worker.CheckPhoneModeSupported(device.PhoneModeVoLTE); err != nil {
return "", automation.Permanent(err)
}
}
owner := captureAutomaticTaskDeviceOwner(e.server.pool, worker)
profileAction, err := resolveAutomaticTaskProfile(task, worker.CurrentICCID())
if err != nil {
@@ -236,8 +241,9 @@ func (e *automaticTaskExecutor) executeSMS(
if err := reportAutomationProgress(progress, "正在提交短信"); err != nil {
return "", err
}
selector := device.SMSIdentity{ICCID: task.ProfileICCID}
if task.Environment == automation.EnvironmentVoWiFi {
routed, err := e.server.pool.SendRoutedSMS(ctx, worker, task.Payload.Phone, task.Payload.Message, smscodec.SubmitOptions{})
routed, err := e.server.pool.SendRoutedSMSForIdentity(ctx, worker, task.Payload.Phone, task.Payload.Message, smscodec.SubmitOptions{}, selector)
if err != nil {
return "", automation.Permanent(fmt.Errorf("send VoWiFi SMS: %w", err))
}
@@ -256,7 +262,7 @@ func (e *automaticTaskExecutor) executeSMS(
routed.Outcome.MessageID, routed.Outcome.DeliveryState, routed.Outcome.PartsTotal,
), nil
}
if err := worker.SendSMS(task.Payload.Phone, task.Payload.Message); err != nil {
if err := worker.SendSMSForIdentity(ctx, task.Payload.Phone, task.Payload.Message, smscodec.SubmitOptions{}, selector); err != nil {
return "", automation.Permanent(fmt.Errorf("send cellular SMS: %w", err))
}
return "蜂窝短信已由模组提交", nil
+24
View File
@@ -74,6 +74,30 @@ func TestExecuteSMSDoesNotFallbackAfterIMSAccept(t *testing.T) {
}
}
func TestExecuteSMSRejectsChangedTaskProfile(t *testing.T) {
for _, environment := range []string{automation.EnvironmentVoWiFi, automation.EnvironmentCellular} {
t.Run(environment, func(t *testing.T) {
pool := device.NewPool(&config.Config{})
worker := &device.Worker{ID: "wwan0", Pool: pool}
original := device.SMSIdentity{ICCID: "8944000000000000501", IMSI: "234150000000501"}
pool.AttachWorkerWithSMSIdentityForTest(worker, original)
executor := &automaticTaskExecutor{server: &Server{pool: pool}}
_, err := executor.executeSMS(context.Background(), worker, automation.Task{
DeviceID: worker.ID, ProfileICCID: original.ICCID, Environment: environment,
Payload: automation.Payload{Phone: "888", Message: "BAL"},
}, func(string) error {
pool.AttachWorkerWithSMSIdentityForTest(worker, device.SMSIdentity{
ICCID: "8944000000000000502", IMSI: "234150000000502",
})
return nil
})
if !errors.Is(err, device.ErrSMSSelectorMismatch) {
t.Fatalf("submit SMS after changing profile: %v", err)
}
})
}
}
func TestVoWiFiReadyForSMSTaskUsesMOReadiness(t *testing.T) {
state := runtimehost.State{
IMSReady: true, SMSMOReady: true,
+23 -9
View File
@@ -20,7 +20,6 @@ const cardPolicySavedMWIClearFailedCode = "card_policy_saved_mwi_clear_failed"
type cardPolicyStore interface {
Get(string) (db.CardPolicy, error)
Resolve(string) (db.CardPolicy, error)
Upsert(db.CardPolicy) error
ClearMWIRejections(string) (bool, error)
}
@@ -39,10 +38,6 @@ func (databaseCardPolicyStore) Get(iccid string) (db.CardPolicy, error) {
return db.GetCardPolicy(iccid)
}
func (databaseCardPolicyStore) Resolve(iccid string) (db.CardPolicy, error) {
return db.ResolveCardPolicy(iccid)
}
func (databaseCardPolicyStore) Upsert(policy db.CardPolicy) error {
return db.UpsertCardPolicy(policy)
}
@@ -61,6 +56,13 @@ func (s *Server) cardPolicyStore() cardPolicyStore {
// patchCardPolicyForDevice 解析设备当前 ICCID,对 card_policies 行执行原地修改并落库。
// mutate 在 resolve 后的副本上改字段(source 会被强制为 "user")。
func (s *Server) patchCardPolicyForDevice(deviceID string, mutate func(*db.CardPolicy)) (iccid string, applied bool, err error) {
return s.patchCardPolicyForDeviceChecked(deviceID, func(p *db.CardPolicy) error {
mutate(p)
return nil
})
}
func (s *Server) patchCardPolicyForDeviceChecked(deviceID string, mutate func(*db.CardPolicy) error) (iccid string, applied bool, err error) {
worker := s.pool.GetWorker(deviceID)
if worker == nil {
return "", false, fmt.Errorf("设备未找到")
@@ -69,11 +71,16 @@ func (s *Server) patchCardPolicyForDevice(deviceID string, mutate func(*db.CardP
if iccid == "" {
return "", false, errCardPolicyIdentityUnavailable
}
p, err := s.cardPolicyStore().Resolve(iccid)
if err != nil {
p, err := s.cardPolicyStore().Get(iccid)
if errors.Is(err, db.ErrCardPolicyNotFound) {
// Keep the default in memory until the mutation has been validated.
p = db.DefaultCardPolicy(iccid)
} else if err != nil {
return iccid, false, fmt.Errorf("获取卡策略失败: %w", err)
}
mutate(&p)
if err := mutate(&p); err != nil {
return iccid, false, err
}
p.Source = "user"
db.NormalizeCardPolicy(&p)
if err := s.cardPolicyStore().Upsert(p); err != nil {
@@ -357,9 +364,16 @@ func normalizeCardPolicyIPVersion(value string) (string, error) {
}
func writeCardPolicyMutationError(c businessContext, err error) {
if writeLebaraUKRFLockError(c, err) {
return
}
status := http.StatusInternalServerError
if errors.Is(err, errCardPolicyIdentityUnavailable) {
var unsupportedMode *device.PhoneModeUnsupportedError
switch {
case errors.Is(err, errCardPolicyIdentityUnavailable), errors.Is(err, errModemVoiceCallActive):
status = http.StatusConflict
case errors.As(err, &unsupportedMode):
status = http.StatusUnprocessableEntity
}
c.JSON(status, gin.H{"status": "error", "message": err.Error()})
}
+158 -8
View File
@@ -1,6 +1,7 @@
package api
import (
"context"
"encoding/json"
"errors"
"fmt"
@@ -17,12 +18,14 @@ import (
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/device"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/internal/phone"
"github.com/yibaiba/hideck/internal/vowifihost"
)
type cardPolicyStoreStub struct {
policy db.CardPolicy
getErr error
resolveErr error
upsertErr error
cleared []string
remembered bool
@@ -48,10 +51,6 @@ func (s *cardPolicyStoreStub) Get(string) (db.CardPolicy, error) {
return s.policy, s.getErr
}
func (s *cardPolicyStoreStub) Resolve(string) (db.CardPolicy, error) {
return s.policy, s.resolveErr
}
func (s *cardPolicyStoreStub) Upsert(policy db.CardPolicy) error {
s.policy = policy
return s.upsertErr
@@ -524,19 +523,19 @@ func TestApplyNetworkAndVoWiFiInterlock(t *testing.T) {
}
wifiPhone := db.CardPolicy{PhoneMode: "wifi", NetworkEnabled: true}
applyVoWiFiEnableToCardPolicy(&wifiPhone)
applyVoWiFiEnableToCardPolicy(&wifiPhone, wifiPhone.PhoneMode)
if !wifiPhone.VoWiFiEnabled || !wifiPhone.AirplaneEnabled || wifiPhone.NetworkEnabled {
t.Fatalf("开 WiFi calling 应锁定飞行并关流量: %+v", wifiPhone)
}
cellPhone := db.CardPolicy{PhoneMode: "cellular", DataStrategy: "on_demand", AirplaneEnabled: true}
applyVoWiFiEnableToCardPolicy(&cellPhone)
applyVoWiFiEnableToCardPolicy(&cellPhone, cellPhone.PhoneMode)
if !cellPhone.VoWiFiEnabled || cellPhone.AirplaneEnabled || cellPhone.NetworkEnabled {
t.Fatalf("开蜂窝软件电话应驻网且默认不开流量: %+v", cellPhone)
}
voltePhone := db.CardPolicy{PhoneMode: "volte", AirplaneEnabled: true, NetworkEnabled: false}
applyVoWiFiEnableToCardPolicy(&voltePhone)
applyVoWiFiEnableToCardPolicy(&voltePhone, voltePhone.PhoneMode)
if !voltePhone.VoWiFiEnabled || voltePhone.AirplaneEnabled || voltePhone.NetworkEnabled {
t.Fatalf("开 VoLTE 应驻网且不强制开上网流量: %+v", voltePhone)
}
@@ -604,6 +603,122 @@ func TestPutCardPolicyAirplaneField(t *testing.T) {
}
}
func TestPhoneModePatchUsesEffectivePolicy(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, tc := range []struct {
name, imsi, workerMode, storedMode, body, wantReason string
wantEnabled, defaultProfile, missingPolicy bool
}{
{name: "AT-only default profile rejects VoLTE", imsi: "530010000000001", workerMode: "modem_voice", storedMode: "modem_voice", body: `{"enabled":true,"mode":"volte"}`, defaultProfile: true,
wantReason: "该设备没有 QMI 语音接口"},
{name: "AT-only default profile does not create rejected policy", imsi: "530010000000001", workerMode: "modem_voice", body: `{"enabled":true,"mode":"volte"}`, defaultProfile: true, missingPolicy: true,
wantReason: "该设备没有 QMI 语音接口"},
{name: "native VoLTE", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"volte"}`},
{name: "cellular IMS on demand", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"cellular","data_strategy":"on_demand"}`,
wantReason: "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS"},
{name: "saved cellular IMS mode", imsi: "530010000000001", workerMode: "wifi", storedMode: "cellular", body: `{"enabled":true}`,
wantReason: "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS"},
{name: "direct dial", imsi: "530010000000001", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"modem_voice"}`},
{name: "China software fallback", imsi: "460011234567890", workerMode: "wifi", storedMode: "wifi", body: `{"enabled":true,"mode":"wifi"}`},
{name: "stored VoLTE ahead of worker", imsi: "530010000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true}`},
{name: "stored WiFi ahead of worker", imsi: "530010000000001", workerMode: "volte", storedMode: "wifi", body: `{"enabled":true}`, wantEnabled: true},
{name: "default profile honors stored WiFi over worker cellular", imsi: "530010000000001", workerMode: "cellular", storedMode: "wifi", body: `{"enabled":true}`, wantEnabled: true, defaultProfile: true},
{name: "Lebara projects stored VoLTE to WiFi", imsi: "234870000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true}`, wantEnabled: true},
{name: "explicit Lebara VoLTE remains unsupported", imsi: "234870000000001", workerMode: "wifi", storedMode: "volte", body: `{"enabled":true,"mode":"volte"}`},
{name: "unsupported mode on a card without a saved policy", imsi: "530010000000001", workerMode: "wifi", body: `{"enabled":true,"mode":"volte"}`, missingPolicy: true},
} {
t.Run(tc.name, func(t *testing.T) {
cfg := config.DeviceConfig{ID: "test-phone", DeviceBackend: "at", ATPort: "/dev/test-phone", PhoneMode: tc.workerMode, DataStrategy: "on_demand"}
profile := modem.ATProfileML307C
if tc.defaultProfile {
profile = modem.ATProfileDefault
}
manager, err := modem.NewWithATProfile(cfg, profile)
if err != nil {
t.Fatal(err)
}
pool := device.NewPool(&config.Config{})
host := vowifihost.NewManager()
host.LifecycleControllerForTest().TestRun = func(context.Context, vowifihost.LifecycleCommand) error { return nil }
setNestedPrivateField(t, pool, []string{"vowifiHost"}, host)
w := &device.Worker{ID: cfg.ID, Config: cfg, Modem: manager}
policy := db.CardPolicy{ICCID: "8986012345678901234", PhoneMode: tc.storedMode, DataStrategy: "always", Source: "auto"}
setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, policy.ICCID)
setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, tc.imsi)
injectWorker(pool, w)
store := &cardPolicyStoreStub{policy: policy}
if tc.missingPolicy {
store.getErr = db.ErrCardPolicyNotFound
}
s := &Server{pool: pool, cardPolicies: store}
r := gin.New()
r.PATCH("/api/devices/:device_id/vowifi", s.handleDeviceVoWiFiPatch)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPatch, "/api/devices/"+cfg.ID+"/vowifi", strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(rec, req)
if tc.wantEnabled {
if rec.Code != http.StatusOK || !store.policy.VoWiFiEnabled || !w.Config.VoWiFiEnabled ||
store.policy.PhoneMode != tc.storedMode || w.Config.PhoneMode != device.PhoneModeWiFi ||
w.Config.DataStrategy != policy.DataStrategy || !w.Config.AirplaneEnabled || w.Config.NetworkEnabled {
t.Fatalf("code=%d body=%s policy=%+v worker=%+v", rec.Code, rec.Body.String(), store.policy, w.Config)
}
return
}
wantReason := tc.wantReason
if wantReason == "" {
wantReason = "ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨"
}
if rec.Code != http.StatusUnprocessableEntity || !strings.Contains(rec.Body.String(), wantReason) {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
if store.policy != policy || w.Config != cfg {
t.Fatalf("the rejected request changed policy or worker: %+v, %+v", store.policy, w.Config)
}
})
}
}
func TestPhoneDevicesReportsCellularIMSAvailability(t *testing.T) {
gin.SetMode(gin.TestMode)
pool := device.NewPool(&config.Config{})
for id, profile := range map[string]modem.ATProfile{
"ml307c": modem.ATProfileML307C,
"default": modem.ATProfileDefault,
} {
cfg := config.DeviceConfig{ID: id, DeviceBackend: "at", ATPort: "/dev/test-" + id}
manager, err := modem.NewWithATProfile(cfg, profile)
if err != nil {
t.Fatal(err)
}
injectWorker(pool, &device.Worker{ID: id, Config: cfg, Modem: manager})
}
s := &Server{pool: pool, phone: &phone.Service{}}
r := gin.New()
r.GET("/api/phone/devices", s.handlePhoneDevices)
rec := httptest.NewRecorder()
r.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/api/phone/devices", nil))
var response struct {
Devices []struct {
ID string `json:"id"`
Reason *string `json:"cellular_ims_unavailable_reason"`
} `json:"devices"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &response); rec.Code != http.StatusOK || err != nil || len(response.Devices) != 2 {
t.Fatalf("code=%d error=%v body=%s", rec.Code, err, rec.Body.String())
}
for _, item := range response.Devices {
if item.ID == "ml307c" && (item.Reason == nil || *item.Reason != "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS") {
t.Fatalf("missing ML307C reason: %s", rec.Body.String())
}
if item.ID == "default" && item.Reason != nil {
t.Fatalf("unexpected default-profile restriction: %s", rec.Body.String())
}
}
}
func TestLebaraUKRFLockRejectsNetworkAndCellular(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
@@ -654,6 +769,41 @@ func TestLebaraUKRFLockRejectsNetworkAndCellular(t *testing.T) {
}
}
func TestLebaraUKRFLockProjectsSavedCellularModeOnPhoneEnable(t *testing.T) {
gin.SetMode(gin.TestMode)
iccid := "8944000000000000087"
policy := db.CardPolicy{ICCID: iccid, PhoneMode: device.PhoneModeCellular, DataStrategy: "always", AirplaneEnabled: true}
store := &cardPolicyStoreStub{policy: policy}
pool := device.NewPool(&config.Config{})
host := vowifihost.NewManager()
host.LifecycleControllerForTest().TestRun = func(context.Context, vowifihost.LifecycleCommand) error { return nil }
setNestedPrivateField(t, pool, []string{"vowifiHost"}, host)
w := &device.Worker{ID: "lebara", Config: config.DeviceConfig{ID: "lebara", PhoneMode: device.PhoneModeWiFi, AirplaneEnabled: true}}
setNestedPrivateField(t, w, []string{"state", "Identity", "ICCID"}, iccid)
setNestedPrivateField(t, w, []string{"state", "Identity", "IMSI"}, "234870000000001")
injectWorker(pool, w)
s := &Server{pool: pool, cardPolicies: store}
r := gin.New()
r.PATCH("/api/devices/:device_id/vowifi", s.handleDeviceVoWiFiPatch)
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPatch, "/api/devices/lebara/vowifi", strings.NewReader(`{"enabled":true}`))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
if got := store.policy; got.PhoneMode != policy.PhoneMode || got.DataStrategy != policy.DataStrategy ||
!got.VoWiFiEnabled || !got.AirplaneEnabled || got.NetworkEnabled {
t.Fatalf("unexpected saved policy: %+v", got)
}
if got := w.Config; got.PhoneMode != device.PhoneModeWiFi || !got.VoWiFiEnabled || !got.AirplaneEnabled || got.NetworkEnabled {
t.Fatalf("unexpected runtime policy: %+v", got)
}
}
func TestLebaraUKRFLockClassificationErrorBlocksNetworkMutation(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
+2 -2
View File
@@ -33,11 +33,11 @@ func (g *apiBalanceGateway) Snapshot(deviceID string) (balance.DeviceSnapshot, e
return balance.DeviceSnapshot{DeviceID: deviceID, ICCID: "iccid-1", MCC: "234", MNC: "10"}, nil
}
func (g *apiBalanceGateway) SendVoWiFiSMS(context.Context, string, string, string) error {
func (g *apiBalanceGateway) SendVoWiFiSMS(context.Context, balance.DeviceSnapshot, string, string) error {
return errors.New("unexpected VoWiFi route")
}
func (g *apiBalanceGateway) SendBackendSMS(context.Context, string, string, string) error {
func (g *apiBalanceGateway) SendBackendSMS(context.Context, balance.DeviceSnapshot, string, string) error {
g.smsCalls++
return nil
}
+34 -24
View File
@@ -1221,31 +1221,41 @@ func (s *Server) useDeviceMgmtDiscovered(c businessContext) {
imei := strings.TrimSpace(dev.IMEI)
if withIMEI {
managedMatch, hasManaged := managedIndex.Lookup(strings.TrimSpace(dev.ControlPath), strings.TrimSpace(dev.USBPath), strings.TrimSpace(dev.NetInterface))
if hasManaged {
if containsDiscoveredATPort(dev.ATPorts, managedMatch.ATPort) {
resolvedATPort = managedMatch.ATPort
}
if imei == "" {
imei = managedMatch.IMEI
}
} else {
probed, discoveredIMEI := enrichDiscoveredCompatibleModemFn(dev, device.CompatibleModemEnrichOptions{
EnableATProbe: true,
ATProbeTimeout: 900 * time.Millisecond,
EnableQMIIMEIProbe: strings.TrimSpace(dev.ControlPath) != "" && dev.Mode != "mbim",
live, handled := managedIndex.ResolveLiveATIdentity(dev, func(raw device.CompatibleModem) (device.CompatibleModem, string) {
return enrichDiscoveredCompatibleModemFn(raw, device.CompatibleModemEnrichOptions{
EnableATProbe: true, ATProbeTimeout: 900 * time.Millisecond,
})
dev = probed
if resolved := strings.TrimSpace(probed.ATPort); resolved != "" {
resolvedATPort = resolved
}
if imei == "" {
imei = discoveredIMEI
}
// MBIM 设备没有 AT 端口也不支持 QMI,使用 MBIM DeviceCaps 探测 IMEI
if imei == "" && dev.Mode == "mbim" && strings.TrimSpace(dev.ControlPath) != "" {
if mbimIMEI, err := probeIMEIViaMBIMForMgmtFn(dev.ControlPath); err == nil && mbimIMEI != "" {
imei = mbimIMEI
})
if handled {
dev = live
resolvedATPort, imei = dev.ATPort, dev.IMEI
} else {
managedMatch, hasManaged := managedIndex.Lookup(strings.TrimSpace(dev.ControlPath), strings.TrimSpace(dev.USBPath), strings.TrimSpace(dev.NetInterface))
if hasManaged {
if containsDiscoveredATPort(dev.ATPorts, managedMatch.ATPort) {
resolvedATPort = managedMatch.ATPort
}
if imei == "" {
imei = managedMatch.IMEI
}
} else {
probed, discoveredIMEI := enrichDiscoveredCompatibleModemFn(dev, device.CompatibleModemEnrichOptions{
EnableATProbe: true,
ATProbeTimeout: 900 * time.Millisecond,
EnableQMIIMEIProbe: strings.TrimSpace(dev.ControlPath) != "" && dev.Mode != "mbim",
})
dev = probed
if resolved := strings.TrimSpace(probed.ATPort); resolved != "" {
resolvedATPort = resolved
}
if imei == "" {
imei = discoveredIMEI
}
// MBIM 设备没有 AT 端口也不支持 QMI,使用 MBIM DeviceCaps 探测 IMEI
if imei == "" && dev.Mode == "mbim" && strings.TrimSpace(dev.ControlPath) != "" {
if mbimIMEI, err := probeIMEIViaMBIMForMgmtFn(dev.ControlPath); err == nil && mbimIMEI != "" {
imei = mbimIMEI
}
}
}
}
+40 -1
View File
@@ -10,6 +10,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/yibaiba/hideck/internal/config"
@@ -252,11 +253,49 @@ func TestHandleDeviceMgmtDiscoveredExposesPCSCFailure(t *testing.T) {
}
}
func TestHandleDeviceMgmtDiscoveredReadsLiveATIdentityOnlyOnRequest(t *testing.T) {
gin.SetMode(gin.TestMode)
path := writeDeviceMgmtDiscoveryConfig(t, "server:\n port: \":7575\"\ndevices: []")
if err := config.InitGlobalManager(path); err != nil {
t.Fatal(err)
}
restoreDiscoveryStubs(t)
discoverQMIForMgmtFn = func() ([]device.QMIDevice, error) { return nil, nil }
discoverPCSCReadersForMgmtFn = func(context.Context) ([]pcsc.Reader, error) { return nil, nil }
discoverCompatibleModemsFromQMIFn = func([]device.QMIDevice) ([]device.CompatibleModem, error) {
return []device.CompatibleModem{{
USBPath: "/sys/bus/usb/devices/1-1", VendorID: 0x2ecc, ProductID: 0x3012,
ATPort: "/dev/ttyUSB8", ATPorts: []string{"/dev/ttyUSB8"}, Mode: "at",
}}, nil
}
const liveIMEI = "490154203237518"
var calls []device.CompatibleModemEnrichOptions
enrichDiscoveredCompatibleModemFn = func(dev device.CompatibleModem, opts device.CompatibleModemEnrichOptions) (device.CompatibleModem, string) {
calls = append(calls, opts)
return dev, liveIMEI
}
srv := &Server{pool: device.NewPool(&config.Config{}), configPath: path}
static := requestDiscoveredDevicesWithQuery(t, srv, "")
if len(calls) != 0 || len(static.Devices) != 1 || static.Devices[0].IMEI != "" || static.Devices[0].ATPort != "/dev/ttyUSB8" {
t.Fatalf("static discovery probed or lost the attachment: probes=%d devices=%+v", len(calls), static.Devices)
}
live := requestDiscoveredDevices(t, srv)
if len(calls) != 1 || !calls[0].EnableATProbe || calls[0].ATProbeTimeout != 900*time.Millisecond || calls[0].EnableQMIIMEIProbe ||
len(live.Devices) != 1 || live.Devices[0].IMEI != liveIMEI {
t.Fatalf("unexpected live AT discovery: probes=%+v devices=%+v", calls, live.Devices)
}
}
func requestDiscoveredDevices(t *testing.T, srv *Server) discoveredDevicesResponse {
t.Helper()
return requestDiscoveredDevicesWithQuery(t, srv, "?with_imei=1")
}
func requestDiscoveredDevicesWithQuery(t *testing.T, srv *Server, query string) discoveredDevicesResponse {
t.Helper()
recorder := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(recorder)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/devices/discovered?with_imei=1", nil)
ctx.Request = httptest.NewRequest(http.MethodGet, "/api/devices/discovered"+query, nil)
srv.handleDeviceMgmtDiscovered(ctx)
+7 -7
View File
@@ -1,20 +1,20 @@
package api
import (
"net/http"
"errors"
"github.com/gin-gonic/gin"
"github.com/yibaiba/hideck/internal/device"
)
func (s *Server) allowModemVoiceModeChange(c businessContext, id, nextMode string) bool {
var errModemVoiceCallActive = errors.New("请先挂断模组直拨通话,再切换或关闭电话服务")
func (s *Server) checkModemVoiceModeChange(id, nextMode string) error {
if s.pool == nil || s.pool.ModemVoiceController() == nil {
return true
return nil
}
controller := s.pool.ModemVoiceController()
if controller.ActiveCall(id) == nil || nextMode == device.PhoneModeModemVoice {
return true
return nil
}
c.JSON(http.StatusConflict, gin.H{"status": "error", "message": "请先挂断模组直拨通话,再切换或关闭电话服务"})
return false
return errModemVoiceCallActive
}
+16 -1
View File
@@ -446,6 +446,12 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/SMSSendResponse'
'202':
description: 短信提交结果未知或仅确认了部分分段,请勿重发整条
content:
application/json:
schema:
$ref: '#/components/schemas/SMSSendResponse'
'400':
$ref: '#/components/responses/ErrorMessage'
'404':
@@ -4001,6 +4007,12 @@ components:
phone_region:
type: string
description: SIM 归属国家或地区的 ISO 3166-1 alpha-2 代码
native_voice_unavailable_reason:
type: string
description: 设备不支持模组原生语音模式时返回的原因
cellular_ims_unavailable_reason:
type: string
description: 设备无法通过模组蜂窝数据使用软件 IMS 的原因
voice:
type: object
additionalProperties: true
@@ -5205,9 +5217,12 @@ components:
type: string
parts_total:
type: integer
parts_confirmed:
type: integer
description: 202 响应中模组已确认提交的分段数量
delivery_state:
type: string
description: 通道发送状态;acked 仅表示发送端已受理,不保证收件手机已收到
description: acked 表示发送端已受理;202 响应中的 unknown 表示结果未知,partial_ack 表示仅部分分段获确认
SMSDeliveryResponse:
type: object
+6
View File
@@ -109,6 +109,12 @@ func (s *Server) usePhoneDevices(c businessContext) {
"software_ims_blocked": device.WorkerSoftwareIMSBlocked(worker),
"rf_lock": class.RFLock(),
}
if err := worker.CheckPhoneModeSupported(device.PhoneModeVoLTE); err != nil {
item["native_voice_unavailable_reason"] = err.Error()
}
if reason := worker.CellularIMSUnavailableReason(); reason != "" {
item["cellular_ims_unavailable_reason"] = reason
}
if region := s.phoneNumberRegion(worker.ID); region != "" {
item["phone_region"] = region
if code := phonenumbers.GetCountryCodeForRegion(region); code != 0 {
+56 -52
View File
@@ -1,6 +1,7 @@
package api
import (
"fmt"
"net/http"
"strings"
@@ -127,55 +128,61 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) {
}
if *req.Enabled {
// 落库:置 vowifi_enabled=true。若带 mode/data_strategy 则一并落库。
mode := normalizePhoneMode(req.Mode)
if req.Mode == nil {
if w := s.pool.GetWorker(deviceID); w != nil {
mode = w.Config.PhoneMode
w := s.pool.GetWorker(deviceID)
var mode, strategy string
if _, _, err := s.patchCardPolicyForDeviceChecked(deviceID, func(p *db.CardPolicy) error {
db.NormalizeCardPolicy(p)
mode = p.PhoneMode
if req.Mode != nil {
mode = normalizePhoneMode(req.Mode)
}
}
if !s.allowModemVoiceModeChange(c, deviceID, mode) {
return
}
strategy := normalizeDataStrategy(req.DataStrategy)
forceVoLTE := false
if w := s.pool.GetWorker(deviceID); device.WorkerSoftwareIMSBlocked(w) && !device.IsModemVoiceMode(mode) {
mode = device.PhoneModeVoLTE
forceVoLTE = true
}
// Native VoLTE is driven over QMI (IMS clients, IMSA registration, VOICEDial).
// An AT-only device has none of that, so the enable pass is guaranteed to
// fail after this handler has already answered "VoLTE 已设置" and written
// the mode into the card policy. Refuse here so the caller gets a reason
// instead of a success message followed by a silent fall back.
if device.IsNativeVoLTEMode(mode) && !s.pool.HasQMIVoice(deviceID) {
c.JSON(http.StatusBadRequest, gin.H{
"status": "error",
"message": "该设备没有 QMI 语音接口,无法启用 VoLTE,请改用模组直拨",
"device": deviceID,
})
return
}
if device.PhoneModeCampsOnCell(mode) {
class, classifyErr := s.classifyLebaraUKForDevice(businessRequestContext(c), deviceID)
if rejectLebaraUKRFUnlock(c, class, classifyErr) {
return
softwareIMSBlocked := device.WorkerSoftwareIMSBlocked(w)
if softwareIMSBlocked && !device.IsModemVoiceMode(mode) {
mode = device.PhoneModeVoLTE
}
}
if _, _, err := s.patchCardPolicyForDevice(deviceID, func(p *db.CardPolicy) {
if req.Mode != nil || forceVoLTE {
var rfPolicyErr error
keepSavedMode := false
if device.PhoneModeCampsOnCell(mode) {
class, err := s.classifyLebaraUKForDevice(businessRequestContext(c), deviceID)
switch {
case err != nil:
rfPolicyErr = fmt.Errorf("识别 Lebara UK 射频策略失败: %w", err)
case class.IsLebara && req.Mode == nil && !softwareIMSBlocked:
// Lebara projects the saved mode to WiFi while its RF lock is active.
mode = device.PhoneModeWiFi
keepSavedMode = true
case class.IsLebara:
rfPolicyErr = device.ErrLebaraUKRFLocked
}
}
if err := s.checkModemVoiceModeChange(deviceID, mode); err != nil {
return err
}
if err := w.CheckPhoneModeSupported(mode); err != nil {
return err
}
if device.IsNativeVoLTEMode(mode) && !s.pool.HasQMIVoice(deviceID) {
return &device.PhoneModeUnsupportedError{Reason: "该设备没有 QMI 语音接口,无法启用 VoLTE,请改用模组直拨"}
}
if rfPolicyErr != nil {
return rfPolicyErr
}
strategy = p.DataStrategy
if req.DataStrategy != nil {
strategy = normalizeDataStrategy(req.DataStrategy)
}
if !keepSavedMode {
p.PhoneMode = mode
}
if req.DataStrategy != nil {
p.DataStrategy = strategy
}
applyVoWiFiEnableToCardPolicy(p)
p.DataStrategy = strategy
applyVoWiFiEnableToCardPolicy(p, mode)
return nil
}); err != nil {
writeCardPolicyMutationError(c, err)
return
}
// 同步 w.Config,使概览即时切到 VoWiFi 模式面板(EnableVoWiFi 不碰 Config)。
w := s.pool.GetWorker(deviceID)
w = s.pool.GetWorker(deviceID)
prevMode, prevStrategy := "", ""
if w != nil {
prevMode = w.Config.PhoneMode
@@ -186,12 +193,8 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) {
if prevStrategy == "" {
prevStrategy = "on_demand"
}
if req.Mode != nil || forceVoLTE {
w.Config.PhoneMode = mode
}
if req.DataStrategy != nil {
w.Config.DataStrategy = strategy
}
w.Config.PhoneMode = mode
w.Config.DataStrategy = strategy
}
s.pool.SetWorkerVoWiFiPolicy(deviceID, true)
if w := s.pool.GetWorker(deviceID); w != nil && device.IsModemVoiceMode(w.Config.PhoneMode) {
@@ -234,8 +237,8 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) {
})
return
}
modeChanged := req.Mode != nil && mode != prevMode
strategyChanged := req.DataStrategy != nil && strategy != prevStrategy
modeChanged := mode != prevMode
strategyChanged := strategy != prevStrategy
if s.pool.IsVoWiFiActive(deviceID) && (modeChanged || strategyChanged) {
if err := s.pool.RestartVoWiFi(deviceID); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
@@ -257,7 +260,8 @@ func (s *Server) useDeviceVoWiFiPatch(c businessContext) {
}
// 落库:仅清 vowifi_enabled=false,保留 airplane_enabled(用户飞行意图)。
if !s.allowModemVoiceModeChange(c, deviceID, "") {
if err := s.checkModemVoiceModeChange(deviceID, ""); err != nil {
writeCardPolicyMutationError(c, err)
return
}
// 关闭 VoWiFi 后 DisableVoWiFi 会按当前卡策略重投影:之前是飞行则回飞行,否则回在线。
@@ -308,19 +312,19 @@ func applyNetworkEnableToCardPolicy(p *db.CardPolicy) {
}
// applyVoWiFiEnableToCardPolicy 按通话方式联动射频和流量。
func applyVoWiFiEnableToCardPolicy(p *db.CardPolicy) {
func applyVoWiFiEnableToCardPolicy(p *db.CardPolicy, mode string) {
if p == nil {
return
}
p.VoWiFiEnabled = true
if p.PhoneMode == "cellular" {
if mode == device.PhoneModeCellular {
p.AirplaneEnabled = false
if p.DataStrategy == "always" {
p.NetworkEnabled = true
}
return
}
if p.PhoneMode == "volte" || p.PhoneMode == "modem_voice" {
if device.UsesModemPhoneControl(mode) {
p.AirplaneEnabled = false
return
}
+4 -3
View File
@@ -12,8 +12,9 @@ import (
)
const (
defaultHTTPSAddress = ":7576"
maxServerHeaderBytes = 1 << 20
defaultHTTPSAddress = ":7576"
maxServerHeaderBytes = 1 << 20
managedHTTPWriteTimeout = 120 * time.Second
)
func (s *Server) serveHTTP() error {
@@ -63,7 +64,7 @@ func (s *Server) serveHTTPAndHTTPS(certificate tls.Certificate) error {
func newManagedHTTPServer(address string, handler http.Handler) *http.Server {
return &http.Server{
Addr: address, Handler: handler, ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 120 * time.Second, WriteTimeout: 120 * time.Second,
ReadTimeout: 120 * time.Second, WriteTimeout: managedHTTPWriteTimeout,
IdleTimeout: 60 * time.Second, MaxHeaderBytes: maxServerHeaderBytes,
}
}
+52 -1
View File
@@ -1,10 +1,13 @@
package api
import (
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/device"
"github.com/yibaiba/hideck/pkg/smscodec"
@@ -52,7 +55,28 @@ func (s *Server) useSendSMS(c businessContext) {
partsTotal := 1
deliveryState := "acked"
routed, err := s.pool.SendRoutedSMS(businessRequestContext(c), worker, req.Phone, req.Message, sendOpts)
// A multi-part send can outlast the server's write deadline. Preserve a
// fresh write window for the result without changing modem timeouts.
var responseController *http.ResponseController
if rest, ok := c.(*gin.Context); ok {
controller := http.NewResponseController(rest.Writer)
if err := controller.SetWriteDeadline(time.Time{}); err == nil {
responseController = controller
} else if !errors.Is(err, http.ErrNotSupported) {
logger.Warn("取消短信发送等待写入超时失败", "err", err)
}
}
selector := device.SMSIdentity{ICCID: db.CanonicalICCID(req.ICCID), IMSI: strings.TrimSpace(req.IMSI)}
routed, err := s.pool.SendRoutedSMSForIdentity(businessRequestContext(c), worker, req.Phone, req.Message, sendOpts, selector)
if responseController != nil {
if err := responseController.SetWriteDeadline(time.Now().Add(managedHTTPWriteTimeout)); err != nil && !errors.Is(err, http.ErrNotSupported) {
logger.Warn("恢复短信响应写入超时失败", "err", err)
}
}
if errors.Is(err, device.ErrSMSSelectorMismatch) {
c.JSON(http.StatusConflict, gin.H{"status": "error", "message": err.Error()})
return
}
if respondOutboundLimit(c, err) {
return
}
@@ -64,6 +88,33 @@ func (s *Server) useSendSMS(c businessContext) {
}
messageID = strings.TrimSpace(routed.Outcome.MessageID)
if err != nil {
if routed.Via == device.RoutedSMSViaCS &&
(deliveryState == db.SMSDeliveryStateUnknown || deliveryState == db.SMSDeliveryStatePartialAck) {
if persistErr := saveRoutedSMSRecord(routedSMSRecord{
Identity: routed.Identity, Sender: worker.ID, Recipient: req.Phone,
Content: req.Message, Status: db.SMSStatusSubmitUnconfirmed,
}); persistErr != nil {
logger.Warn("短信提交状态未确认记录入库失败", "device", deviceID, "err", persistErr)
}
message := "短信发送结果未知,请勿重发整条"
if deliveryState == db.SMSDeliveryStatePartialAck {
message = fmt.Sprintf("短信仅确认提交 %d/%d 段,请勿重发整条", routed.PartsConfirmed, partsTotal)
} else if routed.PartsConfirmed > 0 {
message = fmt.Sprintf("短信已确认提交 %d/%d 段,整体结果未知,请勿重发整条", routed.PartsConfirmed, partsTotal)
}
c.JSON(http.StatusAccepted, gin.H{
"status": "uncertain",
"message": message,
"device": deviceID,
"phone": req.Phone,
"destination": routed.Destination,
"message_id": messageID,
"parts_total": partsTotal,
"parts_confirmed": routed.PartsConfirmed,
"delivery_state": deliveryState,
})
return
}
if routed.Via == device.RoutedSMSViaVoWiFi || routed.FellBackToCS {
deliveryState = "failed"
recordErr := device.RecordVoWiFiSMSSendFailure(s.pool, device.VoWiFiSMSSendFailure{
+218
View File
@@ -0,0 +1,218 @@
package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/device"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/internal/outbound"
"github.com/yibaiba/hideck/pkg/smscodec"
)
func TestSendSMSRecordsUnconfirmedSubmission(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, test := range []struct {
name string
fallback bool
sendError error
state string
confirmed int
total int
}{
{
name: "direct unknown", state: db.SMSDeliveryStateUnknown, total: 1,
sendError: modem.ErrSMSSubmitUnknown,
},
{
name: "unknown after fallback", state: db.SMSDeliveryStateUnknown, fallback: true, confirmed: 1, total: 3,
sendError: &modem.SMSSubmitError{PartsConfirmed: 1, PartsTotal: 3, Err: modem.ErrSMSSubmitUnknown},
},
{
name: "partially accepted", state: db.SMSDeliveryStatePartialAck, confirmed: 1, total: 2,
sendError: &modem.SMSSubmitError{PartsConfirmed: 1, PartsTotal: 2, Err: errors.New("modem rejected submit")},
},
} {
t.Run(test.name, func(t *testing.T) {
openTestDB(t)
pool := device.NewPool(&config.Config{})
worker := &device.Worker{ID: "sms-at", Config: config.DeviceConfig{VoWiFiEnabled: test.fallback}}
identity := device.SMSIdentity{ICCID: "8944000000000000601", IMSI: "234150000000601"}
pool.AttachWorkerWithSMSIdentityForTest(worker, identity)
imsCalls, csCalls := 0, 0
pool.SetRoutedSMSTestSenders(
func(context.Context, string, string, string, smscodec.SubmitOptions) (messaging.SendOutcome, error) {
imsCalls++
return messaging.SendOutcome{MessageID: "ims-only", DeliveryState: "failed",
RecommendCSFallback: true}, messaging.ErrSMSNotReady
},
func(string, string, string) error { csCalls++; return test.sendError },
)
server := &Server{pool: pool}
recorder := httptest.NewRecorder()
c, _ := gin.CreateTestContext(recorder)
c.Request = httptest.NewRequest(http.MethodPost, "/api/sms/send", strings.NewReader(
`{"device_id":"sms-at","phone":"777","message":"test"}`))
c.Request.Header.Set("Content-Type", "application/json")
server.handleSendSMS(c)
var response struct {
Status string `json:"status"`
DeliveryState string `json:"delivery_state"`
Message string `json:"message"`
MessageID string `json:"message_id"`
PartsTotal int `json:"parts_total"`
PartsConfirmed int `json:"parts_confirmed"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {
t.Fatal(err)
}
if recorder.Code != http.StatusAccepted || response.Status != "uncertain" || response.DeliveryState != test.state ||
!strings.Contains(response.Message, "请勿重发整条") || response.MessageID != "" ||
response.PartsTotal != test.total || response.PartsConfirmed != test.confirmed || csCalls != 1 || (imsCalls == 1) != test.fallback {
t.Fatalf("HTTP %d: %s (IMS calls %d, CS calls %d)", recorder.Code, recorder.Body, imsCalls, csCalls)
}
messages, err := db.GetSMSByICCID(identity.ICCID, 10)
if err != nil || len(messages) != 1 || messages[0].Type != 2 || messages[0].Status != db.SMSStatusSubmitUnconfirmed {
t.Fatalf("SMS history = %+v, err = %v", messages, err)
}
})
}
}
func TestRESTSMSUncertainResultSurvivesWriteTimeout(t *testing.T) {
gin.SetMode(gin.TestMode)
openTestDB(t)
pool := device.NewPool(&config.Config{})
worker := &device.Worker{ID: "sms-at"}
pool.AttachWorkerWithSMSIdentityForTest(worker, device.SMSIdentity{
ICCID: "8944000000000000601", IMSI: "234150000000601",
})
const writeTimeout = 100 * time.Millisecond
var sends atomic.Int32
pool.SetRoutedSMSTestSenders(nil, func(string, string, string) error {
sends.Add(1)
time.Sleep(3 * writeTimeout)
return &modem.SMSSubmitError{PartsTotal: 3, PartsConfirmed: 2, Err: modem.ErrSMSSubmitUnknown}
})
server := &Server{pool: pool}
router := gin.New()
router.POST("/api/sms/send", server.handleSendSMS)
httpServer := httptest.NewUnstartedServer(router)
httpServer.Config.WriteTimeout = writeTimeout
httpServer.Start()
t.Cleanup(httpServer.Close)
client := httpServer.Client()
client.Timeout = 3 * time.Second
resp, err := client.Post(httpServer.URL+"/api/sms/send", "application/json", strings.NewReader(
`{"device_id":"sms-at","phone":"777","message":"test"}`))
if err != nil {
t.Fatalf("await SMS submission response: %v", err)
}
defer resp.Body.Close()
var result struct {
DeliveryState string `json:"delivery_state"`
PartsTotal int `json:"parts_total"`
PartsConfirmed int `json:"parts_confirmed"`
Message string `json:"message"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
t.Fatalf("decode HTTP %d: %v", resp.StatusCode, err)
}
if resp.StatusCode != http.StatusAccepted || result.DeliveryState != db.SMSDeliveryStateUnknown ||
result.PartsTotal != 3 || result.PartsConfirmed != 2 || !strings.Contains(result.Message, "请勿重发整条") || sends.Load() != 1 {
t.Fatalf("HTTP %d result=%+v CS sends=%d", resp.StatusCode, result, sends.Load())
}
}
type smsWriteDeadlineRecorder struct {
*httptest.ResponseRecorder
onClear func()
}
func (r *smsWriteDeadlineRecorder) SetWriteDeadline(deadline time.Time) error {
if deadline.IsZero() {
r.onClear()
}
return nil
}
type smsSelectorTestBackend struct {
ussdDeviceBackendStub
imsi string
}
func (b *smsSelectorTestBackend) GetIMSI(context.Context) (string, error) {
return b.imsi, nil
}
type smsSelectorTestLimiter struct {
attempts int
}
func (l *smsSelectorTestLimiter) Consume(context.Context, outbound.Request) error {
l.attempts++
return nil
}
func TestSendSMSKeepsExplicitSIMSelectorThroughSubmission(t *testing.T) {
gin.SetMode(gin.TestMode)
original := device.SMSIdentity{ICCID: "8944000000000000601", IMSI: "234150000000601"}
for _, test := range []struct {
name, request string
active device.SMSIdentity
wantStatus int
wantSends int
}{
{"matching ICCID", `"iccid":" 8944000000000000601f "`, original, http.StatusOK, 1},
{"matching IMSI", `"imsi":" 234150000000601 "`, original, http.StatusOK, 1},
{"stale ICCID", `"iccid":"8944000000000000601"`, device.SMSIdentity{ICCID: "8944000000000000602", IMSI: original.IMSI}, http.StatusConflict, 0},
{"stale IMSI", `"imsi":"234150000000601"`, device.SMSIdentity{ICCID: original.ICCID, IMSI: "234150000000602"}, http.StatusConflict, 0},
{"device selection follows active SIM", `"device_id":"sms-at"`, device.SMSIdentity{ICCID: "8944000000000000602", IMSI: "234150000000602"}, http.StatusOK, 1},
} {
t.Run(test.name, func(t *testing.T) {
openTestDB(t)
pool := device.NewPool(&config.Config{})
backend := &smsSelectorTestBackend{imsi: original.IMSI}
worker := &device.Worker{ID: "sms-at", Backend: backend}
pool.AttachWorkerWithSMSIdentityForTest(worker, original)
limiter := &smsSelectorTestLimiter{}
pool.SetOutboundLimiter(limiter)
sends := 0
pool.SetRoutedSMSTestSenders(nil, func(string, string, string) error {
sends++
return nil
})
writer := &smsWriteDeadlineRecorder{ResponseRecorder: httptest.NewRecorder(), onClear: func() {
// The handler clears its write deadline after selecting a worker.
backend.imsi = test.active.IMSI
pool.AttachWorkerWithSMSIdentityForTest(worker, test.active)
}}
c, _ := gin.CreateTestContext(writer)
c.Request = httptest.NewRequest(http.MethodPost, "/api/sms/send", strings.NewReader(
`{`+test.request+`,"phone":"777","message":"test"}`))
c.Request.Header.Set("Content-Type", "application/json")
server := &Server{pool: pool}
server.handleSendSMS(c)
if writer.Code != test.wantStatus || limiter.attempts != test.wantSends || sends != test.wantSends {
t.Fatalf("HTTP %d: %s, quota attempts=%d, sends=%d", writer.Code, writer.Body, limiter.attempts, sends)
}
messages, err := db.GetSMSByICCID(test.active.ICCID, 10)
if err != nil || len(messages) != test.wantSends {
t.Fatalf("active SIM history = %+v, error = %v", messages, err)
}
})
}
}
+26
View File
@@ -261,6 +261,32 @@ func (a *ATBackend) GetOperatingMode(ctx context.Context) (OperatingMode, error)
return OperatingMode(mode), nil
}
func (a *ATBackend) SupportsOfflineSIMReload() bool {
return a.modem.ATProfile().SupportsOfflineSIMReload()
}
// ReloadSIMOffline refreshes the SIM while keeping the radio off.
func (a *ATBackend) ReloadSIMOffline(ctx context.Context) error {
mode, err := a.GetOperatingMode(ctx)
if err != nil {
return err
}
if mode != ModeRFOff {
return fmt.Errorf("offline SIM reload requires CFUN=4, got %d", mode)
}
if err := ctx.Err(); err != nil {
return err
}
reloadErr := a.SetOperatingMode(ctx, ModeLowPower)
if reloadErr == nil {
time.Sleep(time.Second)
}
// A command that timed out might still have taken effect.
restoreErr := a.SetOperatingMode(ctx, ModeRFOff)
return errors.Join(reloadErr, restoreErr)
}
func (a *ATBackend) Reboot(ctx context.Context) error {
_, err := a.modem.ExecuteAT("AT+CFUN=1,1", 5*time.Second)
return err
+6 -6
View File
@@ -40,24 +40,24 @@ func (g *PoolGateway) Snapshot(deviceID string) (DeviceSnapshot, error) {
RouteSMSViaVoWiFi: g.pool.ShouldRouteSMSViaVoWiFi(worker.ID)}, nil
}
func (g *PoolGateway) SendVoWiFiSMS(ctx context.Context, deviceID, destination, payload string) error {
func (g *PoolGateway) SendVoWiFiSMS(ctx context.Context, snapshot DeviceSnapshot, destination, payload string) error {
if g == nil || g.pool == nil {
return ErrDeviceNotFound
}
worker := g.pool.GetWorker(deviceID)
worker := g.pool.GetWorker(snapshot.DeviceID)
if worker == nil {
return ErrDeviceNotFound
}
_, err := g.pool.SendRoutedSMS(ctx, worker, destination, payload, smscodec.SubmitOptions{})
_, err := g.pool.SendRoutedSMSForIdentity(ctx, worker, destination, payload, smscodec.SubmitOptions{}, device.SMSIdentity{ICCID: snapshot.ICCID})
return err
}
func (g *PoolGateway) SendBackendSMS(_ context.Context, deviceID, destination, payload string) error {
worker := g.pool.GetWorker(deviceID)
func (g *PoolGateway) SendBackendSMS(ctx context.Context, snapshot DeviceSnapshot, destination, payload string) error {
worker := g.pool.GetWorker(snapshot.DeviceID)
if worker == nil {
return ErrDeviceNotFound
}
return worker.SendSMSWithOptions(destination, payload, smscodec.SubmitOptions{})
return worker.SendSMSForIdentity(ctx, destination, payload, smscodec.SubmitOptions{}, device.SMSIdentity{ICCID: snapshot.ICCID})
}
func (g *PoolGateway) SendVoWiFiUSSD(ctx context.Context, deviceID, code string) (USSDResponse, error) {
+15 -2
View File
@@ -25,7 +25,7 @@ func TestPoolGatewaySendVoWiFiSMSFallsBackToCSWithoutDoubleSend(t *testing.T) {
},
func(string, string, string) error { csCalls++; return nil },
)
if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), "wwan0", "85075", "INFO"); err != nil {
if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), DeviceSnapshot{DeviceID: "wwan0", ICCID: "8944100000000000001"}, "85075", "INFO"); err != nil {
t.Fatalf("SendVoWiFiSMS() = %v", err)
}
if vowifiCalls != 1 || csCalls != 1 {
@@ -46,7 +46,7 @@ func TestPoolGatewaySendVoWiFiSMSDoesNotFallbackAfterIMSAccept(t *testing.T) {
},
func(string, string, string) error { csCalls++; return nil },
)
if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), "wwan0", "85075", "INFO"); err == nil ||
if err := NewPoolGateway(pool).SendVoWiFiSMS(context.Background(), DeviceSnapshot{DeviceID: "wwan0", ICCID: "8944100000000000001"}, "85075", "INFO"); err == nil ||
!strings.Contains(err.Error(), "403") {
t.Fatalf("expected IMS 403 to stay on VoWiFi, got %v", err)
}
@@ -54,3 +54,16 @@ func TestPoolGatewaySendVoWiFiSMSDoesNotFallbackAfterIMSAccept(t *testing.T) {
t.Fatalf("calls vowifi=%d cs=%d", vowifiCalls, csCalls)
}
}
func TestPoolGatewayRejectsSMSAfterCardChanges(t *testing.T) {
pool := device.NewPool(&config.Config{})
worker := &device.Worker{ID: "wwan0", Pool: pool}
pool.AttachWorkerWithSMSIdentityForTest(worker, device.SMSIdentity{ICCID: "8944100000000000002", IMSI: "234150000000002"})
gateway := NewPoolGateway(pool)
stale := DeviceSnapshot{DeviceID: "wwan0", ICCID: "8944100000000000001"}
for _, send := range []func(context.Context, DeviceSnapshot, string, string) error{gateway.SendVoWiFiSMS, gateway.SendBackendSMS} {
if err := send(context.Background(), stale, "85075", "INFO"); !errors.Is(err, device.ErrSMSSelectorMismatch) {
t.Fatalf("send with stale ICCID = %v", err)
}
}
}
+15 -9
View File
@@ -10,6 +10,7 @@ import (
"github.com/google/uuid"
"github.com/yibaiba/hideck/internal/carrierquery"
"github.com/yibaiba/hideck/internal/modem"
)
type Service struct {
@@ -40,19 +41,24 @@ func (s *Service) StartQuery(ctx context.Context, deviceID string) (Query, error
if err := s.repo.CreatePending(ctx, query); err != nil {
return Query{}, err
}
if err := s.send(ctx, snapshot, rule, query.ID); err != nil {
_ = s.repo.MarkFailed(context.Background(), query.ID, err, s.now())
failed, _, _ := s.repo.Get(context.Background(), query.ID)
return failed, err
sendErr := s.send(ctx, snapshot, rule, query.ID)
// Submission may finish after the caller's deadline. Read the persisted
// result without losing a late acknowledgement or an early reply.
readbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
stored, _, err := s.repo.Get(readbackCtx, query.ID)
if sendErr == nil || (err == nil && stored.State == StateCompleted) {
return stored, err
}
stored, _, err := s.repo.Get(ctx, query.ID)
return stored, err
_ = s.repo.MarkFailed(readbackCtx, query.ID, sendErr, s.now())
failed, _, _ := s.repo.Get(readbackCtx, query.ID)
return failed, sendErr
}
func (s *Service) send(ctx context.Context, snapshot DeviceSnapshot, rule carrierquery.Rule, queryID string) error {
switch rule.Transport {
case carrierquery.TransportSMS:
if err := s.sendSMS(ctx, snapshot, rule); err != nil {
if err := s.sendSMS(ctx, snapshot, rule); err != nil && !errors.Is(err, modem.ErrSMSSubmitUnknown) {
return err
}
return s.repo.MarkAwaitingReply(context.Background(), queryID, s.now())
@@ -65,9 +71,9 @@ func (s *Service) send(ctx context.Context, snapshot DeviceSnapshot, rule carrie
func (s *Service) sendSMS(ctx context.Context, snapshot DeviceSnapshot, rule carrierquery.Rule) error {
if snapshot.VoWiFiActive || snapshot.RouteSMSViaVoWiFi {
return s.gateway.SendVoWiFiSMS(ctx, snapshot.DeviceID, rule.Destination, rule.Payload)
return s.gateway.SendVoWiFiSMS(ctx, snapshot, rule.Destination, rule.Payload)
}
return s.gateway.SendBackendSMS(ctx, snapshot.DeviceID, rule.Destination, rule.Payload)
return s.gateway.SendBackendSMS(ctx, snapshot, rule.Destination, rule.Payload)
}
func (s *Service) sendUSSD(ctx context.Context, snapshot DeviceSnapshot, rule carrierquery.Rule, queryID string) error {
+37 -2
View File
@@ -10,23 +10,28 @@ import (
"github.com/yibaiba/hideck/internal/carrierquery"
appdb "github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/modem"
)
type fakeGateway struct {
snapshot DeviceSnapshot
sendErr error
onBackendSMS func()
wifiSMS, backendSMS int
wifiUSSD, backendUSSD int
ussdResponse USSDResponse
}
func (g *fakeGateway) Snapshot(string) (DeviceSnapshot, error) { return g.snapshot, nil }
func (g *fakeGateway) SendVoWiFiSMS(context.Context, string, string, string) error {
func (g *fakeGateway) SendVoWiFiSMS(context.Context, DeviceSnapshot, string, string) error {
g.wifiSMS++
return g.sendErr
}
func (g *fakeGateway) SendBackendSMS(context.Context, string, string, string) error {
func (g *fakeGateway) SendBackendSMS(context.Context, DeviceSnapshot, string, string) error {
g.backendSMS++
if g.onBackendSMS != nil {
g.onBackendSMS()
}
return g.sendErr
}
func (g *fakeGateway) SendVoWiFiUSSD(context.Context, string, string) (USSDResponse, error) {
@@ -117,6 +122,36 @@ func TestStartQueryFailureIsPersistedWithoutRetry(t *testing.T) {
}
}
func TestSMSQueryWithUnknownSubmissionCanReceiveReply(t *testing.T) {
now := time.Date(2026, 8, 11, 10, 0, 0, 0, time.UTC)
gateway := &fakeGateway{
snapshot: DeviceSnapshot{DeviceID: "wwan0", ICCID: "iccid-1", MCC: "234", MNC: "10"},
sendErr: modem.ErrSMSSubmitUnknown,
}
service, store := newTestService(t, gateway, smsTestRule(), now)
request, cancel := context.WithCancel(context.Background())
defer cancel()
gateway.onBackendSMS = cancel
query, err := service.StartQuery(request, "wwan0")
if err != nil || query.State != StateAwaitingReply {
t.Fatalf("StartQuery() = %+v, %v", query, err)
}
ctx := context.Background()
if _, err := service.StartQuery(ctx, "wwan0"); !errors.Is(err, ErrPendingQuery) || gateway.backendSMS != 1 {
t.Fatalf("pending query retried SMS: calls=%d err=%v", gateway.backendSMS, err)
}
matched, err := service.HandleInboundSMS(ctx, InboundSMS{
ICCID: "iccid-1", Sender: "giffgaff", Content: "credit 5.00", Time: now.Add(time.Second),
})
if err != nil || !matched {
t.Fatalf("HandleInboundSMS() = %t, %v", matched, err)
}
stored, _, err := store.Get(ctx, query.ID)
if err != nil || stored.State != StateCompleted || stored.Amount != "5.00" {
t.Fatalf("stored query = %+v, %v", stored, err)
}
}
func TestUSSDQueryUsesSelectedRouteAndPersistsRawResponse(t *testing.T) {
for _, test := range []struct {
name string
+2 -2
View File
@@ -91,8 +91,8 @@ type Completion struct {
type Gateway interface {
Snapshot(deviceID string) (DeviceSnapshot, error)
SendVoWiFiSMS(context.Context, string, string, string) error
SendBackendSMS(context.Context, string, string, string) error
SendVoWiFiSMS(context.Context, DeviceSnapshot, string, string) error
SendBackendSMS(context.Context, DeviceSnapshot, string, string) error
SendVoWiFiUSSD(context.Context, string, string) (USSDResponse, error)
SendBackendUSSD(context.Context, string, string) (USSDResponse, error)
}
+8 -1
View File
@@ -82,6 +82,9 @@ type PendingPhoneNumber struct {
func (PendingPhoneNumber) TableName() string { return "pending_phone_numbers" }
// SMS 短信表 (关联 IMSI)
// SMSStatusSubmitUnconfirmed marks an outbound attempt without complete confirmation.
const SMSStatusSubmitUnconfirmed = 4
type SMS struct {
ID uint `gorm:"primaryKey" json:"id"`
IMSI string `gorm:"column:imsi;index:idx_sms_imsi_peer_ts,priority:1;index:idx_sms_imsi_ts,priority:1;index:idx_sms_fragment_session,priority:1" json:"imsi"`
@@ -92,7 +95,7 @@ type SMS struct {
Recipient string `json:"recipient"`
Content string `json:"content"`
Type int `json:"type"` // 1: 接收, 2: 发送
Status int `json:"status"` // 0: 未读, 1: 已读, 2: 发送成功, 3: 发送失败
Status int `json:"status"` // 0: 未读, 1: 已读, 2: 提交成功, 3: 发送失败, 4: 提交未完全确认
Timestamp time.Time `gorm:"index:idx_sms_imsi_peer_ts,priority:3,sort:desc;index:idx_sms_ts,sort:desc;index:idx_sms_imsi_ts,priority:2,sort:desc" json:"timestamp"`
CreatedAt time.Time `json:"created_at"`
FragmentSessionKey string `gorm:"column:fragment_session_key;index:idx_sms_fragment_session,priority:2" json:"-"`
@@ -169,6 +172,7 @@ func Init(dbPath string) error {
&SMSDelivery{},
&SMSDeliveryPart{},
&SMSInboundFragment{},
&atSMSReceipt{},
&CommandExecution{},
&CommandEvent{},
&BalanceQuery{},
@@ -215,6 +219,9 @@ func Init(dbPath string) error {
if err := ensureSMSFragmentSessionUniqueIndex(DB); err != nil {
return err
}
if err := backfillATSMSReceipts(DB); err != nil {
return err
}
if err := MigrateCardPolicyCanonicalICCID(DB); err != nil {
return err
}
+36
View File
@@ -0,0 +1,36 @@
package db
import (
"errors"
"strings"
"gorm.io/gorm"
)
// atSMSReceipt keeps the receive session after its user-visible history is removed.
type atSMSReceipt struct {
ICCID string `gorm:"column:iccid;primaryKey"`
IMSI string `gorm:"column:imsi"`
SessionKey string `gorm:"column:session_key;primaryKey"`
}
func (atSMSReceipt) TableName() string { return "sms_at_receipt" }
func backfillATSMSReceipts(database *gorm.DB) error {
return database.Exec(`INSERT INTO sms_at_receipt (iccid, imsi, session_key)
SELECT iccid, imsi, fragment_session_key FROM sms
WHERE type = 1 AND incomplete = false AND fragment_session_key GLOB ?
ON CONFLICT (iccid, session_key) DO NOTHING`, ATSMSInboundPrefix+"*").Error
}
func HasATSMSReceipt(iccid, imsi, sessionKey string) (bool, error) {
if DB == nil {
return false, errors.New("database not initialized")
}
var row atSMSReceipt
err := DB.Where("iccid = ? AND imsi = ? AND session_key = ?", CanonicalICCID(iccid), strings.TrimSpace(imsi), sessionKey).Take(&row).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
return false, nil
}
return err == nil, err
}
+73
View File
@@ -0,0 +1,73 @@
package db
import (
"path/filepath"
"testing"
"time"
)
func TestATSMSReceiptsBackfillExistingHistory(t *testing.T) {
previousDB := DB
path := filepath.Join(t.TempDir(), "receipt.db")
if err := Init(path); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
closeSMSFragmentTestDB(t)
DB = previousDB
})
legacy := SMS{
ICCID: "8944100000000000088", IMSI: "234150000000088", Peer: "+10086",
Sender: "+10086", Content: "legacy", Timestamp: time.Now(), Type: 1,
FragmentSessionKey: ATSMSInboundPrefix + "legacy",
}
// Write directly to emulate a version that persisted no receipt.
if err := DB.Create(&legacy).Error; err != nil {
t.Fatal(err)
}
closeSMSFragmentTestDB(t)
if err := Init(path); err != nil {
t.Fatal(err)
}
if _, _, _, err := DeleteSMSByID(legacy.ID); err != nil {
t.Fatal(err)
}
input := ReceivedMultipartSMS{
ICCID: legacy.ICCID, IMSI: legacy.IMSI, Sender: legacy.Sender, Content: legacy.Content,
Timestamp: legacy.Timestamp, FragmentSessionKey: legacy.FragmentSessionKey,
}
for _, imsi := range []string{legacy.IMSI, "234150000000089"} {
input.IMSI = imsi
result, err := SaveReceivedMultipartSMS(input)
if err != nil || !result.Duplicate || result.Created {
t.Fatalf("backfilled duplicate for %s: %+v, %v", imsi, result, err)
}
}
if found, err := HasATSMSReceipt(input.ICCID, input.IMSI, input.FragmentSessionKey); err != nil || found {
t.Fatalf("different IMSI acquired deletion evidence: %v, %v", found, err)
}
}
func TestATSMSReceiptRollsBackWhenHistoryWriteFails(t *testing.T) {
openTestDB(t)
input := ReceivedMultipartSMS{
ICCID: "8944100000000000088", IMSI: "234150000000088", Sender: "+10086",
Timestamp: time.Now(), Content: "retry", FragmentSessionKey: ATSMSInboundPrefix + "write-failure",
}
if err := DB.Exec(`CREATE TRIGGER reject_at_sms BEFORE INSERT ON sms
BEGIN SELECT RAISE(ABORT, 'test SMS write failure'); END`).Error; err != nil {
t.Fatal(err)
}
if result, err := SaveReceivedMultipartSMS(input); err == nil || result.Created {
t.Fatalf("fault injection: %+v, %v", result, err)
}
if found, err := HasATSMSReceipt(input.ICCID, input.IMSI, input.FragmentSessionKey); err != nil || found {
t.Fatalf("failed history write left a receipt: %v, %v", found, err)
}
if err := DB.Exec("DROP TRIGGER reject_at_sms").Error; err != nil {
t.Fatal(err)
}
if result, err := SaveReceivedMultipartSMS(input); err != nil || !result.Created {
t.Fatalf("retry: %+v, %v", result, err)
}
}
+1
View File
@@ -14,6 +14,7 @@ const (
SMSDeliveryStatePartialAck = "partial_ack"
SMSDeliveryStateAcked = "acked"
SMSDeliveryStateFailed = "failed"
SMSDeliveryStateUnknown = "unknown"
)
const (
+20 -1
View File
@@ -6,6 +6,7 @@ import (
"time"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const (
@@ -69,6 +70,8 @@ func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSR
return ReceivedMultipartSMSResult{}, err
}
var result ReceivedMultipartSMSResult
recordATReceipt := !normalized.Incomplete && strings.HasPrefix(normalized.FragmentSessionKey, ATSMSInboundPrefix)
receipt := atSMSReceipt{ICCID: normalized.ICCID, IMSI: normalized.IMSI, SessionKey: normalized.FragmentSessionKey}
smsPublicationMu.Lock()
defer smsPublicationMu.Unlock()
err = DB.Transaction(func(tx *gorm.DB) error {
@@ -78,6 +81,16 @@ func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSR
normalized.ICCID, normalized.FragmentSessionKey,
).First(&existing).Error
if errors.Is(findErr, gorm.ErrRecordNotFound) {
if recordATReceipt {
insert := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&receipt)
if insert.Error != nil {
return insert.Error
}
if insert.RowsAffected == 0 {
result.Duplicate = true
return nil
}
}
created, createErr := createReceivedMultipartSMS(tx, normalized)
result = created
return createErr
@@ -87,7 +100,13 @@ func SaveReceivedMultipartSMS(input ReceivedMultipartSMS) (ReceivedMultipartSMSR
}
reconciled, reconcileErr := reconcileReceivedMultipartSMS(tx, existing, normalized)
result = reconciled
return reconcileErr
if reconcileErr != nil {
return reconcileErr
}
if recordATReceipt && existing.IMSI == normalized.IMSI {
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&receipt).Error
}
return nil
})
if err == nil && (result.Created || result.Reconciled) {
publishIncomingSMSByID(result.SMSID)
+23 -20
View File
@@ -8,6 +8,8 @@ import (
"gorm.io/gorm"
)
const ATSMSInboundPrefix = "at:"
var ErrSMSInboundFragmentCollision = errors.New("SMS inbound fragment collision")
type SMSInboundFragmentScope struct {
@@ -18,26 +20,27 @@ type SMSInboundFragmentScope struct {
}
type SMSInboundFragment struct {
ID uint `gorm:"primaryKey"`
DeviceID string `gorm:"column:device_id;index"`
ICCID string `gorm:"column:iccid"`
IMSI string `gorm:"column:imsi;index"`
SessionKey string `gorm:"column:session_key"`
Sequence int `gorm:"column:sequence"`
Reference int `gorm:"column:reference"`
ReferenceBits int `gorm:"column:reference_bits"`
Total int `gorm:"column:total"`
Content string `gorm:"column:content"`
ArrivedAt time.Time `gorm:"column:arrived_at;index"`
RPMR int `gorm:"column:rp_mr"`
CallID string `gorm:"column:call_id"`
ToURI string `gorm:"column:to_uri"`
ServiceCenter string `gorm:"column:service_center"`
AckSent bool `gorm:"column:ack_sent"`
AckSentAt time.Time `gorm:"column:ack_sent_at"`
DegradedAt time.Time `gorm:"column:degraded_at;index"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
ID uint `gorm:"primaryKey"`
DeviceID string `gorm:"column:device_id;index"`
ICCID string `gorm:"column:iccid"`
IMSI string `gorm:"column:imsi;index"`
SessionKey string `gorm:"column:session_key"`
Sequence int `gorm:"column:sequence"`
Reference int `gorm:"column:reference"`
ReferenceBits int `gorm:"column:reference_bits"`
Total int `gorm:"column:total"`
Content string `gorm:"column:content"`
PDUFingerprint string `gorm:"column:pdu_fingerprint"`
ArrivedAt time.Time `gorm:"column:arrived_at;index"`
RPMR int `gorm:"column:rp_mr"`
CallID string `gorm:"column:call_id"`
ToURI string `gorm:"column:to_uri"`
ServiceCenter string `gorm:"column:service_center"`
AckSent bool `gorm:"column:ack_sent"`
AckSentAt time.Time `gorm:"column:ack_sent_at"`
DegradedAt time.Time `gorm:"column:degraded_at;index"`
CreatedAt time.Time `gorm:"column:created_at"`
UpdatedAt time.Time `gorm:"column:updated_at"`
}
func (SMSInboundFragment) TableName() string { return "sms_inbound_fragment" }
+37
View File
@@ -0,0 +1,37 @@
package device
import "github.com/yibaiba/hideck/internal/modem"
type atDeviceRules struct {
verifyLiveIMEI bool
strictSIMIdentity bool
simStatusSource string
model string
storedSMSInbox bool
nativeVoiceUnavailableReason string
cellularIMSUnavailableReason string
}
func atDeviceRulesFor(profile modem.ATProfile) atDeviceRules {
switch profile {
case modem.ATProfileML307C:
return atDeviceRules{
verifyLiveIMEI: true,
strictSIMIdentity: true,
simStatusSource: "ml307c_sim_status",
model: "ML307C",
storedSMSInbox: true,
nativeVoiceUnavailableReason: "ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨",
cellularIMSUnavailableReason: "ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS",
}
default:
return atDeviceRules{model: "EC20"}
}
}
func (w *Worker) atDeviceRules() atDeviceRules {
if w == nil || w.Modem == nil {
return atDeviceRulesFor(modem.ATProfileDefault)
}
return atDeviceRulesFor(w.Modem.ATProfile())
}
+20
View File
@@ -11,6 +11,7 @@ import (
// probeIMEICachedFn 允许测试替换底层 IMEI 探测实现。
var probeIMEICachedFn = modem.ProbeIMEICached
var probeIMEICachedContextFn = modem.ProbeIMEICachedContext
var probeProfileIMEIFn = modem.ATProfile.ProbeIMEI
// orderedATPortCandidates 按“单设备定界”规则生成探测顺序。
// 只允许在当前设备自己的 ATPorts 集合内排序和前置候选口;
@@ -94,6 +95,9 @@ func ResolveQMIDeviceATPort(dev QMIDevice, timeout time.Duration) (QMIDevice, st
// ResolveCompatibleModemATPort 为兼容发现结果解析真实可用的主 AT 口。
// 行为与 QMI 设备一致,同样只允许在该设备自己的 ATPorts 范围内探测。
func ResolveCompatibleModemATPort(dev CompatibleModem, timeout time.Duration) (CompatibleModem, string) {
if atDeviceRulesFor(dev.ATProfile()).verifyLiveIMEI {
return ResolveCompatibleModemATPortContext(context.Background(), dev, timeout)
}
atPort, imei := ResolveATPortForDevice(dev.ATPort, dev.ATPorts, timeout)
dev.ATPort = atPort
if imei != "" {
@@ -108,6 +112,22 @@ func ResolveCompatibleModemATPortContext(
dev CompatibleModem,
timeout time.Duration,
) (CompatibleModem, string) {
profile := dev.ATProfile()
if atDeviceRulesFor(profile).verifyLiveIMEI {
preferred := dev.ATPort
dev.ATPort, dev.IMEI = "", ""
for _, port := range orderedATPortCandidates(preferred, dev.ATPorts) {
imei, err := probeProfileIMEIFn(profile, ctx, port, timeout)
if err == nil && imei != "" {
dev.ATPort, dev.IMEI = port, imei
return dev, imei
}
if ctx.Err() != nil {
break
}
}
return dev, ""
}
atPort, imei := ResolveATPortForDeviceContext(ctx, dev.ATPort, dev.ATPorts, timeout)
dev.ATPort = atPort
if imei != "" {
+2 -2
View File
@@ -9,11 +9,11 @@ import (
"github.com/yibaiba/hideck/internal/modem"
)
func newWorkerModem(cfg config.DeviceConfig, backendMode string) (*modem.Manager, error) {
func newWorkerModem(cfg config.DeviceConfig, backendMode string, profile modem.ATProfile) (*modem.Manager, error) {
if backend.NormalizeBackendMode(backendMode) == backend.BackendMBIM {
return modem.NewSMSAuxiliary(cfg)
}
return modem.New(cfg)
return modem.NewWithATProfile(cfg, profile)
}
func newWorkerBackendStrict(deviceID, backendMode, controlDevice string, m *modem.Manager, source backend.QMISource, mbimSource backend.MBIMSource) (backend.DeviceBackend, error) {
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/yibaiba/hideck/internal/config"
)
const DefaultFreeDeviceLimit = 5
const DefaultFreeDeviceLimit = 10
func FreeDeviceLimitReached(count int) bool {
return count >= DefaultFreeDeviceLimit
+32 -5
View File
@@ -10,6 +10,7 @@ import (
"time"
"github.com/iniwex5/quectel-qmi-go/pkg/qmi"
"github.com/yibaiba/hideck/internal/modem"
qmicore "github.com/yibaiba/hideck/internal/qmi"
"github.com/yibaiba/hideck/pkg/logger"
)
@@ -31,6 +32,17 @@ type CompatibleModem struct {
NetworkCapable bool
}
func (m CompatibleModem) ATProfile() modem.ATProfile {
return (usbDeviceIdentity{vendorID: m.VendorID, productID: m.ProductID}).atProfile()
}
func (id usbDeviceIdentity) atProfile() modem.ATProfile {
if layout, ok := id.atOnlyLayout(); ok {
return layout.profile
}
return modem.ATProfileDefault
}
var discoverFallbackModemsFn = discoverFallbackModems
// DiscoveryKey 用于去重 (USBPath + ATPort)。
@@ -144,10 +156,18 @@ func compatibleModemFromQMIStaticDevice(d QMIDevice) CompatibleModem {
func discoverFallbackOne(usbPath string) (CompatibleModem, bool) {
scanUSBPath := resolveUSBPathForScan(usbPath)
vid := readHexFile16(filepath.Join(scanUSBPath, "idVendor"))
pid := readHexFile16(filepath.Join(scanUSBPath, "idProduct"))
identity := usbDeviceIdentity{vendorID: vid, productID: pid}
identity := readUSBDeviceIdentity(scanUSBPath)
vid, pid := identity.vendorID, identity.productID
if _, ok := identity.atOnlyLayout(); ok {
ports, port, _ := discoverATPortsForUSBDevice(scanUSBPath, identity, "at")
if port == "" {
return CompatibleModem{}, false
}
return CompatibleModem{
USBPath: usbPath, VendorID: vid, ProductID: pid,
ATPorts: ports, ATPort: port, Mode: "at", TransportType: "at",
}, true
}
if capability, ok := detectQMIUSBCapability(scanUSBPath); ok {
mode := classifyMode(capability.ControlPath, capability.DriverName)
atPorts, atPort, imei := discoverATPortsForUSBDevice(scanUSBPath, identity, mode)
@@ -187,7 +207,7 @@ func discoverFallbackOne(usbPath string) (CompatibleModem, bool) {
}, true
}
if vid != 0x2c7c && vid != 0x05c6 {
if vid != quectelVendorID && vid != qualcommVendorID {
return CompatibleModem{}, false
}
@@ -281,6 +301,13 @@ func resolveUSBPathForScan(usbPath string) string {
return resolved
}
func readUSBDeviceIdentity(usbPath string) usbDeviceIdentity {
return usbDeviceIdentity{
vendorID: readHexFile16(filepath.Join(usbPath, "idVendor")),
productID: readHexFile16(filepath.Join(usbPath, "idProduct")),
}
}
func readHexFile16(path string) uint16 {
b, err := os.ReadFile(path)
if err != nil {
+70 -7
View File
@@ -185,17 +185,24 @@ type WorkerDiscoveryInfo struct {
USBNetMode *int
}
type workerATIdentityReader struct {
worker *Worker
query func() (string, error)
}
type WorkerDiscoveryIndex struct {
byControl map[string]WorkerDiscoveryInfo
byUSB map[string]WorkerDiscoveryInfo
byIface map[string]WorkerDiscoveryInfo
byControl map[string]WorkerDiscoveryInfo
byUSB map[string]WorkerDiscoveryInfo
byIface map[string]WorkerDiscoveryInfo
atIdentityByPort map[string]workerATIdentityReader
}
func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) WorkerDiscoveryIndex {
idx := WorkerDiscoveryIndex{
byControl: map[string]WorkerDiscoveryInfo{},
byUSB: map[string]WorkerDiscoveryInfo{},
byIface: map[string]WorkerDiscoveryInfo{},
byControl: map[string]WorkerDiscoveryInfo{},
byUSB: map[string]WorkerDiscoveryInfo{},
byIface: map[string]WorkerDiscoveryInfo{},
atIdentityByPort: map[string]workerATIdentityReader{},
}
for _, worker := range workers {
@@ -211,7 +218,13 @@ func BuildWorkerDiscoveryIndex(workers []*Worker, includeRuntimeStatus bool) Wor
ATPort: strings.TrimSpace(cfg.ATPort),
IMEI: strings.TrimSpace(cfg.ModemIMEI),
}
if includeRuntimeStatus {
if worker.Modem != nil && worker.Modem.OwnsATRuntime() && worker.ResolvedATPort() != "" {
port := worker.ResolvedATPort()
owner := workerATIdentityReader{worker: worker, query: worker.Modem.QueryIMEI}
idx.atIdentityByPort[port] = owner
idx.atIdentityByPort[resolveUSBPathForScan(port)] = owner
}
if includeRuntimeStatus && !worker.atDeviceRules().verifyLiveIMEI {
status := worker.GetDeviceStatus()
if imei := strings.TrimSpace(status.IMEI); imei != "" {
info.IMEI = imei
@@ -261,6 +274,56 @@ func (idx WorkerDiscoveryIndex) Lookup(controlPath, usbPath, iface string) (Work
return WorkerDiscoveryInfo{}, false
}
// atScanObservation retains a static attachment even if its IMEI could not
// be verified. Only the separate verified modem result can establish identity.
type atScanObservation struct {
usbPath string
atPorts []string
unreadableOwner *Worker
}
// ResolveLiveATIdentity handles hardware that requires a live AT IMEI.
// The caller retains its cache and transport fallback for other hardware.
func (idx WorkerDiscoveryIndex) ResolveLiveATIdentity(dev CompatibleModem, probe func(CompatibleModem) (CompatibleModem, string)) (CompatibleModem, bool) {
resolved, observation := idx.observeLiveATIdentity(dev, probe)
return resolved, observation != nil
}
func (idx WorkerDiscoveryIndex) observeLiveATIdentity(dev CompatibleModem, probe func(CompatibleModem) (CompatibleModem, string)) (CompatibleModem, *atScanObservation) {
if !atDeviceRulesFor(dev.ATProfile()).verifyLiveIMEI {
return dev, nil
}
observation := &atScanObservation{usbPath: dev.USBPath, atPorts: dev.ATPorts}
if port, owner := idx.ownedATPort(dev.ATPorts); port != "" {
dev.ATPort, dev.IMEI = port, ""
if imei, err := owner.query(); err == nil {
dev.IMEI = imei
}
if config.NormalizeIMEI(dev.IMEI) == "" {
// Do not open a second reader while the worker owns the port.
observation.unreadableOwner = owner.worker
}
return dev, observation
}
resolved, imei := probe(dev)
resolved.IMEI = imei
return resolved, observation
}
func (idx WorkerDiscoveryIndex) ownedATPort(ports []string) (string, workerATIdentityReader) {
for _, port := range ports {
if owner := idx.atIdentityByPort[port]; owner.query != nil {
return port, owner
}
if canonical := resolveUSBPathForScan(port); canonical != port {
if owner := idx.atIdentityByPort[canonical]; owner.query != nil {
return port, owner
}
}
}
return "", workerATIdentityReader{}
}
type ConfiguredDeviceIndex struct {
byControl map[string]string
byUSB map[string]string
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"github.com/yibaiba/hideck/internal/backend"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/modem"
)
func TestRequiresMBIMCore(t *testing.T) {
@@ -48,7 +49,7 @@ func TestNewWorkerModemUsesSMSAuxiliaryForMBIM(t *testing.T) {
ID: "dev-mbim",
DeviceBackend: backend.BackendMBIM,
ATPort: "/dev/ttyUSB2",
}, backend.BackendMBIM)
}, backend.BackendMBIM, modem.ATProfileDefault)
if err != nil {
t.Fatalf("newWorkerModem() error = %v", err)
}
+418
View File
@@ -0,0 +1,418 @@
package device
import (
"context"
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/yibaiba/hideck/internal/backend"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/modem"
)
func TestConfiguredATPortSelectsDialectWithoutIMEI(t *testing.T) {
port := filepath.Join(t.TempDir(), "ttyUSB8")
if err := os.WriteFile(port, nil, 0o600); err != nil {
t.Fatal(err)
}
alias := filepath.Join(filepath.Dir(port), "by-id")
if err := os.Symlink(port, alias); err != nil {
t.Fatal(err)
}
realPort, err := filepath.EvalSymlinks(port)
if err != nil {
t.Fatal(err)
}
original := discoverFallbackModemsFn
t.Cleanup(func() { discoverFallbackModemsFn = original })
discoverFallbackModemsFn = func() ([]CompatibleModem, error) {
return []CompatibleModem{{
VendorID: cmIoTVendorID, ProductID: ml307cProductID, ATPorts: []string{realPort},
}}, nil
}
configured, ok := configuredATDevice(config.DeviceConfig{ManagePort: alias})
if !ok || configured.ATProfile() != modem.ATProfileML307C || configured.ATPort != realPort {
t.Fatalf("aliased legacy port = %+v, %t", configured, ok)
}
if got, ok := configuredATDevice(config.DeviceConfig{ATPort: "/dev/ttyUSB2", ManagePort: alias}); ok {
t.Fatalf("unmatched AT port selected %+v", got)
}
// Simulate the same modem already managed over its other AT interface.
const managedPort = "/dev/ttyUSB9"
devices := discoverFallbackModemsFn
discoverFallbackModemsFn = func() ([]CompatibleModem, error) {
found, _ := devices()
found[0].ATPorts = append(found[0].ATPorts, managedPort)
return found, nil
}
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
managed := config.DeviceConfig{ID: "active", DeviceBackend: "at", ATPort: managedPort}
m, err := modem.NewWithATProfile(managed, modem.ATProfileML307C)
if err != nil {
t.Fatal(err)
}
p.AttachWorkerForTest(&Worker{ID: managed.ID, Pool: p, Config: managed, Modem: m})
_, err = p.AddWorkerFromConfig(config.DeviceConfig{ID: "duplicate", DeviceBackend: "at", ManagePort: alias})
if err == nil || !strings.Contains(err.Error(), "已由现有设备接管") {
t.Fatalf("startup over a second AT interface returned %v", err)
}
}
func TestML307CDiscoveryAndRebind(t *testing.T) {
usbPath := filepath.Join(t.TempDir(), "1-1")
for _, node := range []string{"1-1:1.2/ttyUSB8", "1-1:1.3/ttyUSB2", "1-1:1.4/ttyUSB3"} {
if err := os.MkdirAll(filepath.Join(usbPath, node), 0o700); err != nil {
t.Fatal(err)
}
}
for name, value := range map[string]string{"idVendor": "2ecc\n", "idProduct": "3012\n"} {
if err := os.WriteFile(filepath.Join(usbPath, name), []byte(value), 0o600); err != nil {
t.Fatal(err)
}
}
dev, ok := discoverFallbackOne(usbPath)
if !ok || dev.Mode != "at" || dev.NetworkCapable || dev.ControlPath != "" || dev.ATProfile() != modem.ATProfileML307C {
t.Fatalf("discovery = %+v, %v", dev, ok)
}
if dev.ATPort != "/dev/ttyUSB8" || !slices.Equal(dev.ATPorts, []string{"/dev/ttyUSB8", "/dev/ttyUSB2"}) {
t.Fatalf("ATPort=%q ATPorts=%v", dev.ATPort, dev.ATPorts)
}
const imei = "490154203237518"
owned := WorkerDiscoveryIndex{atIdentityByPort: map[string]workerATIdentityReader{
"/dev/ttyUSB8": {query: func() (string, error) { return imei, nil }},
}}
unexpectedProbe := func(raw CompatibleModem) (CompatibleModem, string) {
t.Fatal("unexpected independent AT probe")
return raw, ""
}
active, ok := owned.ResolveLiveATIdentity(dev, unexpectedProbe)
if !ok || active.IMEI != imei {
t.Fatalf("owned IMEI = %q, %v", active.IMEI, ok)
}
owned.atIdentityByPort["/dev/ttyUSB8"] = workerATIdentityReader{
query: func() (string, error) { return "", errors.New("old tty closed") },
}
dev.IMEI = imei
active, ok = owned.ResolveLiveATIdentity(dev, unexpectedProbe)
if !ok || active.IMEI != "" {
t.Fatalf("stale owned tty = %q, %v", active.IMEI, ok)
}
ordinary := dev
ordinary.VendorID, ordinary.ProductID = 0, 0
if _, handled := owned.ResolveLiveATIdentity(ordinary, unexpectedProbe); handled {
t.Fatal("ordinary AT must retain the caller's existing fallback")
}
if active, handled := (WorkerDiscoveryIndex{}).ResolveLiveATIdentity(dev, func(raw CompatibleModem) (CompatibleModem, string) {
return raw, ""
}); !handled || active.IMEI != "" {
t.Fatalf("unowned failed read retained a cached IMEI: %q, %v", active.IMEI, handled)
}
origProbe := probeProfileIMEIFn
t.Cleanup(func() { probeProfileIMEIFn = origProbe })
var probed []string
probeProfileIMEIFn = func(profile modem.ATProfile, _ context.Context, port string, _ time.Duration) (string, error) {
if profile != modem.ATProfileML307C {
t.Fatalf("IMEI probe profile = %v", profile)
}
probed = append(probed, port)
if port == "/dev/ttyUSB2" {
return imei, nil
}
return "", errors.New("no IMEI")
}
rebound, readIMEI := ResolveCompatibleModemATPort(dev, time.Second)
if readIMEI != imei || !slices.Equal(probed, dev.ATPorts) {
t.Fatalf("rebind IMEI = %q, ports = %v", readIMEI, probed)
}
cfg := rescanWorkerConfig(config.DeviceConfig{ID: "c", DeviceBackend: "at", ModemIMEI: imei, ATPort: "/dev/ttyUSB0"}, rebound)
if cfg.USBPath != usbPath || cfg.ATPort != "/dev/ttyUSB2" || cfg.ManagePort != cfg.ATPort {
t.Fatalf("rebind USBPath=%q ATPort=%q ManagePort=%q", cfg.USBPath, cfg.ATPort, cfg.ManagePort)
}
if err := os.RemoveAll(filepath.Join(usbPath, "1-1:1.2")); err != nil {
t.Fatal(err)
}
if err := os.RemoveAll(filepath.Join(usbPath, "1-1:1.3")); err != nil {
t.Fatal(err)
}
if _, ok := discoverFallbackOne(usbPath); ok {
t.Fatal("Diag alone must not be discovered as an ML307C AT port")
}
}
func TestML307CRescanPreservesAndRebindsDiscoveredDevice(t *testing.T) {
const imei = "490154203237518"
const oldPort = "/dev/ttyUSB8"
cfg := config.DeviceConfig{
ID: "ml307c", DeviceBackend: backend.BackendAT, ESIMTransport: config.ESIMTransportAT,
ModemIMEI: imei, USBPath: "/sys/bus/usb/devices/1-1", ATPort: oldPort, ManagePort: oldPort,
}
original := CompatibleModem{
USBPath: cfg.USBPath, VendorID: 0x2ecc, ProductID: 0x3012,
ATPort: oldPort, ATPorts: []string{oldPort}, IMEI: imei, Mode: "at", TransportType: backend.BackendAT,
}
other := CompatibleModem{USBPath: "/sys/bus/usb/devices/1-2", ATPort: "/dev/ttyUSB4", Mode: "at"}
candidates := []CompatibleModem{original, other}
prevQMI, prevFallback, prevEnrich := discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn
t.Cleanup(func() {
discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn = prevQMI, prevFallback, prevEnrich
})
discoverQMIDevicesFn = func() ([]QMIDevice, error) { return nil, nil }
discoverFallbackModemsFn = func() ([]CompatibleModem, error) { return candidates, nil }
resolveDiscoveredCompatibleModemFn = func(dev CompatibleModem, _ time.Duration) (CompatibleModem, string) {
if dev.ATProfile() != modem.ATProfileML307C {
t.Fatalf("explicit port configuration triggered an unrelated AT probe: %+v", dev)
}
return dev, dev.IMEI
}
p := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}})
t.Cleanup(p.cancel)
// Use the existing fake health backend so the rescan needs no real AT owner.
worker := &Worker{ID: cfg.ID, Config: cfg, Backend: &workerStatusBackendStub{mode: backend.BackendQMI}}
p.workers[cfg.ID] = worker
if err := p.RescanAndReconnect(); err != nil || p.GetWorker(cfg.ID) != worker {
t.Fatalf("rescan retired an unchanged, healthy ML307C: %v", err)
}
// The offline-worker recovery must select by IMEI even when another
// ML307C gets the previous USB location and tty number.
delete(p.workers, cfg.ID)
reused := original
reused.IMEI = "490154203237526"
moved := original
moved.USBPath = "/sys/bus/usb/devices/2-1"
moved.ATPort = "/dev/ttyUSB13"
moved.ATPorts = []string{moved.ATPort}
candidates = []CompatibleModem{reused, moved, other}
managed := p.managedDevices()
hardware, _ := p.collectRescanHardware(nil, BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false), configuredDevicesATDiscovery(managed))
resolved := ResolveDeviceIdentities(hardware, managed)
if len(resolved.Matched) != 1 || len(resolved.Offline) != 0 {
t.Fatalf("rescan did not rediscover an offline ML307C: %+v", resolved)
}
pair := resolved.Matched[0]
rebound := rescanWorkerConfig(pair.Config, pair.Hardware)
if rebound.ModemIMEI != imei || rebound.USBPath != moved.USBPath || rebound.ATPort != moved.ATPort || rebound.ManagePort != moved.ATPort {
t.Fatalf("rescan selected the wrong attachment: %+v", rebound)
}
}
func TestML307CBootstrapRejectsUnreadableIdentityOnConfiguredPort(t *testing.T) {
dir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
port := filepath.Join(dir, "ttyUSB8")
if err := os.WriteFile(port, nil, 0o600); err != nil {
t.Fatal(err)
}
alias := filepath.Join(dir, "by-id")
if err := os.Symlink(port, alias); err != nil {
t.Fatal(err)
}
cfg := config.DeviceConfig{
ID: "ml307c", DeviceBackend: backend.BackendAT, ESIMTransport: config.ESIMTransportAT,
ModemIMEI: "490154203237518", ATPort: alias, ManagePort: alias,
}
prevFallback, prevEnrich := discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn
t.Cleanup(func() { discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn = prevFallback, prevEnrich })
discoverFallbackModemsFn = func() ([]CompatibleModem, error) {
return []CompatibleModem{
{USBPath: "/sys/bus/usb/devices/1-1", VendorID: 0x2ecc, ProductID: 0x3012, ATPort: port, ATPorts: []string{port}, Mode: "at"},
{USBPath: "/sys/bus/usb/devices/1-2", ATPort: "/dev/ttyUSB4", Mode: "at"},
}, nil
}
probes := 0
resolveDiscoveredCompatibleModemFn = func(dev CompatibleModem, _ time.Duration) (CompatibleModem, string) {
if dev.ATProfile() != modem.ATProfileML307C {
t.Fatalf("bootstrap probed an unrelated AT device: %+v", dev)
}
probes++
return dev, ""
}
prevStart := startWorkerModem
t.Cleanup(func() { startWorkerModem = prevStart })
startWorkerModem = func(m *modem.Manager, expected string) error {
if m.ATProfile() != modem.ATProfileML307C || m.ATPort() != port || expected != cfg.ModemIMEI {
t.Fatalf("unreadable discovered port lost its startup identity gate: port=%q profile=%v expected=%q", m.ATPort(), m.ATProfile(), expected)
}
return errors.New("无法验证")
}
p := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}})
t.Cleanup(p.cancel)
worker, err := p.AddWorkerFromConfig(cfg)
if worker != nil || err == nil || !strings.Contains(err.Error(), "无法验证") || probes != 1 {
t.Fatalf("unverified ML307C port did not block startup: worker=%v err=%v probes=%d", worker, err, probes)
}
}
func TestML307CRescanKeepsHealthyOwnerWhenIMEIUnavailable(t *testing.T) {
const port = "/dev/ttyUSB8"
const usbPath = "/sys/bus/usb/devices/1-1"
cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: backend.BackendAT, ModemIMEI: "490154203237518"}
p := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}})
t.Cleanup(p.cancel)
workerCfg := cfg
workerCfg.USBPath = usbPath
workerCfg.ATPort = port
m, err := modem.NewWithATProfile(workerCfg, modem.ATProfileML307C)
if err != nil {
t.Fatal(err)
}
// The unopened manager rejects the identity query; the health stub keeps
// the failure isolated to this single command for the test.
worker := &Worker{ID: cfg.ID, Config: workerCfg, Modem: m,
Backend: &workerStatusBackendStub{mode: backend.BackendQMI}, stop: make(chan struct{})}
p.workers[cfg.ID] = worker
prevQMI, prevFallback, prevEnrich := discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn
t.Cleanup(func() {
discoverQMIDevicesFn, discoverFallbackModemsFn, resolveDiscoveredCompatibleModemFn = prevQMI, prevFallback, prevEnrich
})
discoverQMIDevicesFn = func() ([]QMIDevice, error) { return nil, nil }
discoverFallbackModemsFn = func() ([]CompatibleModem, error) {
return []CompatibleModem{{
USBPath: usbPath, VendorID: 0x2ecc, ProductID: 0x3012,
ATPort: port, ATPorts: []string{port}, Mode: "at",
}}, nil
}
resolveDiscoveredCompatibleModemFn = func(dev CompatibleModem, _ time.Duration) (CompatibleModem, string) {
t.Fatalf("rescan attempted an independent identity probe on the owned AT port: %+v", dev)
return dev, ""
}
if err := p.RescanAndReconnect(); err != nil || p.GetWorker(cfg.ID) != worker {
t.Fatalf("rescan retired the healthy owner after its identity query failed: %v", err)
}
}
func TestBootstrapExplicitATIMEI(t *testing.T) {
const expectedIMEI = "490154203237518"
dir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
port := filepath.Join(dir, "ttyUSB8")
if err := os.WriteFile(port, nil, 0o600); err != nil {
t.Fatal(err)
}
alias := filepath.Join(dir, "by-id")
if err := os.Symlink(port, alias); err != nil {
t.Fatal(err)
}
prevFallback, prevLive, prevStart := discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem
t.Cleanup(func() {
discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem = prevFallback, prevLive, prevStart
})
discoverFallbackModemsFn = func() ([]CompatibleModem, error) {
// The original ML307C is gone. An ordinary modem now has the same tty and USB path.
return []CompatibleModem{{
USBPath: dir, VendorID: 0x2c7c, ProductID: 0x0125,
Mode: "at", ATPort: port, ATPorts: []string{port},
}}, nil
}
probeProfileIMEIFn = func(modem.ATProfile, context.Context, string, time.Duration) (string, error) {
t.Fatal("explicit AT fallback opened a serial handle before manager startup")
return "", nil
}
for _, tc := range []struct {
name, expected, wantError string
owned bool
}{
{name: "same tty different vendor", expected: expectedIMEI, wantError: "实时 IMEI 与配置不匹配"},
{name: "legacy configuration", wantError: "打开串口"},
{name: "owned tty alias", expected: expectedIMEI, wantError: "已由现有设备接管", owned: true},
} {
t.Run(tc.name, func(t *testing.T) {
startWorkerModem = func(m *modem.Manager, expected string) error {
if tc.owned || m.ATProfile() != modem.ATProfileDefault || m.ATPort() != alias || expected != tc.expected {
t.Fatalf("manager port=%q profile=%v expected=%q", m.ATPort(), m.ATProfile(), expected)
}
return errors.New(tc.wantError)
}
cfg := config.DeviceConfig{ID: "target", DeviceBackend: backend.BackendAT, ModemIMEI: tc.expected, USBPath: dir, ManagePort: alias}
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
if tc.owned {
existing := config.DeviceConfig{ID: "active", DeviceBackend: backend.BackendAT, ATPort: alias}
m, err := modem.New(existing)
if err != nil {
t.Fatal(err)
}
p.AttachWorkerForTest(&Worker{ID: existing.ID, Pool: p, Config: existing, Modem: m})
}
worker, err := p.AddWorkerFromConfig(cfg)
if worker != nil || err == nil || !strings.Contains(err.Error(), tc.wantError) || p.GetWorker(cfg.ID) != nil {
t.Fatalf("worker=%v err=%v, want %q", worker, err, tc.wantError)
}
})
}
}
func TestBootstrapDiscoveryProbesOnceBeforeOpen(t *testing.T) {
const imei = "490154203237518"
port := filepath.Join(t.TempDir(), "ttyUSB8")
if err := os.WriteFile(port, nil, 0o600); err != nil {
t.Fatal(err)
}
cfg := config.DeviceConfig{ID: "ml307c", DeviceBackend: backend.BackendAT, ModemIMEI: imei}
prevFallback, prevLive, prevStart := discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem
t.Cleanup(func() {
discoverFallbackModemsFn, probeProfileIMEIFn, startWorkerModem = prevFallback, prevLive, prevStart
})
discoverFallbackModemsFn = func() ([]CompatibleModem, error) {
return []CompatibleModem{{
USBPath: filepath.Dir(port), VendorID: cmIoTVendorID, ProductID: ml307cProductID,
Mode: "at", ATPort: port, ATPorts: []string{port},
}}, nil
}
probes := 0
probeProfileIMEIFn = func(profile modem.ATProfile, _ context.Context, path string, _ time.Duration) (string, error) {
probes++
if profile != modem.ATProfileML307C || path != port {
t.Fatalf("probe profile = %v, path = %q", profile, path)
}
return imei, nil
}
startWorkerModem = func(m *modem.Manager, expected string) error {
if m.ATPort() != port || m.ATProfile() != modem.ATProfileML307C || expected != imei {
t.Fatalf("strict discovery lost its startup identity gate: port=%q profile=%v expected=%q", m.ATPort(), m.ATProfile(), expected)
}
return errors.New("实时 IMEI 与配置不匹配")
}
for _, tc := range []struct{ name, path string }{
{name: "explicit path", path: port},
{name: "IMEI only"},
} {
t.Run(tc.name, func(t *testing.T) {
cfg.ATPort = tc.path
probes = 0
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
worker, err := p.AddWorkerFromConfig(cfg)
if worker != nil || err == nil || !strings.Contains(err.Error(), "实时 IMEI 与配置不匹配") || probes != 1 {
t.Fatalf("worker=%v err=%v probes=%d, want startup to reach identity gate after one discovery probe", worker, err, probes)
}
})
}
}
+4 -1
View File
@@ -93,10 +93,13 @@ func (p *Pool) stopNativeVoLTEForModemVoice(id string) error {
// This constructor is the infrastructure boundary. Optional tools and bundles
// are accessed only after the user explicitly selects modem_voice.
func (p *Pool) prepareModemVoice(ctx context.Context, id string) (*host.Resources, error) {
w := p.GetWorker(id)
if err := w.CheckPhoneModeSupported(PhoneModeModemVoice); err != nil {
return nil, err
}
if runtime.GOOS != "linux" {
return nil, errors.New("模组直拨音频目前仅支持 Linux")
}
w := p.GetWorker(id)
if w == nil || w.CurrentICCID() == "" {
return nil, errors.New("模组直拨需要已识别的 SIM 卡")
}
+2 -6
View File
@@ -15,9 +15,7 @@ func TestModemVoicePolicyKeepsExplicitModeAndDoesNotForceData(t *testing.T) {
w := &Worker{ID: "test"}
w.state.Identity.IMSI = imsi
pol := cardpolicy.Policy{VoWiFiEnabled: true, PhoneMode: PhoneModeModemVoice, DataStrategy: "always"}
if err := applyPolicyToWorker(w, pol); err != nil {
t.Fatal(err)
}
applyTestCardPolicy(t, w, pol)
if w.Config.PhoneMode != PhoneModeModemVoice || w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() {
t.Fatalf("unexpected projection: %+v", w.Config)
}
@@ -28,9 +26,7 @@ func TestModemVoicePolicyKeepsExplicitModeAndDoesNotForceData(t *testing.T) {
func TestModemVoiceCannotOverrideLebaraRadioLock(t *testing.T) {
w := &Worker{ID: "test"}
w.state.Identity.IMSI = "234870000000001"
if err := applyPolicyToWorker(w, cardpolicy.Policy{VoWiFiEnabled: true, PhoneMode: PhoneModeModemVoice}); err != nil {
t.Fatal(err)
}
applyTestCardPolicy(t, w, cardpolicy.Policy{VoWiFiEnabled: true, PhoneMode: PhoneModeModemVoice})
if !w.Config.AirplaneEnabled || w.Config.NetworkEnabled || !w.cellularRadioIsSuppressed() || w.Config.PhoneMode != PhoneModeWiFi {
t.Fatalf("radio lock bypassed: %+v", w.Config)
}
+19 -8
View File
@@ -27,7 +27,7 @@ func (p *Pool) AuthorizeOutboundCall(ctx context.Context, id, number string) err
if !outboundNumber.MatchString(strings.TrimSpace(number)) {
return errors.New("无效的外呼号码")
}
return p.consumeOutbound(ctx, p.GetWorker(id), outbound.Request{Kind: outbound.Call, Units: 1})
return p.consumeOutbound(ctx, p.GetWorker(id), outbound.Request{Kind: outbound.Call, Units: 1}, nil)
}
// DialAuthorizedCellularCall keeps the SIM owner stable from quota charging
@@ -36,6 +36,9 @@ func (p *Pool) DialAuthorizedCellularCall(ctx context.Context, worker *Worker, n
if p == nil || worker == nil || worker.Modem == nil {
return errors.New("cellular calling requires an AT modem channel")
}
if err := worker.CheckPhoneModeSupported(PhoneModeVoLTE); err != nil {
return err
}
release, err := p.acquireOutboundOperation(worker)
if err != nil {
return err
@@ -68,9 +71,10 @@ func (p *Pool) acquireOutboundOperation(worker *Worker) (func(), error) {
}
type outboundSMSRequest struct {
Worker *Worker
To, Text string
Options smscodec.SubmitOptions
Worker *Worker
To, Text string
Options smscodec.SubmitOptions
CheckOwner func() error
}
func (p *Pool) authorizeSMS(ctx context.Context, request outboundSMSRequest) error {
@@ -81,7 +85,7 @@ func (p *Pool) authorizeSMS(ctx context.Context, request outboundSMSRequest) err
if err != nil {
return err
}
return p.consumeOutbound(ctx, request.Worker, outbound.Request{Kind: outbound.SMS, Units: len(parts)})
return p.consumeOutbound(ctx, request.Worker, outbound.Request{Kind: outbound.SMS, Units: len(parts)}, request.CheckOwner)
}
// A queued operation must not spend one SIM's budget on another.
@@ -95,7 +99,7 @@ func (p *Pool) outboundOwnerCheck(w *Worker) func() error {
}
}
func (p *Pool) consumeOutbound(ctx context.Context, w *Worker, request outbound.Request) error {
func (p *Pool) consumeOutbound(ctx context.Context, w *Worker, request outbound.Request, checkOwner func() error) error {
if p == nil {
return nil
}
@@ -111,14 +115,21 @@ func (p *Pool) consumeOutbound(ctx context.Context, w *Worker, request outbound.
if limiter == nil {
return nil
}
if w == nil || p.GetWorker(w.ID) != w || p.IsESIMSwitching(w.ID) {
sim := currentSIMOwnership(w)
if checkOwner != nil {
if err := checkOwner(); err != nil {
return err
}
} else if w == nil || p.GetWorker(w.ID) != w || p.IsESIMSwitching(w.ID) {
return errors.New("设备或 SIM 正在变更,不能发起外发请求")
}
sim := currentSIMOwnership(w)
attempt := outbound.Request{ICCID: sim.iccid, Kind: request.Kind, Units: request.Units}
if err := limiter.Consume(contextOrBackground(ctx), attempt); err != nil {
return err
}
if checkOwner != nil {
return checkOwner()
}
if p.GetWorker(w.ID) != w || currentSIMOwnership(w) != sim || p.IsESIMSwitching(w.ID) {
return errors.New("记录额度期间设备或 SIM 已变更,请重新操作")
}
+87
View File
@@ -11,6 +11,7 @@ import (
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
"github.com/iniwex5/vowifi-go/runtimehost/voicehost"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/internal/outbound"
"github.com/yibaiba/hideck/pkg/smscodec"
)
@@ -143,3 +144,89 @@ func TestQueuedSMSSIMReplacementStopsBeforeNewRuntimeSend(t *testing.T) {
t.Fatalf("queued send crossed SIM: err=%v sent=%d", err, newRuntime.sendCount())
}
}
func TestML307CCSSMSChecksLiveSIMBeforeSubmitting(t *testing.T) {
for _, tc := range []struct {
name string
iccid, imsi string
simErr, want error
simAbsent bool
}{
{name: "matching", iccid: "card-old", imsi: "imsi-old"},
{name: "different_card", iccid: "card-new", imsi: "imsi-new", want: ErrSMSIdentityConflict},
{name: "same_iccid_different_imsi", iccid: "card-old", imsi: "imsi-new", want: ErrSMSIdentityConflict},
{name: "incomplete", iccid: "card-old", want: ErrSMSIdentityUnknown},
{name: "absent", simAbsent: true, want: ErrSMSIdentityUnknown},
{name: "pin_required", iccid: "card-old", imsi: "imsi-old", simErr: modem.ErrSIMPINRequired, want: modem.ErrSIMPINRequired},
} {
t.Run(tc.name, func(t *testing.T) {
p, w, be := newML307CIdentityWorker(t)
limiter := &recordingOutboundLimiter{}
p.SetOutboundLimiter(limiter)
be.liveICCID, be.liveIMSI, be.simErr, be.simAbsent = tc.iccid, tc.imsi, tc.simErr, tc.simAbsent
if err := w.SendSMS("10010", "test"); !errors.Is(err, tc.want) {
t.Fatalf("SendSMS() = %v, want %v", err, tc.want)
}
count := 0
if tc.want == nil {
count = 1
}
if be.sends != count || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "card-old" {
t.Fatalf("sends=%d want %d; charges=%+v want one on intended card", be.sends, count, limiter.requests)
}
if tc.want != nil && !w.SIMIdentityConvergenceMatches("", 0) {
t.Fatal("confirmed SIM state did not invalidate cached readiness")
}
})
}
}
func TestML307CCSSMSRejectsSilentSIMSwapDuringAuthorization(t *testing.T) {
p, w, be := newML307CIdentityWorker(t)
be.liveICCID, be.liveIMSI = "card-old", "imsi-old"
limiter := &recordingOutboundLimiter{after: func() {
be.liveICCID, be.liveIMSI = "card-new", "imsi-new"
}}
p.SetOutboundLimiter(limiter)
if err := w.SendSMS("10010", "test"); !errors.Is(err, ErrSMSIdentityConflict) {
t.Fatalf("SendSMS() = %v, want SIM conflict", err)
}
if be.sends != 0 || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "card-old" {
t.Fatalf("wrong send or quota owner: sends=%d charges=%+v", be.sends, limiter.requests)
}
}
type directSMSSelectorBackend struct {
workerStatusBackendStub
sends int
}
func (b *directSMSSelectorBackend) SendSMS(context.Context, string, string) error {
b.sends++
return nil
}
func TestDirectSMSMatchesICCIDWithoutIMSI(t *testing.T) {
_, w, limiter := outboundTestWorker(t)
backend := &directSMSSelectorBackend{workerStatusBackendStub: workerStatusBackendStub{mode: "qmi"}}
w.Backend = backend
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "123"})
err := w.SendSMSForIdentity(context.Background(), "10010", "test", smscodec.SubmitOptions{}, SMSIdentity{ICCID: "123f"})
if err != nil || backend.sends != 1 || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "123" {
t.Fatalf("send error=%v, sends=%d, quota=%+v", err, backend.sends, limiter.requests)
}
}
func TestRoutedSMSReportsStaleSelectorBeforeFallback(t *testing.T) {
p, w, limiter := outboundTestWorker(t)
w.Config.VoWiFiEnabled, w.Config.PhoneMode = true, "wifi"
cs := false
p.SetRoutedSMSTestSenders(func(context.Context, string, string, string, smscodec.SubmitOptions) (messaging.SendOutcome, error) {
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "456", IMSI: "234150123456789"})
return messaging.SendOutcome{}, messaging.ErrSMSNotReady
}, func(string, string, string) error { cs = true; return nil })
_, err := p.SendRoutedSMSForIdentity(context.Background(), w, "10010", "test", smscodec.SubmitOptions{}, SMSIdentity{ICCID: "123"})
if !errors.Is(err, ErrSMSSelectorMismatch) || cs || len(limiter.requests) != 1 || limiter.requests[0].ICCID != "123" {
t.Fatalf("fallback: error=%v CS sent=%v quota=%+v", err, cs, limiter.requests)
}
}
+35 -3
View File
@@ -11,6 +11,14 @@ import (
var ErrModemVoiceSoftwareIMS = errors.New("模组直拨模式不使用软件 IMS")
type PhoneModeUnsupportedError struct {
Reason string
}
func (e *PhoneModeUnsupportedError) Error() string {
return e.Reason
}
const (
PhoneModeWiFi = "wifi"
PhoneModeCellular = "cellular"
@@ -51,23 +59,47 @@ func cellularAlwaysData(cfg config.DeviceConfig) bool {
return strings.TrimSpace(cfg.PhoneMode) == PhoneModeCellular && strings.TrimSpace(cfg.DataStrategy) == "always"
}
// WorkerSoftwareIMSBlocked reports China MCC 460/461, which has no ePDG
// software IMS path in this stack. Phone service must use modem call control.
// WorkerSoftwareIMSBlocked reports whether the SIM's MCC is blocked by the
// software IMS policy. Phone service must use modem call control.
func WorkerSoftwareIMSBlocked(w *Worker) bool {
if w == nil {
return false
}
w.cacheMu.RLock()
mcc := strings.TrimSpace(w.state.Identity.NativeMCC)
imsi := strings.TrimSpace(w.state.Identity.IMSI)
w.cacheMu.RUnlock()
if carrier.IsVoWiFiBlockedMCC(mcc) {
return true
}
imsi := strings.TrimSpace(w.state.Identity.IMSI)
if len(imsi) >= 3 && carrier.IsVoWiFiBlockedMCC(imsi[:3]) {
return true
}
return false
}
// CellularIMSUnavailableReason reports the modem data-path limitation, independent of SIM policy.
func (w *Worker) CellularIMSUnavailableReason() string {
if w.NetworkController() != nil {
return ""
}
return w.atDeviceRules().cellularIMSUnavailableReason
}
// CheckPhoneModeSupported checks the device and SIM capabilities for a phone mode.
func (w *Worker) CheckPhoneModeSupported(mode string) error {
if reason := w.atDeviceRules().nativeVoiceUnavailableReason; reason != "" &&
(UsesModemPhoneControl(mode) || WorkerSoftwareIMSBlocked(w)) {
return &PhoneModeUnsupportedError{Reason: reason}
}
if strings.TrimSpace(mode) == PhoneModeCellular {
if reason := w.CellularIMSUnavailableReason(); reason != "" {
return &PhoneModeUnsupportedError{Reason: reason}
}
}
return nil
}
func forceSoftwareIMSBlockedToVoLTE(w *Worker, pol cardpolicy.Policy) {
if w == nil || !PhoneServiceEnabled(w.Config) || !WorkerSoftwareIMSBlocked(w) || IsModemVoiceMode(w.Config.PhoneMode) {
return
+150
View File
@@ -1,9 +1,16 @@
package device
import (
"context"
"errors"
"testing"
"time"
"github.com/yibaiba/hideck/internal/backend"
"github.com/yibaiba/hideck/internal/cardpolicy"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/internal/vowifihost"
)
func TestWorkerSoftwareIMSBlockedChinaMCC(t *testing.T) {
@@ -55,3 +62,146 @@ func TestApplyPhoneRadioPolicyByMode(t *testing.T) {
t.Fatalf("volte should camp without forcing data: %+v", volte)
}
}
func TestML307CPhonePolicyKeepsExplicitRadioSettings(t *testing.T) {
for _, tc := range []struct {
name, imsi, mode string
airplane bool
}{
{name: "China WiFi", imsi: "460011234567890", mode: PhoneModeWiFi},
{name: "China cellular", imsi: "460011234567890", mode: PhoneModeCellular},
{name: "overseas cellular", imsi: "530240000000001", mode: PhoneModeCellular},
{name: "overseas cellular in airplane", imsi: "530240000000001", mode: PhoneModeCellular, airplane: true},
{name: "overseas VoLTE", imsi: "530240000000001", mode: PhoneModeVoLTE},
{name: "overseas direct dial", imsi: "530240000000001", mode: PhoneModeModemVoice, airplane: true},
} {
t.Run(tc.name, func(t *testing.T) {
p := newDesiredVoWiFiTestPool(t, "ml307c", false, tc.imsi)
t.Cleanup(p.cancel)
w := p.GetWorker("ml307c")
w.Modem = newML307CPhoneTestModem(t, w.ID)
w.state.Identity.Phase = simIdentityPhaseReady
radio := &esimSwitchRestoreBackendStub{mode: backend.BackendAT, getMode: backend.ModeOnline}
w.Backend = radio
pol := cardpolicy.Policy{
ICCID: w.CurrentICCID(), VoWiFiEnabled: true, AirplaneEnabled: tc.airplane,
NetworkEnabled: !tc.airplane, PhoneMode: tc.mode, DataStrategy: "on_demand",
}
resolver := &stubPolicyResolver{pol: pol}
p.SetPolicyResolver(resolver)
result := p.resolveAndApplyPolicy(w, "test")
if !result.Applied || result.Err != nil {
t.Fatalf("apply policy: %+v", result)
}
if w.Config.VoWiFiEnabled || p.IsNativeVoLTE(w.ID) || p.IsModemVoice(w.ID) ||
w.Config.PhoneMode != tc.mode || w.Config.AirplaneEnabled != tc.airplane ||
w.Config.NetworkEnabled != pol.NetworkEnabled || !w.Config.SMSEnabled {
t.Fatalf("unexpected effective config: %+v", w.Config)
}
if tc.airplane {
if len(radio.setCalls) != 1 || radio.setCalls[0] != backend.ModeRFOff {
t.Fatalf("explicit airplane mode was not applied: %v", radio.setCalls)
}
} else if len(radio.setCalls) != 0 || w.cellularRadioIsSuppressed() {
t.Fatalf("unsupported voice mode changed radio state: %v", radio.setCalls)
}
if resolver.pol != pol || p.currentCardPolicyAllowsVoWiFi(w, pol.ICCID, "test", LebaraUKClass{}) {
t.Fatalf("card policy changed or still enables recovery: %+v", resolver.pol)
}
if !tc.airplane && (tc.mode == PhoneModeWiFi || tc.mode == PhoneModeCellular) {
var unsupported *PhoneModeUnsupportedError
if err := p.EnableVoWiFi(w.ID); !errors.As(err, &unsupported) {
t.Fatalf("direct software IMS start error = %v", err)
}
if len(radio.setCalls) != 0 || w.cellularRadioIsSuppressed() {
t.Fatalf("direct software IMS start changed radio state: %v", radio.setCalls)
}
}
})
}
}
func TestML307CCellularIMSCapabilityWithNetworkController(t *testing.T) {
w := &Worker{ID: "ml307c", netOverride: &fakeController{}}
w.Modem = newML307CPhoneTestModem(t, w.ID)
if err := w.CheckPhoneModeSupported(PhoneModeCellular); err != nil {
t.Fatalf("cellular IMS with a controller: %v", err)
}
}
func TestML307COneNZWiFiPolicyStillStarts(t *testing.T) {
p := newDesiredVoWiFiTestPool(t, "ml307c", false, "530010000000001")
t.Cleanup(p.cancel)
w := p.GetWorker("ml307c")
w.Modem = newML307CPhoneTestModem(t, w.ID)
w.state.Identity.Phase = simIdentityPhaseReady
p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{
ICCID: w.CurrentICCID(), PhoneMode: PhoneModeWiFi, VoWiFiEnabled: true,
}})
commands := make(chan vowifihost.LifecycleCommand, 1)
p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, cmd vowifihost.LifecycleCommand) error {
commands <- cmd
return nil
}
if result := p.resolveAndApplyPolicy(w, "test"); !result.Applied || result.Err != nil {
t.Fatalf("apply policy: %+v", result)
}
if !w.Config.VoWiFiEnabled || !w.Config.AirplaneEnabled || w.Config.PhoneMode != PhoneModeWiFi {
t.Fatalf("WiFi policy changed: %+v", w.Config)
}
if !p.currentCardPolicyAllowsVoWiFi(w, w.CurrentICCID(), "test", LebaraUKClass{}) {
t.Fatal("One NZ lost software IMS recovery")
}
select {
case cmd := <-commands:
if cmd.DeviceID != w.ID {
t.Fatalf("unexpected recovery: %+v", cmd)
}
case <-time.After(time.Second):
t.Fatal("WiFi recovery was not scheduled")
}
}
func TestML307CLebaraSavedVoLTERecoversEffectiveWiFi(t *testing.T) {
p := newDesiredVoWiFiTestPool(t, "ml307c", false, "234870000000001")
t.Cleanup(p.cancel)
w := p.GetWorker("ml307c")
w.Modem = newML307CPhoneTestModem(t, w.ID)
w.state.Identity.Phase = simIdentityPhaseReady
pol := cardpolicy.Policy{
ICCID: w.CurrentICCID(), PhoneMode: PhoneModeVoLTE, VoWiFiEnabled: true,
}
resolver := &stubPolicyResolver{pol: pol}
p.SetPolicyResolver(resolver)
commands := make(chan vowifihost.LifecycleCommand, 1)
p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, command vowifihost.LifecycleCommand) error {
commands <- command
return nil
}
if result := p.resolveAndApplyPolicy(w, "test"); !result.Applied || result.Err != nil {
t.Fatalf("apply policy: %+v", result)
}
if !w.Config.VoWiFiEnabled || !w.Config.AirplaneEnabled || w.Config.NetworkEnabled ||
w.Config.PhoneMode != PhoneModeWiFi || resolver.pol != pol {
t.Fatalf("effective config = %+v, saved policy = %+v", w.Config, resolver.pol)
}
class, err := ClassifyWorkerLebaraUK(w)
if err != nil || !class.IsLebara || !p.currentCardPolicyAllowsVoWiFi(w, pol.ICCID, "test", class) {
t.Fatalf("saved native mode blocked effective WiFi recovery: %+v, %v", class, err)
}
select {
case <-commands:
case <-time.After(time.Second):
t.Fatal("WiFi recovery was not scheduled")
}
}
func newML307CPhoneTestModem(t *testing.T, id string) *modem.Manager {
t.Helper()
m, err := modem.NewWithATProfile(config.DeviceConfig{ID: id, DeviceBackend: "at", ATPort: "/dev/test-ml307c"}, modem.ATProfileML307C)
if err != nil {
t.Fatal(err)
}
return m
}
+7 -4
View File
@@ -54,6 +54,12 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR
if err := validate(); err != nil {
return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: err}
}
class, err := ClassifyWorkerLebaraUK(worker)
if err != nil {
logger.Warn("识别 Lebara UK 射频策略失败", "device", worker.ID, "iccid", iccid, "err", err)
return policyApplyResult{ICCID: iccid, Reason: "apply_failed", Err: err}
}
pol = effectiveCardPhonePolicy(worker, pol, class)
// Finish the old call before projecting a policy that disallows new calls.
// Failed hangup leaves the current session and policy available for retry.
var finishNativeTransition func()
@@ -93,10 +99,7 @@ func (p *Pool) resolveAndApplyPolicy(worker *Worker, reason string) policyApplyR
if err := validate(); err != nil {
return policyApplyResult{ICCID: iccid, Reason: "owner_changed", Err: err}
}
if err := applyPolicyToWorker(worker, pol); err != nil {
logger.Warn("投影卡策略失败", "device", worker.ID, "iccid", iccid, "err", err)
return policyApplyResult{ICCID: iccid, Reason: "apply_failed", Err: err}
}
applyPolicyToWorker(worker, pol, class)
effective := worker.Config
logger.Info("已投影卡策略", "device", worker.ID, "iccid", iccid,
"network", effective.NetworkEnabled, "vowifi", effective.VoWiFiEnabled,
+4
View File
@@ -60,6 +60,10 @@ func (p *Pool) validatePolicyOwner(owner policyOwner, transition *policyTransiti
if strings.TrimSpace(identity.ICCID) != owner.iccid || identity.Generation != owner.identityGeneration {
return errPolicyOwnerChanged
}
if w.atDeviceRules().strictSIMIdentity && (!identity.Ready || identity.Phase != simIdentityPhaseReady ||
strings.TrimSpace(identity.ICCID) == "" || strings.TrimSpace(identity.IMSI) == "") {
return errPolicyOwnerChanged
}
p.switchMu.Lock()
switching, snapshot := p.switchingDevices[w.ID], p.switchContexts[w.ID]
p.switchMu.Unlock()
+19 -13
View File
@@ -42,15 +42,23 @@ func shouldEnterAirplaneOnDeviceBind(cfg config.DeviceConfig) bool {
return shouldSuppressCellularRadio(cfg)
}
// applyPolicyToWorker 把卡策略投影进 worker.Config 的运行时有效字段。
// 不在此触发 re-apply,仅做纯投影,便于单测。
func applyPolicyToWorker(w *Worker, p cardpolicy.Policy) error {
if w == nil {
return nil
// effectiveCardPhonePolicy applies the RF lock before checking the mode.
func effectiveCardPhonePolicy(w *Worker, p cardpolicy.Policy, class LebaraUKClass) cardpolicy.Policy {
if class.IsLebara {
p.PhoneMode = PhoneModeWiFi
p.AirplaneEnabled = true
p.NetworkEnabled = false
}
class, err := ClassifyWorkerLebaraUK(w)
if err != nil {
return fmt.Errorf("识别 Lebara UK 射频策略失败: %w", err)
if w.CheckPhoneModeSupported(p.PhoneMode) != nil {
p.VoWiFiEnabled = false
}
return p
}
// applyPolicyToWorker projects the effective policy without persisting it.
func applyPolicyToWorker(w *Worker, p cardpolicy.Policy, class LebaraUKClass) {
if w == nil {
return
}
w.Config.NetworkEnabled = p.NetworkEnabled
w.Config.VoWiFiEnabled = p.VoWiFiEnabled
@@ -69,7 +77,9 @@ func applyPolicyToWorker(w *Worker, p cardpolicy.Policy) error {
w.Config.NetworkEnabled = false
}
}
forceSoftwareIMSBlockedToVoLTE(w, p)
if !class.IsLebara {
forceSoftwareIMSBlockedToVoLTE(w, p)
}
w.Config.IPVersion = strings.TrimSpace(p.IPVersion)
if w.Config.IPVersion == "" {
w.Config.IPVersion = "v4"
@@ -78,11 +88,7 @@ func applyPolicyToWorker(w *Worker, p cardpolicy.Policy) error {
w.Config.SMSEnabled = true // SMS 恒开
// 用投影后的有效网络开关。WiFi calling 已强制关流量,启动失败不得借此把射频拉回来。
w.restoreNetworkAfterVoWiFi = w.Config.NetworkEnabled
if class.IsLebara {
applyLebaraUKRFLock(w)
}
w.setCellularRadioSuppressed(shouldSuppressCellularRadio(w.Config))
return nil
}
func withConnectHoldRF(cfg config.DeviceConfig) config.DeviceConfig {
+18 -11
View File
@@ -15,9 +15,18 @@ import (
"github.com/yibaiba/hideck/pkg/logger"
)
func applyTestCardPolicy(t *testing.T, w *Worker, pol cardpolicy.Policy) {
t.Helper()
class, err := ClassifyWorkerLebaraUK(w)
if err != nil {
t.Fatal(err)
}
applyPolicyToWorker(w, effectiveCardPhonePolicy(w, pol, class), class)
}
func TestApplyPolicyCellularAirplaneKeepsSoftwarePhone(t *testing.T) {
w := &Worker{ID: "wwan0"}
applyPolicyToWorker(w, cardpolicy.Policy{
applyTestCardPolicy(t, w, cardpolicy.Policy{
ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular",
AirplaneEnabled: true, NetworkEnabled: true, DataStrategy: "on_demand",
})
@@ -33,7 +42,7 @@ func TestApplyPolicyChinaUnicomForcesNativeVoLTE(t *testing.T) {
w := &Worker{ID: "wwan1"}
w.state.Identity.NativeMCC = "460"
w.state.Identity.IMSI = "460011234567890"
applyPolicyToWorker(w, cardpolicy.Policy{
applyTestCardPolicy(t, w, cardpolicy.Policy{
ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular", DataStrategy: "on_demand",
})
if w.Config.PhoneMode != PhoneModeVoLTE {
@@ -46,7 +55,7 @@ func TestApplyPolicyChinaUnicomForcesNativeVoLTE(t *testing.T) {
func TestApplyPolicyVoLTECampsWithoutForcingData(t *testing.T) {
w := &Worker{ID: "wwan1"}
applyPolicyToWorker(w, cardpolicy.Policy{
applyTestCardPolicy(t, w, cardpolicy.Policy{
ICCID: "x", VoWiFiEnabled: true, PhoneMode: "volte",
})
if w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() {
@@ -59,14 +68,14 @@ func TestApplyPolicyVoLTECampsWithoutForcingData(t *testing.T) {
func TestApplyPolicyCellularIdleKeepsCamped(t *testing.T) {
w := &Worker{ID: "wwan0"}
applyPolicyToWorker(w, cardpolicy.Policy{
applyTestCardPolicy(t, w, cardpolicy.Policy{
ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular", DataStrategy: "on_demand",
})
if w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() {
t.Fatalf("蜂窝未开流量应保持驻网: %+v suppressed=%v", w.Config, w.cellularRadioIsSuppressed())
}
applyPolicyToWorker(w, cardpolicy.Policy{
applyTestCardPolicy(t, w, cardpolicy.Policy{
ICCID: "x", VoWiFiEnabled: true, PhoneMode: "cellular", DataStrategy: "on_demand", NetworkEnabled: true,
})
if w.Config.AirplaneEnabled || !w.Config.NetworkEnabled || w.cellularRadioIsSuppressed() {
@@ -82,9 +91,7 @@ func TestApplyPolicyLocksLebaraUKRadioWithoutRewritingIntent(t *testing.T) {
ICCID: "8944000000000000087", AirplaneEnabled: false, NetworkEnabled: true,
PhoneMode: "cellular", VoWiFiEnabled: true, DataStrategy: "always",
}
if err := applyPolicyToWorker(w, pol); err != nil {
t.Fatal(err)
}
applyTestCardPolicy(t, w, pol)
if !w.Config.AirplaneEnabled || w.Config.NetworkEnabled || w.Config.PhoneMode != "wifi" {
t.Fatalf("Lebara 运行时应锁射频: %+v", w.Config)
}
@@ -125,7 +132,7 @@ func TestResolveAndApplyPolicyKeepsLebaraUKRadioOff(t *testing.T) {
func TestApplyPolicyDoesNotLockBareVodafoneNL(t *testing.T) {
w := &Worker{ID: "wwan-nl"}
w.state.Identity.IMSI = "204040000000001"
applyPolicyToWorker(w, cardpolicy.Policy{
applyTestCardPolicy(t, w, cardpolicy.Policy{
ICCID: "x", AirplaneEnabled: false, NetworkEnabled: true, PhoneMode: "cellular",
})
if w.Config.AirplaneEnabled || !w.Config.NetworkEnabled || w.Config.PhoneMode != "cellular" {
@@ -135,7 +142,7 @@ func TestApplyPolicyDoesNotLockBareVodafoneNL(t *testing.T) {
func TestApplyPolicyProjectsFields(t *testing.T) {
w := &Worker{ID: "wwan0"}
applyPolicyToWorker(w, cardpolicy.Policy{
applyTestCardPolicy(t, w, cardpolicy.Policy{
ICCID: "x", NetworkEnabled: true, VoWiFiEnabled: true,
AirplaneEnabled: true, IPVersion: "v4v6", APN: "ims",
})
@@ -293,7 +300,7 @@ func TestInitialCellularRadioSuppressionWaitsForLiveCardPolicy(t *testing.T) {
w := &Worker{ID: "wwan0"}
w.setCellularRadioSuppressed(p.initialCellularRadioSuppression(w.Config))
applyPolicyToWorker(w, cardpolicy.Policy{ICCID: "123", NetworkEnabled: true})
applyTestCardPolicy(t, w, cardpolicy.Policy{ICCID: "123", NetworkEnabled: true})
if w.cellularRadioIsSuppressed() {
t.Fatal("在线卡策略投影后必须解除蜂窝驻网抑制")
}
+118 -28
View File
@@ -156,7 +156,8 @@ type Worker struct {
operatorScanCancel context.CancelFunc
operatorScanActive bool
reassembler *smscodec.Reassembler
reassembler *smscodec.Reassembler
storedSMSNotices storedSMSNotices
// 短信工作模式:AT / QMI / VoWiFi(三模完全隔离)。MBIM 网络使用 AT 短信模式。
smsMode smsMode
@@ -663,6 +664,10 @@ func (w *Worker) RefreshIdentityLive(ctx context.Context, reason string) error {
}
func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSIMIdentityRefreshResult, error) {
return w.refreshIdentityLiveWithPresence(ctx, reason, false)
}
func (w *Worker) refreshIdentityLiveWithPresence(ctx context.Context, reason string, presenceConfirmed bool) (liveSIMIdentityRefreshResult, error) {
if w == nil {
return liveSIMIdentityRefreshResult{}, fmt.Errorf("worker_nil")
}
@@ -679,12 +684,34 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI
defer cancel()
}
strictSIMIdentity := w.atDeviceRules().strictSIMIdentity
var generation uint64
if strictSIMIdentity {
generation = w.SIMIdentityGeneration()
}
if strictSIMIdentity && !presenceConfirmed {
inserted, err := w.Backend.IsSimInserted(ctx)
if err != nil {
if errors.Is(err, modem.ErrSIMPINRequired) {
w.recordStrictSIMLock(generation, reason)
}
return liveSIMIdentityRefreshResult{}, err
}
if !inserted {
w.recordStrictSIMAbsence(generation, reason)
return liveSIMIdentityRefreshResult{}, errATNoSIM
}
}
iccid, imsi, nativeSPN := "", "", ""
var simMetadata *backend.SIMMetadata
spnReadOK, metadataReadOK := false, false
if snapshotReader, supported := w.Backend.(liveSIMIdentitySnapshotReader); supported {
snapshot, err := snapshotReader.ReadSIMIdentityLive(ctx)
if err != nil {
if strictSIMIdentity {
w.degradeStrictSIMIdentity(generation, reason, err)
}
return liveSIMIdentityRefreshResult{}, err
}
iccid = strings.TrimSpace(snapshot.ICCID)
@@ -725,6 +752,11 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI
}
}
}
if strictSIMIdentity && (iccid == "" || imsi == "") {
err := errors.New("live_identity_incomplete")
w.degradeStrictSIMIdentity(generation, reason, err)
return liveSIMIdentityRefreshResult{}, err
}
_, snapshotSupported := w.Backend.(liveSIMIdentitySnapshotReader)
if !snapshotSupported && (simMetadata == nil ||
strings.TrimSpace(simMetadata.NativeMCC) == "" ||
@@ -745,7 +777,7 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI
}
}
imei := ""
if iccid == "" || imsi == "" {
if (iccid == "" || imsi == "") && !strictSIMIdentity {
if ident, atErr := probeWorkerATIdentity(ctx, w); atErr == nil {
if iccid == "" {
iccid = strings.TrimSpace(ident.ICCID)
@@ -787,6 +819,10 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI
now := time.Now()
w.cacheMu.Lock()
if strictSIMIdentity && w.state.Identity.Generation != generation {
w.cacheMu.Unlock()
return liveSIMIdentityRefreshResult{}, ErrSMSIdentityTransitioning
}
identityIncomplete := (iccid == "") != (imsi == "")
hasCachedIdentity := strings.TrimSpace(w.state.Identity.ICCID) != "" ||
strings.TrimSpace(w.state.Identity.IMSI) != ""
@@ -815,8 +851,10 @@ func (w *Worker) refreshIdentityLive(ctx context.Context, reason string) (liveSI
(imsi != "" && imsi != strings.TrimSpace(w.state.Identity.IMSI))
// Physical swaps do not necessarily pass through the eSIM transition hook.
// Retain a generation change even if the original ICCID later returns.
if iccid != "" && w.state.Identity.ICCID != "" &&
normalizeSIMIdentityForCompare(iccid) != normalizeSIMIdentityForCompare(w.state.Identity.ICCID) {
iccidChanged := iccid != "" && w.state.Identity.ICCID != "" &&
normalizeSIMIdentityForCompare(iccid) != normalizeSIMIdentityForCompare(w.state.Identity.ICCID)
if iccidChanged || (strictSIMIdentity && imsi != "" && w.state.Identity.IMSI != "" &&
imsi != strings.TrimSpace(w.state.Identity.IMSI)) {
w.state.Identity.Generation++
}
if iccid != "" {
@@ -1022,10 +1060,26 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s
if p == nil || owner.worker == nil || !p.workerLifecycleOwnerCurrent(owner) {
return
}
if insertedHint != nil && *insertedHint {
return
}
if strings.EqualFold(strings.TrimSpace(state), "READY") {
state = strings.ToUpper(strings.TrimSpace(state))
pinHint := false
if owner.worker.atDeviceRules().strictSIMIdentity {
pinHint = modem.IsSIMPINRequiredState(state)
if insertedHint != nil {
if *insertedHint && !owner.worker.SIMIdentityConvergenceMatches("", 0) {
return
}
if !*insertedHint {
owner.worker.cacheMu.RLock()
confirmedAbsent := owner.worker.state.Identity.LastError == "sim_removed"
owner.worker.cacheMu.RUnlock()
if confirmedAbsent {
return
}
}
} else if !pinHint && state != "READY" && state != "SIM REMOVED" && state != "SIM NOT INSERTED" {
return
}
} else if (insertedHint != nil && *insertedHint) || state == "READY" {
return
}
deviceID := owner.worker.ID
@@ -1035,11 +1089,16 @@ func (p *Pool) handleSIMStatusEventForOwner(owner workerLifecycleOwner, source s
p.simEventTimers = make(map[string]*time.Timer)
}
if timer := p.simEventTimers[deviceID]; timer != nil {
// A pending status check will already detect a live PIN lock.
if pinHint {
p.simEventMu.Unlock()
return
}
timer.Stop()
}
var timer *time.Timer
timer = time.AfterFunc(1500*time.Millisecond, func() {
p.confirmSIMRemovedForOwner(owner, source, timer)
p.confirmSIMStatusForOwner(owner, source, timer, pinHint)
})
p.simEventTimers[deviceID] = timer
p.simEventMu.Unlock()
@@ -1152,11 +1211,15 @@ func (p *Pool) confirmSIMRemovedAndStopVoWiFi(deviceID, source string) {
}
func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source string, expected *time.Timer) {
p.confirmSIMStatusForOwner(owner, source, expected, false)
}
func (p *Pool) confirmSIMStatusForOwner(owner workerLifecycleOwner, source string, expected *time.Timer, pinHint bool) {
if p == nil || owner.worker == nil {
return
}
deviceID := owner.worker.ID
if !p.consumeSIMEventTimer(deviceID, expected) {
if expected != nil && !p.consumeSIMEventTimer(deviceID, expected) {
return
}
releaseMutation := p.AcquireManagedDeviceMutation(deviceID)
@@ -1167,6 +1230,9 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri
transition.Unlock()
return
}
if expected == nil {
p.consumeSIMEventTimer(deviceID, nil)
}
if p.IsESIMSwitching(deviceID) {
transition.Unlock()
logger.Info("SIM 状态变化发生在 eSIM 切换中,跳过 VoWiFi 自动停止", "device", deviceID, "source", source)
@@ -1183,19 +1249,29 @@ func (p *Pool) confirmSIMRemovedForOwner(owner workerLifecycleOwner, source stri
}
ctx, cancel := context.WithTimeout(baseCtx, 3*time.Second)
defer cancel()
generation := w.SIMIdentityGeneration()
inserted, err := w.Backend.IsSimInserted(ctx)
if err != nil {
if w.atDeviceRules().strictSIMIdentity && errors.Is(err, modem.ErrSIMPINRequired) {
p.handleConfirmedSIMPINRequired(owner, generation)
transition.Unlock()
return
}
transition.Unlock()
logger.Warn("SIM 拔卡确认失败,跳过 VoWiFi 自动停止", "device", deviceID, "source", source, "err", err)
return
}
if inserted {
if pinHint && !w.SIMIdentityConvergenceMatches("", 0) {
transition.Unlock()
return
}
result := p.refreshConfirmedSIMInsertion(owner)
transition.Unlock()
p.finishConfirmedSIMInsertion(owner, source, result)
return
}
p.handleConfirmedSIMRemoval(owner, source, baseCtx)
p.handleConfirmedSIMRemoval(owner, source, baseCtx, generation)
transition.Unlock()
}
@@ -1219,7 +1295,7 @@ type simInsertionRefreshResult struct {
func (p *Pool) refreshConfirmedSIMInsertion(owner workerLifecycleOwner) simInsertionRefreshResult {
w := owner.worker
previous := currentSIMOwnership(w)
_, err := p.refreshWorkerIdentityState(w, "sim_status_inserted")
_, err := p.refreshWorkerIdentityState(w, "sim_status_inserted", true)
return simInsertionRefreshResult{
current: p.workerLifecycleOwnerCurrent(owner),
identityChanged: err == nil && currentSIMOwnership(w) != previous,
@@ -1259,7 +1335,7 @@ func (p *Pool) finishConfirmedSIMInsertion(owner workerLifecycleOwner, source st
}
// Caller holds the device policy transition lock.
func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source string, baseCtx context.Context) {
func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source string, baseCtx context.Context, generation uint64) {
if !p.workerLifecycleOwnerCurrent(owner) {
return
}
@@ -1268,7 +1344,9 @@ func (p *Pool) handleConfirmedSIMRemoval(owner workerLifecycleOwner, source stri
refreshCtx, cancel := context.WithTimeout(baseCtx, 3*time.Second)
_ = w.RefreshRuntime(refreshCtx, "sim_removed")
cancel()
w.markSIMRemoved("sim_removed")
if !w.markSIMRemoved("sim_removed", generation) {
return
}
p.detachPersistedSIMBinding(w)
p.broadcastVoWiFiStateChange(deviceID)
p.clearDesiredVoWiFiRecoverState(deviceID)
@@ -1614,7 +1692,7 @@ func (p *Pool) refreshIdentityAndApplyCardPolicy(worker *Worker, reason string)
if worker == nil {
return liveSIMIdentityRefreshResult{}, nil
}
result, identityErr := p.refreshWorkerIdentityState(worker, reason)
result, identityErr := p.refreshWorkerIdentityState(worker, reason, false)
refreshErr := identityErr
if p != nil {
@@ -1632,12 +1710,12 @@ func (p *Pool) refreshIdentityAndApplyCardPolicy(worker *Worker, reason string)
return result, refreshErr
}
func (p *Pool) refreshWorkerIdentityState(worker *Worker, reason string) (liveSIMIdentityRefreshResult, error) {
func (p *Pool) refreshWorkerIdentityState(worker *Worker, reason string, presenceConfirmed bool) (liveSIMIdentityRefreshResult, error) {
if worker == nil {
return liveSIMIdentityRefreshResult{}, fmt.Errorf("worker_nil")
}
_ = worker.RefreshRuntime(nil, reason)
result, err := worker.refreshIdentityLive(nil, reason)
result, err := worker.refreshIdentityLiveWithPresence(nil, reason, presenceConfirmed)
if p != nil {
p.PersistRuntimeState(worker)
p.PersistIdentityState(worker)
@@ -1908,8 +1986,7 @@ func (p *Pool) RescanAndReconnect() error {
return p.rescanAndReconnect(rescanReconnectOptions{})
}
func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex) []CompatibleModem {
var hardware []CompatibleModem
func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex WorkerDiscoveryIndex, scan compatibleATDiscoveryScope) (hardware []CompatibleModem, atObservations []atScanObservation) {
for i := range discovered {
raw := discovered[i]
// Paths are attachment hints, never proof that the old worker still
@@ -1935,8 +2012,7 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor
})
}
managed := config.ListDevices()
if configuredDevicesNeedCompatibleATDiscovery(managed) {
if scan != compatibleATDiscoveryNone {
if compatList, err := DiscoverCompatibleModemsFromQMI(discovered); err == nil {
seen := map[string]bool{}
for _, hw := range hardware {
@@ -1944,12 +2020,25 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor
seen[k] = true
}
}
probe := func(dev CompatibleModem) (CompatibleModem, string) {
return resolveDiscoveredCompatibleModemFn(dev, 1200*time.Millisecond)
}
for _, raw := range compatList {
m, imei := resolveDiscoveredCompatibleModemFn(raw, 1200*time.Millisecond)
if config.NormalizeIMEI(imei) == "" {
if scan == compatibleATDiscoveryLiveIdentity && !atDeviceRulesFor(raw.ATProfile()).verifyLiveIMEI {
continue
}
if seen[config.NormalizeIMEI(imei)] {
m, observation := liveWorkerIndex.observeLiveATIdentity(raw, probe)
imei := m.IMEI
if observation == nil {
m, imei = probe(raw)
} else {
atObservations = append(atObservations, *observation)
}
key := config.NormalizeIMEI(imei)
if key == "" {
continue
}
if seen[key] {
continue
}
m.IMEI = imei
@@ -1957,7 +2046,7 @@ func (p *Pool) collectRescanHardware(discovered []QMIDevice, liveWorkerIndex Wor
}
}
}
return hardware
return hardware, atObservations
}
func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error {
@@ -1971,9 +2060,9 @@ func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error {
}
liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false)
hardware := p.collectRescanHardware(discovered, liveWorkerIndex)
managed := p.managedDevices()
modemDevices, pcscDevices := partitionManagedDevices(managed)
hardware, atObservations := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(modemDevices))
resolved := ResolveDeviceIdentities(hardware, modemDevices)
if len(resolved.Degraded) > 0 || len(resolved.Unmatched) > 0 {
@@ -1984,7 +2073,7 @@ func (p *Pool) rescanAndReconnect(opts rescanReconnectOptions) error {
}
for _, snapshot := range resolved.Offline {
p.reconcileOfflineRescanDevice(opts, snapshot, hardware, managed)
p.reconcileOfflineRescanDevice(opts, snapshot, hardware, atObservations, managed)
}
return p.reconcilePCSCReaders(opts, managed, pcscDevices)
@@ -2673,7 +2762,8 @@ func (p *Pool) PersistRuntimeState(worker *Worker) {
}
// 更新 Device 表
if err := db.UpsertDevice(imei, worker.ID, "EC20", worker.Config.ATPort); err != nil {
model := worker.atDeviceRules().model
if err := db.UpsertDevice(imei, worker.ID, model, worker.Config.ATPort); err != nil {
logger.Warn(fmt.Sprintf("[%s] 更新设备信息失败", worker.ID), "err", err)
}
}
+1
View File
@@ -10,6 +10,7 @@ import (
)
var errATIdentityUnavailable = errors.New("at identity unavailable")
var errATNoSIM = errors.New("AT modem has no SIM")
var probeATIdentityFn = modem.ProbeATIdentity
+105 -17
View File
@@ -13,6 +13,7 @@ import (
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/esim"
mbimcore "github.com/yibaiba/hideck/internal/mbim"
"github.com/yibaiba/hideck/internal/modem"
qmicore "github.com/yibaiba/hideck/internal/qmi"
"github.com/yibaiba/hideck/pkg/logger"
"github.com/yibaiba/hideck/pkg/smscodec"
@@ -126,20 +127,56 @@ func resolveDiscoveredCompatibleModem(dev CompatibleModem, timeout time.Duration
})
}
func configuredDevicesNeedCompatibleATDiscovery(devices []config.DeviceConfig) bool {
type compatibleATDiscoveryScope uint8
const (
compatibleATDiscoveryNone compatibleATDiscoveryScope = iota
compatibleATDiscoveryLiveIdentity
compatibleATDiscoveryAll
)
func configuredDevicesATDiscovery(devices []config.DeviceConfig) compatibleATDiscoveryScope {
scope := compatibleATDiscoveryNone
for _, dev := range devices {
if requiresQMICore(dev) {
if requiresQMICore(dev) || resolvedBackendMode(dev) == backend.BackendPCSC || strings.TrimSpace(dev.ModemIMEI) == "" {
continue
}
if strings.TrimSpace(dev.ModemIMEI) == "" {
continue
if strings.TrimSpace(dev.ATPort) == "" && strings.TrimSpace(dev.ManagePort) == "" {
return compatibleATDiscoveryAll
}
if strings.TrimSpace(dev.ATPort) != "" || strings.TrimSpace(dev.ManagePort) != "" {
continue
if resolvedBackendMode(dev) == backend.BackendAT {
// Profiles that require live identity must verify even an
// explicitly configured tty. Other explicit ports do not expand discovery.
scope = compatibleATDiscoveryLiveIdentity
}
return true
}
return false
return scope
}
func configuredATPort(cfg config.DeviceConfig) string {
if port := strings.TrimSpace(cfg.ATPort); port != "" {
return port
}
return strings.TrimSpace(cfg.ManagePort)
}
// configuredATDevice finds which USB device owns the explicitly selected port.
func configuredATDevice(cfg config.DeviceConfig) (CompatibleModem, bool) {
port := configuredATPort(cfg)
if port == "" {
return CompatibleModem{}, false
}
port = resolveUSBPathForScan(port)
devices, err := discoverFallbackModemsFn()
if err == nil {
for _, dev := range devices {
if containsPort(dev.ATPorts, port) {
dev.ATPort = port
return dev, true
}
}
}
return CompatibleModem{}, false
}
type qmiBootstrapDiscoveryCache struct {
@@ -210,6 +247,8 @@ type apduArbiterAwareTransport interface {
SetAPDUArbiter(arbiter *apduarbiter.Arbiter)
}
var startWorkerModem = (*modem.Manager).StartWithExpectedIMEI
func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error) {
p.mu.Lock()
if _, exists := p.workers[devCfg.ID]; exists {
@@ -270,16 +309,32 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
}
var matched *QMIDevice
var atProfile modem.ATProfile
explicitATIdentity := configuredATPort(devCfg) != "" && strings.TrimSpace(devCfg.ModemIMEI) != ""
discoveryCache := &qmiBootstrapDiscoveryCache{}
liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false)
configuredIndex := BuildConfiguredDeviceIndex(config.ListDevices())
if !needsQMICore {
liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), true)
hardware := p.collectRescanHardware(nil, liveWorkerIndex)
scan := configuredDevicesATDiscovery([]config.DeviceConfig{devCfg})
if scan == compatibleATDiscoveryNone && configuredDevicesATDiscovery(config.ListDevices()) == compatibleATDiscoveryAll {
scan = compatibleATDiscoveryAll
}
hardware, _ := p.collectRescanHardware(nil, liveWorkerIndex, scan)
resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg})
if len(resolved.Matched) > 0 {
hw := resolved.Matched[0].Hardware
atProfile = hw.ATProfile()
if atDeviceRulesFor(atProfile).verifyLiveIMEI {
if resolvedBackendMode(devCfg) == backend.BackendAT {
if port, _ := liveWorkerIndex.ownedATPort(hw.ATPorts); port != "" {
return nil, fmt.Errorf("AT 口 %s 已由现有设备接管", port)
}
}
devCfg.USBPath = hw.USBPath
devCfg.ATPort = hw.ATPort
devCfg.ManagePort = hw.ATPort
}
if devCfg.Interface == "" {
devCfg.Interface = hw.NetInterface
}
@@ -298,10 +353,8 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
devCfg.ModemIMEI = resolved.Matched[0].BackfillIMEI
logger.Info(fmt.Sprintf("[%s] MBIM/AT 通过 USB 路径认领成功,回填实时 IMEI", devCfg.ID), "imei", devCfg.ModemIMEI)
}
} else {
if strings.TrimSpace(devCfg.ATPort) == "" && strings.TrimSpace(devCfg.ControlDevice) == "" {
return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动")
}
} else if configuredATPort(devCfg) == "" && strings.TrimSpace(devCfg.ControlDevice) == "" {
return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动")
}
} else if hasManagedQMINetwork(devCfg) {
configuredStatic := QMIDevice{
@@ -317,7 +370,11 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
if qmiErr != nil {
logger.Debug("QMI 静态路径启动前发现失败", "device", devCfg.ID, "err", qmiErr)
} else {
hardware := p.collectRescanHardware(qmiList, liveWorkerIndex)
scan := compatibleATDiscoveryNone
if configuredDevicesATDiscovery(config.ListDevices()) == compatibleATDiscoveryAll {
scan = compatibleATDiscoveryAll
}
hardware, _ := p.collectRescanHardware(qmiList, liveWorkerIndex, scan)
resolved := ResolveDeviceIdentities(hardware, []config.DeviceConfig{devCfg})
if len(resolved.Matched) > 0 {
hw := resolved.Matched[0].Hardware
@@ -370,7 +427,27 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
}
backendMode := resolvedBackendMode(devCfg)
m, err := newWorkerModem(devCfg, backendMode)
if backendMode == backend.BackendAT && atProfile == modem.ATProfileDefault &&
(strings.TrimSpace(devCfg.ModemIMEI) == "" || explicitATIdentity) {
ports := []string{configuredATPort(devCfg)}
if hw, ok := configuredATDevice(devCfg); ok {
atProfile = hw.ATProfile()
ports = hw.ATPorts
if atDeviceRulesFor(atProfile).verifyLiveIMEI {
devCfg.USBPath, devCfg.ATPort, devCfg.ManagePort = hw.USBPath, hw.ATPort, hw.ATPort
}
} else if usb := resolveUSBPathForScan(devCfg.USBPath); explicitATIdentity && usb != "" &&
atDeviceRulesFor(readUSBDeviceIdentity(usb).atProfile()).verifyLiveIMEI {
// The selected path is not a recognized AT interface of the attached modem.
return nil, fmt.Errorf("未找到匹配的非 QMI 硬件(AT-only 或 MBIM),跳过启动")
}
if explicitATIdentity || atDeviceRulesFor(atProfile).verifyLiveIMEI {
if port, _ := liveWorkerIndex.ownedATPort(ports); port != "" {
return nil, fmt.Errorf("AT 口 %s 已由现有设备接管", port)
}
}
}
m, err := newWorkerModem(devCfg, backendMode, atProfile)
if err != nil {
return nil, fmt.Errorf("初始化 Modem 失败: %w", err)
}
@@ -571,6 +648,11 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
p.scheduleATDisconnectRecovery(owner, reason)
})
p.bindModemReadyIndications(w)
if source := atDeviceRulesFor(atProfile).simStatusSource; source != "" {
m.SetSIMStatusHandler(func(inserted *bool, state string) {
p.handleSIMStatusEventForOwner(owner, source, inserted, state)
})
}
}
if backendMode == backend.BackendQMI {
@@ -603,7 +685,11 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
}
logger.Info(fmt.Sprintf("[%s] 短信模式已配置", w.ID), "sms_mode", w.smsMode.String(), "backend", backendMode)
if err := m.Start(); err != nil {
expectedOpenedIMEI := ""
if backendMode == backend.BackendAT && (explicitATIdentity || atDeviceRulesFor(atProfile).verifyLiveIMEI) {
expectedOpenedIMEI = strings.TrimSpace(devCfg.ModemIMEI)
}
if err := startWorkerModem(m, expectedOpenedIMEI); err != nil {
if qmiTransportLifecycle != nil {
_ = qmiTransportLifecycle.Stop()
}
@@ -706,6 +792,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
default:
}
worker.PreWarmCache()
worker.scanATSMS()
// 缓存预热完成后,触发一次状态广播,强制前端 SSE 推流更新最新设备数据
p.broadcastVoWiFiStateChange(worker.ID)
}(w)
@@ -749,6 +836,7 @@ func (p *Pool) AddWorkerFromConfig(devCfg config.DeviceConfig) (*Worker, error)
case <-ticker.C:
switch worker.smsMode {
case smsModeAT:
worker.scanATSMS()
case smsModeQMI:
if worker.QMICore != nil {
if err := worker.CheckAllSMSQMI(); err != nil {
+1 -1
View File
@@ -1276,7 +1276,7 @@ func (p *Pool) handleESIMSwitchAfter(deviceID string, token uint64) {
"network_enabled_before", snapshot.NetworkEnabledBefore)
convergence := p.runPostSwitchConvergence(deviceID, token, worker, snapshot)
if !p.esimSwitchOwnerCurrent(deviceID, worker, snapshot) {
if !p.switchTokenStillCurrent(deviceID, token, "sim_convergence") || !p.esimSwitchOwnerCurrent(deviceID, worker, snapshot) {
return
}
if convergence.Degraded {
+6 -1
View File
@@ -2,6 +2,7 @@ package device
import (
"context"
"errors"
"fmt"
"os"
"strings"
@@ -510,8 +511,12 @@ func (w *Worker) PreWarmCache() {
return
}
_ = w.RefreshRuntime(nil, "prewarm")
_ = w.RefreshIdentityLive(nil, "prewarm")
identityErr := w.RefreshIdentityLive(nil, "prewarm")
if w.Pool != nil {
if errors.Is(identityErr, errATNoSIM) {
owner := workerLifecycleOwner{worker: w, generation: w.generation}
w.Pool.confirmSIMRemovedForOwner(owner, "at_startup", nil)
}
w.Pool.PersistRuntimeState(w)
w.Pool.PersistIdentityState(w)
}
+4 -4
View File
@@ -330,8 +330,8 @@ func TestConfiguredDevicesNeedCompatibleATDiscoverySkipsPureQMI(t *testing.T) {
},
}
if configuredDevicesNeedCompatibleATDiscovery(devices) {
t.Fatal("configuredDevicesNeedCompatibleATDiscovery() = true for pure QMI config, want false")
if scope := configuredDevicesATDiscovery(devices); scope != compatibleATDiscoveryNone {
t.Fatalf("configuredDevicesATDiscovery() = %v for pure QMI config, want none", scope)
}
}
@@ -344,8 +344,8 @@ func TestConfiguredDevicesNeedCompatibleATDiscoveryForATMissingPort(t *testing.T
},
}
if !configuredDevicesNeedCompatibleATDiscovery(devices) {
t.Fatal("configuredDevicesNeedCompatibleATDiscovery() = false for AT config missing port, want true")
if scope := configuredDevicesATDiscovery(devices); scope != compatibleATDiscoveryAll {
t.Fatalf("configuredDevicesATDiscovery() = %v for AT config missing port, want all", scope)
}
}
+5
View File
@@ -1,6 +1,7 @@
package device
import (
"errors"
"fmt"
"os"
"strings"
@@ -8,6 +9,7 @@ import (
"github.com/yibaiba/hideck/internal/backend"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/pkg/logger"
)
@@ -42,6 +44,9 @@ func (p *Pool) refreshModemRebootRecoveredIdentity(w *Worker, reason string) err
}
result, err := p.refreshIdentityAndApplyCardPolicy(w, reason)
if errors.Is(err, errATNoSIM) || errors.Is(err, modem.ErrSIMPINRequired) {
return nil
}
if err != nil {
return fmt.Errorf("refresh_identity: %w", err)
}
+2 -2
View File
@@ -31,7 +31,7 @@ func TestCollectRescanHardwarePopulatesIMEIAndPaths(t *testing.T) {
discovered, _ := discoverQMIDevicesFn()
liveWorkerIndex := BuildWorkerDiscoveryIndex(nil, false)
hardware := p.collectRescanHardware(discovered, liveWorkerIndex)
hardware, _ := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(config.ListDevices()))
if len(hardware) != 1 {
t.Fatalf("expected 1 hardware, got %d", len(hardware))
@@ -101,7 +101,7 @@ func TestCollectRescanHardwarePopulatesNonQMIIMEIAndPaths(t *testing.T) {
discovered, _ := discoverQMIDevicesFn()
liveWorkerIndex := BuildWorkerDiscoveryIndex(nil, false)
hardware := p.collectRescanHardware(discovered, liveWorkerIndex)
hardware, _ := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(config.ListDevices()))
if len(hardware) != 1 {
t.Fatalf("expected 1 hardware, got %d", len(hardware))
+20 -2
View File
@@ -87,7 +87,9 @@ func (p *Pool) reconcileHealthyRescanWorker(
})
return
}
if hw.ATPort == "" || hw.ATPort == worker.Config.ATPort || !opts.allowWorkerMutation(pair.Config.ID) {
usbChanged := atDeviceRulesFor(hw.ATProfile()).verifyLiveIMEI && hw.USBPath != "" && hw.USBPath != worker.Config.USBPath
portChanged := hw.ATPort != "" && hw.ATPort != worker.Config.ATPort
if (!usbChanged && !portChanged) || !opts.allowWorkerMutation(pair.Config.ID) {
return
}
logger.Info("检测到设备端口变化,重建 Worker",
@@ -108,6 +110,9 @@ func rescanWorkerConfig(cfg config.DeviceConfig, hw CompatibleModem) config.Devi
if hw.NetInterface != "" {
cfg.Interface = hw.NetInterface
}
if hw.USBPath != "" {
cfg.USBPath = hw.USBPath
}
cfg.ControlDevice = strings.TrimSpace(hw.ControlPath)
cfg.QMIDevice = strings.TrimSpace(hw.ControlPath)
cfg.ATPort = hw.ATPort
@@ -206,6 +211,7 @@ func (p *Pool) reconcileOfflineRescanDevice(
opts rescanReconnectOptions,
snapshot config.DeviceConfig,
hardware []CompatibleModem,
atObservations []atScanObservation,
fallback []config.DeviceConfig,
) {
releaseMutation := p.AcquireManagedDeviceMutation(snapshot.ID)
@@ -223,9 +229,21 @@ func (p *Pool) reconcileOfflineRescanDevice(
if worker == nil {
return
}
healthy := worker.IsDeviceHealthy()
if healthy && worker.atDeviceRules().verifyLiveIMEI && config.IMEIMatches(worker.Config.ModemIMEI, current.ModemIMEI) {
usb := strings.TrimSpace(worker.Config.USBPath)
port := worker.ResolvedATPort()
for _, candidate := range atObservations {
if candidate.unreadableOwner == worker && usb != "" && candidate.usbPath == usb &&
containsPort(candidate.atPorts, port) {
// Keep the existing owner until the next scan can verify its IMEI.
return
}
}
}
logger.Info("检测到设备离线,清理 Worker 以便后续重建",
"device", current.ID, "imei", current.ModemIMEI,
"was_healthy", worker.IsDeviceHealthy())
"was_healthy", healthy)
p.teardownVoWiFiForReconnect(current.ID)
if p.lifecycle != nil {
p.lifecycle.BeginRecovery(current.ID, LifecyclePhaseUSBWait, "rescan_device_missing", qmiLifecycleRecoveryTTL)
+1 -1
View File
@@ -22,7 +22,7 @@ func TestRescanReusedPathsDoNotInheritOldWorkerIMEI(t *testing.T) {
{ControlPath: "/dev/cdc-wdm0", USBPath: "/sys/usb/1-1", NetInterface: "wwan0"},
{ControlPath: "/dev/cdc-wdm1", USBPath: "/sys/usb/1-2", NetInterface: "wwan1"},
}
hardware := (&Pool{}).collectRescanHardware(discovered, BuildWorkerDiscoveryIndex([]*Worker{old}, false))
hardware, _ := (&Pool{}).collectRescanHardware(discovered, BuildWorkerDiscoveryIndex([]*Worker{old}, false), compatibleATDiscoveryNone)
if len(hardware) != 2 || hardware[0].IMEI != "222222222222222" || hardware[1].IMEI != "111111111111111" {
t.Fatalf("identities = %+v", hardware)
}
+1 -1
View File
@@ -75,7 +75,7 @@ func TestRescanReconnectsNonQMIDeviceByIMEI(t *testing.T) {
// 验证 resolver 把它放进 Matched 而非 Offline
discovered, _ := discoverQMIDevicesFn()
liveWorkerIndex := BuildWorkerDiscoveryIndex(p.GetAllWorkers(), false)
hardware := p.collectRescanHardware(discovered, liveWorkerIndex)
hardware, _ := p.collectRescanHardware(discovered, liveWorkerIndex, configuredDevicesATDiscovery(config.ListDevices()))
managed := config.ListDevices()
resolved := ResolveDeviceIdentities(hardware, managed)
+32 -3
View File
@@ -401,6 +401,11 @@ func (w *Worker) SendSMS(phone, message string) error {
}
func (w *Worker) SendSMSWithOptions(phone, message string, opts smscodec.SubmitOptions) error {
return w.SendSMSForIdentity(context.Background(), phone, message, opts, SMSIdentity{})
}
// SendSMSForIdentity binds a SIM selector to a direct backend send.
func (w *Worker) SendSMSForIdentity(ctx context.Context, phone, message string, opts smscodec.SubmitOptions, selector SMSIdentity) error {
if w == nil || w.Pool == nil {
return errors.New("短信发送需要有效的设备池")
}
@@ -409,11 +414,35 @@ func (w *Worker) SendSMSWithOptions(phone, message string, opts smscodec.SubmitO
return err
}
defer release()
check := w.Pool.outboundOwnerCheck(w)
if err := w.Pool.authorizeSMS(context.Background(), outboundSMSRequest{Worker: w, To: phone, Text: message, Options: opts}); err != nil {
explicitSelector := selector != (SMSIdentity{})
selector = normalizeSMSIdentity(selector)
check := w.Pool.smsSendOwnerCheck(w, selector)
request := outboundSMSRequest{Worker: w, To: phone, Text: message, Options: opts}
var intended SMSIdentity
if w.atDeviceRules().strictSIMIdentity {
intended, err = w.strictSMSSendIdentity()
if err != nil {
return err
}
} else if explicitSelector {
intended = w.cachedSMSIdentity()
}
if explicitSelector {
if !selector.matches(intended) {
return ErrSMSSelectorMismatch
}
if err := check(); err != nil {
return err
}
request.CheckOwner = check
}
if err := w.Pool.authorizeSMS(ctx, request); err != nil {
return err
}
if err := check(); err != nil {
if err := w.confirmCSSMSIdentity(ctx, intended, check); err != nil {
if explicitSelector && errors.Is(err, ErrSMSIdentityConflict) {
return ErrSMSSelectorMismatch
}
return err
}
return w.sendSMSWithOptions(phone, message, opts)
+4
View File
@@ -204,6 +204,10 @@ func (w *Worker) MarkSIMIdentityDegraded(reason string, err error) {
now := time.Now()
w.cacheMu.Lock()
defer w.cacheMu.Unlock()
w.markSIMIdentityDegradedLocked(reason, err, now)
}
func (w *Worker) markSIMIdentityDegradedLocked(reason string, err error, now time.Time) {
w.state.Identity.Ready = false
w.state.Identity.Phase = simIdentityPhaseDegraded
w.state.Identity.LastReason = strings.TrimSpace(reason)
+3 -5
View File
@@ -125,9 +125,6 @@ func (p *Pool) shouldReconcileVoWiFiForReason(w *Worker, reason string) bool {
logger.Warn("VoWiFi 目标态恢复跳过:SIM 身份未就绪", "event", "VOWIFI_DESIRED_RECOVER_SKIPPED_IDENTITY", "device", deviceID)
return false
}
if !p.currentCardPolicyAllowsVoWiFi(w, status.ICCID, reason) {
return false
}
mcc, _, _ := vowifiProfileMCCMNC(status)
if mcc != "" && carrier.IsVoWiFiBlockedMCC(mcc) {
p.clearDesiredVoWiFiRecoverState(deviceID)
@@ -147,7 +144,7 @@ func (p *Pool) shouldReconcileVoWiFiForReason(w *Worker, reason string) bool {
"device", deviceID, "imsi", class.LiveIMSI)
return false
}
return true
return p.currentCardPolicyAllowsVoWiFi(w, status.ICCID, reason, class)
}
func (p *Pool) stopLebaraUKFlippedVoWiFi(w *Worker, class LebaraUKClass) {
@@ -181,7 +178,7 @@ func (p *Pool) isWorkerRebuilding(deviceID string) bool {
return rebuilding
}
func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason string) bool {
func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason string, class LebaraUKClass) bool {
if p == nil || w == nil {
return false
}
@@ -223,6 +220,7 @@ func (p *Pool) currentCardPolicyAllowsVoWiFi(w *Worker, statusICCID, reason stri
"err", err)
return false
}
pol = effectiveCardPhonePolicy(w, pol, class)
if UsesModemPhoneControl(pol.PhoneMode) || UsesModemPhoneControl(w.Config.PhoneMode) {
p.clearDesiredVoWiFiRecoverState(deviceID)
return false
+10 -5
View File
@@ -205,11 +205,16 @@ func (p *Pool) enableVoWiFi(deviceID string, lifecycleGeneration uint64) error {
if p.IsESIMSwitching(deviceID) {
return fmt.Errorf("设备 %s 正在切卡,暂不允许启动 VoWiFi", deviceID)
}
if w := p.GetWorker(deviceID); w != nil && IsNativeVoLTEMode(w.Config.PhoneMode) {
return p.EnableNativeVoLTE(deviceID)
}
if w := p.GetWorker(deviceID); w != nil && IsModemVoiceMode(w.Config.PhoneMode) {
return fmt.Errorf("设备 %s: %w", deviceID, ErrModemVoiceSoftwareIMS)
if w := p.GetWorker(deviceID); w != nil {
if err := w.CheckPhoneModeSupported(w.Config.PhoneMode); err != nil {
return err
}
if IsNativeVoLTEMode(w.Config.PhoneMode) {
return p.EnableNativeVoLTE(deviceID)
}
if IsModemVoiceMode(w.Config.PhoneMode) {
return fmt.Errorf("设备 %s: %w", deviceID, ErrModemVoiceSoftwareIMS)
}
}
p.stopNativeVoLTE(deviceID, "enable_vowifi")
if err := p.stopModemVoice(deviceID); err != nil {
@@ -3,6 +3,7 @@ package device
import (
"context"
"errors"
"fmt"
"strings"
"time"
@@ -56,6 +57,13 @@ type postSwitchSIMReloader interface {
UIMPostSwitchReload(ctx context.Context, readiness qmimanager.UIMReadiness, opts qmimanager.UIMPostSwitchReloadOptions) (uint8, error)
}
// This capability is used only for eSIM recovery, apart from regular radio readiness.
type postSwitchOfflineSIMReloader interface {
SupportsOfflineSIMReload() bool
GetICCIDLive(context.Context) (string, error)
ReloadSIMOffline(context.Context) error
}
type postSwitchSIMPowerController interface {
UIMPowerOffSIM(ctx context.Context, slot uint8) error
UIMPowerOnSIM(ctx context.Context, slot uint8) error
@@ -311,6 +319,48 @@ func effectivePostSwitchReinitWindow(cfg config.ESIMSwitchConfig) time.Duration
return 5 * time.Second
}
func (p *Pool) convergePostSwitchOfflineSIM(deviceID string, token uint64, worker *Worker,
snapshot esimSwitchContext, reloader postSwitchOfflineSIMReloader,
) postSwitchConvergenceResult {
releaseOperation, err := p.AcquireDeviceOperation(deviceID)
if err != nil {
return postSwitchConvergenceResult{Degraded: true, Reason: err.Error()}
}
defer releaseOperation()
transition := p.policyTransitionFor(deviceID)
transition.Lock()
defer transition.Unlock()
if !p.switchTokenStillCurrent(deviceID, token, "offline_sim_reload") || !p.esimSwitchOwnerCurrent(deviceID, worker, snapshot) {
return postSwitchConvergenceResult{Degraded: true, Reason: "switch_superseded"}
}
ctx, cancel := context.WithTimeout(p.Context(), 5*time.Second)
defer cancel()
releaseAT, err := p.acquireDeviceAT(ctx, deviceID)
if err != nil {
return postSwitchConvergenceResult{Degraded: true, Reason: err.Error()}
}
defer releaseAT()
iccid, err := reloader.GetICCIDLive(ctx)
if err != nil {
return postSwitchConvergenceResult{Degraded: true, Reason: err.Error()}
}
current := normalizeSIMIdentityForCompare(iccid)
if current == normalizeSIMIdentityForCompare(snapshot.TargetICCID) {
return postSwitchConvergenceResult{Ready: true, Reason: "target_iccid_already_active"}
}
if current == "" || current != normalizeSIMIdentityForCompare(snapshot.ICCIDBefore) {
return postSwitchConvergenceResult{Degraded: true, Reason: "unexpected_iccid_before_reload"}
}
if err := reloader.ReloadSIMOffline(ctx); err != nil {
return postSwitchConvergenceResult{Degraded: true, Reason: fmt.Sprintf("offline SIM reload: %v", err)}
}
// The common identity refresh still waits for the target ICCID and IMSI.
return postSwitchConvergenceResult{Ready: true, Reason: "offline_sim_reloaded"}
}
func (p *Pool) runPostSwitchConvergence(deviceID string, token uint64, worker *Worker, snapshot esimSwitchContext) postSwitchConvergenceResult {
if worker == nil || worker.Backend == nil {
return postSwitchConvergenceResult{Degraded: true, Reason: "worker_or_backend_missing"}
@@ -318,6 +368,10 @@ func (p *Pool) runPostSwitchConvergence(deviceID string, token uint64, worker *W
if resolvedBackendMode(worker.Config) == backend.BackendPCSC {
return postSwitchConvergenceResult{Ready: true, Reason: "pcsc_card_reset_complete"}
}
if reloader, ok := worker.Backend.(postSwitchOfflineSIMReloader); ok && reloader.SupportsOfflineSIMReload() &&
snapshot.FlightModeBefore && !worker.Config.ESIMSwitch.RadioCycle && normalizeSIMIdentityForCompare(snapshot.TargetICCID) != "" {
return p.convergePostSwitchOfflineSIM(deviceID, token, worker, snapshot, reloader)
}
readiness, ok := worker.Backend.(postSwitchReadinessProvider)
if !ok {
return postSwitchConvergenceResult{Degraded: true, Reason: "uim_readiness_not_supported"}
@@ -206,6 +206,57 @@ func (s *postSwitchRunBackendStub) UIMPowerOnSIM(ctx context.Context, slot uint8
return nil
}
type offlineSIMReloadBackendStub struct {
workerStatusBackendStub
iccid string
reloadCalls int
}
func (s *offlineSIMReloadBackendStub) SupportsOfflineSIMReload() bool { return true }
func (s *offlineSIMReloadBackendStub) GetICCIDLive(context.Context) (string, error) {
return s.iccid, nil
}
func (s *offlineSIMReloadBackendStub) ReloadSIMOffline(context.Context) error {
s.reloadCalls++
return nil
}
func TestPostSwitchOfflineSIMReloadUsesLiveICCID(t *testing.T) {
const deviceID = "dev-1"
const previousICCID = "8985203103011907194"
const targetICCID = "8985203103011907195"
for _, tc := range []struct {
name, liveICCID string
token uint64
radioCycle bool
wantReady bool
wantReloads int
}{
{name: "target already active", liveICCID: targetICCID + "F", token: 2, wantReady: true},
{name: "old ICCID needs reload", liveICCID: previousICCID, token: 2, wantReady: true, wantReloads: 1},
{name: "different live card", liveICCID: "8985203103011907196", token: 2},
{name: "newer switch owns device", liveICCID: previousICCID, token: 1},
{name: "radio cycle may enable RF", liveICCID: previousICCID, token: 2, radioCycle: true},
} {
t.Run(tc.name, func(t *testing.T) {
deviceBackend := &offlineSIMReloadBackendStub{iccid: tc.liveICCID}
worker := &Worker{
ID: deviceID, Backend: deviceBackend,
Config: config.DeviceConfig{ESIMSwitch: config.ESIMSwitchConfig{RadioCycle: tc.radioCycle}},
}
pool := &Pool{workers: map[string]*Worker{deviceID: worker}, switchTokens: map[string]uint64{deviceID: 2}}
snapshot := esimSwitchContext{ICCIDBefore: previousICCID, TargetICCID: targetICCID, FlightModeBefore: true}
result := pool.runPostSwitchConvergence(deviceID, tc.token, worker, snapshot)
if result.Ready != tc.wantReady || result.Degraded == tc.wantReady || deviceBackend.reloadCalls != tc.wantReloads {
t.Fatalf("result=%+v, reloads=%d; want ready=%t and reloads=%d",
result, deviceBackend.reloadCalls, tc.wantReady, tc.wantReloads)
}
})
}
}
func TestRunPostSwitchConvergenceFlagOffUsesLegacyPollingOnly(t *testing.T) {
worker := &Worker{Config: config.DeviceConfig{}}
backend := &postSwitchRunBackendStub{
+82 -6
View File
@@ -7,18 +7,21 @@ import (
"github.com/yibaiba/hideck/internal/backend"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/pkg/logger"
)
func (w *Worker) markSIMRemoved(reason string) {
if w == nil {
return
}
func (w *Worker) markSIMRemoved(reason string, generation uint64) bool {
now := time.Now()
w.cacheMu.Lock()
defer w.cacheMu.Unlock()
strict := w.atDeviceRules().strictSIMIdentity
if strict && w.state.Identity.Generation != generation {
return false
}
hadIdentity := strings.TrimSpace(w.state.Identity.ICCID) != "" ||
strings.TrimSpace(w.state.Identity.IMSI) != "" || w.state.Identity.Ready
if hadIdentity {
if hadIdentity || (strict && w.state.Identity.LastError != "sim_removed") {
w.state.Identity.Generation++
}
w.state.Identity.ICCID = ""
@@ -34,7 +37,75 @@ func (w *Worker) markSIMRemoved(reason string) {
w.state.Meta.IdentityUpdatedAt = now
w.state.Meta.RuntimeUpdatedAt = now
w.state.Meta.UpdatedAt = now
w.cacheMu.Unlock()
return true
}
func (w *Worker) scheduleSIMStatusCheck(source string, inserted *bool, state string) {
if w.Pool == nil {
return
}
owner := workerLifecycleOwner{worker: w, generation: w.generation}
w.Pool.handleSIMStatusEventForOwner(owner, source, inserted, state)
}
func (w *Worker) recordStrictSIMAbsence(generation uint64, source string) {
w.degradeStrictSIMIdentity(generation, source, errATNoSIM)
inserted := false
w.scheduleSIMStatusCheck(source, &inserted, "")
}
func (w *Worker) recordStrictSIMLock(generation uint64, source string) {
if w.Pool != nil && w.Pool.IsESIMSwitching(w.ID) {
return
}
if w.markSIMPINRequired(generation) {
w.scheduleSIMStatusCheck(source, nil, "SIM PIN")
}
}
func (w *Worker) degradeStrictSIMIdentity(generation uint64, reason string, err error) bool {
now := time.Now()
w.cacheMu.Lock()
defer w.cacheMu.Unlock()
if w.state.Identity.Generation != generation || !w.state.Identity.Ready ||
w.state.Identity.Phase == simIdentityPhaseTransitioning {
return false
}
w.markSIMIdentityDegradedLocked(reason, err, now)
w.state.Identity.Generation++
return true
}
func (w *Worker) markSIMPINRequired(generation uint64) bool {
now := time.Now()
w.cacheMu.Lock()
defer w.cacheMu.Unlock()
if w.state.Identity.Generation != generation {
return false
}
if w.state.Identity.LastError == modem.ErrSIMPINRequired.Error() && !w.state.Identity.Ready {
return true
}
w.markSIMIdentityDegradedLocked("sim_pin_required", modem.ErrSIMPINRequired, now)
w.state.Identity.Generation++
w.state.Runtime.SimInserted = false
w.state.Meta.RuntimeUpdatedAt = now
return true
}
// Caller holds the device policy transition lock.
func (p *Pool) handleConfirmedSIMPINRequired(owner workerLifecycleOwner, generation uint64) {
if !p.workerLifecycleOwnerCurrent(owner) || p.IsESIMSwitching(owner.worker.ID) {
return
}
w := owner.worker
if !w.markSIMPINRequired(generation) {
return
}
if err := p.retirePhoneRuntimesForSIMChangeLocked(owner); err != nil {
logger.Warn("SIM PIN 锁定后停止电话业务失败", "device", w.ID, "err", err)
}
p.broadcastVoWiFiStateChange(w.ID)
}
func (p *Pool) retirePhoneRuntimesForSIMChange(owner workerLifecycleOwner) error {
@@ -45,9 +116,14 @@ func (p *Pool) retirePhoneRuntimesForSIMChange(owner workerLifecycleOwner) error
transition := p.policyTransitionFor(deviceID)
transition.Lock()
defer transition.Unlock()
return p.retirePhoneRuntimesForSIMChangeLocked(owner)
}
func (p *Pool) retirePhoneRuntimesForSIMChangeLocked(owner workerLifecycleOwner) error {
if !p.workerLifecycleOwnerCurrent(owner) {
return errPolicyOwnerChanged
}
deviceID := owner.worker.ID
p.stopNativeVoLTE(deviceID, "sim_identity_changed")
if err := p.stopModemVoice(deviceID); err != nil {
return fmt.Errorf("stop modem voice: %w", err)
+346
View File
@@ -2,12 +2,15 @@ package device
import (
"context"
"errors"
"testing"
"time"
"github.com/iniwex5/vowifi-go/runtimehost"
"github.com/yibaiba/hideck/internal/cardpolicy"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/internal/vowifihost"
)
@@ -43,6 +46,42 @@ func TestPhysicalSIMInsertEventRefreshesIdentity(t *testing.T) {
}
}
func TestStaleSIMConfirmationKeepsCurrentWorkerTimer(t *testing.T) {
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
w := &Worker{ID: "dev", Pool: p}
p.AttachWorkerForTest(w)
timer := time.NewTimer(time.Hour)
t.Cleanup(func() { timer.Stop() })
p.simEventMu.Lock()
p.simEventTimers = map[string]*time.Timer{w.ID: timer}
p.simEventMu.Unlock()
old := workerLifecycleOwner{worker: &Worker{ID: w.ID, Pool: p}}
oldTimer := time.NewTimer(time.Hour)
t.Cleanup(func() { oldTimer.Stop() })
p.confirmSIMRemovedForOwner(old, "at_startup", nil)
p.confirmSIMRemovedForOwner(old, "sim_event", oldTimer)
p.simEventMu.Lock()
current := p.simEventTimers[w.ID]
p.simEventTimers[w.ID] = oldTimer
p.simEventMu.Unlock()
if current != timer {
t.Fatal("stale worker consumed the current worker's SIM status timer")
}
// An expired callback can still consume the exact timer it was scheduled for.
p.confirmSIMRemovedForOwner(old, "sim_event", oldTimer)
p.simEventMu.Lock()
current = p.simEventTimers[w.ID]
p.simEventMu.Unlock()
if current != nil {
t.Fatal("expired callback left its own timer registered")
}
}
func TestConfirmedSIMRemovalClearsIdentityAndDatabaseBinding(t *testing.T) {
initDevicePhoneNumberTestDB(t)
p := NewPool(&config.Config{})
@@ -137,6 +176,313 @@ func TestConfirmedSIMRemovalCancelsStartingVoWiFi(t *testing.T) {
}
}
type ml307cSIMBackendStub struct {
workerStartupIdentityBackendStub
simErr error
simAbsent bool
onSIMQuery func()
onICCID func()
sends int
}
func (s *ml307cSIMBackendStub) IsSimInserted(context.Context) (bool, error) {
if s.onSIMQuery != nil {
s.onSIMQuery()
}
return !s.simAbsent && s.simErr == nil, s.simErr
}
func (s *ml307cSIMBackendStub) GetICCIDLive(context.Context) (string, error) {
if s.onICCID != nil {
s.onICCID()
}
return s.liveICCID, nil
}
func (s *ml307cSIMBackendStub) SendSMS(context.Context, string, string) error {
s.sends++
return nil
}
func newML307CIdentityWorker(t *testing.T) (*Pool, *Worker, *ml307cSIMBackendStub) {
t.Helper()
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
cfg := config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"}
m, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C)
if err != nil {
t.Fatal(err)
}
be := &ml307cSIMBackendStub{}
w := &Worker{ID: cfg.ID, Pool: p, Config: cfg, Modem: m, Backend: be}
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-old", IMSI: "imsi-old"})
p.AttachWorkerForTest(w)
t.Cleanup(func() { p.cancelWorkerLifecycleTimers(w.ID) })
return p, w, be
}
func TestML307CIncompleteReadyIdentityBlocksOldCardAndRetries(t *testing.T) {
p, w, be := newML307CIdentityWorker(t)
before := w.SIMIdentityGeneration()
be.liveICCID = "card-new"
p.confirmSIMRemovedAndStopVoWiFi(w.ID, "test")
if !w.SIMIdentityConvergenceMatches("", 0) || w.SIMIdentityGeneration() <= before {
t.Fatal("incomplete live identity left the previous SIM ready")
}
p.SetPolicyResolver(&stubPolicyResolver{pol: cardpolicy.Policy{ICCID: "card-old"}})
if result := p.resolveAndApplyPolicy(w, "test"); result.Applied || !errors.Is(result.Err, errPolicyOwnerChanged) {
t.Fatalf("unready SIM applied cached policy: %+v", result)
}
p.SetPolicyResolver(nil)
be.liveIMSI = "imsi-new"
owner := p.captureWorkerLifecycleOwner(w.ID)
ready := true
p.handleSIMStatusEventForOwner(owner, "test", &ready, "")
p.simEventMu.Lock()
timer := p.simEventTimers[w.ID]
p.simEventMu.Unlock()
if timer == nil || !timer.Stop() {
t.Fatal("subsequent READY did not schedule an identity retry")
}
p.confirmSIMRemovedForOwner(owner, "test", timer)
if w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-new" || w.GetCachedIMSI() != "imsi-new" {
t.Fatal("subsequent READY did not settle on the new identity")
}
before = w.SIMIdentityGeneration()
be.liveIMSI = "imsi-rotated"
if err := w.RefreshIdentityLive(context.Background(), "test"); err != nil || w.SIMIdentityGeneration() <= before {
t.Fatalf("changed IMSI on a stable ICCID did not retire the old generation: %v", err)
}
w.BeginSIMIdentityTransition("target", "test")
be.liveICCID, be.liveIMSI = "", ""
if err := w.RefreshIdentityLive(context.Background(), "test"); err == nil {
t.Fatal("incomplete identity unexpectedly succeeded during the switch")
}
w.cacheMu.RLock()
phase, target := w.state.Identity.Phase, w.state.Identity.TargetICCID
w.cacheMu.RUnlock()
if phase != simIdentityPhaseTransitioning || target != "target" {
t.Fatalf("incomplete read interrupted eSIM identity transition: phase=%s target=%s", phase, target)
}
}
func TestML307CAbsentIdentityBlocksOldCardBeforeDebouncedCleanup(t *testing.T) {
p, w, be := newML307CIdentityWorker(t)
be.simAbsent = true
if err := w.RefreshIdentityLive(context.Background(), "test"); !errors.Is(err, errATNoSIM) {
t.Fatalf("absent SIM returned %v", err)
}
if !w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-old" {
t.Fatal("absent SIM should immediately become unready and keep its binding until confirmation")
}
p.simEventMu.Lock()
timer := p.simEventTimers[w.ID]
p.simEventMu.Unlock()
if timer == nil || !timer.Stop() {
t.Fatal("absent SIM did not schedule debounced cleanup")
}
p.confirmSIMRemovedForOwner(p.captureWorkerLifecycleOwner(w.ID), "test", timer)
if w.CurrentICCID() != "" {
t.Fatal("confirmed absence retained the previous identity")
}
}
func TestML307CAbsentConfirmationDoesNotClearNewerSIM(t *testing.T) {
p, w, be := newML307CIdentityWorker(t)
be.simAbsent = true
be.onSIMQuery = func() {
w.cacheMu.Lock()
defer w.cacheMu.Unlock()
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"})
w.state.Identity.Generation++
}
p.confirmSIMRemovedAndStopVoWiFi(w.ID, "test")
if w.CurrentICCID() != "card-new" || w.SIMIdentityConvergenceMatches("", 0) {
t.Fatal("stale absence cleared the live SIM generation")
}
}
func TestML307CSlowIdentityCannotReviveOlderSIMGeneration(t *testing.T) {
for _, before := range []bool{false, true} {
name := "probe_presence"
if before {
name = "confirmed_presence"
}
t.Run(name, func(t *testing.T) {
_, w, be := newML307CIdentityWorker(t)
be.liveICCID, be.liveIMSI = "card-old", "imsi-old"
started, finish := make(chan struct{}), make(chan struct{})
be.onICCID = func() {
close(started)
<-finish
}
done := make(chan error, 1)
go func() {
_, err := w.refreshIdentityLiveWithPresence(context.Background(), "old-read", before)
done <- err
}()
<-started
generation := w.BeginSIMIdentityTransition("target", "test")
close(finish)
if err := <-done; !errors.Is(err, ErrSMSIdentityTransitioning) {
t.Fatalf("superseded identity read returned %v", err)
}
if !w.SIMIdentityConvergenceMatches("target", generation) || currentSIMOwnership(w).iccid != "" {
t.Fatal("superseded read reset the current identity transition")
}
})
}
}
func confirmScheduledSIMPIN(t *testing.T, p *Pool, owner workerLifecycleOwner) {
t.Helper()
p.simEventMu.Lock()
timer := p.simEventTimers[owner.worker.ID]
p.simEventMu.Unlock()
if timer == nil {
t.Fatal("PIN event did not schedule a SIM status check")
}
if !timer.Stop() {
t.Fatal("SIM status check ran before the test could confirm it")
}
p.confirmSIMStatusForOwner(owner, "test", timer, true)
}
func TestML307CDelayedPINKeepsCurrentSIMAndCall(t *testing.T) {
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
cfg := config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"}
m, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C)
if err != nil {
t.Fatal(err)
}
be := &ml307cSIMBackendStub{}
be.liveICCID, be.liveIMSI = "card-new", "imsi-new"
w := &Worker{ID: cfg.ID, Pool: p, Config: cfg, Modem: m, Backend: be}
p.AttachWorkerForTest(w)
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-old", IMSI: "imsi-old"})
w.state.Identity.Generation++
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"})
w.state.Identity.Generation++
before := currentSIMOwnership(w)
owner := p.captureWorkerLifecycleOwner(w.ID)
instance := &runtimehost.Instance{}
p.voWiFiRuntimeStore().SetInstance(w.ID, instance)
t.Cleanup(func() { p.voWiFiRuntimeStore().DeleteInstance(w.ID, nil) })
stops := 0
p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, _ vowifihost.LifecycleCommand) error {
stops++
return nil
}
p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PIN")
confirmScheduledSIMPIN(t, p, owner)
if got := currentSIMOwnership(w); got != before || w.SIMIdentityConvergenceMatches("", 0) {
t.Fatalf("stale PIN changed ready SIM ownership: before=%+v after=%+v", before, got)
}
if stops != 0 {
t.Fatalf("stale PIN stopped an active runtime %d times", stops)
}
p.switchMu.Lock()
p.switchingDevices[w.ID] = true
p.switchMu.Unlock()
be.simErr = modem.ErrSIMPINRequired
p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PIN")
confirmScheduledSIMPIN(t, p, owner)
if got := currentSIMOwnership(w); got != before || stops != 0 {
t.Fatalf("PIN during eSIM switch changed SIM ownership or stopped calls: before=%+v after=%+v stops=%d", before, got, stops)
}
p.switchMu.Lock()
delete(p.switchingDevices, w.ID)
p.switchMu.Unlock()
// A separate live identity refresh can publish a new generation while
// the PIN confirmation reads the backend.
be.onSIMQuery = func() {
w.cacheMu.Lock()
defer w.cacheMu.Unlock()
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-newer", IMSI: "imsi-newer"})
w.state.Identity.Generation++
}
p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PIN")
confirmScheduledSIMPIN(t, p, owner)
if got := currentSIMOwnership(w); got.iccid != "card-newer" || got.generation != before.generation+1 ||
w.SIMIdentityConvergenceMatches("", 0) || stops != 0 {
t.Fatalf("old PIN result affected a newer SIM generation: ownership=%+v stops=%d", got, stops)
}
}
func TestML307CPINRecoveryRetriesIdentityOnRepeatedReady(t *testing.T) {
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
cfg := config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"}
m, err := modem.NewWithATProfile(cfg, modem.ATProfileML307C)
if err != nil {
t.Fatal(err)
}
be := &ml307cSIMBackendStub{simErr: modem.ErrSIMPINRequired}
w := &Worker{ID: cfg.ID, Pool: p, Config: cfg, Modem: m, Backend: be}
setWorkerSMSIdentity(w, SMSIdentity{ICCID: "card-old", IMSI: "imsi-old"})
p.AttachWorkerForTest(w)
owner := p.captureWorkerLifecycleOwner(w.ID)
t.Cleanup(func() { p.cancelWorkerLifecycleTimers(w.ID) })
p.voWiFiRuntimeStore().SetInstance(w.ID, &runtimehost.Instance{})
t.Cleanup(func() { p.voWiFiRuntimeStore().DeleteInstance(w.ID, nil) })
commands := make(chan vowifihost.LifecycleCommand, 1)
p.voWiFiHost().LifecycleControllerForTest().TestRun = func(_ context.Context, command vowifihost.LifecycleCommand) error {
commands <- command
return nil
}
p.handleSIMStatusEventForOwner(owner, "test", nil, "SIM PUK")
confirmScheduledSIMPIN(t, p, owner)
select {
case command := <-commands:
if command.Kind != vowifihost.LifecycleCommandDisable {
t.Fatalf("PIN lock lifecycle command = %s", command.Kind)
}
default:
t.Fatal("PIN lock left the old VoWiFi runtime active")
}
p.voWiFiRuntimeStore().DeleteInstance(w.ID, nil)
if !w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-old" {
t.Fatal("PIN lock must block the old identity and preserve its binding")
}
if err := p.refreshModemRebootRecoveredIdentity(w, "manual_reboot"); err != nil {
t.Fatalf("PIN lock must allow control-plane recovery: %v", err)
}
be.simErr = nil
ready := true
confirmPoll := func() {
t.Helper()
p.handleSIMStatusEventForOwner(owner, "test", &ready, "")
p.simEventMu.Lock()
timer := p.simEventTimers[w.ID]
p.simEventMu.Unlock()
if timer == nil {
t.Fatal("READY did not schedule SIM identity convergence")
}
timer.Stop()
p.confirmSIMRemovedForOwner(owner, "test", timer)
}
confirmPoll() // CPIN says READY, but the first live ICCID/IMSI read is empty.
if !w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-old" {
t.Fatal("failed identity refresh must leave SIM convergence pending")
}
be.liveICCID, be.liveIMSI = "card-new", "imsi-new"
confirmPoll()
if w.SIMIdentityConvergenceMatches("", 0) || w.CurrentICCID() != "card-new" {
t.Fatalf("repeated READY did not converge to the fresh ICCID: %q", w.CurrentICCID())
}
}
func TestConfirmedSIMInsertionWaitsForActiveMBNPolicy(t *testing.T) {
p := NewPool(&config.Config{})
t.Cleanup(func() { _ = p.Shutdown() })
+732
View File
@@ -0,0 +1,732 @@
package device
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/internal/smsnotify"
"github.com/yibaiba/hideck/pkg/logger"
"github.com/yibaiba/hideck/pkg/smscodec"
)
var storedSMSStores = [...]string{"ME", "SM"}
type storedSMSOwner struct {
workerLifecycleOwner
SMSIdentity
simGeneration uint64
}
func (w *Worker) storedSMSOwner() (storedSMSOwner, error) {
w.cacheMu.RLock()
id := w.state.Identity
w.cacheMu.RUnlock()
identity := normalizeSMSIdentity(SMSIdentity{ICCID: id.ICCID, IMSI: id.IMSI})
if !id.Ready || id.Phase != simIdentityPhaseReady || identity.ICCID == "" || identity.IMSI == "" {
return storedSMSOwner{}, ErrSMSIdentityUnknown
}
return storedSMSOwner{
workerLifecycleOwner: workerLifecycleOwner{worker: w, generation: w.generation},
SMSIdentity: identity, simGeneration: id.Generation,
}, nil
}
func (owner storedSMSOwner) check() error {
w := owner.worker
if !w.Pool.workerLifecycleOwnerCurrent(owner.workerLifecycleOwner) ||
w.Pool.IsESIMSwitching(w.ID) || !w.Modem.StoredSMSReceiving() {
return ErrSMSIdentityTransitioning
}
current, err := w.storedSMSOwner()
if err != nil || current != owner {
return ErrSMSIdentityTransitioning
}
return nil
}
type storedSMSIdentityReader interface {
QuerySIMInserted() (bool, error)
QueryICCID() (string, error)
QueryIMSI() (string, error)
}
func (owner storedSMSOwner) verifyLive() error {
return owner.verifyLiveFrom(owner.worker.Modem)
}
func (owner storedSMSOwner) verifyLiveFrom(reader storedSMSIdentityReader) error {
if err := owner.check(); err != nil {
return err
}
inserted, err := reader.QuerySIMInserted()
if err != nil {
return err
}
if !inserted {
return ErrSMSIdentityUnknown
}
iccid, err := reader.QueryICCID()
if err != nil {
return err
}
imsi, err := reader.QueryIMSI()
if err != nil {
return err
}
if err := owner.check(); err != nil {
return err
}
live := normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi})
switch {
case live.ICCID == "" || live.IMSI == "":
err = ErrSMSIdentityUnknown
case live != owner.SMSIdentity:
err = ErrSMSIdentityConflict
}
if err != nil && owner.worker.atDeviceRules().strictSIMIdentity {
return owner.worker.rejectLiveCSSMSIdentity(owner.simGeneration, "at_sms_inbox_identity", err)
}
return err
}
// A CMTI only proves provenance within the current worker and SIM generation.
type storedSMSSlot struct {
store string
index int
}
type storedSMSNotice struct {
owner storedSMSOwner
slot storedSMSSlot
observedAt time.Time
pdu string // Set under the notice lock after the first successful read.
}
type storedSMSNotices struct {
mu sync.Mutex
slots map[storedSMSSlot]*storedSMSNotice
}
func (notices *storedSMSNotices) add(notice *storedSMSNotice) {
notices.mu.Lock()
defer notices.mu.Unlock()
if notices.slots == nil {
notices.slots = make(map[storedSMSSlot]*storedSMSNotice)
}
notices.slots[notice.slot] = notice
}
func (notices *storedSMSNotices) snapshot(owner storedSMSOwner, store string) map[int]*storedSMSNotice {
notices.mu.Lock()
defer notices.mu.Unlock()
var pending map[int]*storedSMSNotice
for slot, notice := range notices.slots {
if notice.owner != owner {
if notice.owner.workerLifecycleOwner == owner.workerLifecycleOwner && notice.owner.simGeneration < owner.simGeneration {
delete(notices.slots, slot)
}
} else if slot.store == store {
if pending == nil {
pending = make(map[int]*storedSMSNotice)
}
pending[slot.index] = notice
}
}
return pending
}
func (notices *storedSMSNotices) current(notice *storedSMSNotice) bool {
notices.mu.Lock()
defer notices.mu.Unlock()
return notices.slots[notice.slot] == notice
}
func (notices *storedSMSNotices) bind(notice *storedSMSNotice, pdu string) bool {
notices.mu.Lock()
defer notices.mu.Unlock()
if notice == nil || notices.slots[notice.slot] != notice {
return false
}
if notice.pdu != "" && !strings.EqualFold(notice.pdu, pdu) {
// A previously read slot has been replaced. Only its new CMTI can
// establish provenance for the replacement.
delete(notices.slots, notice.slot)
return false
}
notice.pdu = pdu
return true
}
func (notices *storedSMSNotices) forget(notice *storedSMSNotice) {
if notice == nil {
return
}
notices.mu.Lock()
defer notices.mu.Unlock()
if notices.slots[notice.slot] == notice {
delete(notices.slots, notice.slot)
}
}
func (w *Worker) handleStoredSMS(storage, index string) {
slot, err := strconv.Atoi(index)
if err != nil || slot < 0 || slot > 65535 || (storage != "ME" && storage != "SM") {
return
}
// Capture before queuing the work. A delayed URC must keep its original
// worker and SIM generation across eSIM and physical card changes.
owner, err := w.storedSMSOwner()
if err != nil {
return
}
notice := &storedSMSNotice{
owner: owner, slot: storedSMSSlot{store: storage, index: slot}, observedAt: time.Now(),
}
w.storedSMSNotices.add(notice)
go w.receiveStoredSMS(owner, notice)
}
// scanATSMS polls the stored inbox when the active AT SMS path enables it.
func (w *Worker) scanATSMS() {
if w.Modem == nil || !w.Modem.StoredSMSReceiving() {
return
}
owner, err := w.storedSMSOwner()
if err != nil {
return
}
w.receiveStoredSMS(owner, nil)
}
func (w *Worker) receiveStoredSMS(owner storedSMSOwner, notice *storedSMSNotice) {
var notifications []InboundSMS
if err := w.readStoredSMSInbox(owner, notice, &notifications); err != nil {
logger.Warn("AT 短信收件未完成", "device", w.ID, "err", err)
}
for _, inbound := range notifications {
w.Pool.notifyInboundSMS(inbound)
if notifier := w.Pool.getNotifier(); notifier != nil {
notifySMS(notifier, inbound, "")
}
}
}
func (w *Worker) readStoredSMSInbox(owner storedSMSOwner, notice *storedSMSNotice, notifications *[]InboundSMS) error {
// The eSIM manager uses the same transition lock. Take it before the
// serial inbox lock, matching the lock order used for sending.
release, err := w.Pool.AcquireDeviceOperation(w.ID)
if err != nil {
return err
}
defer release()
transition := w.Pool.policyTransitionFor(w.ID)
transition.Lock()
defer transition.Unlock()
gateCtx, cancelGate := context.WithTimeout(w.Pool.Context(), 5*time.Second)
defer cancelGate()
releaseAT, err := w.Pool.acquireDeviceAT(gateCtx, w.ID)
if err != nil {
return err
}
defer releaseAT()
if err := owner.verifyLive(); err != nil {
return err
}
scope := db.SMSInboundFragmentScope{DeviceID: w.ID, ICCID: owner.ICCID, IMSI: owner.IMSI}
return w.Modem.WithSMSInbox(func(inbox *modem.SMSInbox) error {
state, err := loadATSMSParts(scope)
if err != nil {
return err
}
if notice != nil {
if !w.storedSMSNotices.current(notice) {
return nil
}
if err := inbox.Select(notice.slot.store); err != nil {
return err
}
record, err := inbox.Read(notice.slot.index)
if err != nil {
return err
}
if err := owner.verifyLive(); err != nil {
return err
}
return w.ingestStoredSMSSlot(inbox, owner, state, record, notice.slot.store == "SM", notice, notifications)
}
var scanErr error
scanIncomplete := false
for _, store := range storedSMSStores {
if err := inbox.Select(store); err != nil {
scanErr = errors.Join(scanErr, err)
scanIncomplete = true
continue
}
// Only notices already observed before this snapshot can identify
// a listed PDU. A newer CMTI may refer to a reused slot.
pending := w.storedSMSNotices.snapshot(owner, store)
records, err := inbox.List()
if err != nil {
scanErr = errors.Join(scanErr, err)
scanIncomplete = true
continue
}
if err := owner.verifyLive(); err != nil {
return errors.Join(scanErr, err)
}
for _, record := range records {
notice := pending[record.Index]
delete(pending, record.Index)
if err := w.ingestStoredSMSSlot(inbox, owner, state, record, store == "SM", notice, notifications); err != nil {
scanErr = errors.Join(scanErr, err)
}
}
for _, absent := range pending {
w.storedSMSNotices.forget(absent)
}
}
if scanIncomplete {
return scanErr
}
if err := owner.check(); err != nil {
return errors.Join(scanErr, err)
}
recovered, err := state.archiveSettledATFragments(time.Now())
*notifications = append(*notifications, recovered...)
if err != nil || scanErr != nil {
return errors.Join(scanErr, err)
}
return state.clearCompletedGroups()
})
}
func (w *Worker) ingestStoredSMSSlot(inbox *modem.SMSInbox, owner storedSMSOwner, state *atSMSParts, record modem.SMSPDURecord, sourceKnown bool, notice *storedSMSNotice, notifications *[]InboundSMS) error {
if !record.Received() {
w.storedSMSNotices.forget(notice)
return nil
}
if err := owner.check(); err != nil {
return err
}
if notice != nil && !w.storedSMSNotices.bind(notice, record.PDU) {
return nil
}
part, err := decodeATInboxPart(owner.SMSIdentity, record.PDU)
if err != nil {
return fmt.Errorf("SMS slot %d: %w", record.Index, err)
}
if notice != nil {
part.observedAt = notice.observedAt
sourceKnown = true
}
stored, inbound, err := state.persist(part, sourceKnown)
if err != nil {
return fmt.Errorf("persist SMS slot %d: %w", record.Index, err)
}
if inbound != nil {
*notifications = append(*notifications, *inbound)
}
if !stored {
return nil
}
if err := inbox.DeleteMatching(record, owner.verifyLive); err != nil {
return fmt.Errorf("delete persisted SMS slot %d: %w", record.Index, err)
}
w.storedSMSNotices.forget(notice)
return nil
}
type atInboxPart struct {
smscodec.ATDeliverSMS
key string
family string
fingerprint [32]byte
observedAt time.Time
}
func decodeATInboxPart(identity SMSIdentity, pduHex string) (atInboxPart, error) {
raw, err := hex.DecodeString(pduHex)
if err != nil {
return atInboxPart{}, errors.New("invalid SMS PDU hex")
}
decoded, err := smscodec.DecodeATDeliverSMS(raw)
if err != nil || decoded.Sender == "" || decoded.Timestamp.IsZero() {
return atInboxPart{}, errors.New("cannot decode stored SMS-DELIVER")
}
fingerprint := sha256.Sum256(raw)
key := fmt.Sprintf("%ssingle:%x", db.ATSMSInboundPrefix, fingerprint)
var family string
concat := decoded.Concat
if concat.IsConcat {
if concat.Seq < 1 || concat.Seq > concat.Total {
return atInboxPart{}, errors.New("invalid SMS fragment sequence")
}
group := fmt.Sprintf("%q:%q:%d:%d:%d:%s", identity.IMSI, decoded.Sender, concat.RefBits, concat.Ref, concat.Total, decoded.SCTS)
key = fmt.Sprintf("%sparts:%x", db.ATSMSInboundPrefix, sha256.Sum256([]byte(group)))
origin := fmt.Sprintf("%q:%q:%q:%d:%d:%d:%d:%d:%q", identity.IMSI, decoded.Sender, decoded.SMSC,
decoded.PID, decoded.DCS, concat.RefBits, concat.Ref, concat.Total, decoded.ApplicationPorts)
family = fmt.Sprintf("%x", sha256.Sum256([]byte(origin)))
if decoded.ApplicationPorts != "" {
// Application-addressed text needs an exact SCTS and port match.
family = "app-" + family
}
}
return atInboxPart{ATDeliverSMS: decoded, key: key, family: family, fingerprint: fingerprint}, nil
}
type atSMSParts struct {
scope db.SMSInboundFragmentScope
groups map[string][]db.SMSInboundFragment
seen map[string]bool
observed map[atSMSFragmentObservation]string
blockedFamilies map[string]bool
}
type atSMSFragmentObservation struct {
sessionKey string
sequence int
fingerprint string
}
func loadATSMSParts(scope db.SMSInboundFragmentScope) (*atSMSParts, error) {
rows, err := db.LoadSMSInboundFragments(scope)
if err != nil {
return nil, err
}
state := &atSMSParts{
scope: scope, groups: make(map[string][]db.SMSInboundFragment),
seen: make(map[string]bool), observed: make(map[atSMSFragmentObservation]string), blockedFamilies: make(map[string]bool),
}
for _, row := range rows {
if strings.HasPrefix(row.SessionKey, db.ATSMSInboundPrefix) {
state.groups[row.SessionKey] = append(state.groups[row.SessionKey], row)
}
}
return state, nil
}
func (state *atSMSParts) persist(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) {
if part.Concat.IsConcat {
if part.Binary {
state.seen[part.key] = true
return false, nil, nil
}
if sourceKnown && part.observedAt.IsZero() {
part.observedAt = time.Now()
}
stored, inbound, err := state.persistFragment(part, sourceKnown)
if err != nil {
// The scan saw an exact piece for this family. If it could
// not be recorded, its older partial groups are insufficient
// evidence for any cross-SCTS assembly in this scan.
state.blockedFamilies[part.family] = true
}
return stored, inbound, err
}
if smsnotify.ShouldSuppressReceivedSMS(part.Content) {
return false, nil, nil
}
if !sourceKnown {
// The single-part session key already hashes the full PDU.
found, err := db.HasATSMSReceipt(state.scope.ICCID, state.scope.IMSI, part.key)
return found, nil, err
}
return state.commit(part, part.Content)
}
const (
atSMSPartGroupPrefix = db.ATSMSInboundPrefix + "parts:v2:"
atSMSReassemblyWindow = 2 * time.Minute
)
func (state *atSMSParts) fragmentGroup(part atInboxPart, fingerprint string, sourceKnown bool) (string, bool, error) {
matches := func(saved db.SMSInboundFragment) bool {
if saved.PDUFingerprint != "" {
return saved.PDUFingerprint == fingerprint
}
return sourceKnown && saved.Content == part.Content
}
// Older fragments only have the legacy exact-SCTS key. It remains valid
// for exact matches, but cannot prove the new metadata for a fuzzy join.
if fragments := state.groups[part.key]; len(fragments) != 0 {
for _, saved := range fragments {
if saved.Sequence == part.Concat.Seq {
if matches(saved) {
return part.key, true, nil
}
if sourceKnown {
return "", false, db.ErrSMSInboundFragmentCollision
}
break
}
}
if sourceKnown {
return part.key, false, nil
}
return "", false, nil
}
prefix := atSMSPartGroupPrefix + part.family + ":" + part.SCTS + ":"
var duplicates, candidates []string
for key, fragments := range state.groups {
if !strings.HasPrefix(key, prefix) {
continue
}
occupied := false
for _, saved := range fragments {
if saved.Sequence == part.Concat.Seq {
occupied = true
if matches(saved) {
duplicates = append(duplicates, key)
}
break
}
}
// An ME slot with no CMTI can retry only an already persisted PDU.
if sourceKnown && !occupied && len(fragments) < part.Concat.Total {
candidates = append(candidates, key)
}
}
switch {
case len(duplicates) > 1 || len(duplicates) == 0 && len(candidates) > 1:
return "", false, db.ErrSMSInboundFragmentCollision
case len(duplicates) == 1:
return duplicates[0], true, nil
case len(candidates) == 1:
return candidates[0], false, nil
case sourceKnown:
return fmt.Sprintf("%s%d:%x", prefix, part.observedAt.UnixNano(), part.fingerprint), false, nil
default:
return "", false, nil
}
}
func (state *atSMSParts) persistFragment(part atInboxPart, sourceKnown bool) (bool, *InboundSMS, error) {
fingerprint := hex.EncodeToString(part.fingerprint[:])
key, matched, err := state.fragmentGroup(part, fingerprint, sourceKnown)
if err != nil || key == "" {
return false, nil, err
}
state.seen[key] = true
fragments := state.groups[key]
if !matched {
scope := state.scope
scope.SessionKey = key
concat := part.Concat
result, err := db.SaveSMSInboundFragment(scope, db.SMSInboundFragment{
Sequence: concat.Seq, Reference: concat.Ref, ReferenceBits: concat.RefBits,
Total: concat.Total, Content: part.Content, ArrivedAt: part.Timestamp,
PDUFingerprint: fingerprint,
})
if err != nil {
return false, nil, err
}
fragments = result.Fragments
state.groups[key] = fragments
}
state.observed[atSMSFragmentObservation{key, part.Concat.Seq, fingerprint}] = part.Sender
if len(fragments) < part.Concat.Total {
// Keep the source while other exact groups can still arrive.
return false, nil, nil
}
part.key, part.Content, err = completeATMultipart(key, fragments)
if err != nil {
return false, nil, err
}
part.Timestamp = fragments[0].ArrivedAt
return state.commit(part, part.Content)
}
func (state *atSMSParts) archiveSettledATFragments(now time.Time) ([]InboundSMS, error) {
observedSender := func(fragment db.SMSInboundFragment) string {
return state.observed[atSMSFragmentObservation{fragment.SessionKey, fragment.Sequence, fragment.PDUFingerprint}]
}
var notifications []InboundSMS
for _, fragments := range state.settledATFragments(now) {
// Each fragment must match a PDU observed in the current scan.
if slices.ContainsFunc(fragments, func(fragment db.SMSInboundFragment) bool {
return observedSender(fragment) == ""
}) {
continue
}
sender := observedSender(fragments[0])
key, content, err := completeATMultipart(fragments[0].SessionKey, fragments)
if err != nil {
return notifications, err
}
part := atInboxPart{key: key, ATDeliverSMS: smscodec.ATDeliverSMS{Sender: sender, Timestamp: fragments[0].ArrivedAt}}
_, inbound, err := state.commit(part, content)
if err != nil {
return notifications, err
}
if inbound != nil {
notifications = append(notifications, *inbound)
}
// Keep cross-SCTS source slots and exact fragment rows for retry.
}
return notifications, nil
}
// settledATFragments only identifies candidates. The caller must first finish
// a complete scan and commit a candidate before touching its storage slots.
func (state *atSMSParts) settledATFragments(now time.Time) [][]db.SMSInboundFragment {
type observedGroup struct {
at time.Time
parts []db.SMSInboundFragment
}
families := make(map[string][]observedGroup)
for key, parts := range state.groups {
if len(parts) == 0 || len(parts) >= parts[0].Total {
continue
}
body, ok := strings.CutPrefix(key, atSMSPartGroupPrefix)
if !ok {
continue // Legacy groups lack the SMSC and coding metadata.
}
fields := strings.Split(body, ":")
if len(fields) != 4 || strings.HasPrefix(fields[0], "app-") || state.blockedFamilies[fields[0]] {
continue
}
observed, err := strconv.ParseInt(fields[2], 10, 64)
if err != nil {
continue
}
families[fields[0]] = append(families[fields[0]], observedGroup{time.Unix(0, observed), parts})
}
var settled [][]db.SMSInboundFragment
for _, groups := range families {
slices.SortFunc(groups, func(a, b observedGroup) int { return a.at.Compare(b.at) })
for start := 0; start < len(groups); {
end := start + 1
for end < len(groups) && groups[end].at.Sub(groups[end-1].at) <= atSMSReassemblyWindow {
end++
}
window := groups[start:end]
start = end
last := window[len(window)-1].at
if len(window) < 2 || last.Sub(window[0].at) > atSMSReassemblyWindow || now.Sub(last) < atSMSReassemblyWindow {
continue
}
var parts []db.SMSInboundFragment
for _, group := range window {
parts = append(parts, group.parts...)
}
if assembled := uniqueATFragmentSet(parts); assembled != nil {
settled = append(settled, assembled)
}
}
}
return settled
}
func uniqueATFragmentSet(parts []db.SMSInboundFragment) []db.SMSInboundFragment {
if len(parts) != parts[0].Total {
return nil
}
ordered := make([]db.SMSInboundFragment, len(parts))
earliest, latest := parts[0].ArrivedAt, parts[0].ArrivedAt
for _, part := range parts {
if part.Total != len(ordered) || part.Sequence < 1 || part.Sequence > len(ordered) ||
ordered[part.Sequence-1].Sequence != 0 {
return nil
}
ordered[part.Sequence-1] = part
if part.ArrivedAt.Before(earliest) {
earliest = part.ArrivedAt
}
if part.ArrivedAt.After(latest) {
latest = part.ArrivedAt
}
}
if latest.Sub(earliest) > atSMSReassemblyWindow {
return nil
}
return ordered
}
func completeATMultipart(key string, fragments []db.SMSInboundFragment) (string, string, error) {
var content strings.Builder
var signature strings.Builder
family, _, versioned := strings.Cut(strings.TrimPrefix(key, atSMSPartGroupPrefix), ":")
versioned = versioned && strings.HasPrefix(key, atSMSPartGroupPrefix)
for i, fragment := range fragments {
if fragment.Sequence != i+1 || fragment.Total != len(fragments) {
return "", "", db.ErrSMSInboundFragmentCollision
}
content.WriteString(fragment.Content)
if versioned {
fields := strings.Split(strings.TrimPrefix(fragment.SessionKey, atSMSPartGroupPrefix), ":")
if len(fields) != 4 || fields[0] != family {
return "", "", db.ErrSMSInboundFragmentCollision
}
fmt.Fprintf(&signature, "%s:%q;", fields[1], fragment.Content)
}
}
if versioned {
// Independent of which part arrived first or which worker read it.
key = fmt.Sprintf("%sparts:complete:v2:%x", db.ATSMSInboundPrefix, sha256.Sum256([]byte(family+":"+signature.String())))
}
return key, content.String(), nil
}
func (state *atSMSParts) commit(part atInboxPart, content string) (bool, *InboundSMS, error) {
timestamp := correctSMSCTimestamp(state.scope.DeviceID, state.scope.IMSI, part.Timestamp, time.Now())
result, err := db.SaveReceivedMultipartSMS(db.ReceivedMultipartSMS{
ICCID: state.scope.ICCID, IMSI: state.scope.IMSI,
Sender: part.Sender, Content: content, Timestamp: timestamp, FragmentSessionKey: part.key,
})
if err != nil {
return false, nil, err
}
if !result.Created {
// History dedup follows ICCID. Slot deletion also requires the
// receipt to attest the current IMSI.
found, err := db.HasATSMSReceipt(state.scope.ICCID, state.scope.IMSI, part.key)
return found, nil, err
}
return true, &InboundSMS{
DeviceID: state.scope.DeviceID, ICCID: state.scope.ICCID, IMSI: state.scope.IMSI,
Sender: part.Sender, Content: content, Time: timestamp,
}, nil
}
func (state *atSMSParts) clearCompletedGroups() error {
for key, fragments := range state.groups {
if state.seen[key] || len(fragments) != fragments[0].Total {
continue
}
if slices.ContainsFunc(fragments, func(part db.SMSInboundFragment) bool {
return part.DeviceID != state.scope.DeviceID
}) {
continue
}
completedKey, _, err := completeATMultipart(key, fragments)
if err != nil {
return err
}
found, err := db.HasATSMSReceipt(state.scope.ICCID, state.scope.IMSI, completedKey)
if err != nil {
return err
}
if found {
scope := state.scope
scope.SessionKey = key
if err := db.DeleteSMSInboundFragments(scope); err != nil {
return err
}
}
}
return nil
}
+517
View File
@@ -0,0 +1,517 @@
package device
import (
"context"
"encoding/hex"
"errors"
"path/filepath"
"testing"
"time"
"github.com/yibaiba/hideck/internal/db"
)
func TestATStoredSMSPersistence(t *testing.T) {
dbPath := filepath.Join(t.TempDir(), "at-sms.db")
open := func() {
t.Helper()
if err := db.Init(dbPath); err != nil {
t.Fatal(err)
}
}
closeDB := func() {
t.Helper()
sqlDB, err := db.DB.DB()
if err != nil {
t.Fatal(err)
}
if err := sqlDB.Close(); err != nil {
t.Fatal(err)
}
}
open()
t.Cleanup(func() {
closeDB()
db.DB = nil
})
identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"}
scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI}
multipart := func(total, seq, minute, second byte, ch rune, observed time.Time, extraUDH ...byte) atInboxPart {
t.Helper()
pdu := []byte{
0, // default SMSC
0x40, 3, 0x81, 0x77, 0xF7, // SMS-DELIVER, UDHI, sender 777
0, 8, // PID, UCS2
0x62, 0x11, 0x91, 0x21, minute, second, 0, // SCTS
byte(8 + len(extraUDH)), byte(5 + len(extraUDH)), 0, 3, 17, total, seq,
}
pdu = append(pdu, extraUDH...)
pdu = append(pdu, byte(ch>>8), byte(ch))
part, err := decodeATInboxPart(identity, hex.EncodeToString(pdu))
if err != nil {
t.Fatal(err)
}
if !part.Concat.IsConcat || part.Sender != "777" || part.Content != string(ch) {
t.Fatalf("unexpected decoded part: %+v", part)
}
part.observedAt = observed
return part
}
fragment := func(seq, minute, second byte, ch rune, observed time.Time, extraUDH ...byte) atInboxPart {
t.Helper()
return multipart(2, seq, minute, second, ch, observed, extraUDH...)
}
load := func(scope db.SMSInboundFragmentScope) *atSMSParts {
t.Helper()
state, err := loadATSMSParts(scope)
if err != nil {
t.Fatal(err)
}
return state
}
apply := func(state *atSMSParts, part atInboxPart, sourceKnown, wantStored bool, wantContent string) {
t.Helper()
stored, notification, err := state.persist(part, sourceKnown)
if err != nil || stored != wantStored {
t.Fatalf("persist = %t, %v, want %t", stored, err, wantStored)
}
if wantContent == "" {
if notification != nil {
t.Fatalf("unexpected notification: %+v", notification)
}
} else if notification == nil || notification.Content != wantContent {
t.Fatalf("notification = %+v, want %q", notification, wantContent)
}
}
lookupHistory := func(key string) (db.SMS, bool, error) {
var row db.SMS
query := db.DB.Where("iccid = ? AND imsi = ? AND fragment_session_key = ?", scope.ICCID, scope.IMSI, key).
Limit(1).Find(&row)
return row, query.RowsAffected == 1, query.Error
}
observed := time.Now()
a1 := fragment(1, 0, 0, '甲', observed)
a2 := fragment(2, 0, 0, '乙', observed.Add(2*time.Second))
b1 := fragment(1, 0, 0x10, '丙', observed.Add(3*time.Second))
b2 := fragment(2, 0, 0x10, '丁', observed.Add(time.Second))
state := load(scope)
apply(state, a1, false, false, "") // unknown ME: no history and no delete.
apply(state, a1, true, false, "") // CMTI proves provenance, but an incomplete message retains its source slot.
state = load(scope)
if len(state.groups) != 1 {
t.Fatalf("first fragment was not restored: %+v", state.groups)
}
// A stale ME slot from another SIM can have the same sender, reference,
// SCTS and total as this SIM's pending first part.
otherSIM := scope
otherSIM.ICCID = "8988110000000000003"
staleTail := fragment(2, 0, 0, '异', observed)
apply(load(otherSIM), staleTail, true, false, "")
apply(state, staleTail, false, false, "")
if len(state.groups) != 1 {
t.Fatal("unknown ME tail created another group")
}
for _, group := range state.groups {
if len(group) != 1 {
t.Fatal("unknown ME tail filled a pending sequence")
}
}
apply(state, b2, true, false, "") // Another message reused the ref inside the collection window.
if got := state.settledATFragments(observed.Add(time.Second)); len(got) != 0 {
t.Fatal("merged A1 and B2 before their exact partners arrived")
}
apply(state, a2, true, true, "甲乙")
apply(state, b1, true, true, "丙丁")
if got := state.settledATFragments(observed.Add(5 * time.Minute)); len(got) != 0 {
t.Fatal("already complete exact messages must not be merged")
}
state = load(scope)
// A different, unrecognised UDH IE leaves the decoded text and all
// grouping metadata equal but changes the raw PDU.
differentPDU := fragment(2, 0, 0, '乙', observed, 0x70, 1, 0x01)
if differentPDU.family != a2.family || differentPDU.key != a2.key || differentPDU.fingerprint == a2.fingerprint {
t.Fatalf("raw mismatch fixture: %+v", differentPDU)
}
apply(state, differentPDU, false, false, "")
exactKey := ""
for key, group := range state.groups {
if group[0].Content == a1.Content {
var err error
exactKey, _, err = completeATMultipart(key, group)
if err != nil {
t.Fatal(err)
}
}
}
exact, found, err := lookupHistory(exactKey)
if err != nil || !found {
t.Fatalf("exact archived SMS: %+v, %v, %v", exact, found, err)
}
if _, _, _, err := db.DeleteSMSByID(exact.ID); err != nil {
t.Fatal(err)
}
closeDB()
open()
state = load(scope)
apply(state, a2, false, true, "") // A failed deletion can retry from durable evidence.
if err := state.clearCompletedGroups(); err != nil {
t.Fatal(err)
}
if len(load(scope).groups) != 1 {
t.Fatal("a scan containing a residual slot retired its fragment rows")
}
otherDevice := scope
otherDevice.DeviceID = "c-other"
if err := load(otherDevice).clearCompletedGroups(); err != nil {
t.Fatal(err)
}
if len(load(scope).groups) != 1 {
t.Fatal("another module's empty scan retired the original module's fragments")
}
if err := load(scope).clearCompletedGroups(); err != nil {
t.Fatal(err)
}
if len(load(scope).groups) != 0 {
t.Fatal("completed fragment groups were not collected")
}
// A new message can reuse the exact grouping fields and first-part text
// of a completed one. Its different PDU must have its own receipt.
first := fragment(1, 0x03, 0, '同', observed)
firstTail := fragment(2, 0x03, 0, '甲', observed.Add(time.Second))
second := fragment(1, 0x03, 0, '同', observed.Add(2*time.Second), 0x70, 1, 0x01)
secondTail := fragment(2, 0x03, 0, '乙', observed.Add(3*time.Second))
if first.key != second.key || first.family != second.family || first.fingerprint == second.fingerprint {
t.Fatal("fixture must share grouping fields and have distinct first-part PDUs")
}
state = load(scope)
apply(state, first, true, false, "")
apply(state, firstTail, true, true, "同甲")
state = load(scope)
apply(state, second, true, false, "")
apply(state, secondTail, true, true, "同乙")
state = load(scope)
apply(state, second, false, true, "")
if err := load(scope).clearCompletedGroups(); err != nil {
t.Fatal(err)
}
// Legacy groups can still finish after upgrade with their original key.
legacy1 := fragment(1, 0x05, 0, '旧', observed)
legacy2 := fragment(2, 0x05, 0, '件', observed)
legacyScope := scope
legacyScope.SessionKey = legacy1.key
if _, err := db.SaveSMSInboundFragment(legacyScope, db.SMSInboundFragment{
Sequence: 1, Reference: 17, ReferenceBits: 8, Total: 2, Content: legacy1.Content, ArrivedAt: legacy1.Timestamp,
}); err != nil {
t.Fatal(err)
}
apply(load(scope), legacy2, false, false, "")
apply(load(scope), legacy1, false, false, "")
apply(load(scope), legacy2, true, true, "旧件")
apply(load(scope), legacy1, false, false, "") // No raw PDU hash on the pre-upgrade row.
apply(load(scope), legacy1, true, true, "") // Known sources can still match legacy rows by text.
observed = observed.Add(5 * time.Minute)
c1 := fragment(1, 0x30, 0x95, '跨', observed)
c2 := fragment(2, 0x40, 0x10, '秒', observed.Add(2*time.Second))
state = load(scope)
apply(state, c1, true, false, "")
apply(state, c2, false, false, "") // Nearby SCTS alone is insufficient proof for an unknown ME slot.
if len(state.groups) != 2 {
t.Fatal("unknown ME tail was persisted")
}
apply(state, c2, true, false, "")
state = load(scope) // Process restart before the follow-up full scan.
apply(state, c1, false, false, "")
if messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute)); err != nil || len(messages) != 0 {
t.Fatalf("archived a cross-SCTS SMS using a DB-only group: %+v, %v", messages, err)
}
apply(state, c2, false, false, "")
if messages, err := state.archiveSettledATFragments(observed.Add(time.Minute)); err != nil || len(messages) != 0 {
t.Fatalf("cross-minute group settled before its collection window elapsed: %+v, %v", messages, err)
}
got := state.settledATFragments(observed.Add(3 * time.Minute))
if len(got) != 1 {
t.Fatalf("settled cross-minute groups = %d, want 1", len(got))
}
key, content, err := completeATMultipart(got[0][0].SessionKey, got[0])
if err != nil || content != "跨秒" {
t.Fatalf("complete fragment set: %q, %q, %v", key, content, err)
}
messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute))
if err != nil || len(messages) != 1 || messages[0].Content != content {
t.Fatalf("archive after restart: %+v, %v", messages, err)
}
saved, found, err := lookupHistory(key)
if err != nil || !found || saved.Content != content {
t.Fatalf("archived history: %+v, %v, %v", saved, found, err)
}
if err := db.DeleteArchivedRecords(context.Background(), db.DB, db.ArchiveDeleteRequest{SMSIDs: []uint{saved.ID}}); err != nil {
t.Fatal(err)
}
closeDB()
open()
state = load(scope)
apply(state, c1, false, false, "")
apply(state, c2, false, false, "")
if messages, err := state.archiveSettledATFragments(observed.Add(4 * time.Minute)); err != nil || len(messages) != 0 {
t.Fatalf("repeat scan notified an archived SMS twice: %+v, %v", messages, err)
}
for _, deletedKey := range []string{exactKey, key} {
if _, found, err := lookupHistory(deletedKey); err != nil || found {
t.Fatalf("repeat scan recreated a removed history row: %s, %v, %v", deletedKey, found, err)
}
}
// A second possible first part within the same family/window makes the
// entire candidate ambiguous, regardless of how close the older SCTS is.
otherFirst := fragment(1, 0x40, 0, '混', observed.Add(time.Second))
apply(state, otherFirst, true, false, "")
if got := state.settledATFragments(observed.Add(3 * time.Minute)); len(got) != 0 {
t.Fatal("settled a cross-SCTS group with conflicting sequences")
}
port1 := fragment(1, 0x55, 0, '端', observed, 4, 2, 0x10, 0x20)
port2 := fragment(2, 0x55, 0, '隔', observed, 4, 2, 0x10, 0x21)
if port1.ApplicationPorts == "" || port1.family == port2.family {
t.Fatal("8-bit source application ports did not distinguish groups")
}
apply(state, port1, true, false, "")
apply(state, port2, true, false, "")
port3 := fragment(1, 0x65, 0, '应', observed, 5, 4, 0x0b, 0x01, 0x0b, 0x03)
port4 := fragment(2, 0x65, 0x10, '离', observed, 5, 4, 0x0b, 0x02, 0x0b, 0x03)
if port3.ApplicationPorts == "" || port3.family == port4.family {
t.Fatal("16-bit destination application ports did not distinguish groups")
}
apply(state, port3, true, false, "")
apply(state, port4, true, false, "")
if messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute)); err != nil || len(messages) != 0 {
t.Fatalf("application-addressed SMS merged across SCTS: %+v, %v", messages, err)
}
// A2 is visible in this scan, but its durable write fails. Without that
// evidence the older A1/B2 pair looks unique and must still stay pending.
observed = observed.Add(10 * time.Minute)
x1 := fragment(1, 0x64, 0, '先', observed)
y2 := fragment(2, 0x64, 0x10, '后', observed.Add(time.Second))
x2 := fragment(2, 0x64, 0, '正', observed.Add(2*time.Second))
state = load(scope)
apply(state, x1, true, false, "")
apply(state, y2, true, false, "")
if err := db.DB.Exec(`CREATE TRIGGER test_reject_fragment BEFORE INSERT ON sms_inbound_fragment
WHEN NEW.content = '正' BEGIN SELECT RAISE(ABORT, 'test fragment write failure'); END`).Error; err != nil {
t.Fatal(err)
}
if stored, message, err := state.persist(x2, true); err == nil || stored || message != nil {
t.Fatalf("fault injection failed: %v, %+v, %v", stored, message, err)
}
if messages, err := state.archiveSettledATFragments(observed.Add(3 * time.Minute)); err != nil || len(messages) != 0 {
t.Fatalf("archive ignored a same-family write failure: %+v, %v", messages, err)
}
// One exact group contains two of the three parts. Observing its first
// part alone cannot prove the other part is still in modem storage.
observed = observed.Add(10 * time.Minute)
p1 := multipart(3, 1, 0x15, 0, '全', observed)
p2 := multipart(3, 2, 0x15, 0, '部', observed.Add(time.Second))
p3 := multipart(3, 3, 0x15, 0x10, '在', observed.Add(2*time.Second))
state = load(scope)
for _, part := range []atInboxPart{p1, p2, p3} {
apply(state, part, true, false, "")
}
settledAt := observed.Add(3 * time.Minute)
state = load(scope)
apply(state, p1, false, false, "")
apply(state, p3, false, false, "")
if messages, err := state.archiveSettledATFragments(settledAt); err != nil || len(messages) != 0 {
t.Fatalf("archived a cross-SCTS SMS with an unobserved part: %+v, %v", messages, err)
}
state = load(scope)
for _, part := range []atInboxPart{p1, p2, p3} {
apply(state, part, false, false, "")
}
messages, err = state.archiveSettledATFragments(settledAt)
if err != nil || len(messages) != 1 || messages[0].Content != "全部在" {
t.Fatalf("archive with all parts observed: %+v, %v", messages, err)
}
swapped := scope
swapped.ICCID, swapped.IMSI = "8988110000000000002", "001010123456788"
apply(load(swapped), a1, false, false, "") // unknown old ME after a card change
state = load(scope)
database := db.DB
db.DB = nil
stored, _, err := state.persist(a1, true)
db.DB = database
if err == nil || stored {
t.Fatalf("DB failure allowed deleting the slot: %t, %v", stored, err)
}
}
func TestATStoredSMSNoticeSurvivesReadFailure(t *testing.T) {
w := &Worker{}
slot := storedSMSSlot{store: "ME", index: 7}
// With identity still unknown, a notification cannot attest a later card.
w.handleStoredSMS(slot.store, "7")
if len(w.storedSMSNotices.slots) != 0 {
t.Fatal("unknown SIM claimed an ME slot")
}
owner := storedSMSOwner{simGeneration: 1}
notice := &storedSMSNotice{owner: owner, slot: slot, observedAt: time.Now()}
w.storedSMSNotices.add(notice) // An unsuccessful CMGR leaves the notification unresolved.
retry := w.storedSMSNotices.snapshot(owner, slot.store)[slot.index]
if retry != notice || !w.storedSMSNotices.bind(retry, "001122") {
t.Fatal("periodic list could not recover the pending ME notification")
}
if w.storedSMSNotices.bind(retry, "aabbcc") {
t.Fatal("retry accepted a replacement after the original PDU was read")
}
next := &storedSMSNotice{owner: owner, slot: slot, observedAt: time.Now()}
w.storedSMSNotices.add(next)
w.storedSMSNotices.forget(notice)
if !w.storedSMSNotices.bind(next, "aabbcc") {
t.Fatal("old task discarded a newer slot notification")
}
owner.simGeneration++
if len(w.storedSMSNotices.snapshot(owner, slot.store)) != 0 || w.storedSMSNotices.bind(next, "aabbcc") {
t.Fatal("new SIM generation inherited an ME notice")
}
latest := &storedSMSNotice{owner: owner, slot: slot, observedAt: time.Now()}
w.storedSMSNotices.add(latest)
if len(w.storedSMSNotices.snapshot(next.owner, slot.store)) != 0 || !w.storedSMSNotices.current(latest) {
t.Fatal("an old scan discarded a newer SIM generation's notice")
}
}
func TestATStoredSMSDuplicateRequiresReceiptIMSIForDeletion(t *testing.T) {
initDevicePhoneNumberTestDB(t)
identity := SMSIdentity{ICCID: "8988110000000000001", IMSI: "001010123456789"}
part, err := decodeATInboxPart(identity, "0004038177F7000862119121000000027532")
if err != nil || part.Concat.IsConcat || part.Content != "甲" {
t.Fatalf("single PDU fixture = %+v, %v", part, err)
}
scope := db.SMSInboundFragmentScope{DeviceID: "c", ICCID: identity.ICCID, IMSI: identity.IMSI}
original, err := loadATSMSParts(scope)
if err != nil {
t.Fatal(err)
}
if stored, inbound, err := original.persist(part, true); err != nil || !stored || inbound == nil {
t.Fatalf("initial persist = %t, %+v, %v", stored, inbound, err)
}
scope.IMSI = "001010123456788"
changed, err := loadATSMSParts(scope)
if err != nil {
t.Fatal(err)
}
assertRetry := func(state *atSMSParts, sourceKnown, wantDelete bool) {
t.Helper()
if stored, inbound, err := state.persist(part, sourceKnown); err != nil || stored != wantDelete || inbound != nil {
t.Fatalf("replay persist = %t, %+v, %v, want delete=%t", stored, inbound, err, wantDelete)
}
}
assertRetry(changed, true, false)
assertRetry(original, true, true)
var row db.SMS
if err := db.DB.Where("iccid = ? AND fragment_session_key = ?", identity.ICCID, part.key).First(&row).Error; err != nil {
t.Fatal(err)
}
if _, _, _, err := db.DeleteSMSByID(row.ID); err != nil {
t.Fatal(err)
}
assertRetry(changed, true, false)
assertRetry(changed, false, false)
assertRetry(original, true, true)
assertRetry(original, false, true)
var count int64
if err := db.DB.Model(&db.SMS{}).Where("iccid = ?", identity.ICCID).Count(&count).Error; err != nil || count != 0 {
t.Fatalf("replay recreated removed history: count=%d, err=%v", count, err)
}
}
type storedSMSIdentityTestReader struct {
SMSIdentity
onIMSI func()
}
func (r storedSMSIdentityTestReader) QuerySIMInserted() (bool, error) { return true, nil }
func (r storedSMSIdentityTestReader) QueryICCID() (string, error) { return r.ICCID, nil }
func (r storedSMSIdentityTestReader) QueryIMSI() (string, error) {
if r.onIMSI != nil {
r.onIMSI()
}
return r.IMSI, nil
}
func TestATStoredSMSLiveSwapSchedulesSIMConvergence(t *testing.T) {
p, w, be := newML307CIdentityWorker(t)
configureWorkerATSMS(w)
owner, err := w.storedSMSOwner()
if err != nil {
t.Fatal(err)
}
live := SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"}
be.liveICCID, be.liveIMSI = live.ICCID, live.IMSI
if err := owner.verifyLiveFrom(storedSMSIdentityTestReader{SMSIdentity: live}); !errors.Is(err, ErrSMSIdentityConflict) {
t.Fatalf("live swap returned %v", err)
}
if !w.SIMIdentityConvergenceMatches("", 0) || w.SIMIdentityGeneration() != owner.simGeneration+1 {
t.Fatal("live swap left old cached identity ready")
}
var messages []InboundSMS
if err := w.readStoredSMSInbox(owner, nil, &messages); !errors.Is(err, ErrSMSIdentityTransitioning) || len(messages) != 0 {
t.Fatalf("old owner could enter the inbox: messages=%+v, err=%v", messages, err)
}
p.simEventMu.Lock()
timer := p.simEventTimers[w.ID]
p.simEventMu.Unlock()
if timer == nil || !timer.Stop() {
t.Fatal("inbox mismatch did not schedule SIM status convergence")
}
p.confirmSIMRemovedForOwner(owner.workerLifecycleOwner, "test", timer)
current, err := w.storedSMSOwner()
if err != nil || current.SMSIdentity != live || current.simGeneration <= owner.simGeneration {
t.Fatalf("inbox did not converge to the live identity: %+v, %v", current.SMSIdentity, err)
}
}
func TestATStoredSMSStaleLiveReadLeavesNewerSIMReady(t *testing.T) {
p, w, _ := newML307CIdentityWorker(t)
configureWorkerATSMS(w)
owner, err := w.storedSMSOwner()
if err != nil {
t.Fatal(err)
}
live := SMSIdentity{ICCID: "card-new", IMSI: "imsi-new"}
reader := storedSMSIdentityTestReader{
SMSIdentity: SMSIdentity{ICCID: "card-intermediate", IMSI: "imsi-intermediate"},
onIMSI: func() {
w.cacheMu.Lock()
defer w.cacheMu.Unlock()
setWorkerSMSIdentity(w, live)
w.state.Identity.Generation++
},
}
if err := owner.verifyLiveFrom(reader); !errors.Is(err, ErrSMSIdentityTransitioning) {
t.Fatalf("superseded read returned %v", err)
}
current, err := w.storedSMSOwner()
if err != nil || current.SMSIdentity != live || current.simGeneration != owner.simGeneration+1 {
t.Fatalf("superseded read altered the newer generation: %+v, %v", current.SMSIdentity, err)
}
p.simEventMu.Lock()
timer := p.simEventTimers[w.ID]
p.simEventMu.Unlock()
if timer != nil {
t.Fatal("superseded read scheduled a new SIM status check")
}
}
+104
View File
@@ -1,6 +1,7 @@
package device
import (
"context"
"errors"
"fmt"
"strings"
@@ -9,9 +10,11 @@ import (
"github.com/yibaiba/hideck/internal/backend"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/modem"
)
var (
ErrSMSSelectorMismatch = errors.New("所选 SIM 身份已变更,请重新选择")
ErrSMSIdentityUnknown = errors.New("短信身份未知")
ErrSMSIdentityConflict = errors.New("短信身份冲突")
ErrSMSIdentityTransitioning = errors.New("SIM 身份正在切换")
@@ -54,6 +57,34 @@ func (databaseSMSIdentityStore) SaveReceived(identity SMSIdentity, message inbou
})
}
func (p *Pool) smsSendOwnerCheck(worker *Worker, selector SMSIdentity) func() error {
checkOwner := p.outboundOwnerCheck(worker)
if selector == (SMSIdentity{}) {
return checkOwner
}
return func() error {
if selector.IMSI != "" && worker.cachedSMSIdentity().IMSI != selector.IMSI {
return ErrSMSSelectorMismatch
}
if err := checkOwner(); err != nil {
return ErrSMSSelectorMismatch
}
return nil
}
}
func (w *Worker) cachedSMSIdentity() SMSIdentity {
w.cacheMu.RLock()
defer w.cacheMu.RUnlock()
return normalizeSMSIdentity(SMSIdentity{ICCID: w.state.Identity.ICCID, IMSI: w.state.Identity.IMSI})
}
func (selector SMSIdentity) matches(identity SMSIdentity) bool {
return selector != (SMSIdentity{}) &&
(selector.ICCID == "" || selector.ICCID == identity.ICCID) &&
(selector.IMSI == "" || selector.IMSI == identity.IMSI)
}
func (p *Pool) ResolveSMSIdentity(deviceID string) (SMSIdentity, error) {
return p.resolveSMSIdentity(deviceID, true)
}
@@ -108,6 +139,9 @@ func (p *Pool) runtimeSMSIdentity(deviceID string) (smsIdentityCandidate, error)
}
worker.cacheMu.RLock()
defer worker.cacheMu.RUnlock()
if worker.atDeviceRules().strictSIMIdentity && (!worker.state.Identity.Ready || !worker.Modem.IsSimInserted()) {
return smsIdentityCandidate{}, ErrSMSIdentityUnknown
}
phase := worker.state.Identity.Phase
if phase == simIdentityPhaseTransitioning || phase == simIdentityPhaseDegraded {
return smsIdentityCandidate{}, fmt.Errorf("%w: device=%s phase=%s", ErrSMSIdentityTransitioning, deviceID, phase)
@@ -127,6 +161,76 @@ func (p *Pool) runtimeSMSIdentity(deviceID string) (smsIdentityCandidate, error)
}, nil
}
func (w *Worker) strictSMSSendIdentity() (SMSIdentity, error) {
w.cacheMu.RLock()
state := w.state.Identity
w.cacheMu.RUnlock()
identity := normalizeSMSIdentity(SMSIdentity{ICCID: state.ICCID, IMSI: state.IMSI})
if !state.Ready || state.Phase != simIdentityPhaseReady || identity.ICCID == "" || identity.IMSI == "" {
return SMSIdentity{}, ErrSMSIdentityUnknown
}
return identity, nil
}
// Caller holds the outbound operation through confirmation and submission.
func (w *Worker) confirmCSSMSIdentity(ctx context.Context, intended SMSIdentity, checkOwner func() error) error {
if err := checkOwner(); err != nil || !w.atDeviceRules().strictSIMIdentity {
return err
}
reader, ok := w.Backend.(liveSIMIdentityReader)
if !ok {
return ErrSMSIdentityUnknown
}
const source = "cs_sms_identity"
generation := w.SIMIdentityGeneration()
ctx, cancel := context.WithTimeout(contextOrBackground(ctx), 8*time.Second)
defer cancel()
inserted, err := w.Backend.IsSimInserted(ctx)
if err != nil {
if errors.Is(err, modem.ErrSIMPINRequired) {
w.recordStrictSIMLock(generation, source)
}
return err
}
if !inserted {
w.recordStrictSIMAbsence(generation, source)
return ErrSMSIdentityUnknown
}
iccid, err := reader.GetICCIDLive(ctx)
if err != nil {
return err
}
imsi, err := reader.GetIMSILive(ctx)
if err != nil {
return err
}
live := normalizeSMSIdentity(SMSIdentity{ICCID: iccid, IMSI: imsi})
cached, err := w.strictSMSSendIdentity()
if err != nil {
return err
}
if err := checkOwner(); err != nil {
return err
}
switch {
case live.ICCID == "" || live.IMSI == "":
err = ErrSMSIdentityUnknown
case live != intended || cached != intended:
err = ErrSMSIdentityConflict
}
if err != nil {
return w.rejectLiveCSSMSIdentity(generation, source, err)
}
return ctx.Err()
}
func (w *Worker) rejectLiveCSSMSIdentity(generation uint64, source string, err error) error {
if w.degradeStrictSIMIdentity(generation, source, err) {
w.scheduleSIMStatusCheck(source, nil, "READY")
}
return err
}
// smsIMSIAliasChecker is implemented by stores that remember every IMSI read on a
// card, so a multi-IMSI SIM switching EF_IMSI is not treated as a different card.
type smsIMSIAliasChecker interface {
+4
View File
@@ -15,6 +15,10 @@ func configureWorkerATSMS(w *Worker) {
}
w.Modem.SetNewSMSHandler(nil)
w.Modem.SetDisableURCRead(false)
if w.atDeviceRules().storedSMSInbox {
w.Modem.SetStoredSMSHandler(w.handleStoredSMS)
return
}
w.Modem.SetSMSReadinessCheck(func() error {
_, err := w.resolveSMSIdentity()
return err
+38 -1
View File
@@ -1,8 +1,14 @@
package device
import "strings"
import (
"strings"
"github.com/yibaiba/hideck/internal/modem"
)
const (
cmIoTVendorID = 0x2ecc
ml307cProductID = 0x3012
quectelVendorID = 0x2c7c
qualcommVendorID = 0x05c6
quectel0125ProductID = 0x0125
@@ -27,6 +33,24 @@ type usbDeviceIdentity struct {
productID uint16
}
// usbATOnlyLayout describes USB compositions managed only through an AT port.
type usbATOnlyLayout struct {
profile modem.ATProfile
preferredInterface int
alternateInterface int
}
func (id usbDeviceIdentity) atOnlyLayout() (usbATOnlyLayout, bool) {
if id.vendorID == cmIoTVendorID && id.productID == ml307cProductID {
return usbATOnlyLayout{
profile: modem.ATProfileML307C,
preferredInterface: 2,
alternateInterface: 3,
}, true
}
return usbATOnlyLayout{}, false
}
type usbATPortRule struct {
interfaceNumber int
serialPortCount int
@@ -34,6 +58,9 @@ type usbATPortRule struct {
}
func usbATPortRuleFor(identity usbDeviceIdentity, mode string) (usbATPortRule, bool) {
if layout, ok := identity.atOnlyLayout(); ok {
return usbInterfaceATPortRule(layout.preferredInterface), true
}
mode = strings.ToLower(strings.TrimSpace(mode))
if identity.vendorID == qualcommVendorID && mode == "qmi" {
return usbInterfaceATPortRule(2), true
@@ -109,6 +136,16 @@ func supportsStaticQuectelATInterface(mode string) bool {
func discoverATPortsForUSBDevice(usbPath string, identity usbDeviceIdentity, mode string) (ports []string, bestPort, imei string) {
portScan := scanATPortsForUSBDevice(usbPath)
if layout, ok := identity.atOnlyLayout(); ok {
var atOnly usbATPortScan
for _, port := range portScan.interfaceOrdered {
if port.interfaceNumber == layout.preferredInterface || port.interfaceNumber == layout.alternateInterface {
atOnly.interfaceOrdered = append(atOnly.interfaceOrdered, port)
atOnly.candidates = append(atOnly.candidates, port.path)
}
}
portScan = atOnly
}
bestPort, imei = selectBestATPortForUSBDevice(identity, mode, portScan)
return portScan.candidates, bestPort, imei
}
+3
View File
@@ -125,6 +125,9 @@ func (p *Pool) validateNativeVoLTEStart(deviceID string, start *nativeVoLTEStart
if w == nil || w != start.worker || currentSIMOwnership(w) != start.sim || p.IsESIMSwitching(deviceID) {
return errors.New("VoLTE 启动已失效:设备或 SIM 已更换或正在切卡")
}
if err := w.CheckPhoneModeSupported(PhoneModeVoLTE); err != nil {
return err
}
if !IsNativeVoLTEMode(w.Config.PhoneMode) || !PhoneServiceEnabled(w.Config) || w.Config.AirplaneEnabled {
return errors.New("VoLTE 启动已失效:电话模式已切换或处于飞行模式")
}
+1 -3
View File
@@ -61,9 +61,7 @@ func TestNativeStartCanceledDuringReadinessCannotOutliveHandoff(t *testing.T) {
if err := p.stopNativeVoLTEForModemVoice(port.worker.ID); err != nil {
t.Fatal(err)
}
if err := applyPolicyToWorker(port.worker, cardpolicy.Policy{PhoneMode: PhoneModeModemVoice, VoWiFiEnabled: true}); err != nil {
t.Fatal(err)
}
applyTestCardPolicy(t, port.worker, cardpolicy.Policy{PhoneMode: PhoneModeModemVoice, VoWiFiEnabled: true})
// Readiness must stop without waiting for the backend to become ready.
select {
case err := <-done:
+4
View File
@@ -2,6 +2,7 @@ package device
import (
"errors"
"strings"
"time"
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
@@ -95,6 +96,9 @@ func (vowifiDeliveryStore) LoadInboundFragments(
}
result := make([]messaging.StoredInboundFragment, 0, len(rows))
for _, row := range rows {
if strings.HasPrefix(row.SessionKey, db.ATSMSInboundPrefix) {
continue
}
// The rows already match the owner's canonical ICCID and IMSI. Hand
// the owner back as given so imscore's exact owner check accepts
// fragments saved on another device or under a padded ICCID.
+65 -15
View File
@@ -9,6 +9,8 @@ import (
"github.com/iniwex5/vowifi-go/runtimehost"
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/pkg/smscodec"
)
@@ -19,12 +21,13 @@ const (
)
type routedSMSSendResult struct {
Via string
Outcome messaging.SendOutcome
FellBackToCS bool
Destination string
Identity SMSIdentity
IdentityRead bool
Via string
Outcome messaging.SendOutcome
FellBackToCS bool
PartsConfirmed int
Destination string
Identity SMSIdentity
IdentityRead bool
}
// ShouldFallbackVoWiFiSMSToCS reports whether IMS never accepted the MESSAGE.
@@ -55,6 +58,13 @@ func sendRoutedSMS(
return routedSMSSendResult{Via: RoutedSMSViaVoWiFi, Outcome: outcome}, err
}
if csErr := sendCS(); csErr != nil {
if errors.Is(csErr, ErrSMSSelectorMismatch) {
return routedSMSSendResult{Via: RoutedSMSViaVoWiFi, Outcome: outcome, FellBackToCS: true}, csErr
}
if result := csSMSResult(csErr); result.Outcome.DeliveryState != "" {
result.FellBackToCS = true
return result, csErr
}
return routedSMSSendResult{Via: RoutedSMSViaVoWiFi, Outcome: outcome, FellBackToCS: true}, err
}
return routedSMSSendResult{Via: RoutedSMSViaCS, Outcome: outcome, FellBackToCS: true}, nil
@@ -62,10 +72,24 @@ func sendRoutedSMS(
if sendCS == nil {
return routedSMSSendResult{Via: RoutedSMSViaCS}, errors.New("sms route: CS sender is unavailable")
}
if err := sendCS(); err != nil {
return routedSMSSendResult{Via: RoutedSMSViaCS}, err
err := sendCS()
return csSMSResult(err), err
}
func csSMSResult(err error) routedSMSSendResult {
result := routedSMSSendResult{Via: RoutedSMSViaCS}
var progress *modem.SMSSubmitError
if errors.As(err, &progress) {
result.Outcome.PartsTotal = progress.PartsTotal
result.PartsConfirmed = progress.PartsConfirmed
}
return routedSMSSendResult{Via: RoutedSMSViaCS}, nil
switch {
case errors.Is(err, modem.ErrSMSSubmitUnknown):
result.Outcome.DeliveryState = db.SMSDeliveryStateUnknown
case result.PartsConfirmed > 0:
result.Outcome.DeliveryState = db.SMSDeliveryStatePartialAck
}
return result
}
// SendRoutedSMS sends via VoWiFi when that path is selected, and falls back to
@@ -75,6 +99,17 @@ func (p *Pool) SendRoutedSMS(
worker *Worker,
phone, message string,
opts smscodec.SubmitOptions,
) (routedSMSSendResult, error) {
return p.SendRoutedSMSForIdentity(ctx, worker, phone, message, opts, SMSIdentity{})
}
// SendRoutedSMSForIdentity binds an explicit SIM selector to the selected worker through submission.
func (p *Pool) SendRoutedSMSForIdentity(
ctx context.Context,
worker *Worker,
phone, message string,
opts smscodec.SubmitOptions,
selector SMSIdentity,
) (routedSMSSendResult, error) {
if p == nil {
return routedSMSSendResult{}, errors.New("sms route: pool is nil")
@@ -84,15 +119,27 @@ func (p *Pool) SendRoutedSMS(
}
deviceID := worker.ID
destination := strings.TrimSpace(phone)
checkOwner := p.outboundOwnerCheck(worker)
identity, identityErr := p.ResolveSMSIdentity(deviceID)
if identityErr != nil {
return routedSMSSendResult{}, fmt.Errorf("sms route: resolve SIM identity: %w", identityErr)
explicitSelector := selector != (SMSIdentity{})
selector = normalizeSMSIdentity(selector)
checkOwner := p.smsSendOwnerCheck(worker, selector)
identity, err := p.ResolveSMSIdentity(deviceID)
if err != nil {
if explicitSelector && (errors.Is(err, ErrSMSIdentityUnknown) || errors.Is(err, ErrSMSIdentityConflict) || errors.Is(err, ErrSMSIdentityTransitioning)) {
return routedSMSSendResult{}, ErrSMSSelectorMismatch
}
return routedSMSSendResult{}, fmt.Errorf("sms route: resolve SIM identity: %w", err)
}
if explicitSelector && !selector.matches(identity) {
return routedSMSSendResult{}, ErrSMSSelectorMismatch
}
if err := checkOwner(); err != nil {
return routedSMSSendResult{Identity: identity, IdentityRead: true}, err
}
if err := p.authorizeSMS(ctx, outboundSMSRequest{Worker: worker, To: destination, Text: message, Options: opts}); err != nil {
request := outboundSMSRequest{Worker: worker, To: destination, Text: message, Options: opts}
if explicitSelector {
request.CheckOwner = checkOwner
}
if err := p.authorizeSMS(ctx, request); err != nil {
return routedSMSSendResult{Identity: identity, IdentityRead: true}, err
}
p.mu.RLock()
@@ -125,7 +172,10 @@ func (p *Pool) SendRoutedSMS(
return err
}
defer release()
if err := checkOwner(); err != nil {
if err := worker.confirmCSSMSIdentity(ctx, identity, checkOwner); err != nil {
if explicitSelector && errors.Is(err, ErrSMSIdentityConflict) {
return ErrSMSSelectorMismatch
}
return err
}
if sendCSHook != nil {
+17
View File
@@ -12,6 +12,7 @@ import (
"github.com/iniwex5/vowifi-go/runtimehost"
"github.com/iniwex5/vowifi-go/runtimehost/messaging"
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/pkg/smscodec"
)
@@ -297,6 +298,22 @@ func TestSendRoutedSMSKeepsVoWiFiErrorWhenCSAlsoFails(t *testing.T) {
}
}
func TestSendRoutedSMSKeepsUnknownCSFallbackResult(t *testing.T) {
imsErr := errors.New("503")
csErr := fmt.Errorf("CS submit: %w", modem.ErrSMSSubmitUnknown)
calls := 0
result, err := sendRoutedSMS(true,
func() (messaging.SendOutcome, error) {
return messaging.SendOutcome{MessageID: "ims-1", RecommendCSFallback: true, DeliveryState: "failed"}, imsErr
},
func() error { calls++; return csErr },
)
if err != csErr || !result.FellBackToCS || result.Via != RoutedSMSViaCS ||
result.Outcome.DeliveryState != "unknown" || result.Outcome.MessageID != "" || calls != 1 {
t.Fatalf("fallback result=%+v err=%v CS calls=%d", result, err, calls)
}
}
type voWiFiSMSSendResult struct {
outcome messaging.SendOutcome
err error
@@ -151,6 +151,9 @@ func (p *Pool) prepareVoWiFiStartContext(ctx context.Context, deviceID, traceID,
if w == nil {
return startCtx, fmt.Errorf("设备 %s 不存在", deviceID)
}
if err := w.CheckPhoneModeSupported(w.Config.PhoneMode); err != nil {
return startCtx, err
}
startCtx.worker = w
if IsModemVoiceMode(w.Config.PhoneMode) {
return startCtx, ErrModemVoiceSoftwareIMS
+39 -4
View File
@@ -114,7 +114,11 @@ func parseIMSI(resp string) string {
}
func parseQCCID(resp string) string {
line, ok := findLineWithPrefix(resp, "+QCCID:")
return parseICCID(resp, "+QCCID:")
}
func parseICCID(resp, prefix string) string {
line, ok := findLineWithPrefix(resp, prefix)
if !ok {
return ""
}
@@ -165,7 +169,11 @@ func parseCOPSAct(resp string) (string, bool) {
}
func parseCREG(resp string) (int, string, string, bool) {
line, ok := findLineWithPrefix(resp, "+CREG:")
return parseRegistration(resp, "+CREG:")
}
func parseRegistration(resp, prefix string) (int, string, string, bool) {
line, ok := findLineWithPrefix(resp, prefix)
if !ok {
return 0, "", "", false
}
@@ -428,7 +436,13 @@ func extractSMSPDURecordsAfterPrefix(resp string, prefix string) []SMSPDURecord
index, err := strconv.Atoi(strings.TrimSpace(fields[0]))
if err == nil {
pdu, _ := smscodec.TrimFullPDUHexByATHeader(next, lines[i])
out = append(out, SMSPDURecord{Index: index, PDU: pdu})
status := -1
if len(fields) > 1 {
if parsed, err := strconv.Atoi(fields[1]); err == nil {
status = parsed
}
}
out = append(out, SMSPDURecord{Index: index, Status: status, PDU: pdu})
}
}
i++
@@ -540,7 +554,7 @@ func ParseUSBNetMode(resp string) (int, error) {
}
// parseCCHO 解析 AT+CCHO 响应,提取逻辑通道号
// 响应格式: +CCHO: <channel>
// 响应格式: +CCHO: <channel>。ML307C 返回单行裸通道号。
func parseCCHO(resp string) (int, bool) {
line, ok := findLineWithPrefix(resp, "+CCHO:")
if !ok {
@@ -558,6 +572,27 @@ func parseCCHO(resp string) (int, bool) {
return -1, false
}
func parseML307CCCHO(resp string) (int, bool) {
if channel, ok := parseCCHO(resp); ok {
return channel, true
}
var channel int
for _, line := range splitLines(resp) {
if line == "" || line == "OK" {
continue
}
value, err := strconv.ParseUint(line, 10, 8)
if channel != 0 || err != nil || value == 0 {
return -1, false
}
channel = int(value)
}
if channel == 0 {
return -1, false
}
return channel, true
}
// parseCGLA 解析 AT+CGLA 响应,提取 APDU 响应
// 响应格式: +CGLA: <len>,"<apdu>"
func parseCGLA(resp string) (string, bool) {
+30
View File
@@ -214,3 +214,33 @@ func TestParseCOPSOperator(t *testing.T) {
})
}
}
func TestParseCCHO(t *testing.T) {
tests := []struct {
name string
resp string
profile ATProfile
channel int
}{
{name: "prefixed", resp: "\r\n+CCHO: 2\r\nOK\r\n", channel: 2},
{name: "default rejects bare channel", resp: "2\r\nOK", channel: -1},
{name: "ML307C prefixed", resp: "+CCHO: 2\r\nOK", profile: ATProfileML307C, channel: 2},
{name: "ML307C bare", profile: ATProfileML307C, resp: "\r\n2\r\nOK\r\n", channel: 2},
{name: "terminal stripped", profile: ATProfileML307C, resp: "2", channel: 2},
{name: "only OK", profile: ATProfileML307C, resp: "OK", channel: -1},
{name: "bare followed by ERROR", profile: ATProfileML307C, resp: "2\nERROR", channel: -1},
{name: "command rejected", profile: ATProfileML307C, resp: "+CME ERROR: 3", channel: -1},
{name: "multiple numbers", profile: ATProfileML307C, resp: "2\n3\nOK", channel: -1},
{name: "number with suffix", profile: ATProfileML307C, resp: "2,3\nOK", channel: -1},
{name: "basic channel", profile: ATProfileML307C, resp: "0\nOK", channel: -1},
{name: "out of range", profile: ATProfileML307C, resp: "258\nOK", channel: -1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
channel, ok := tt.profile.dialect().parseCCHO(tt.resp)
if channel != tt.channel || ok != (tt.channel > 0) {
t.Fatalf("parseCCHO(%q) = (%d, %t), want (%d, %t)", tt.resp, channel, ok, tt.channel, tt.channel > 0)
}
})
}
}
+211
View File
@@ -0,0 +1,211 @@
package modem
import (
"errors"
"strings"
"time"
)
type ATProfile uint8
const (
ATProfileDefault ATProfile = iota
ATProfileML307C
)
type atTextQuery struct {
command string
parse func(string) string
}
type atRadioQuery struct {
command string
parse func(string) (mode, duplex, band string, channel uint32)
}
type atCPINPresenceQuery struct {
parse func(string) (bool, error)
isAbsentError func(string) bool
}
type atOwnedSMSSubmit struct {
promptTimeout time.Duration
finalTimeout time.Duration
}
type atDialect struct {
imei atTextQuery
firmware atTextQuery
iccid atTextQuery
parseProbeIMEI func(string) string
missingIMEIError error
operatorFormat string
registration string
registrationPrefix string
radio atRadioQuery
radioFallback atRadioQuery
servingCell string
imsStatus string
usbnet string
simStatus string
cpinPresence *atCPINPresenceQuery
parseCCHO func(string) (int, bool)
offlineSIMReload bool
voiceInit []string
ownedSMSSubmit *atOwnedSMSSubmit
}
var defaultATDialect = atDialect{
imei: atTextQuery{"AT+CGSN", parseIMEI},
firmware: atTextQuery{"AT+CGMR", parseFirmware},
iccid: atTextQuery{"AT+QCCID", parseQCCID},
parseProbeIMEI: parseIMEI,
operatorFormat: "AT+COPS=3,2",
registration: "AT+CREG?",
registrationPrefix: "+CREG:",
radio: atRadioQuery{"AT+QNWINFO", parseQNWInfoRadio},
radioFallback: atRadioQuery{"AT+COPS?", parseCOPSRadio},
servingCell: "AT+QENG=\"servingcell\"",
imsStatus: "AT+QIMS?",
usbnet: "AT+QCFG=\"usbnet\"?",
simStatus: "AT+QSIMSTAT?",
parseCCHO: parseCCHO,
voiceInit: []string{"AT+CLIP=1", "AT+QPCMV=1,2"},
}
var ml307cATDialect = atDialect{
imei: atTextQuery{"AT+CGSN=1", parseML307CIMEI},
firmware: atTextQuery{"AT+MSWVER", parseML307CFirmware},
iccid: atTextQuery{"AT+MCCID", parseMCCID},
parseProbeIMEI: parseML307CProbeIMEI,
missingIMEIError: errors.New("invalid IMEI response"),
registration: "AT+CEREG?",
registrationPrefix: "+CEREG:",
radio: atRadioQuery{"AT+COPS?", parseCOPSRadio},
cpinPresence: &atCPINPresenceQuery{parse: parseML307CCPIN, isAbsentError: isML307CNoSIMError},
parseCCHO: parseML307CCCHO,
offlineSIMReload: true,
ownedSMSSubmit: &atOwnedSMSSubmit{promptTimeout: ml307cSMSPromptTimeout, finalTimeout: ml307cSMSResultTimeout},
}
func (profile ATProfile) dialect() *atDialect {
if profile == ATProfileML307C {
return &ml307cATDialect
}
return &defaultATDialect
}
// SupportsOfflineSIMReload reports whether the SIM can reload without enabling RF.
func (profile ATProfile) SupportsOfflineSIMReload() bool {
return profile.dialect().offlineSIMReload
}
func parseML307CIMEI(resp string) string {
if line, ok := findLineWithPrefix(resp, "+CGSN:"); ok {
return parseIMEI(strings.TrimPrefix(line, "+CGSN:"))
}
return parseIMEI(resp)
}
func parseML307CProbeIMEI(resp string) string {
// A serial read can end in the middle of an identifier.
return parseML307CIMEI(resp[:strings.LastIndexAny(resp, "\r\n")+1])
}
func parseML307CFirmware(resp string) string {
// MSWVER reports model, firmware version and build on separate lines.
var fields []string
for _, line := range splitLines(resp) {
if line == "" || line == "OK" || line == "AT+MSWVER" || strings.HasPrefix(line, "+") {
continue
}
fields = append(fields, line)
}
if len(fields) != 3 {
return ""
}
return fields[1] + " / " + fields[2]
}
func parseMCCID(resp string) string {
return parseICCID(resp, "+MCCID:")
}
func parseCOPSRadio(resp string) (string, string, string, uint32) {
mode, _ := parseCOPSAct(resp)
return mode, "", "", 0
}
const (
cpinQuery = "AT+CPIN?"
cpinPrefix = "+CPIN:"
)
var (
errSIMNotInserted = errors.New("SIM not inserted")
ErrSIMPINRequired = errors.New("SIM PIN or PUK required")
)
func parseML307CCPIN(resp string) (bool, error) {
line, ok := findLineWithPrefix(resp, cpinPrefix)
if !ok {
return false, errors.New("unrecognized CPIN response")
}
state := strings.TrimSpace(strings.TrimPrefix(line, cpinPrefix))
if IsSIMPINRequiredState(state) {
return false, ErrSIMPINRequired
}
switch strings.ToUpper(state) {
case "READY":
return true, nil
case "SIM REMOVED", "SIM NOT INSERTED", "NOT INSERTED":
return false, nil
default:
return false, errors.New("unrecognized CPIN state")
}
}
// IsSIMPINRequiredState recognizes CPIN states where the SIM is present and locked.
func IsSIMPINRequiredState(state string) bool {
switch strings.ToUpper(strings.TrimSpace(state)) {
case "SIM PIN", "SIM PUK", "SIM PIN2", "SIM PUK2":
return true
default:
return false
}
}
func (m *Manager) queryCPINSIMPresence(query *atCPINPresenceQuery) (bool, error) {
resp, err := m.ExecuteATSilent(cpinQuery, 2*time.Second)
if errors.Is(err, errSIMNotInserted) {
m.cacheCPINSIMState(false, nil)
return false, nil
}
if err != nil {
return false, err
}
inserted, err := query.parse(resp)
if err == nil || errors.Is(err, ErrSIMPINRequired) {
m.cacheCPINSIMState(inserted, err)
}
return inserted, err
}
func (m *Manager) cacheCPINSIMState(inserted bool, err error) {
m.infoMu.Lock()
defer m.infoMu.Unlock()
m.simInserted = inserted
if !inserted && err == nil {
m.iccid = ""
m.imsi = ""
}
}
func isML307CNoSIMError(line string) bool {
value, ok := strings.CutPrefix(line, "+CME ERROR:")
if !ok {
return false
}
value = strings.TrimSpace(value)
return value == "10" || strings.EqualFold(value, "SIM not inserted")
}
+127
View File
@@ -0,0 +1,127 @@
package modem
import (
"errors"
"slices"
"testing"
"time"
"github.com/yibaiba/hideck/internal/config"
)
func TestML307CATQueries(t *testing.T) {
m, err := NewWithATProfile(config.DeviceConfig{ID: "c", DeviceBackend: "at", ATPort: "/dev/ttyUSB8"}, ATProfileML307C)
if err != nil {
t.Fatal(err)
}
if got := m.initializationCommands(); !slices.Equal(got, []string{"ATE0", "AT+CMGF=0", "AT+CNMI=2,1,0,0,0"}) {
t.Fatalf("init commands = %v", got)
}
fixtures := map[string][]string{
"AT+CGSN=1": {"+CGSN: 490154203237518", "OK"},
"AT+MCCID": {"+MCCID: 8988110000000000001F", "OK"},
"AT+MSWVER": {"ML307C-DC-CN-MBRH0S00", "4.0.8.2506051839_release", "6c31ce603", "OK"},
"AT+CEREG?": {"+CEREG: 0,5", "OK"},
"AT+COPS?": {"+COPS: 0,0,\"CHN-UNICOM\",7", "OK"},
"AT+CSQ": {"+CSQ: 24,99", "OK"},
}
var pinResponses = [][]string{
{"+CPIN: READY", "OK"}, {"+CPIN: SIM PIN", "OK"}, {"+CME ERROR: SIM not inserted"}, {"ERROR"},
}
m.port = &timeoutSerialPort{}
m.setRunning(true)
t.Cleanup(m.Stop)
go func() {
for {
select {
case <-m.stop:
return
case req := <-m.cmdChan:
lines := fixtures[req.cmd]
if req.cmd == "AT+CPIN?" && len(pinResponses) > 0 {
lines, pinResponses = pinResponses[0], pinResponses[1:]
}
if len(lines) == 0 {
req.errChan <- errors.New("unexpected AT command: " + req.cmd)
continue
}
for _, line := range lines {
m.rxChan <- rxMsg{Data: line}
}
m.handleCommand(req)
}
}
}()
if imei, err := m.QueryIMEI(); err != nil || imei != "490154203237518" {
t.Fatalf("QueryIMEI() = %q, %v", imei, err)
}
if firmware, err := m.QueryFirmware(); err != nil || firmware != "4.0.8.2506051839_release / 6c31ce603" {
t.Fatalf("QueryFirmware() = %q, %v", firmware, err)
}
if iccid, err := m.QueryICCID(); err != nil || iccid != "8988110000000000001" {
t.Fatalf("QueryICCID() = %q, %v", iccid, err)
}
if status, _, _, _, err := m.QueryRegistration(); err != nil || status != 5 {
t.Fatalf("QueryRegistration() = %d, %v", status, err)
}
if operator, err := m.QueryOperator(); err != nil || operator != "CHN-UNICOM" {
t.Fatalf("QueryOperator() = %q, %v", operator, err)
}
if rat, _, _, _, err := m.QueryNetworkRadio(); err != nil || rat != "LTE" {
t.Fatalf("QueryNetworkRadio() = %q, %v", rat, err)
}
if _, rssi, err := m.QueryCSQ(); err != nil || rssi != -65 {
t.Fatalf("QueryCSQ() RSSI = %d, %v", rssi, err)
}
if ready, err := m.QuerySIMInserted(); !ready || err != nil || !m.IsSimInserted() {
t.Fatalf("ready CPIN = %v, %v", ready, err)
}
simEvents := make(chan string, 2)
m.SetSIMStatusHandler(func(_ *bool, state string) { simEvents <- state })
m.handleURC("+CPIN: SIM PIN")
select {
case state := <-simEvents:
if state != "SIM PIN" || !m.IsSimInserted() {
t.Fatalf("PIN URC changed confirmed readiness: event=%q ready=%v", state, m.IsSimInserted())
}
case <-time.After(time.Second):
t.Fatal("PIN URC was not dispatched")
}
if ready, err := m.QuerySIMInserted(); ready || !errors.Is(err, ErrSIMPINRequired) || m.IsSimInserted() {
t.Fatalf("locked CPIN = %v, %v", ready, err)
}
select {
case state := <-simEvents:
t.Fatalf("live PIN query requeued a SIM callback: %q", state)
case <-time.After(50 * time.Millisecond):
}
if ready, err := m.QuerySIMInserted(); ready || err != nil {
t.Fatalf("absent CPIN = %v, %v", ready, err)
}
if ready, err := m.QuerySIMInserted(); ready || err == nil || !m.IsHealthy() {
t.Fatalf("failed CPIN = %v, %v, healthy=%v", ready, err, m.IsHealthy())
}
}
func TestML307CFirmwareParsingRejectsIncompleteReply(t *testing.T) {
if got := ATProfileML307C.dialect().firmware.parse("AT+MSWVER\nML307C-DC-CN-MBRH0S00\n+CPIN: READY\nOK"); got != "" {
t.Fatalf("incomplete MSWVER reply parsed as %q", got)
}
if got := ATProfileDefault.dialect().firmware.parse("EC20EFAR06A05M4G\nOK"); got != "EC20EFAR06A05M4G" {
t.Fatalf("default firmware parsed as %q", got)
}
}
func TestML307CIMEIParsing(t *testing.T) {
profile := ATProfileML307C
for _, invalid := range []string{"20200X000000000000", "+CGSN: 4901542032375180", "+CGSN: 490154203237518,0"} {
if imei := profile.dialect().imei.parse(invalid); imei != "" {
t.Fatalf("invalid CGSN response %q parsed as %q", invalid, imei)
}
}
if imei := profile.dialect().imei.parse("490154203237518"); imei != "490154203237518" {
t.Fatalf("bare IMEI parsed as %q", imei)
}
}
+94 -28
View File
@@ -2,6 +2,7 @@ package modem
import (
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
@@ -11,28 +12,40 @@ import (
)
func (m *Manager) QueryIMEI() (string, error) {
resp, err := m.ExecuteATSilent("AT+CGSN", 2*time.Second)
dialect := m.atProfile.dialect()
resp, err := m.ExecuteATSilent(dialect.imei.command, 2*time.Second)
if err != nil {
return "", err
}
return parseIMEI(resp), nil
imei := dialect.imei.parse(resp)
if imei == "" {
return "", dialect.missingIMEIError
}
return imei, nil
}
func (m *Manager) QueryFirmware() (string, error) {
resp, err := m.ExecuteATSilent("AT+CGMR", 2*time.Second)
query := m.atProfile.dialect().firmware
resp, err := m.ExecuteATSilent(query.command, 2*time.Second)
if err != nil {
return "", err
}
return parseFirmware(resp), nil
return query.parse(resp), nil
}
func (m *Manager) QuerySIMInserted() (bool, error) {
if resp, err := m.ExecuteATSilent("AT+QSIMSTAT?", 2*time.Second); err == nil {
if inserted, ok := parseQSIMSTATInserted(resp); ok {
return inserted, nil
dialect := m.atProfile.dialect()
if query := dialect.cpinPresence; query != nil {
return m.queryCPINSIMPresence(query)
}
if cmd := dialect.simStatus; cmd != "" {
if resp, err := m.ExecuteATSilent(cmd, 2*time.Second); err == nil {
if inserted, ok := parseQSIMSTATInserted(resp); ok {
return inserted, nil
}
}
}
resp, err := m.ExecuteATSilent("AT+CPIN?", 2*time.Second)
resp, err := m.ExecuteATSilent(cpinQuery, 2*time.Second)
if err != nil {
return false, err
}
@@ -51,15 +64,18 @@ func (m *Manager) QueryIMSI() (string, error) {
}
func (m *Manager) QueryICCID() (string, error) {
resp, err := m.ExecuteATSilent("AT+QCCID", 2*time.Second)
query := m.atProfile.dialect().iccid
resp, err := m.ExecuteATSilent(query.command, 2*time.Second)
if err != nil {
return "", err
}
return parseQCCID(resp), nil
return query.parse(resp), nil
}
func (m *Manager) QueryOperator() (string, error) {
_, _ = m.ExecuteATSilent("AT+COPS=3,2", 2*time.Second)
if cmd := m.atProfile.dialect().operatorFormat; cmd != "" {
_, _ = m.ExecuteATSilent(cmd, 2*time.Second)
}
resp, err := m.ExecuteATSilent("AT+COPS?", 2*time.Second)
if err != nil {
return "", err
@@ -68,11 +84,12 @@ func (m *Manager) QueryOperator() (string, error) {
}
func (m *Manager) QueryRegistration() (int, string, string, string, error) {
resp, err := m.ExecuteATSilent("AT+CREG?", 2*time.Second)
dialect := m.atProfile.dialect()
resp, err := m.ExecuteATSilent(dialect.registration, 2*time.Second)
if err != nil {
return 0, "", "", "", err
}
regStatus, lac, cellID, ok := parseCREG(resp)
regStatus, lac, cellID, ok := parseRegistration(resp, dialect.registrationPrefix)
if !ok {
return 0, "", "", "", nil
}
@@ -100,7 +117,11 @@ func (m *Manager) QueryServingCellLTE() (int, int, error) {
}
func (m *Manager) QueryServingCellLTEInfo() (ServingCellLTEInfo, error) {
resp, err := m.ExecuteATSilent("AT+QENG=\"servingcell\"", 3*time.Second)
cmd := m.atProfile.dialect().servingCell
if cmd == "" {
return ServingCellLTEInfo{}, nil
}
resp, err := m.ExecuteATSilent(cmd, 3*time.Second)
if err != nil {
return ServingCellLTEInfo{}, err
}
@@ -120,7 +141,11 @@ func (m *Manager) QueryAPN() (string, error) {
}
func (m *Manager) QueryIMSStatus() (int, error) {
resp, err := m.ExecuteATSilent("AT+QIMS?", 2*time.Second)
cmd := m.atProfile.dialect().imsStatus
if cmd == "" {
return 0, nil
}
resp, err := m.ExecuteATSilent(cmd, 2*time.Second)
if err != nil {
return 0, err
}
@@ -134,11 +159,12 @@ func (m *Manager) QueryNetworkModeAndDuplex() (string, string, error) {
}
func (m *Manager) QueryNetworkRadio() (string, string, string, uint32, error) {
resp, err := m.ExecuteATSilent("AT+QNWINFO", 2*time.Second)
query := m.atProfile.dialect().radio
resp, err := m.ExecuteATSilent(query.command, 2*time.Second)
if err != nil {
return "", "", "", 0, err
}
mode, duplex, band, channel := parseQNWInfoRadio(resp)
mode, duplex, band, channel := query.parse(resp)
return mode, duplex, band, channel, nil
}
@@ -149,18 +175,19 @@ func (m *Manager) QueryNetworkMode() (string, error) {
func (m *Manager) QueryNetworkModeFallbackAndDuplex() (string, string, error) {
networkMode, networkDuplex, err := m.QueryNetworkModeAndDuplex()
if err == nil && networkMode != "" {
return networkMode, networkDuplex, nil
fallback := m.atProfile.dialect().radioFallback
if fallback.command == "" || (err == nil && networkMode != "") {
return networkMode, networkDuplex, err
}
resp, err2 := m.ExecuteATSilent("AT+COPS?", 2*time.Second)
resp, err2 := m.ExecuteATSilent(fallback.command, 2*time.Second)
if err2 != nil {
if err != nil {
return "", "", err
}
return "", "", err2
}
mode, _ := parseCOPSAct(resp)
return mode, "", nil
mode, duplex, _, _ := fallback.parse(resp)
return mode, duplex, nil
}
func (m *Manager) QueryNetworkModeFallback() (string, error) {
@@ -187,19 +214,54 @@ func (m *Manager) SMSReadPDU(index string) (string, error) {
}
type SMSPDURecord struct {
Index int
PDU string
Index int
Status int
PDU string
}
func (r SMSPDURecord) Received() bool { return r.Status == 0 || r.Status == 1 }
func (m *Manager) SMSListAllPDURecords() ([]SMSPDURecord, error) {
resp, err := m.ExecuteAT("AT+CMGL=4", 10*time.Second)
return m.smsListAllPDURecords(false)
}
func (m *Manager) smsListAllPDURecords(verify bool) ([]SMSPDURecord, error) {
execute := m.ExecuteAT
if verify {
execute = m.ExecuteATSilent
}
resp, err := execute("AT+CMGL=4", 10*time.Second)
if err != nil {
return nil, err
}
if strings.TrimSpace(resp) == "OK" {
return nil, nil
}
return extractSMSPDURecordsAfterPrefix(resp, "+CMGL:"), nil
records := extractSMSPDURecordsAfterPrefix(resp, "+CMGL:")
if verify {
headers, data := 0, 0
for _, line := range splitLines(resp) {
switch {
case line == "", line == "OK":
case strings.HasPrefix(line, "+CMGL:"):
headers++
default:
if _, err := hex.DecodeString(line); err != nil {
return nil, errors.New("unexpected CMGL response line")
}
data++
}
}
if headers != len(records) || data != len(records) {
return nil, errors.New("incomplete CMGL response")
}
for _, record := range records {
if record.Index < 0 || record.Status < 0 || record.Status > 3 {
return nil, errors.New("invalid CMGL record")
}
}
}
return records, nil
}
func (m *Manager) SMSListAllPDU() ([]string, error) {
@@ -263,7 +325,11 @@ func (m *Manager) QueryMSISDN() (string, error) {
// QueryUSBNetMode 查询 USBNET 模式
func (m *Manager) QueryUSBNetMode() (int, error) {
resp, err := m.ExecuteATSilent("AT+QCFG=\"usbnet\"?", 2*time.Second)
cmd := m.atProfile.dialect().usbnet
if cmd == "" {
return -1, nil
}
resp, err := m.ExecuteATSilent(cmd, 2*time.Second)
if err != nil {
return -1, err
}
@@ -327,7 +393,7 @@ func (m *Manager) openLogicalChannel(aid, leaseOwner, sessionOwner string, class
if err != nil {
return -1, fmt.Errorf("打开 logical channel 失败: %w", err)
}
channel, ok := parseCCHO(resp)
channel, ok := m.atProfile.dialect().parseCCHO(resp)
if !ok {
return -1, fmt.Errorf("解析 logical channel 响应失败: %s", resp)
}
+84 -4
View File
@@ -3,11 +3,13 @@ package modem
import (
"context"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/yibaiba/hideck/internal/config"
"go.bug.st/serial"
)
@@ -82,6 +84,11 @@ func ProbeIMEI(atPort string, timeout time.Duration) (string, error) {
// ProbeIMEIContext 在取消时主动关闭串口,避免 USB 重枚举期间阻塞设备恢复。
func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration) (string, error) {
return ATProfileDefault.ProbeIMEI(ctx, atPort, timeout)
}
// ProbeIMEI reads the current IMEI with the selected AT dialect and bypasses the cache.
func (profile ATProfile) ProbeIMEI(ctx context.Context, atPort string, timeout time.Duration) (string, error) {
atPort = strings.TrimSpace(atPort)
if atPort == "" {
return "", errors.New("empty at port")
@@ -103,7 +110,7 @@ func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration)
probeCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
p, err := openIMEISerialPort(probeCtx, atPort, mode)
p, err := openIMEISerialPortFn(probeCtx, atPort, mode)
if err != nil {
return "", err
}
@@ -116,6 +123,7 @@ func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration)
buf := make([]byte, 1024)
var acc strings.Builder
dialect := profile.dialect()
write := func(s string) {
_, _ = p.Write([]byte(s))
@@ -124,14 +132,14 @@ func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration)
// 写入 AT 测试命令与查询 IMEI 的 AT+CGSN 命令
write("AT\r\n")
time.Sleep(40 * time.Millisecond)
write("AT+CGSN\r\n")
write(dialect.imei.command + "\r\n")
// 在指定的截止时间内轮询并解析串口输出内容
for probeCtx.Err() == nil {
n, rerr := p.Read(buf)
if n > 0 {
acc.Write(buf[:n])
if imei := parseIMEI(acc.String()); imei != "" {
if imei := dialect.parseProbeIMEI(acc.String()); imei != "" {
return imei, nil
}
}
@@ -146,7 +154,7 @@ func ProbeIMEIContext(ctx context.Context, atPort string, timeout time.Duration)
}
// 最终尝试解析一次累积的串口缓冲区
if imei := parseIMEI(acc.String()); imei != "" {
if imei := dialect.parseProbeIMEI(acc.String()); imei != "" {
return imei, nil
}
if err := probeCtx.Err(); err != nil && !errors.Is(err, context.DeadlineExceeded) {
@@ -160,6 +168,8 @@ type imeiSerialOpenResult struct {
err error
}
var openIMEISerialPortFn = openIMEISerialPort
func openIMEISerialPort(ctx context.Context, atPort string, mode *serial.Mode) (serial.Port, error) {
result := make(chan imeiSerialOpenResult, 1)
go func() {
@@ -189,3 +199,73 @@ func closeIMEISerialPortOnCancel(ctx context.Context, port serial.Port, stop <-c
case <-stop:
}
}
var errIMEIReplyUnavailable = errors.New("IMEI reply unavailable")
// verifyOpenedIMEI consumes the entire identity reply before the manager starts
// reading URCs or issuing initialization commands on this handle.
func (m *Manager) verifyOpenedIMEI(expected string) error {
const timeout = 1200 * time.Millisecond
dialect := m.atProfile.dialect()
live, err := readOpenedIMEI(m.port, dialect, timeout)
if errors.Is(err, errIMEIReplyUnavailable) {
time.Sleep(250 * time.Millisecond)
live, err = readOpenedIMEI(m.port, dialect, timeout)
}
if err != nil {
return fmt.Errorf("无法验证 AT 口 %s 的实时 IMEI: %w", m.atPort, err)
}
if !config.IMEIMatches(live, expected) {
return fmt.Errorf("AT 口 %s 的实时 IMEI 与配置不匹配", m.atPort)
}
return nil
}
func readOpenedIMEI(port serial.Port, dialect *atDialect, timeout time.Duration) (string, error) {
if err := port.SetReadTimeout(80 * time.Millisecond); err != nil {
return "", err
}
if err := port.ResetInputBuffer(); err != nil {
return "", err
}
cmd := dialect.imei.command + "\r\n"
n, err := port.Write([]byte(cmd))
if err != nil {
return "", err
}
if n != len(cmd) {
return "", errors.New("incomplete IMEI command write")
}
deadline := time.Now().Add(timeout)
var response strings.Builder
var pending string
buf := make([]byte, 1024)
for time.Now().Before(deadline) {
n, err := port.Read(buf)
if err != nil {
return "", err
}
pending += string(buf[:n])
for {
line, rest, complete := strings.Cut(pending, "\n")
if !complete {
break
}
pending = rest
line = strings.TrimSpace(line)
switch {
case line == "OK":
imei := dialect.imei.parse(response.String())
if imei == "" {
return "", fmt.Errorf("%w: empty IMEI response", errIMEIReplyUnavailable)
}
return imei, nil
case line == "ERROR" || strings.HasPrefix(line, "+CME ERROR:") || strings.HasPrefix(line, "+CMS ERROR:"):
return "", fmt.Errorf("%w: %s", errIMEIReplyUnavailable, line)
}
response.WriteString(line + "\n")
}
}
return "", fmt.Errorf("%w: timeout", errIMEIReplyUnavailable)
}
+177
View File
@@ -0,0 +1,177 @@
package modem
import (
"context"
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yibaiba/hideck/internal/config"
"go.bug.st/serial"
)
type imeiProbeSerialPort struct {
serial.Port
reply *strings.Reader
written []string
}
func (p *imeiProbeSerialPort) SetReadTimeout(time.Duration) error { return nil }
func (p *imeiProbeSerialPort) Close() error { return nil }
func (p *imeiProbeSerialPort) Read(b []byte) (int, error) { return p.reply.Read(b) }
func (p *imeiProbeSerialPort) Write(b []byte) (int, error) {
p.written = append(p.written, string(b))
return len(b), nil
}
func TestLiveIMEIProbeBypassesCacheForUnchangedTTYNode(t *testing.T) {
path := filepath.Join(t.TempDir(), "ttyUSB8")
if err := os.WriteFile(path, nil, 0o600); err != nil {
t.Fatal(err)
}
node, err := os.Stat(path)
if err != nil {
t.Fatal(err)
}
const cachedIMEI, replacementIMEI = "490154203237518", "490154203237526"
t.Cleanup(func() {
imeiCache.mu.Lock()
delete(imeiCache.m, path)
imeiCache.mu.Unlock()
})
storeCachedIMEI(path, cachedIMEI, node)
serialPort := &imeiProbeSerialPort{reply: strings.NewReader("\r\n+CGSN: " + replacementIMEI + "\r\n\r\nOK\r\n")}
origOpen := openIMEISerialPortFn
t.Cleanup(func() { openIMEISerialPortFn = origOpen })
openIMEISerialPortFn = func(_ context.Context, port string, _ *serial.Mode) (serial.Port, error) {
if port != path {
t.Fatalf("probe opened %q, want %q", port, path)
}
return serialPort, nil
}
live, err := ATProfileML307C.ProbeIMEI(context.Background(), path, time.Second)
if err != nil || live != replacementIMEI {
t.Fatalf("live probe = %q, %v", live, err)
}
if want := []string{"AT\r\n", "AT+CGSN=1\r\n"}; !reflect.DeepEqual(serialPort.written, want) {
t.Fatalf("AT commands = %q, want %q", serialPort.written, want)
}
cached, err := ProbeIMEICached(path, time.Second)
if err != nil || cached != cachedIMEI || len(serialPort.written) != 2 {
t.Fatalf("default cached probe = %q, %v, commands %q", cached, err, serialPort.written)
}
}
type openedIMEISerialPort struct {
failingSerialPort
probeCommand string
replies [][]string
response []string
commands atomic.Int32
probes atomic.Int32
terminalRead atomic.Bool
inputFlushed bool
earlyInit atomic.Bool
}
func (p *openedIMEISerialPort) ResetInputBuffer() error {
p.inputFlushed = true
return nil
}
func (p *openedIMEISerialPort) Write(b []byte) (int, error) {
p.commands.Add(1)
if p.inputFlushed {
p.inputFlushed = false
if string(b) != p.probeCommand || len(p.replies) == 0 {
return 0, errors.New("unexpected IMEI probe")
}
p.probes.Add(1)
p.terminalRead.Store(false)
p.response = p.replies[0]
p.replies = p.replies[1:]
return len(b), nil
}
if !p.terminalRead.Load() {
p.earlyInit.Store(true)
}
return 0, errors.New("fake device stops after IMEI")
}
func (p *openedIMEISerialPort) Read(b []byte) (int, error) {
if len(p.response) == 0 {
time.Sleep(time.Millisecond)
return 0, nil
}
part := p.response[0]
p.response = p.response[1:]
if part == "\n" {
p.terminalRead.Store(true)
}
return copy(b, part), nil
}
func TestManagerVerifiesTheOpenedPortBeforeATInitialization(t *testing.T) {
const expected = "490154203237518"
original := openManagerSerialPort
t.Cleanup(func() { openManagerSerialPort = original })
match := []string{"+CGSN: " + expected + "\r\n", "OK\r", "\n"}
empty := []string{"OK\r", "\n"}
for _, tc := range []struct {
name, wantError string
profile ATProfile
replies [][]string
}{
{name: "matched", profile: ATProfileML307C, replies: [][]string{match}},
{name: "replacement", profile: ATProfileML307C, replies: [][]string{{"+CGSN: 490154203237526\r\n", "OK\r", "\n"}}, wantError: "实时 IMEI 与配置不匹配"},
{name: "unreadable after retry", profile: ATProfileML307C, replies: [][]string{empty, empty}, wantError: "无法验证"},
{name: "default AT retries ERROR", profile: ATProfileDefault, replies: [][]string{{"ERROR\r", "\n"}, {expected + "\r\n", "OK\r", "\n"}}},
{name: "timeout then matched", profile: ATProfileML307C, replies: [][]string{nil, match}},
} {
t.Run(tc.name, func(t *testing.T) {
m, err := NewWithATProfile(config.DeviceConfig{
ID: "imei-gate", DeviceBackend: "at", ATPort: filepath.Join(t.TempDir(), "ttyUSB8"),
}, tc.profile)
if err != nil {
t.Fatal(err)
}
port := &openedIMEISerialPort{
probeCommand: tc.profile.dialect().imei.command + "\r\n",
replies: tc.replies,
}
opens := 0
openManagerSerialPort = func(string, *serial.Mode) (serial.Port, error) {
opens++
if opens == 1 {
return nil, errors.New("device or resource busy")
}
return port, nil
}
err = m.StartWithExpectedIMEI(expected)
wantProbes := int32(len(tc.replies))
if opens != 2 || port.probes.Load() != wantProbes || !port.terminalRead.Load() || port.earlyInit.Load() {
m.Stop()
t.Fatalf("opens=%d probes=%d want=%d terminalRead=%v earlyInit=%v",
opens, port.probes.Load(), wantProbes, port.terminalRead.Load(), port.earlyInit.Load())
}
if tc.wantError != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantError) || !port.closed.Load() ||
m.CanExecuteAT() || port.commands.Load() != wantProbes {
t.Fatalf("err=%v closed=%v running=%v commands=%d", err, port.closed.Load(), m.CanExecuteAT(), port.commands.Load())
}
return
}
defer m.Stop()
if err != nil || !m.CanExecuteAT() || port.closed.Load() {
t.Fatalf("err=%v running=%v closed=%v", err, m.CanExecuteAT(), port.closed.Load())
}
})
}
}
+127 -34
View File
@@ -50,18 +50,20 @@ type commandRequest struct {
highPriority bool
// 交互式模式支持
interactive bool // 是否为交互式命令 (如发送短信)
waitPrompt bool // 是否等待 "> " 提示符
followUp string // 后续指令 (当 waitPrompt=true 且收到提示符时发送)
interactive bool // 是否为交互式命令 (如发送短信)
waitPrompt bool // 是否等待 "> " 提示符
followUp string // 后续指令 (当 waitPrompt=true 且收到提示符时发送)
smsFinalTimeout time.Duration // ML307C CMGS budget after a complete Ctrl+Z write.
}
// Manager 管理单个 EC20 模块的 AT 指令通信
type Manager struct {
cfg config.DeviceConfig
atPort string
port serial.Port
portMode *serial.Mode
role runtimeRole
atProfile ATProfile
cfg config.DeviceConfig
atPort string
port serial.Port
portMode *serial.Mode
role runtimeRole
// 通道驱动的异步架构
stop chan struct{}
@@ -120,6 +122,8 @@ type Manager struct {
smsCallback SMSCallback
smsProcessor SMSProcessor
smsReadinessCheck func() error
smsStorageMu sync.Mutex
storedSMSHandler func(storage, index string)
newSMSHandler func(index string) // 处理新短信索引的回调 (用于 bubble up URC)
disableURCRead bool // 如果启用 QMI,禁用 AT 自动读取
simStatusHandler func(inserted *bool, state string)
@@ -176,19 +180,26 @@ func (m *Manager) pureQMIBackend() bool {
}
func New(cfg config.DeviceConfig) (*Manager, error) {
return newManager(cfg, runtimeRoleDefault)
return NewWithATProfile(cfg, ATProfileDefault)
}
func NewWithATProfile(cfg config.DeviceConfig, profile ATProfile) (*Manager, error) {
return newManager(cfg, runtimeRoleDefault, profile)
}
func (m *Manager) ATProfile() ATProfile { return m.atProfile }
// NewSMSAuxiliary creates the single AT runtime used by an MBIM worker for
// SMS, SMSC, URCs, and manual AT commands. Network, identity, and APDU remain
// owned by the MBIM backend.
func NewSMSAuxiliary(cfg config.DeviceConfig) (*Manager, error) {
return newManager(cfg, runtimeRoleSMSAuxiliary)
return newManager(cfg, runtimeRoleSMSAuxiliary, ATProfileDefault)
}
func newManager(cfg config.DeviceConfig, role runtimeRole) (*Manager, error) {
func newManager(cfg config.DeviceConfig, role runtimeRole, profile ATProfile) (*Manager, error) {
m := &Manager{
cfg: cfg,
atProfile: profile,
atPort: cfg.ATPort,
role: role,
stop: make(chan struct{}),
@@ -511,6 +522,11 @@ func (m *Manager) tripATTimeoutWatchdog(cmd string, failures int) {
// Start 启动 AT 管理器的后台协程
func (m *Manager) Start() error {
return m.StartWithExpectedIMEI("")
}
// StartWithExpectedIMEI verifies the opened AT port before modem initialization.
func (m *Manager) StartWithExpectedIMEI(expected string) error {
m.startStopMu.Lock()
defer m.startStopMu.Unlock()
select {
@@ -533,7 +549,7 @@ func (m *Manager) Start() error {
var err error
for attempt := 0; attempt < 8; attempt++ {
m.port, err = serial.Open(m.atPort, m.portMode)
m.port, err = openManagerSerialPort(m.atPort, m.portMode)
if err == nil {
break
}
@@ -546,6 +562,13 @@ func (m *Manager) Start() error {
return fmt.Errorf("打开串口 %s 失败: %w", m.atPort, err)
}
if expected != "" {
if err := m.verifyOpenedIMEI(expected); err != nil {
_ = m.port.Close()
m.port = nil
return err
}
}
m.port.SetReadTimeout(100 * time.Millisecond)
m.setRunning(true)
@@ -582,6 +605,8 @@ func (m *Manager) Start() error {
return nil
}
var openManagerSerialPort = serial.Open
func isRetryableSerialOpenErr(err error) bool {
if err == nil {
return false
@@ -708,6 +733,12 @@ func (m *Manager) handleCommand(req commandRequest) {
m.handleFileUpload(req)
return
}
if req.smsFinalTimeout > 0 {
m.handleML307CSMS(req)
return
}
cpinPresence := m.atProfile.dialect().cpinPresence
queryingPresence := cpinPresence != nil && req.cmd == cpinQuery
startTime := time.Now()
// 发送命令
@@ -769,7 +800,9 @@ RespLoop:
"resp", logATResponse(req.cmd, strings.Join(fullResponse, " | ")),
"cost", time.Since(startTime).Truncate(time.Millisecond).String())
}
if req.cmd == "AT+CLCC" {
if queryingPresence && cpinPresence.isAbsentError(line) {
req.errChan <- errSIMNotInserted
} else if req.cmd == "AT+CLCC" {
req.errChan <- &clccResponseError{response: strings.Join(fullResponse, "\n"), terminal: line}
} else {
req.errChan <- fmt.Errorf("设备返回错误: %s", logATResponse(req.cmd, strings.Join(fullResponse, "\n")))
@@ -796,6 +829,8 @@ RespLoop:
req.respChan <- "> "
break RespLoop
} else if queryingPresence && strings.HasPrefix(line, cpinPrefix) {
fullResponse = append(fullResponse, line)
} else if m.isURC(line) {
// 对于确认为 URC 的行,始终分发出去
m.handleURC(line)
@@ -1010,8 +1045,11 @@ func (m *Manager) collectDeviceInfo() {
imsi = v
}
}
if v, err := m.QueryICCID(); err == nil {
iccid = v
tracksSIMByCPIN := m.atProfile.dialect().cpinPresence != nil
if simInserted || !tracksSIMByCPIN {
if v, err := m.QueryICCID(); err == nil {
iccid = v
}
}
if v, err := m.QueryOperator(); err == nil {
operator = v
@@ -1062,7 +1100,9 @@ func (m *Manager) collectDeviceInfo() {
if operator != "" {
m.operator = operator
}
m.simInserted = simInserted
if !tracksSIMByCPIN {
m.simInserted = simInserted
}
if signalDBM != -999 {
m.signalDBM = signalDBM
}
@@ -1279,6 +1319,13 @@ func (m *Manager) RefreshStatus(onAlert func(msg string), onRecover func(msg str
// 检查 SIM 卡是否存活
simInserted, simErr := m.QuerySIMInserted()
if m.atProfile.dialect().cpinPresence != nil {
if errors.Is(simErr, ErrSIMPINRequired) {
m.dispatchSIMStatusURC(nil, "SIM PIN")
} else if simErr == nil {
m.dispatchSIMStatusURC(&simInserted, "")
}
}
if v, err := m.QueryOperator(); err == nil {
operator = v
@@ -1474,8 +1521,16 @@ func (m *Manager) handleURC(line string) {
m.infoMu.RLock()
disabled := m.disableURCRead
handler := m.newSMSHandler
storedHandler := m.storedSMSHandler
m.infoMu.RUnlock()
if storedHandler != nil {
if !disabled {
storedHandler(storage, index)
}
return
}
if handler != nil {
go handler(index)
return
@@ -1847,6 +1902,7 @@ func (m *Manager) executeAT(cmd string, timeout time.Duration, silent, highPrior
req.interactive = false
req.waitPrompt = false
req.followUp = ""
req.smsFinalTimeout = 0
// 确保回收资源
defer func() {
@@ -2098,6 +2154,25 @@ func (m *Manager) DeleteSMS(index uint32) error {
return err
}
// ErrSMSSubmitUnknown means the payload was written but acceptance is unconfirmed.
var ErrSMSSubmitUnknown = errors.New("短信发送结果未知,请勿自动重发")
// SMSSubmitError retains the segment counts when submission stopped early.
type SMSSubmitError struct {
PartsTotal int
PartsConfirmed int
Err error
}
func (e *SMSSubmitError) Error() string {
if e.PartsConfirmed == 0 {
return e.Err.Error()
}
return fmt.Sprintf("短信已确认提交 %d/%d 段: %v", e.PartsConfirmed, e.PartsTotal, e.Err)
}
func (e *SMSSubmitError) Unwrap() error { return e.Err }
// SendSMS 使用 PDU 模式发送短信
func (m *Manager) SendSMS(phone, message string) error {
return m.SendSMSWithOptions(phone, message, smscodec.SubmitOptions{})
@@ -2105,10 +2180,17 @@ func (m *Manager) SendSMS(phone, message string) error {
// SendSMSWithOptions 使用 PDU 模式发送短信,并允许调用方指定文本编码策略。
func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.SubmitOptions) error {
ownedSubmit := m.atProfile.dialect().ownedSMSSubmit
if ownedSubmit != nil {
m.smsStorageMu.Lock()
defer m.smsStorageMu.Unlock()
}
m.SetBusy(true)
defer m.SetBusy(false)
logger.Info(fmt.Sprintf("[%s] 准备发送短信 (PDU)", m.cfg.ID), "to", phone)
if ownedSubmit == nil {
logger.Info(fmt.Sprintf("[%s] 准备发送短信 (PDU)", m.cfg.ID), "to", phone)
}
// 确保处于 PDU 模式
if _, err := m.ExecuteATHigh("AT+CMGF=0", 3*time.Second); err != nil {
@@ -2123,8 +2205,6 @@ func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.Submit
for i, pduHex := range pduHexList {
tpduLen := tpduLenList[i]
logger.Debug(fmt.Sprintf("[%s] PDU 编码完成 (分片 %d/%d)", m.cfg.ID, i+1, len(pduHexList)), "pdu", pduHex, "tpdu_len", tpduLen)
req := commandRequest{
cmd: fmt.Sprintf("AT+CMGS=%d", tpduLen), // PDU 长度 (不含 SMSC)
respChan: make(chan string, 1),
@@ -2136,23 +2216,36 @@ func (m *Manager) SendSMSWithOptions(phone, message string, opts smscodec.Submit
followUp: pduHex + "\x1A", // PDU + Ctrl+Z
}
// 使用高优先级通道原子执行
select {
case m.cmdChanHigh <- req:
case <-time.After(5 * time.Second):
return errors.New("command queue full")
}
if ownedSubmit != nil {
req.timeout = ownedSubmit.promptTimeout
req.smsFinalTimeout = ownedSubmit.finalTimeout
if err := m.sendML307CSMSPart(req); err != nil {
partErr := fmt.Errorf("发送分片 %d: %w", i+1, err)
if i > 0 || errors.Is(err, ErrSMSSubmitUnknown) {
return &SMSSubmitError{PartsTotal: len(pduHexList), PartsConfirmed: i, Err: partErr}
}
return partErr
}
} else {
logger.Debug(fmt.Sprintf("[%s] PDU 编码完成 (分片 %d/%d)", m.cfg.ID, i+1, len(pduHexList)), "pdu", pduHex, "tpdu_len", tpduLen)
// 使用高优先级通道原子执行
select {
case m.cmdChanHigh <- req:
case <-time.After(5 * time.Second):
return errors.New("command queue full")
}
// 等待最终响应 (OK)
select {
case resp := <-req.respChan:
if !strings.Contains(resp, "OK") && !strings.Contains(resp, "+CMGS:") {
return fmt.Errorf("发送分片 %d 失败: %s", i+1, resp)
// 等待最终响应 (OK)
select {
case resp := <-req.respChan:
if !strings.Contains(resp, "OK") && !strings.Contains(resp, "+CMGS:") {
return fmt.Errorf("发送分片 %d 失败: %s", i+1, resp)
}
case err := <-req.errChan:
return fmt.Errorf("发送分片 %d 失败: %w", i+1, err)
case <-time.After(20 * time.Second):
return errors.New("发送超时")
}
case err := <-req.errChan:
return fmt.Errorf("发送分片 %d 失败: %w", i+1, err)
case <-time.After(20 * time.Second):
return errors.New("发送超时")
}
// 稍微等待下一段发信,防止模组队列溢出
+120
View File
@@ -51,6 +51,62 @@ func TestHandleCMTIUsesIndicatedStorageForReadAndDelete(t *testing.T) {
}
}
func TestML307CSMSInboxRestoresStorageAfterDeleteFailure(t *testing.T) {
m := newRunningTestManager(t)
m.SetStoredSMSHandler(func(_, _ string) {})
m.atProfile = ATProfileML307C
const pdu = "0004038101F100006250724190410A3754747A0E4ABBCD6F793B4C4FBFDDA0F41CE47ED341617B38CD0E8BD96590F92D07E5DF7539283C1EBFEB6E3A889E87971B"
deleteErr := errors.New("slot could not be deleted")
done := make(chan []string, 1)
go func() {
selection := `+CPMS: "ME",1,180,"ME",1,180,"ME",1,180`
done <- respondToCommands(t, m, 9, func(req commandRequest) {
switch req.cmd {
case "AT+CPMS?":
req.respChan <- selection
case `AT+CPMS="SM","SM","SM"`:
selection = `+CPMS: "SM",2,10,"SM",2,10,"SM",2,10`
req.respChan <- "OK"
case "AT+CMGL=4":
req.respChan <- "+CMGL: 7,0,,59\n" + pdu + "\n+CMGL: 8,3,,59\n" + pdu
case "AT+CMGR=7":
req.respChan <- "+CMGR: 1,,59\n" + pdu
case "AT+CMGD=7":
req.errChan <- deleteErr
case `AT+CPMS="ME","ME","ME"`:
selection = `+CPMS: "ME",1,180,"ME",1,180,"ME",1,180`
req.respChan <- "OK"
default:
req.errChan <- errors.New("unexpected command " + req.cmd)
}
})
}()
err := m.WithSMSInbox(func(inbox *SMSInbox) error {
if err := inbox.Select("SM"); err != nil {
return err
}
records, err := inbox.List()
if err != nil {
return err
}
if len(records) != 2 || records[0].Index != 7 || !records[0].Received() || records[1].Received() {
t.Fatalf("CMGL records = %+v", records)
}
return inbox.DeleteMatching(records[0], func() error { return nil })
})
if !errors.Is(err, deleteErr) {
t.Fatalf("WithSMSInbox() error = %v, want delete failure", err)
}
want := []string{
"AT+CPMS?", `AT+CPMS="SM","SM","SM"`, "AT+CPMS?", "AT+CMGL=4",
"AT+CPMS?", "AT+CMGR=7", "AT+CMGD=7", `AT+CPMS="ME","ME","ME"`, "AT+CPMS?",
}
if got := <-done; !reflect.DeepEqual(got, want) {
t.Fatalf("commands = %v, want %v", got, want)
}
}
func TestHandleCommandDispatchesCMTIWithoutPollutingResponse(t *testing.T) {
m := newRunningTestManager(t)
m.port = &timeoutSerialPort{}
@@ -140,3 +196,67 @@ func TestReadSMSRetainsMessageWhenProcessorFails(t *testing.T) {
t.Fatalf("commands=%v, want read without delete", commands)
}
}
func TestML307CSMSInboxRecoversOtherStoreAfterSelectionFailure(t *testing.T) {
m := newRunningTestManager(t)
m.SetStoredSMSHandler(func(_, _ string) {})
m.atProfile = ATProfileML307C
const (
pdu = "0004038177F7000862119121000000027532"
initial = `+CPMS: "SM",1,10,"ME",1,180,"ME",1,180`
)
selectErr := errors.New("ME selection failed")
done := make(chan []string, 1)
go func() {
selection := initial
done <- respondToCommands(t, m, 8, func(req commandRequest) {
switch req.cmd {
case "AT+CPMS?":
req.respChan <- selection
case `AT+CPMS="ME","ME","ME"`:
// The modem changed its read location despite returning an error.
selection = `+CPMS: "ME",1,180,"ME",1,180,"ME",1,180`
req.errChan <- selectErr
case `AT+CPMS="SM","SM","SM"`:
selection = `+CPMS: "SM",1,10,"SM",1,10,"SM",1,10`
req.respChan <- "OK"
case "AT+CMGL=4":
if selection != `+CPMS: "SM",1,10,"SM",1,10,"SM",1,10` {
req.errChan <- errors.New("listed the wrong store")
return
}
req.respChan <- "+CMGL: 7,0,,17\n" + pdu
case `AT+CPMS="SM","ME","ME"`:
selection = initial
req.respChan <- "OK"
default:
req.errChan <- errors.New("unexpected command " + req.cmd)
}
})
}()
err := m.WithSMSInbox(func(inbox *SMSInbox) error {
err := inbox.Select("ME")
if !errors.Is(err, selectErr) {
t.Fatalf("ME selection error = %v", err)
}
if err := inbox.Select("SM"); err != nil {
t.Fatal(err)
}
records, err := inbox.List()
if err != nil || len(records) != 1 || records[0].PDU != pdu || !records[0].Received() {
t.Fatalf("SM records = %+v, %v", records, err)
}
return selectErr
})
if !errors.Is(err, selectErr) {
t.Fatalf("WithSMSInbox() error = %v", err)
}
want := []string{
"AT+CPMS?", `AT+CPMS="ME","ME","ME"`, "AT+CPMS?", `AT+CPMS="SM","SM","SM"`,
"AT+CPMS?", "AT+CMGL=4", `AT+CPMS="SM","ME","ME"`, "AT+CPMS?",
}
if got := <-done; !reflect.DeepEqual(got, want) {
t.Fatalf("commands = %v, want %v", got, want)
}
}
+1 -4
View File
@@ -28,8 +28,5 @@ func (m *Manager) initializationCommands() []string {
if m.role == runtimeRoleSMSAuxiliary {
return commands
}
return append(commands,
"AT+CLIP=1",
"AT+QPCMV=1,2",
)
return append(commands, m.atProfile.dialect().voiceInit...)
}
+148
View File
@@ -0,0 +1,148 @@
package modem
import (
"errors"
"fmt"
"slices"
"strconv"
"strings"
"time"
)
// SMSInbox keeps one AT receive transaction on a verified CPMS read store.
type SMSInbox struct {
modem *Manager
current []string
dirty bool
}
func (m *Manager) SetStoredSMSHandler(handler func(storage, index string)) {
m.infoMu.Lock()
defer m.infoMu.Unlock()
m.storedSMSHandler = handler
}
func (m *Manager) StoredSMSReceiving() bool {
m.infoMu.RLock()
defer m.infoMu.RUnlock()
return m.storedSMSHandler != nil && !m.disableURCRead
}
// WithSMSInbox shares the storage lock with PDU sending. The callback may
// select both stores before the original three CPMS locations are restored.
func (m *Manager) WithSMSInbox(run func(*SMSInbox) error) (err error) {
m.smsStorageMu.Lock()
defer m.smsStorageMu.Unlock()
if !m.StoredSMSReceiving() {
return errors.New("AT SMS receive is paused")
}
initial, err := m.smsStorageSelection()
if err != nil {
return err
}
inbox := &SMSInbox{modem: m, current: initial}
defer func() {
if inbox.dirty {
err = errors.Join(err, m.setAndVerifySMSStorage(initial))
}
}()
return run(inbox)
}
func (m *Manager) smsStorageSelection() ([]string, error) {
reply, err := m.ExecuteATSilent("AT+CPMS?", 3*time.Second)
if err != nil {
return nil, err
}
selection := parseCPMSStorages(reply)
if len(selection) != 3 {
return nil, errors.New("cannot verify all three CPMS locations")
}
return selection, nil
}
func (m *Manager) setAndVerifySMSStorage(selection []string) error {
if _, err := m.ExecuteATSilent(cpmsSetCommand(selection...), 5*time.Second); err != nil {
return err
}
return m.verifySMSStorage(selection)
}
func (m *Manager) verifySMSStorage(selection []string) error {
actual, err := m.smsStorageSelection()
if err != nil {
return err
}
if !slices.Equal(actual, selection) {
return fmt.Errorf("CPMS selected %v, expected %v", actual, selection)
}
return nil
}
func (inbox *SMSInbox) Select(storage string) error {
storage = strings.ToUpper(strings.TrimSpace(storage))
if storage != "SM" && storage != "ME" {
return fmt.Errorf("unsupported SMS read store %q", storage)
}
if inbox.current == nil {
// A failed CPMS may still have changed one or more locations.
actual, err := inbox.modem.smsStorageSelection()
if err != nil {
return err
}
inbox.current = actual
}
if inbox.current[0] == storage {
return nil
}
// ML307C accepts the same store for all three locations.
selection := []string{storage, storage, storage}
inbox.dirty = true
inbox.current = nil
if err := inbox.modem.setAndVerifySMSStorage(selection); err != nil {
return err
}
inbox.current = selection
return nil
}
func (inbox *SMSInbox) List() ([]SMSPDURecord, error) {
return inbox.modem.smsListAllPDURecords(true)
}
func (inbox *SMSInbox) Read(index int) (SMSPDURecord, error) {
reply, err := inbox.modem.ExecuteATSilent("AT+CMGR="+strconv.Itoa(index), 5*time.Second)
if err != nil {
return SMSPDURecord{}, err
}
header, _ := findLineWithPrefix(reply, "+CMGR:")
fields := parseCommaFields(parseURCAfterColon(header))
pdu, ok := extractSMSPDUAfterPrefix(reply, "+CMGR:")
if !ok || len(fields) == 0 {
return SMSPDURecord{}, errors.New("incomplete CMGR record")
}
status, err := strconv.Atoi(fields[0])
if err != nil {
return SMSPDURecord{}, errors.New("invalid CMGR status")
}
return SMSPDURecord{Index: index, Status: status, PDU: pdu}, nil
}
// DeleteMatching confirms that the selected store and slot still match the
// committed PDU. check runs just before the delete to recheck SIM ownership.
func (inbox *SMSInbox) DeleteMatching(record SMSPDURecord, check func() error) error {
if err := inbox.modem.verifySMSStorage(inbox.current); err != nil {
return err
}
current, err := inbox.Read(record.Index)
if err != nil {
return err
}
if !current.Received() || !strings.EqualFold(current.PDU, record.PDU) {
return errors.New("SMS slot changed before deletion")
}
if err := check(); err != nil {
return err
}
return inbox.modem.DeleteSMS(uint32(record.Index))
}
+179
View File
@@ -0,0 +1,179 @@
package modem
import (
"errors"
"fmt"
"io"
"strconv"
"strings"
"time"
"github.com/yibaiba/hideck/pkg/logger"
)
const (
ml307cSMSPromptTimeout = 5 * time.Second
ml307cSMSResultTimeout = 60 * time.Second
)
func (m *Manager) sendML307CSMSPart(req commandRequest) error {
select {
case <-m.stop:
return errors.New("AT 管理器停止")
case m.cmdChanHigh <- req:
case <-time.After(5 * time.Second):
return errors.New("command queue full")
}
select {
case err := <-req.errChan:
return err
case <-req.respChan:
return nil
case <-m.stopped:
select {
case err := <-req.errChan:
return err
case <-req.respChan:
return nil
default:
return errors.New("AT 管理器停止")
}
}
}
// handleML307CSMS owns the AT queue from the command through the final
// response. No caller timeout can release the SMS lock mid-submission.
func (m *Manager) handleML307CSMS(req commandRequest) {
start := time.Now()
stage := "command"
promptSeen, submitted := false, false
written, mr, cms := 0, -1, -1
report := func(err error) {
fields := []any{
"device", m.cfg.ID, "stage", stage, "prompt_seen", promptSeen,
"planned_bytes", len(req.followUp), "written_bytes", written,
"elapsed", time.Since(start).Truncate(time.Millisecond),
}
if mr >= 0 {
fields = append(fields, "mr", mr)
}
if cms >= 0 {
fields = append(fields, "cms_code", cms)
}
if errors.Is(err, ErrSMSSubmitUnknown) {
logger.Warn("ML307C 短信提交结果未知", append(fields, "err", err)...)
} else if err != nil {
logger.Warn("ML307C 短信提交失败", append(fields, "err", err)...)
} else {
logger.Info("ML307C 短信提交已确认", fields...)
}
}
fail := func(err error, recoverPort, cancelInput bool) {
report(err)
if recoverPort {
if cancelInput {
// Cancel is best effort. Retire this owner even if ESC writes.
_, _ = m.port.Write([]byte{0x1B})
}
m.markUnhealthy()
m.Stop()
m.notifyDisconnect("ml307c_sms_unsynchronized")
}
req.errChan <- err
}
command := req.cmd + "\r"
n, err := m.port.Write([]byte(command))
if n != len(command) {
err = errors.Join(err, io.ErrShortWrite)
}
if err != nil {
fail(fmt.Errorf("写入 CMGS 命令失败 (%d/%d): %w", n, len(command), err), true, false)
return
}
stage = "prompt"
timer := time.NewTimer(req.timeout)
defer timer.Stop()
for {
select {
case <-timer.C:
if submitted {
fail(ErrSMSSubmitUnknown, true, false)
} else {
fail(errors.New("等待 CMGS 短信输入提示超时"), true, true)
}
return
case <-m.stop:
err := errors.New("AT 管理器停止")
if submitted {
err = ErrSMSSubmitUnknown
}
fail(err, false, false)
return
case message := <-m.rxChan:
if message.Err != nil {
err := message.Err
if submitted {
err = ErrSMSSubmitUnknown
}
fail(err, true, false)
return
}
line := strings.TrimSpace(message.Data)
switch {
case line == ">":
if promptSeen {
continue
}
stage = "submit"
promptSeen = true
written, err = m.port.Write([]byte(req.followUp))
if written != len(req.followUp) {
fail(errors.Join(errors.New("短信 PDU 写入未完成"), err, io.ErrShortWrite), true, true)
return
}
if err != nil {
fail(ErrSMSSubmitUnknown, true, false)
return
}
submitted = true
stage = "final"
timer.Reset(req.smsFinalTimeout)
case submitted && strings.HasPrefix(line, "+CMGS:"):
if value, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "+CMGS:"))); err == nil {
mr = value
}
case line == "OK":
m.resetATTimeoutWatchdog()
if !submitted {
fail(errors.New("未收到 CMGS 短信输入提示"), false, false)
return
}
if mr < 0 {
fail(ErrSMSSubmitUnknown, false, false)
return
}
report(nil)
req.respChan <- fmt.Sprintf("+CMGS: %d", mr)
return
case line == "ERROR" || strings.HasPrefix(line, "+CMS ERROR:") || strings.HasPrefix(line, "+CME ERROR:"):
m.resetATTimeoutWatchdog()
if value, ok := strings.CutPrefix(line, "+CMS ERROR:"); ok {
if code, err := strconv.Atoi(strings.TrimSpace(value)); err == nil {
cms = code
}
}
err := errors.New("模组拒绝 CMGS 短信提交")
if cms >= 0 {
err = fmt.Errorf("模组拒绝 CMGS 短信提交 (+CMS ERROR: %d)", cms)
}
fail(err, false, false)
return
default:
if m.isURC(line) {
m.handleURC(line)
}
}
}
}
}
+187
View File
@@ -0,0 +1,187 @@
package modem
import (
"errors"
"io"
"slices"
"strings"
"testing"
"time"
"github.com/yibaiba/hideck/pkg/smscodec"
)
type smsSubmitWirePort struct {
timeoutSerialPort
input chan string
done chan struct{}
write func([]byte) (int, error)
}
func (p *smsSubmitWirePort) Read(buf []byte) (int, error) {
select {
case data := <-p.input:
return copy(buf, data), nil
case <-p.done:
return 0, io.EOF
}
}
func (p *smsSubmitWirePort) Write(data []byte) (int, error) { return p.write(data) }
func (p *smsSubmitWirePort) Close() error {
close(p.done)
return nil
}
func TestML307CSMSSubmitWire(t *testing.T) {
const payload = "000100038177F700000341E110\x1A"
tests := []struct {
name string
profile ATProfile
short bool
missingFinal bool
wantErr error
}{
{name: "ML307C success", profile: ATProfileML307C},
{name: "ML307C result unknown", profile: ATProfileML307C, missingFinal: true, wantErr: ErrSMSSubmitUnknown},
{name: "ML307C short payload write", profile: ATProfileML307C, short: true, wantErr: io.ErrShortWrite},
{name: "legacy CRLF", profile: ATProfileDefault},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
m := newRunningTestManager(t)
m.atProfile = tt.profile
wire := &smsSubmitWirePort{input: make(chan string, 2), done: make(chan struct{})}
m.port = wire
t.Cleanup(func() { m.StopAndWait(time.Second) })
disconnected := make(chan string, 1)
m.SetOnDisconnectWithReason(func(reason string) { disconnected <- reason })
var writes []string
wire.write = func(data []byte) (int, error) {
n := len(data)
switch len(writes) {
case 0:
wire.input <- "\r\n> "
case 1:
if tt.short {
n--
} else if !tt.missingFinal {
if tt.profile == ATProfileML307C {
// The final reply arrives after the prompt deadline.
time.AfterFunc(250*time.Millisecond, func() { wire.input <- "\r\n+CMGS: 8\r\nOK\r\n" })
} else {
wire.input <- "\r\n+CMGS: 8\r\nOK\r\n"
}
}
}
writes = append(writes, string(data[:n]))
return n, nil
}
req := commandRequest{
cmd: "AT+CMGS=12", timeout: 200 * time.Millisecond,
respChan: make(chan string, 1), errChan: make(chan error, 1),
interactive: true, waitPrompt: true, followUp: payload,
}
if tt.profile == ATProfileML307C {
req.smsFinalTimeout = time.Second
if tt.missingFinal {
req.smsFinalTimeout = 10 * time.Millisecond
}
}
m.loopWG.Add(2)
go func() {
defer m.loopWG.Done()
m.readLoop()
}()
go func() {
defer m.loopWG.Done()
m.handleCommand(<-m.cmdChanHigh)
}()
wantWire := []string{"AT+CMGS=12\r", payload}
if tt.profile == ATProfileDefault {
m.cmdChanHigh <- req
select {
case reply := <-req.respChan:
if !strings.Contains(reply, "+CMGS: 8") {
t.Fatalf("legacy reply = %q", reply)
}
case err := <-req.errChan:
t.Fatal(err)
case <-time.After(time.Second):
t.Fatal("legacy submit did not complete")
}
wantWire[0] += "\n"
} else if err := m.sendML307CSMSPart(req); !errors.Is(err, tt.wantErr) {
t.Fatalf("submit error = %v, want %v", err, tt.wantErr)
}
if tt.short {
wantWire[1] = payload[:len(payload)-1]
wantWire = append(wantWire, "\x1B")
}
if tt.wantErr != nil {
select {
case reason := <-disconnected:
if reason != "ml307c_sms_unsynchronized" {
t.Fatalf("disconnect reason = %q", reason)
}
case <-time.After(time.Second):
t.Fatal("failed submit did not retire the serial owner")
}
if _, err := m.ExecuteAT("AT+CIMI", time.Millisecond); err == nil {
t.Fatal("AT query accepted on the retired serial owner")
}
}
if !slices.Equal(writes, wantWire) {
t.Fatalf("serial writes = %q, want %q", writes, wantWire)
}
})
}
}
func TestML307CSMSSubmitPreservesConfirmedParts(t *testing.T) {
for _, test := range []struct {
name string
err error
}{
{name: "unknown submit", err: ErrSMSSubmitUnknown},
{name: "explicit rejection", err: errors.New("modem rejected submit")},
} {
t.Run(test.name, func(t *testing.T) {
m := newRunningTestManager(t)
m.atProfile = ATProfileML307C
commands := make(chan []string, 1)
go func() {
var seen []string
for i := 0; i < 3; i++ {
req := <-m.cmdChanHigh
seen = append(seen, req.cmd)
if i == 2 {
req.errChan <- test.err
} else {
req.respChan <- "OK"
}
}
commands <- seen
}()
err := m.SendSMSWithOptions("777", strings.Repeat("A", 320), smscodec.SubmitOptions{})
var progress *SMSSubmitError
if !errors.Is(err, test.err) || !errors.As(err, &progress) || progress.PartsConfirmed != 1 || progress.PartsTotal != 3 {
t.Fatalf("send progress = %+v, err = %v", progress, err)
}
seen := <-commands
if seen[0] != "AT+CMGF=0" || !strings.HasPrefix(seen[1], "AT+CMGS=") || !strings.HasPrefix(seen[2], "AT+CMGS=") {
t.Fatalf("commands = %v", seen)
}
select {
case req := <-m.cmdChanHigh:
t.Fatalf("unexpected submission after a segment failed: %q", req.cmd)
default:
}
})
}
}
+14 -3
View File
@@ -80,20 +80,31 @@ func (m *Manager) handleCmdSendSMS(cmdCtx CommandContext, args []string) string
ctx = messaging.WithSuppressSendTGSuccess(ctx)
routed, sendErr := m.pool.SendRoutedSMS(ctx, worker, phone, message, smscodec.SubmitOptions{})
channel := smsRouteChannelLabel(routed.Via)
if sendErr != nil {
state := routed.Outcome.DeliveryState
unconfirmed := routed.Via == device.RoutedSMSViaCS &&
(state == db.SMSDeliveryStateUnknown || state == db.SMSDeliveryStatePartialAck)
if sendErr != nil && !unconfirmed {
cmdCtx.Reply(fmt.Sprintf("发送短信 / 失败\n设备 %s\n号码 %s\n通道 %s\n原因 %v", displayName, phone, channel, sendErr))
return
}
if routed.Via == device.RoutedSMSViaCS {
status := 2
if unconfirmed {
status = db.SMSStatusSubmitUnconfirmed
}
err := db.SaveSMSForIdentity(db.SMSRecord{
Identity: db.SMSIdentity{ICCID: routed.Identity.ICCID, IMSI: routed.Identity.IMSI},
Sender: worker.ID, Recipient: phone, Content: message,
Type: 2, Status: 2, Timestamp: time.Now(),
Type: 2, Status: status, Timestamp: time.Now(),
})
if err != nil {
logger.Warn("短信发送成功但入库失败", "device", deviceID, "err", err)
logger.Warn("短信发送记录入库失败", "device", deviceID, "err", err)
}
}
if unconfirmed {
cmdCtx.Reply(fmt.Sprintf("发送短信 / 提交未完全确认\n设备 %s\n号码 %s\n通道 %s\n结果 %v\n请勿重发整条", displayName, phone, channel, sendErr))
return
}
cmdCtx.Reply(fmt.Sprintf("发送短信 / 完成\n设备 %s\n号码 %s\n通道 %s\n内容 %s", displayName, phone, channel, message))
}()
+28
View File
@@ -12,6 +12,7 @@ import (
"github.com/yibaiba/hideck/internal/config"
"github.com/yibaiba/hideck/internal/db"
"github.com/yibaiba/hideck/internal/device"
"github.com/yibaiba/hideck/internal/modem"
"github.com/yibaiba/hideck/pkg/smscodec"
)
@@ -72,6 +73,33 @@ func TestHandleCmdSendSMSFallsBackToCSWithoutDoubleSend(t *testing.T) {
}
}
func TestHandleCmdSendSMSReportsUnknownSubmission(t *testing.T) {
pool, _ := newRoutedSMSTestPool(t)
csCalls := 0
pool.SetRoutedSMSTestSenders(
func(context.Context, string, string, string, smscodec.SubmitOptions) (messaging.SendOutcome, error) {
return messaging.SendOutcome{}, messaging.ErrSMSNotReady
},
func(string, string, string) error { csCalls++; return modem.ErrSMSSubmitUnknown },
)
replies := make(chan string, 1)
manager := &Manager{pool: pool}
_ = manager.handleCmdSendSMS(testCommandContext{replies: replies}, []string{"wwan0", "888", "BAL"})
select {
case got := <-replies:
if !strings.Contains(got, "提交未完全确认") || !strings.Contains(got, "请勿重发整条") {
t.Fatalf("reply=%q", got)
}
case <-time.After(time.Second):
t.Fatal("command SMS reply was not delivered")
}
var count int64
err := db.DB.Model(&db.SMS{}).Where("type = ? AND status = ?", 2, db.SMSStatusSubmitUnconfirmed).Count(&count).Error
if csCalls != 1 || err != nil || count != 1 {
t.Fatalf("calls=%d unconfirmed history=%d err=%v", csCalls, count, err)
}
}
func TestHandleCmdSendSMSDoesNotFallbackAfterIMSAccept(t *testing.T) {
pool, _ := newRoutedSMSTestPool(t)
csCalls := 0
+30 -24
View File
@@ -104,8 +104,36 @@ func classifyBinarySMS(t *tpdu.TPDU, msg []byte) binarySMSClassification {
c.SummaryLines = append(c.SummaryLines, fmt.Sprintf("wsp_tid=0x%02x pdu=0x%02x", wsp.TransactionID, wsp.PDUType))
}
// OMA CP:优先由端口识别,其次由 content-type 识别。
if (hasDestPort && destPort == wapPushPort16) || isLikelyOMAContentType(c.ContentType) {
oma := isLikelyOMAContentType(c.ContentType)
si := isLikelySIContentType(c.ContentType)
sl := isLikelySLContentType(c.ContentType)
mms := isLikelyMMSContentType(c.ContentType)
unknownType := !oma && !si && !sl && !mms
// WAP SI / SL
if si || (unknownType && isLikelySIWBXML(c.Payload)) {
c.Kind = binaryKindWAPSI
c.Label = "WAP SI Push"
addSISLHints(&c, c.Payload)
return c
}
if sl || (unknownType && isLikelySLWBXML(c.Payload)) {
c.Kind = binaryKindWAPSL
c.Label = "WAP SL Push"
addSISLHints(&c, c.Payload)
return c
}
// MMS Notification
if mms || (unknownType && isLikelyMMSNotification(c.Payload)) {
c.Kind = binaryKindMMSNotification
c.Label = "MMS Notification"
addMMSHints(&c, c.Payload)
return c
}
// Recognized WAP payloads take precedence over the shared port fallback.
if oma || (hasDestPort && destPort == wapPushPort16) {
c.Kind = binaryKindOmaCP
c.Label = "OMA CP 运营商配置短信"
if cfg, err := DecodeOmaCPFromTPDU(c.Payload); err == nil {
@@ -118,28 +146,6 @@ func classifyBinarySMS(t *tpdu.TPDU, msg []byte) binarySMSClassification {
return c
}
// WAP SI / SL
if isLikelySIContentType(c.ContentType) || isLikelySIWBXML(c.Payload) {
c.Kind = binaryKindWAPSI
c.Label = "WAP SI Push"
addSISLHints(&c, c.Payload)
return c
}
if isLikelySLContentType(c.ContentType) || isLikelySLWBXML(c.Payload) {
c.Kind = binaryKindWAPSL
c.Label = "WAP SL Push"
addSISLHints(&c, c.Payload)
return c
}
// MMS Notification
if isLikelyMMSContentType(c.ContentType) || isLikelyMMSNotification(c.Payload) {
c.Kind = binaryKindMMSNotification
c.Label = "MMS Notification"
addMMSHints(&c, c.Payload)
return c
}
// SIM OTA (23.048) 分类识别(不解密)
if isLikelySIMOTA(t, c.Payload, c.ContentType, hasDestPort, destPort) {
c.Kind = binaryKindSIMOTA
+13 -1
View File
@@ -60,6 +60,15 @@ func TestClassifyBinarySMS_OmaCPByPort(t *testing.T) {
}
}
func TestClassifyBinarySMS_ExplicitOMATypeBeatsMMSHint(t *testing.T) {
ct := "application/vnd.wap.connectivity-wbxml\x00"
msg := append([]byte{0x21, 0x06, byte(len(ct))}, []byte(ct)...)
msg = append(msg, 0x8C, 0x82)
if kind := classifyBinarySMS(&tpdu.TPDU{}, msg).Kind; kind != binaryKindOmaCP {
t.Fatalf("explicit OMA content type classified as %s", kind)
}
}
func TestClassifyBinarySMS_WAPSI(t *testing.T) {
// WSP header 使用文本 content-type,避免依赖 token 映射。
ct := "application/vnd.wap.sic\x00"
@@ -88,7 +97,10 @@ func TestClassifyBinarySMS_MMSNotification(t *testing.T) {
msg := append([]byte{0x31, 0x06, byte(len(ct))}, []byte(ct)...)
msg = append(msg, body...)
c := classifyBinarySMS(&tpdu.TPDU{}, msg)
tp := &tpdu.TPDU{UDH: tpdu.UserDataHeader{
{ID: 0x05, Data: []byte{0x0B, 0x84, 0x23, 0xF0}},
}}
c := classifyBinarySMS(tp, msg)
if c.Kind != binaryKindMMSNotification {
t.Fatalf("应识别为 MMS Notification,实际: %s", c.Kind)
}
+49
View File
@@ -369,9 +369,55 @@ type ConcatInfo struct {
Seq int // 当前序号 (1-based)
}
type ATDeliverSMS struct {
Sender string
Content string
Timestamp time.Time
SCTS string
SMSC string
PID byte
DCS byte
ApplicationPorts string
Concat ConcatInfo
Binary bool
}
// DecodeATDeliverSMS decodes a full PDU from an AT storage slot, preserving
// the original SCTS octets used to separate multipart sessions.
func DecodeATDeliverSMS(fullPDU []byte) (ATDeliverSMS, error) {
if len(fullPDU) == 0 || 1+int(fullPDU[0]) >= len(fullPDU) {
return ATDeliverSMS{}, errors.New("invalid SMSC length")
}
smscEnd := 1 + int(fullPDU[0])
tpduBytes := fullPDU[smscEnd:]
dcs, _, udOffset, _, alphabet, ok := deliverTPDULayout(tpduBytes)
if !ok {
return ATDeliverSMS{}, errors.New("invalid SMS-DELIVER TPDU layout")
}
part := ATDeliverSMS{
SCTS: hex.EncodeToString(tpduBytes[udOffset-8 : udOffset-1]),
SMSC: hex.EncodeToString(fullPDU[:smscEnd]),
PID: tpduBytes[udOffset-10],
DCS: dcs,
Binary: alphabet == tpdu.Alpha8Bit,
}
var err error
var ports udhPorts
part.Sender, part.Content, part.Timestamp, part.Concat, err = decodeDeliverTPDU(tpduBytes, &ports)
if err == nil && (ports.Has8Bit || ports.Has16Bit) {
part.ApplicationPorts = fmt.Sprintf("%t:%d:%d:%t:%d:%d", ports.Has8Bit, ports.DestPort8, ports.SrcPort8,
ports.Has16Bit, ports.DestPort16, ports.SrcPort16)
}
return part, err
}
// DecodeDeliverTPDU 解码下行短信 TPDU,返回发送方号码、文本内容、发送时间、和 concat 分片信息。
// 如果 TPDU 包含 UDH concatenation header(长短信分片),concat.IsConcat 为 true。
func DecodeDeliverTPDU(tpduBytes []byte) (sender string, text string, ts time.Time, concat ConcatInfo, err error) {
return decodeDeliverTPDU(tpduBytes, nil)
}
func decodeDeliverTPDU(tpduBytes []byte, ports *udhPorts) (sender string, text string, ts time.Time, concat ConcatInfo, err error) {
if trimmed, ok := TrimDeliverTPDUToDeclaredLength(tpduBytes); ok {
tpduBytes = trimmed
}
@@ -386,6 +432,9 @@ func DecodeDeliverTPDU(tpduBytes []byte) (sender string, text string, ts time.Ti
if err != nil {
return "", "", time.Time{}, ConcatInfo{}, err
}
if ports != nil {
*ports = parseUDHPorts(t.UDH)
}
// 检测 UDH 中的 concatenation 信息(长短信分片标识)
if t.UDH != nil {
if segments, seqno, mref, ok := t.UDH.ConcatInfo8(); ok && segments > 1 {
+2
View File
@@ -29,6 +29,8 @@ export type PhoneDevice = {
vowifi_enabled?: boolean
vowifi_active?: boolean
software_ims_blocked?: boolean
native_voice_unavailable_reason?: string
cellular_ims_unavailable_reason?: string
phone_region?: string
phone_country_code?: number
rf_lock?: string
+5 -2
View File
@@ -121,10 +121,13 @@ export const smsService = {
},
send(payload: SmsSendPayload) {
return callService(async () => {
const res = await api.post<{ parts_total?: number; destination: string }>('/sms/send', payload)
const res = await api.post<{ parts_total?: number; destination: string; delivery_state?: string; message?: string }>('/sms/send', payload)
const { delivery_state, message } = res.data
const uncertain = res.status === 202 && (delivery_state === 'unknown' || delivery_state === 'partial_ack')
return {
partsTotal: Number(res.data?.parts_total || 0),
destination: res.data.destination
destination: res.data.destination,
submissionWarning: uncertain ? (message || '短信提交未完全确认,请勿重发整条') : ''
}
})
},
+12 -2
View File
@@ -6,7 +6,15 @@ export type PhoneModeWarning = { title: string; message: string }
export function phoneModeDisabledReason(device: PhoneDevice | undefined, mode: string): string | undefined {
if (!device) return '请先选择设备'
if ((mode === 'wifi' || mode === 'cellular') && device.software_ims_blocked) {
return '此 SIM 卡不支持软件 IMS,请使用 VoLTE 或模组直拨'
return device.native_voice_unavailable_reason
? `此 SIM 卡不支持软件 IMS。${device.native_voice_unavailable_reason}`
: '此 SIM 卡不支持软件 IMS,请使用 VoLTE 或模组直拨'
}
if ((mode === 'volte' || mode === 'modem_voice') && device.native_voice_unavailable_reason) {
return device.native_voice_unavailable_reason
}
if (mode === 'cellular' && device.cellular_ims_unavailable_reason) {
return device.cellular_ims_unavailable_reason
}
if (phoneModeCampsOnCell(mode) && device.rf_lock) {
return '此 SIM 卡禁止蜂窝驻网,不能切换到该模式'
@@ -54,7 +62,9 @@ export async function confirmPhoneModeChange(options: ChangeOptions): Promise<bo
const target = options.target
if (!current || options.hasCall() || current.id !== target.id || current.iccid !== target.iccid
|| current.phone_mode !== target.phone_mode || current.vowifi_enabled !== target.vowifi_enabled
|| current.rf_lock !== target.rf_lock || current.software_ims_blocked !== target.software_ims_blocked) {
|| current.rf_lock !== target.rf_lock || current.software_ims_blocked !== target.software_ims_blocked
|| current.native_voice_unavailable_reason !== target.native_voice_unavailable_reason
|| current.cellular_ims_unavailable_reason !== target.cellular_ims_unavailable_reason) {
throw new Error('设备、SIM 卡或通话状态已变化,请重新确认切换')
}
await options.apply()
+20 -5
View File
@@ -57,6 +57,7 @@ const selected = computed(() => phone.devices.find((device) => device.id === sel
const calleeError = computed(() => dialNumberError(callee.value, selected.value?.phone_region))
const canPlaceCall = computed(() => !!callee.value && !calleeError.value
&& !!selected.value
&& !selectedModeBlocked.value
&& (isDeviceReady(selected.value) || selected.value.phone_mode === 'cellular' || selected.value.phone_mode === 'volte')
&& !isDeviceBusy(selected.value))
watch(call, (current) => {
@@ -115,6 +116,10 @@ function deviceModeLabel(device?: PhoneDevice) {
function deviceStatus(device?: PhoneDevice) {
if (!device) return '未选择设备'
if (isDeviceBusy(device)) return '通话占用'
if ((device.native_voice_unavailable_reason || device.cellular_ims_unavailable_reason)
&& phoneModeDisabledReason(device, device.phone_mode || 'wifi')) {
return '当前通话方式不可用'
}
const mode = deviceModeLabel(device)
if (device.phone_mode === 'modem_voice') {
if (device.voice.phase === 'restarting') return `${mode} · 重启模组中`
@@ -147,6 +152,13 @@ const selectedMode = computed(() => {
if (mode === 'cellular' || mode === 'volte' || mode === 'modem_voice') return mode
return 'wifi'
})
const selectedDeviceModeReasons = computed(() => [
selected.value?.native_voice_unavailable_reason,
selected.value?.cellular_ims_unavailable_reason
].filter(Boolean).join('。'))
const selectedModeBlocked = computed(() => selectedDeviceModeReasons.value
? phoneModeDisabledReason(selected.value, selectedMode.value)
: undefined)
const selectedStrategy = computed(() => selected.value?.data_strategy === 'always' ? 'always' : 'on_demand')
const modePending = ref(false)
@@ -473,7 +485,7 @@ async function sendDTMF(digit: string) {
<el-radio-button value="modem_voice" :disabled="!!phoneModeDisabledReason(selected, 'modem_voice')" :title="phoneModeDisabledReason(selected, 'modem_voice')">模组直拨</el-radio-button>
</el-radio-group>
<el-select
v-if="selectedMode === 'cellular'"
v-if="selectedMode === 'cellular' && !selectedModeBlocked"
:model-value="selectedStrategy"
size="small"
style="width: 160px"
@@ -483,17 +495,20 @@ async function sendDTMF(digit: string) {
<el-option label="仅打电话时开" value="on_demand" />
<el-option label="长时间开启" value="always" />
</el-select>
<p v-if="selectedMode === 'cellular'" class="phone-mode-hint">
<p v-if="selectedDeviceModeReasons" class="phone-mode-hint" role="status">
{{ selectedModeBlocked || selectedDeviceModeReasons }}
</p>
<p v-if="selectedMode === 'cellular' && !selectedModeBlocked" class="phone-mode-hint">
{{ selected?.network_enabled
? (selectedStrategy === 'always' ? '网络已开,数据会保持连接。' : '网络已开,只有拨号时才连数据,挂断后关闭。')
: '会正常驻网,待机不走流量。打蜂窝电话会临时打开数据。' }}
</p>
<div v-if="selectedMode === 'modem_voice'" class="phone-mode-hint" role="status" aria-live="polite">
<div v-if="selectedMode === 'modem_voice' && !selectedModeBlocked" class="phone-mode-hint" role="status" aria-live="polite">
<p>使用 SIM 卡拨打和接听,声音通过网页传输。接通后可用键盘按键。</p>
<p v-if="selected?.voice.last_error" class="phone-mode-hint is-warn" role="alert">{{ selected.voice.last_error }}</p>
<el-button v-if="selected?.voice.phase === 'failed'" :loading="modePending" :disabled="!!call" @click="void changePhoneMode('modem_voice')">重新准备</el-button>
</div>
<p v-if="selectedMode === 'volte'" class="phone-mode-hint">
<p v-if="selectedMode === 'volte' && !selectedModeBlocked" class="phone-mode-hint">
{{ selected?.software_ims_blocked
? '这张卡需要使用模组驻网通话,可选择 VoLTE 或已适配的模组直拨。打开「网络」才会用上网流量。'
: selected?.native_volte?.uac_unusable
@@ -517,7 +532,7 @@ async function sendDTMF(digit: string) {
</span>
<el-switch
:model-value="selected?.vowifi_enabled === true"
:disabled="!!call || modePending || lebaraIdentityBusy(selected)"
:disabled="!!call || modePending || lebaraIdentityBusy(selected) || (!!selectedModeBlocked && !selected?.vowifi_enabled)"
:loading="modePending || lebaraIdentityBusy(selected)"
aria-label="启动 WiFi calling"
@change="toggleWifiCalling"
+9 -2
View File
@@ -646,8 +646,12 @@ async function handleSendModal() {
message: sendForm.value.message
})
if (!result.ok) throw new Error(result.error.message || '发送失败')
const parts = result.data.partsTotal
ElMessage.success(`短信已提交${parts > 1 ? `(${parts}段)` : ''}`)
if (result.data.submissionWarning) {
ElMessage.warning(result.data.submissionWarning)
} else {
const parts = result.data.partsTotal
ElMessage.success(`短信已提交${parts > 1 ? `(${parts}段)` : ''}`)
}
showSendModal.value = false
setTimeout(async () => {
await fetchMessagesAndThread()
@@ -673,6 +677,9 @@ async function sendToCurrentThread() {
try {
const result = await smsStore.send({ iccid: t.iccid, phone: t.peer, message: text })
if (!result.ok) throw new Error(result.error.message || '发送失败')
if (result.data.submissionWarning) {
ElMessage.warning(result.data.submissionWarning)
}
composer.value = ''
if (viewingTarget.value && selectedThreadKey.value === t.key) {
showLatestMessages()
+15
View File
@@ -33,6 +33,21 @@ test('mode availability follows SIM capability and RF lock, not country alone',
assert.ok(phoneModeDisabledReason(undefined, 'wifi'))
})
test('ML307C blocks native voice and cellular IMS modes and preserves One NZ WiFi calling', () => {
const reason = 'ML307C 在 HiDeck 中不支持原生 VoLTE 和模组直拨'
const cellularReason = 'ML307C 在 HiDeck 中不支持通过模组蜂窝数据使用软件 IMS'
const oneNZ = {
...device(), phone_region: 'NZ', native_voice_unavailable_reason: reason,
cellular_ims_unavailable_reason: cellularReason
}
assert.equal(phoneModeDisabledReason(oneNZ, 'volte'), reason)
assert.equal(phoneModeDisabledReason(oneNZ, 'modem_voice'), reason)
assert.equal(phoneModeDisabledReason(oneNZ, 'wifi'), undefined)
assert.equal(phoneModeDisabledReason(oneNZ, 'cellular'), cellularReason)
const china = { ...oneNZ, phone_region: 'CN', software_ims_blocked: true }
assert.equal(phoneModeDisabledReason(china, 'wifi'), `此 SIM 卡不支持软件 IMS。${reason}`)
})
test('mode radio buttons use the group change event, not clicks on disabled labels', () => {
const source = readFileSync(new URL('../src/views/Phone.vue', import.meta.url), 'utf8')
const group = source.match(/<el-radio-group[\s\S]*?<\/el-radio-group>/)![0]
+1 -1
View File
@@ -253,7 +253,7 @@ test('wifi calling keeps a dedicated start switch under the mode control', () =>
assert.match(phoneView, /disableVoWiFi\(selectedDevice\.value\)/)
assert.match(phoneView, /打开后开始注册。关掉只停服务,仍是 WiFi calling/)
assert.match(phoneView, /if \(mode === selectedMode\.value\) \{[\s\S]*if \(mode === 'wifi'\) return/)
assert.match(phoneView, /:disabled="!!call \|\| modePending \|\| lebaraIdentityBusy\(selected\)"/)
assert.match(phoneView, /:disabled="!!call \|\| modePending \|\| lebaraIdentityBusy\(selected\)/)
assert.doesNotMatch(phoneView, /modePending \|\| !!selected\?\.rf_lock/)
assert.match(phoneView, /status === 'recovering' \|\| status === 'waiting_identity'/)
assert.match(phoneView, /正在恢复英国身份/)