From 72bd58db1d4f3877411259df85f73fcb075fe210 Mon Sep 17 00:00:00 2001 From: yibaiba <946100224@qq.com> Date: Tue, 8 Sep 2026 17:01:51 +0800 Subject: [PATCH] fix: persist unsupported IMS subscriptions --- internal/db/db.go | 1 + internal/db/ims_subscription_rejection.go | 126 ++++++++++++++++ .../db/ims_subscription_rejection_test.go | 74 +++++++++ internal/device/vowifi_delivery_store.go | 21 ++- internal/device/vowifi_delivery_store_test.go | 1 + .../vowifi/imscore/subscription_attempt.go | 9 +- .../imscore/subscription_attempt_race_test.go | 4 +- .../vowifi/imscore/subscription_exchange.go | 8 +- .../vowifi/imscore/subscription_lifecycle.go | 12 +- .../imscore/subscription_lifecycle_test.go | 14 +- .../subscription_registration_store.go | 142 ++++++++++++++++-- .../subscription_registration_store_test.go | 100 ++++++++++-- .../vowifi/imscore/subscription_timers.go | 2 +- .../internal/vowifi/runtimecore/runtime.go | 4 +- .../internal/vowifi/runtimecore/types.go | 1 + .../vowifi-go/runtimehost/adapters_test.go | 47 ++++++ .../vowifi-go/runtimehost/messaging/types.go | 9 ++ .../runtimehost/runtimecore_adapters.go | 8 + .../runtimehost/runtimecore_start.go | 5 +- third_party/vowifi-go/runtimehost/start.go | 3 + 20 files changed, 544 insertions(+), 47 deletions(-) create mode 100644 internal/db/ims_subscription_rejection.go create mode 100644 internal/db/ims_subscription_rejection_test.go diff --git a/internal/db/db.go b/internal/db/db.go index e9069ac8..0e62d142 100644 --- a/internal/db/db.go +++ b/internal/db/db.go @@ -177,6 +177,7 @@ func Init(dbPath string) error { &VoiceCallRecord{}, &PhoneContact{}, &DisclaimerAcceptance{}, + &IMSSubscriptionRejection{}, ); err != nil { return err } diff --git a/internal/db/ims_subscription_rejection.go b/internal/db/ims_subscription_rejection.go new file mode 100644 index 00000000..de937cdd --- /dev/null +++ b/internal/db/ims_subscription_rejection.go @@ -0,0 +1,126 @@ +package db + +import ( + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "strings" + "time" + + "gorm.io/gorm" +) + +const maxIMSSubscriptionIdentityBytes = 4096 + +type IMSSubscriptionRejection struct { + IdentityHash string `gorm:"column:identity_hash;primaryKey;size:64"` + EventPackage string `gorm:"column:event_package;primaryKey;size:32"` + StatusCode int `gorm:"column:status_code;not null"` + ExpiresAt time.Time `gorm:"column:expires_at;index;not null"` + CreatedAt time.Time `gorm:"column:created_at"` + UpdatedAt time.Time `gorm:"column:updated_at"` +} + +func LoadIMSSubscriptionRejection( + identity, eventPackage string, + now time.Time, +) (int, time.Time, error) { + identityHash, eventPackage, err := normalizeIMSSubscriptionRejectionKey(identity, eventPackage) + if err != nil { + return 0, time.Time{}, err + } + if DB == nil { + return 0, time.Time{}, gorm.ErrInvalidDB + } + var row IMSSubscriptionRejection + err = DB.Where("identity_hash = ? AND event_package = ?", identityHash, eventPackage).First(&row).Error + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return 0, time.Time{}, nil + } + return 0, time.Time{}, err + } + if !now.Before(row.ExpiresAt) { + err = DB.Delete(&row).Error + return 0, time.Time{}, err + } + if !validPersistentSubscriptionStatus(row.StatusCode) { + return 0, time.Time{}, fmt.Errorf("invalid persisted IMS subscription status %d", row.StatusCode) + } + return row.StatusCode, row.ExpiresAt, nil +} + +func SaveIMSSubscriptionRejection( + identity, eventPackage string, + status int, + expiresAt time.Time, +) error { + identityHash, eventPackage, err := normalizeIMSSubscriptionRejectionKey(identity, eventPackage) + if err != nil { + return err + } + if !validPersistentSubscriptionStatus(status) { + return fmt.Errorf("IMS subscription status %d is not persistable", status) + } + if expiresAt.IsZero() { + return fmt.Errorf("IMS subscription rejection expiration is required") + } + if DB == nil { + return gorm.ErrInvalidDB + } + return DB.Transaction(func(tx *gorm.DB) error { + return upsertIMSSubscriptionRejection(tx, IMSSubscriptionRejection{ + IdentityHash: identityHash, EventPackage: eventPackage, + StatusCode: status, ExpiresAt: expiresAt, + }) + }) +} + +func DeleteIMSSubscriptionRejections(identity string) error { + identityHash, _, err := normalizeIMSSubscriptionRejectionKey(identity, "reg") + if err != nil { + return err + } + if DB == nil { + return gorm.ErrInvalidDB + } + return DB.Where("identity_hash = ?", identityHash).Delete(&IMSSubscriptionRejection{}).Error +} + +func upsertIMSSubscriptionRejection(tx *gorm.DB, row IMSSubscriptionRejection) error { + var current IMSSubscriptionRejection + err := tx.Where( + "identity_hash = ? AND event_package = ?", row.IdentityHash, row.EventPackage, + ).First(¤t).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return tx.Create(&row).Error + } + if err != nil { + return err + } + if current.ExpiresAt.After(row.ExpiresAt) { + row.ExpiresAt = current.ExpiresAt + } + return tx.Model(¤t).Updates(map[string]any{ + "status_code": row.StatusCode, + "expires_at": row.ExpiresAt, + }).Error +} + +func normalizeIMSSubscriptionRejectionKey(identity, eventPackage string) (string, string, error) { + identity = strings.TrimSpace(identity) + if identity == "" || len(identity) > maxIMSSubscriptionIdentityBytes { + return "", "", fmt.Errorf("invalid IMS subscription identity length %d", len(identity)) + } + eventPackage = strings.ToLower(strings.TrimSpace(eventPackage)) + if eventPackage != "reg" && eventPackage != "message-summary" { + return "", "", fmt.Errorf("unsupported IMS event package %q", eventPackage) + } + digest := sha256.Sum256([]byte(identity)) + return hex.EncodeToString(digest[:]), eventPackage, nil +} + +func validPersistentSubscriptionStatus(status int) bool { + return status == 405 || status == 489 +} diff --git a/internal/db/ims_subscription_rejection_test.go b/internal/db/ims_subscription_rejection_test.go new file mode 100644 index 00000000..ef83295f --- /dev/null +++ b/internal/db/ims_subscription_rejection_test.go @@ -0,0 +1,74 @@ +package db + +import ( + "path/filepath" + "testing" + "time" +) + +func TestIMSSubscriptionRejectionPersistence(t *testing.T) { + previousDB := DB + if err := Init(filepath.Join(t.TempDir(), "subscription-rejections.db")); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if sqlDB, err := DB.DB(); err == nil { + _ = sqlDB.Close() + } + DB = previousDB + }) + + identity := "wwan0\x00user@ims.example\x00ims.example" + now := time.Now().UTC().Truncate(time.Second) + expiresAt := now.Add(time.Hour) + if err := SaveIMSSubscriptionRejection(identity, "reg", 489, expiresAt); err != nil { + t.Fatal(err) + } + status, loadedExpiry, err := LoadIMSSubscriptionRejection(identity, "reg", now) + if err != nil || status != 489 || !loadedExpiry.Equal(expiresAt) { + t.Fatalf("loaded status=%d expiry=%s err=%v", status, loadedExpiry, err) + } + + if err := SaveIMSSubscriptionRejection(identity, "reg", 405, now.Add(time.Minute)); err != nil { + t.Fatal(err) + } + status, loadedExpiry, err = LoadIMSSubscriptionRejection(identity, "reg", now) + if err != nil || status != 405 || !loadedExpiry.Equal(expiresAt) { + t.Fatalf("short update status=%d expiry=%s err=%v", status, loadedExpiry, err) + } + if err := DeleteIMSSubscriptionRejections(identity); err != nil { + t.Fatal(err) + } + status, _, err = LoadIMSSubscriptionRejection(identity, "reg", now) + if err != nil || status != 0 { + t.Fatalf("deleted status=%d err=%v", status, err) + } +} + +func TestIMSSubscriptionRejectionExpiresAndValidatesBoundary(t *testing.T) { + previousDB := DB + if err := Init(filepath.Join(t.TempDir(), "subscription-rejections.db")); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if sqlDB, err := DB.DB(); err == nil { + _ = sqlDB.Close() + } + DB = previousDB + }) + + now := time.Now().UTC().Truncate(time.Second) + if err := SaveIMSSubscriptionRejection("identity", "message-summary", 405, now.Add(-time.Second)); err != nil { + t.Fatal(err) + } + status, _, err := LoadIMSSubscriptionRejection("identity", "message-summary", now) + if err != nil || status != 0 { + t.Fatalf("expired status=%d err=%v", status, err) + } + if err := SaveIMSSubscriptionRejection("identity", "reg", 503, now.Add(time.Hour)); err == nil { + t.Fatal("transient status was persisted") + } + if _, _, err := LoadIMSSubscriptionRejection("identity", "unknown", now); err == nil { + t.Fatal("unknown event package was accepted") + } +} diff --git a/internal/device/vowifi_delivery_store.go b/internal/device/vowifi_delivery_store.go index 70ab03c3..d9eb2cd9 100644 --- a/internal/device/vowifi_delivery_store.go +++ b/internal/device/vowifi_delivery_store.go @@ -4,13 +4,32 @@ import ( "errors" "time" - "github.com/yibaiba/hideck/internal/db" "github.com/iniwex5/vowifi-go/runtimehost/messaging" + "github.com/yibaiba/hideck/internal/db" "gorm.io/gorm" ) type vowifiDeliveryStore struct{} +func (vowifiDeliveryStore) LoadIMSSubscriptionRejection( + identity, eventPackage string, + now time.Time, +) (int, time.Time, error) { + return db.LoadIMSSubscriptionRejection(identity, eventPackage, now) +} + +func (vowifiDeliveryStore) SaveIMSSubscriptionRejection( + identity, eventPackage string, + status int, + expiresAt time.Time, +) error { + return db.SaveIMSSubscriptionRejection(identity, eventPackage, status, expiresAt) +} + +func (vowifiDeliveryStore) DeleteIMSSubscriptionRejections(identity string) error { + return db.DeleteIMSSubscriptionRejections(identity) +} + func (vowifiDeliveryStore) CreateSMSDelivery(messageID, imsi, deviceID, peer, content string, partsTotal int, at time.Time) error { return db.CreateSMSDelivery(messageID, imsi, deviceID, peer, content, partsTotal, at) } diff --git a/internal/device/vowifi_delivery_store_test.go b/internal/device/vowifi_delivery_store_test.go index fe7bbffe..d924bece 100644 --- a/internal/device/vowifi_delivery_store_test.go +++ b/internal/device/vowifi_delivery_store_test.go @@ -12,6 +12,7 @@ import ( var _ messaging.InboundFragmentStore = vowifiDeliveryStore{} var _ messaging.InboundFragmentLifecycleStore = vowifiDeliveryStore{} +var _ messaging.SubscriptionRejectionStore = vowifiDeliveryStore{} func TestVoWiFiDeliveryStoreReportsMatchedPart(t *testing.T) { previousDB := db.DB diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt.go index 2c7b9452..f2c34a77 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt.go @@ -34,10 +34,11 @@ func (s *Service) subscriptionAttemptBlockedLocked(mwi, unsubscribe bool) error } lifecycle := s.subscriptionFieldsLocked(mwi).lifecycle status := lifecycle.rejectedStatus - if mwi { - if rejected := s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding); rejected != 0 { - status = rejected - } + if rejected := s.subscriptionRegistrations.rejected( + s.subscriptionBinding, + subscriptionEventPackage(mwi), + ); rejected != 0 { + status = rejected } if status != 0 { return fmt.Errorf("imscore: subscription previously rejected with status %d", status) diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt_race_test.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt_race_test.go index 8fbce859..9870583a 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt_race_test.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_attempt_race_test.go @@ -109,7 +109,7 @@ func TestSubscriptionLateResponseCannotChangeReopenedUsage(t *testing.T) { if !reflect.DeepEqual(*f.lifecycle, lifecycle) || !reflect.DeepEqual(*f.dialog, dialog) || *f.lastErr != lastErr || *f.closed { t.Fatal("stale response changed the new usage") } - if s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding) != 0 { + if s.subscriptionRegistrations.rejected(s.subscriptionBinding, subscriptionEventPackage(mwi)) != 0 { t.Fatal("retired response marked the current identity unsupported") } completeProtocolSubscription(t, s, mwi, next) @@ -208,7 +208,7 @@ func TestMWISharedRejectionBlocksAlreadyBuiltAttempt(t *testing.T) { t.Fatal(err) } } - s.subscriptionRegistrations.rejectMWI(s.subscriptionBinding, status) + s.subscriptionRegistrations.reject(s.subscriptionBinding, mwiEventPackage, status) if queued { attempt.err = s.subscriptionSent(attempt, true) } else { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_exchange.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_exchange.go index 36001e57..70ada090 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_exchange.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_exchange.go @@ -123,9 +123,11 @@ func (s *Service) failSubscriptionUsageLocked(f subscriptionFields, result subsc if subscriptionPermanentlyRejected(result.response) { f.terminate(result.err.Error()) f.lifecycle.rejectedStatus = result.response.StatusCode - if f.mwi { - s.subscriptionRegistrations.rejectMWI(result.context.binding, result.response.StatusCode) - } + s.subscriptionRegistrations.reject( + result.context.binding, + subscriptionEventPackage(f.mwi), + result.response.StatusCode, + ) return result.err } if *f.closed { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle.go index fa914328..0c610dd6 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle.go @@ -68,8 +68,8 @@ func (s *Service) trackSubscriptionRegistrationLocked(expires time.Duration) { s.subscriptionBinding = s.subscriptionRegistrations.registered(binding, time.Now().Add(expires)) } -// A normal REGISTER refresh preserves dialogs and negative subscription results. -// MWI 405/489 is scoped to identity deregistration (TS 24.606 4.7.2.1), not a flow. +// A normal REGISTER refresh preserves dialogs and explicit event-package +// rejections. A 405/489 is scoped to identity deregistration, not a TCP flow. func (s *Service) prepareSubscriptionStart(mwi bool) (bool, string) { s.mu.Lock() defer s.mu.Unlock() @@ -78,13 +78,17 @@ func (s *Service) prepareSubscriptionStart(mwi bool) (bool, string) { } lifecycle := s.alignSubscriptionContextLocked(mwi) current := lifecycle.context - if mwi { - if status := s.subscriptionRegistrations.mwiRejected(current.binding); status != 0 { + if status := s.subscriptionRegistrations.rejected(current.binding, subscriptionEventPackage(mwi)); status != 0 { + if mwi { s.mwiSubscriptionClosed = true s.mwiSubscriptionRefreshAt = time.Time{} s.mwiSubscriptionLastErr = fmt.Sprintf("MWI rejected with status %d; waiting for IMS identity deregistration", status) return false, s.mwiSubscriptionLastErr } + s.subscriptionClosed = true + s.subscriptionRefreshAt = time.Time{} + s.subscriptionLastErr = fmt.Sprintf("registration event subscription rejected with status %d; waiting for IMS identity deregistration", status) + return false, s.subscriptionLastErr } if lifecycle.rejectedStatus != 0 { return false, fmt.Sprintf("subscription previously rejected with status %d", lifecycle.rejectedStatus) diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle_test.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle_test.go index f31754cf..4a538122 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle_test.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle_test.go @@ -113,7 +113,7 @@ func TestRegisteredSubscriptionDialogSurvivesRegisterRefresh(t *testing.T) { } } -func TestSubscriptionNewContactRetriesRegButPreservesMWIRejection(t *testing.T) { +func TestSubscriptionNewContactPreservesExplicitRejections(t *testing.T) { store := NewSubscriptionRegistrationStore() s := newSubscriptionLifecycleTestService(t, store) rejectSubscriptionForTest(t, s, false) @@ -123,15 +123,17 @@ func TestSubscriptionNewContactRetriesRegButPreservesMWIRejection(t *testing.T) s.subscriptionGeneration++ s.trackSubscriptionRegistrationLocked(time.Hour) s.mu.Unlock() - if start, _ := s.prepareSubscriptionStart(false); !start { - t.Fatal("new Contact did not initiate reg subscription") + if start, _ := s.prepareSubscriptionStart(false); start { + t.Fatal("new Contact cleared registration event rejection") } if start, _ := s.prepareSubscriptionStart(true); start { t.Fatal("new Contact cleared MWI rejection") } replacement := newSubscriptionLifecycleTestService(t, store) - if start, _ := replacement.prepareSubscriptionStart(true); start { - t.Fatal("Service rebuild cleared MWI rejection") + for _, mwi := range []bool{false, true} { + if start, _ := replacement.prepareSubscriptionStart(mwi); start { + t.Fatalf("Service rebuild cleared rejection for mwi=%t", mwi) + } } } @@ -200,7 +202,7 @@ func TestSubscriptionDeregistrationAllowsNewMWIAttempt(t *testing.T) { } func storeMWIRejection(s *Service) int { - return s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding) + return s.subscriptionRegistrations.rejected(s.subscriptionBinding, mwiEventPackage) } func Test2degreesMWIRejectionDoesNotChangeOnDemandSMSReadiness(t *testing.T) { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store.go index 5b3c1513..725b41c4 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store.go @@ -3,20 +3,32 @@ package imscore import ( "sync" "time" + + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" ) +// SubscriptionRejectionPersistence stores only explicit, durable event-package +// rejections. Transport failures and timeouts must never implement this interface +// as negative capability evidence. +type SubscriptionRejectionPersistence interface { + LoadIMSSubscriptionRejection(identity, eventPackage string, now time.Time) (status int, expiresAt time.Time, err error) + SaveIMSSubscriptionRejection(identity, eventPackage string, status int, expiresAt time.Time) error + DeleteIMSSubscriptionRejections(identity string) error +} + // SubscriptionRegistrationStore follows IMS identity registration lifetimes, // not TCP or Service lifetimes. It is shared across runtime recovery attempts. type SubscriptionRegistrationStore struct { - mu sync.Mutex - nextEpoch uint64 - identities map[string]*subscriptionRegistrationEntry + mu sync.Mutex + nextEpoch uint64 + identities map[string]*subscriptionRegistrationEntry + persistence SubscriptionRejectionPersistence } type subscriptionRegistrationEntry struct { - epoch uint64 - bindings map[string]time.Time - mwiRejection int + epoch uint64 + bindings map[string]time.Time + rejections map[string]int } type subscriptionRegistration struct { @@ -29,6 +41,14 @@ func NewSubscriptionRegistrationStore() *SubscriptionRegistrationStore { return &SubscriptionRegistrationStore{identities: make(map[string]*subscriptionRegistrationEntry)} } +func NewPersistentSubscriptionRegistrationStore( + persistence SubscriptionRejectionPersistence, +) *SubscriptionRegistrationStore { + store := NewSubscriptionRegistrationStore() + store.persistence = persistence + return store +} + func (store *SubscriptionRegistrationStore) registered(binding subscriptionRegistration, expiresAt time.Time) subscriptionRegistration { store.mu.Lock() defer store.mu.Unlock() @@ -37,15 +57,47 @@ func (store *SubscriptionRegistrationStore) registered(binding subscriptionRegis } entry := store.activeLocked(binding.identity, time.Now()) if entry == nil { - store.nextEpoch++ - entry = &subscriptionRegistrationEntry{epoch: store.nextEpoch, bindings: make(map[string]time.Time)} + entry = store.newEntryLocked(binding.identity, time.Now()) store.identities[binding.identity] = entry } entry.bindings[binding.contact] = expiresAt + store.extendRejectionsLocked(binding.identity, entry, expiresAt) binding.epoch = entry.epoch return binding } +func (store *SubscriptionRegistrationStore) newEntryLocked( + identity string, + now time.Time, +) *subscriptionRegistrationEntry { + store.nextEpoch++ + entry := &subscriptionRegistrationEntry{ + epoch: store.nextEpoch, bindings: make(map[string]time.Time), rejections: make(map[string]int), + } + for _, eventPackage := range []string{registrationEventPackage, mwiEventPackage} { + status, expiresAt, err := store.loadRejectionLocked(identity, eventPackage, now) + if err == nil && now.Before(expiresAt) && persistentSubscriptionRejection(status) { + entry.rejections[eventPackage] = status + } + } + return entry +} + +func (store *SubscriptionRegistrationStore) loadRejectionLocked( + identity, eventPackage string, + now time.Time, +) (int, time.Time, error) { + if store.persistence == nil { + return 0, time.Time{}, nil + } + status, expiresAt, err := store.persistence.LoadIMSSubscriptionRejection(identity, eventPackage, now) + if err != nil { + logging.WarnRate("ims-subscription-rejection-load-"+eventPackage, time.Minute, + "IMS subscription rejection persistence load failed", "event_package", eventPackage, "err", err) + } + return status, expiresAt, err +} + func (store *SubscriptionRegistrationStore) activeLocked(identity string, now time.Time) *subscriptionRegistrationEntry { entry := store.identities[identity] if entry == nil { @@ -63,26 +115,34 @@ func (store *SubscriptionRegistrationStore) activeLocked(identity string, now ti return entry } -func (store *SubscriptionRegistrationStore) rejectMWI(binding subscriptionRegistration, status int) { - if status != 405 && status != 489 { +func (store *SubscriptionRegistrationStore) reject( + binding subscriptionRegistration, + eventPackage string, + status int, +) { + if !persistentSubscriptionRejection(status) { return } store.mu.Lock() defer store.mu.Unlock() entry := store.activeLocked(binding.identity, time.Now()) if entry != nil && entry.epoch == binding.epoch { - entry.mwiRejection = status + entry.rejections[eventPackage] = status + store.saveRejectionLocked(binding.identity, eventPackage, status, latestBindingExpiry(entry)) } } -func (store *SubscriptionRegistrationStore) mwiRejected(binding subscriptionRegistration) int { +func (store *SubscriptionRegistrationStore) rejected( + binding subscriptionRegistration, + eventPackage string, +) int { store.mu.Lock() defer store.mu.Unlock() entry := store.activeLocked(binding.identity, time.Now()) if entry == nil || entry.epoch != binding.epoch { return 0 } - return entry.mwiRejection + return entry.rejections[eventPackage] } func (store *SubscriptionRegistrationStore) deregistered(binding subscriptionRegistration, all bool) { @@ -95,5 +155,61 @@ func (store *SubscriptionRegistrationStore) deregistered(binding subscriptionReg delete(entry.bindings, binding.contact) if all || len(entry.bindings) == 0 { delete(store.identities, binding.identity) + store.deleteRejectionsLocked(binding.identity) } } + +func (store *SubscriptionRegistrationStore) extendRejectionsLocked( + identity string, + entry *subscriptionRegistrationEntry, + expiresAt time.Time, +) { + for eventPackage, status := range entry.rejections { + store.saveRejectionLocked(identity, eventPackage, status, expiresAt) + } +} + +func (store *SubscriptionRegistrationStore) saveRejectionLocked( + identity, eventPackage string, + status int, + expiresAt time.Time, +) { + if store.persistence == nil || expiresAt.IsZero() { + return + } + if err := store.persistence.SaveIMSSubscriptionRejection(identity, eventPackage, status, expiresAt); err != nil { + logging.WarnRate("ims-subscription-rejection-save-"+eventPackage, time.Minute, + "IMS subscription rejection persistence save failed", "event_package", eventPackage, "err", err) + } +} + +func (store *SubscriptionRegistrationStore) deleteRejectionsLocked(identity string) { + if store.persistence == nil { + return + } + if err := store.persistence.DeleteIMSSubscriptionRejections(identity); err != nil { + logging.WarnRate("ims-subscription-rejection-delete", time.Minute, + "IMS subscription rejection persistence delete failed", "err", err) + } +} + +func latestBindingExpiry(entry *subscriptionRegistrationEntry) time.Time { + latest := time.Time{} + for _, expiresAt := range entry.bindings { + if expiresAt.After(latest) { + latest = expiresAt + } + } + return latest +} + +func persistentSubscriptionRejection(status int) bool { + return status == 405 || status == 489 +} + +func subscriptionEventPackage(mwi bool) string { + if mwi { + return mwiEventPackage + } + return registrationEventPackage +} diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store_test.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store_test.go index 22b1918c..0cab34f0 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store_test.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_registration_store_test.go @@ -5,26 +5,60 @@ import ( "time" ) +type persistedSubscriptionRejection struct { + status int + expiresAt time.Time +} + +type memorySubscriptionRejectionStore struct { + values map[string]persistedSubscriptionRejection +} + +func (store *memorySubscriptionRejectionStore) LoadIMSSubscriptionRejection( + identity, eventPackage string, + _ time.Time, +) (int, time.Time, error) { + value := store.values[identity+"\x00"+eventPackage] + return value.status, value.expiresAt, nil +} + +func (store *memorySubscriptionRejectionStore) SaveIMSSubscriptionRejection( + identity, eventPackage string, + status int, + expiresAt time.Time, +) error { + store.values[identity+"\x00"+eventPackage] = persistedSubscriptionRejection{ + status: status, expiresAt: expiresAt, + } + return nil +} + +func (store *memorySubscriptionRejectionStore) DeleteIMSSubscriptionRejections(identity string) error { + delete(store.values, identity+"\x00"+registrationEventPackage) + delete(store.values, identity+"\x00"+mwiEventPackage) + return nil +} + func TestMWIRejectionFollowsIdentityNotServiceOrContact(t *testing.T) { store := NewSubscriptionRegistrationStore() first := store.registered(subscriptionRegistration{identity: "sim-a/user", contact: "old-contact"}, time.Now().Add(time.Hour)) - store.rejectMWI(first, 405) + store.reject(first, mwiEventPackage, 405) replacement := store.registered(subscriptionRegistration{identity: first.identity, contact: "new-contact"}, time.Now().Add(time.Hour)) - if got := store.mwiRejected(replacement); got != 405 { + if got := store.rejected(replacement, mwiEventPackage); got != 405 { t.Fatalf("replacement lost MWI rejection: %d", got) } store.deregistered(first, false) - if got := store.mwiRejected(replacement); got != 405 { + if got := store.rejected(replacement, mwiEventPackage); got != 405 { t.Fatalf("retiring old contact cleared active identity rejection: %d", got) } other := store.registered(subscriptionRegistration{identity: "sim-b/user", contact: "other"}, time.Now().Add(time.Hour)) - if store.mwiRejected(other) != 0 { + if store.rejected(other, mwiEventPackage) != 0 { t.Fatal("rejection leaked to another identity") } store.deregistered(replacement, false) next := store.registered(subscriptionRegistration{identity: first.identity, contact: "third-contact"}, time.Now().Add(time.Hour)) - store.rejectMWI(first, 489) - if store.mwiRejected(next) != 0 { + store.reject(first, mwiEventPackage, 489) + if store.rejected(next, mwiEventPackage) != 0 { t.Fatal("late rejection crossed deregistration boundary") } } @@ -32,12 +66,12 @@ func TestMWIRejectionFollowsIdentityNotServiceOrContact(t *testing.T) { func TestMWIRejectionExpiresWithLastKnownRegistration(t *testing.T) { store := NewSubscriptionRegistrationStore() ref := store.registered(subscriptionRegistration{identity: "sim/user", contact: "contact"}, time.Now().Add(time.Hour)) - store.rejectMWI(ref, 489) + store.reject(ref, mwiEventPackage, 489) store.mu.Lock() store.identities[ref.identity].bindings[ref.contact] = time.Now().Add(-time.Second) store.mu.Unlock() next := store.registered(ref, time.Now().Add(time.Hour)) - if next.epoch == ref.epoch || store.mwiRejected(next) != 0 { + if next.epoch == ref.epoch || store.rejected(next, mwiEventPackage) != 0 { t.Fatal("expired registration retained rejection") } } @@ -46,13 +80,59 @@ func TestMWITransientFailuresAreNotUnsupported(t *testing.T) { store := NewSubscriptionRegistrationStore() ref := store.registered(subscriptionRegistration{identity: "sim/user", contact: "contact"}, time.Now().Add(time.Hour)) for _, status := range []int{403, 408, 500, 503} { - store.rejectMWI(ref, status) - if store.mwiRejected(ref) != 0 { + store.reject(ref, mwiEventPackage, status) + if store.rejected(ref, mwiEventPackage) != 0 { t.Fatalf("status %d became network unsupported", status) } } } +func TestExplicitRejectionsSurviveProcessStoreReplacement(t *testing.T) { + persistence := &memorySubscriptionRejectionStore{ + values: make(map[string]persistedSubscriptionRejection), + } + identity := "device\x00impi\x00domain\x00impu" + expiresAt := time.Now().Add(time.Hour) + firstStore := NewPersistentSubscriptionRegistrationStore(persistence) + first := firstStore.registered(subscriptionRegistration{ + identity: identity, contact: "first", + }, expiresAt) + firstStore.reject(first, registrationEventPackage, 489) + firstStore.reject(first, mwiEventPackage, 405) + + restartedStore := NewPersistentSubscriptionRegistrationStore(persistence) + restarted := restartedStore.registered(subscriptionRegistration{ + identity: identity, contact: "replacement", + }, expiresAt.Add(time.Hour)) + if got := restartedStore.rejected(restarted, registrationEventPackage); got != 489 { + t.Fatalf("registration rejection after restart = %d", got) + } + if got := restartedStore.rejected(restarted, mwiEventPackage); got != 405 { + t.Fatalf("MWI rejection after restart = %d", got) + } + for _, eventPackage := range []string{registrationEventPackage, mwiEventPackage} { + value := persistence.values[identity+"\x00"+eventPackage] + if !value.expiresAt.Equal(expiresAt.Add(time.Hour)) { + t.Fatalf("%s expiration was not extended: %s", eventPackage, value.expiresAt) + } + } +} + +func TestExplicitDeregistrationClearsPersistedRejections(t *testing.T) { + persistence := &memorySubscriptionRejectionStore{ + values: make(map[string]persistedSubscriptionRejection), + } + store := NewPersistentSubscriptionRegistrationStore(persistence) + binding := store.registered(subscriptionRegistration{ + identity: "sim/user", contact: "contact", + }, time.Now().Add(time.Hour)) + store.reject(binding, mwiEventPackage, 405) + store.deregistered(binding, false) + if len(persistence.values) != 0 { + t.Fatalf("deregistration left persisted rejections: %#v", persistence.values) + } +} + func TestSubscriptionRefreshUsesNegotiatedLifetime(t *testing.T) { for _, test := range []struct{ expires, want time.Duration }{ {time.Minute, 30 * time.Second}, diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_timers.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_timers.go index ce449975..a1a7ee60 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_timers.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_timers.go @@ -13,7 +13,7 @@ func (s *Service) subscriptionDueLocked(mwi bool, now time.Time) bool { if !eligible || f.retryBlocked() || !f.lifecycle.notifyDeadline.IsZero() { return false } - if mwi && s.subscriptionRegistrations.mwiRejected(s.subscriptionBinding) != 0 { + if s.subscriptionRegistrations.rejected(s.subscriptionBinding, subscriptionEventPackage(mwi)) != 0 { return false } if (mwi && s.mwiSubscriptionInFlight.Load()) || (!mwi && s.subscriptionInFlight.Load()) { diff --git a/third_party/vowifi-go/internal/vowifi/runtimecore/runtime.go b/third_party/vowifi-go/internal/vowifi/runtimecore/runtime.go index b0c35e63..9a69b3ad 100644 --- a/third_party/vowifi-go/internal/vowifi/runtimecore/runtime.go +++ b/third_party/vowifi-go/internal/vowifi/runtimecore/runtime.go @@ -36,7 +36,9 @@ func (Runtime) Start( req.fastReauth = &FastReauthStore{} } if req.subscriptionRegistrations == nil { - req.subscriptionRegistrations = imscore.NewSubscriptionRegistrationStore() + req.subscriptionRegistrations = imscore.NewPersistentSubscriptionRegistrationStore( + req.SubscriptionStore, + ) } if req.Options.Voice != nil && req.voiceBinding == nil { req.voiceBinding = &voiceLifecycleBinding{deviceID: req.DeviceID, voice: req.Options.Voice} diff --git a/third_party/vowifi-go/internal/vowifi/runtimecore/types.go b/third_party/vowifi-go/internal/vowifi/runtimecore/types.go index dc78ea95..95e16c0d 100644 --- a/third_party/vowifi-go/internal/vowifi/runtimecore/types.go +++ b/third_party/vowifi-go/internal/vowifi/runtimecore/types.go @@ -168,6 +168,7 @@ type RuntimeStartRequest struct { Proxy *ProxyConfig DNSServer string DeliveryStore smsdelivery.Store + SubscriptionStore imscore.SubscriptionRejectionPersistence Dispatch events.EventDispatcher Reconnect bool ReconnectDelay func(int) int64 diff --git a/third_party/vowifi-go/runtimehost/adapters_test.go b/third_party/vowifi-go/runtimehost/adapters_test.go index ebddf593..a6c321db 100644 --- a/third_party/vowifi-go/runtimehost/adapters_test.go +++ b/third_party/vowifi-go/runtimehost/adapters_test.go @@ -508,6 +508,33 @@ type fragmentOnlyDeliveryStore struct { fragments messaging.InboundFragmentStore } +type subscriptionRejectionDeliveryStore struct { + messaging.DeliveryStore + status int + expiresAt time.Time +} + +func (store *subscriptionRejectionDeliveryStore) LoadIMSSubscriptionRejection( + _, _ string, + _ time.Time, +) (int, time.Time, error) { + return store.status, store.expiresAt, nil +} + +func (store *subscriptionRejectionDeliveryStore) SaveIMSSubscriptionRejection( + _, _ string, + status int, + expiresAt time.Time, +) error { + store.status, store.expiresAt = status, expiresAt + return nil +} + +func (store *subscriptionRejectionDeliveryStore) DeleteIMSSubscriptionRejections(string) error { + store.status, store.expiresAt = 0, time.Time{} + return nil +} + func (store fragmentOnlyDeliveryStore) LoadInboundFragments( owner messaging.InboundFragmentOwner, ) ([]messaging.StoredInboundFragment, error) { @@ -659,6 +686,26 @@ func TestRuntimeCoreDeliveryStorePreservesOptionalSIPResults(t *testing.T) { } } +func TestRuntimeCoreAdapterPreservesSubscriptionRejectionStore(t *testing.T) { + store := &subscriptionRejectionDeliveryStore{DeliveryStore: &memDeliveryStore{}} + persistence := runtimeCoreSubscriptionRejectionStore(store) + if persistence == nil { + t.Fatal("subscription rejection store was dropped") + } + expiresAt := time.Now().Add(time.Hour) + if err := persistence.SaveIMSSubscriptionRejection( + "identity", "reg", 489, expiresAt, + ); err != nil { + t.Fatal(err) + } + status, loadedExpiry, err := persistence.LoadIMSSubscriptionRejection( + "identity", "reg", time.Now(), + ) + if err != nil || status != 489 || !loadedExpiry.Equal(expiresAt) { + t.Fatalf("status=%d expiry=%s err=%v", status, loadedExpiry, err) + } +} + func TestDeliveryStoreAdaptersDoNotInventFragmentLifecycleCapability(t *testing.T) { underlying := &memDeliveryStore{} store := fragmentOnlyDeliveryStore{DeliveryStore: underlying, fragments: underlying} diff --git a/third_party/vowifi-go/runtimehost/messaging/types.go b/third_party/vowifi-go/runtimehost/messaging/types.go index 2a91b9ec..8a0e45e3 100644 --- a/third_party/vowifi-go/runtimehost/messaging/types.go +++ b/third_party/vowifi-go/runtimehost/messaging/types.go @@ -151,6 +151,15 @@ type DeliveryStore interface { GetSMSDeliveryStatus(messageID string) (*DeliveryStatus, error) } +// SubscriptionRejectionStore persists explicit IMS event-package rejections +// across runtime and process restarts. Expiration follows the associated IMS +// registration lifetime so a genuinely new registration may probe again. +type SubscriptionRejectionStore interface { + LoadIMSSubscriptionRejection(identity, eventPackage string, now time.Time) (status int, expiresAt time.Time, err error) + SaveIMSSubscriptionRejection(identity, eventPackage string, status int, expiresAt time.Time) error + DeleteIMSSubscriptionRejections(identity string) error +} + // SIPResultStore is an optional delivery-store capability used to preserve // the initial SIP MESSAGE result while the part is still waiting for RP-ACK. type SIPResultStore interface { diff --git a/third_party/vowifi-go/runtimehost/runtimecore_adapters.go b/third_party/vowifi-go/runtimehost/runtimecore_adapters.go index c31dce75..0f017edb 100644 --- a/third_party/vowifi-go/runtimehost/runtimecore_adapters.go +++ b/third_party/vowifi-go/runtimehost/runtimecore_adapters.go @@ -4,6 +4,7 @@ import ( "time" "github.com/iniwex5/vowifi-go/internal/vowifi/events" + "github.com/iniwex5/vowifi-go/internal/vowifi/imscore" "github.com/iniwex5/vowifi-go/internal/vowifi/smsdelivery" "github.com/iniwex5/vowifi-go/runtimehost/eventhost" "github.com/iniwex5/vowifi-go/runtimehost/messaging" @@ -16,6 +17,13 @@ func runtimeCoreDispatcher(dispatcher eventhost.Dispatcher) events.EventDispatch return eventDispatcherAdapter{dispatch: dispatcher} } +func runtimeCoreSubscriptionRejectionStore( + store messaging.DeliveryStore, +) imscore.SubscriptionRejectionPersistence { + persistence, _ := store.(messaging.SubscriptionRejectionStore) + return persistence +} + type runtimeCoreDeliveryStoreAdapter struct{ store messaging.DeliveryStore } type runtimeCoreSIPDeliveryStoreAdapter struct { diff --git a/third_party/vowifi-go/runtimehost/runtimecore_start.go b/third_party/vowifi-go/runtimehost/runtimecore_start.go index 9c1930cd..ca07a0d4 100644 --- a/third_party/vowifi-go/runtimehost/runtimecore_start.go +++ b/third_party/vowifi-go/runtimehost/runtimecore_start.go @@ -42,8 +42,9 @@ func (req StartRequest) coreRequest() runtimecore.RuntimeStartRequest { Mode: req.Dataplane.Mode, TUNName: req.Dataplane.TUNName, }, Proxy: runtimeCoreProxy(req.Proxy), DNSServer: req.DNSServer, - DeliveryStore: runtimeCoreDeliveryStore(req.DeliveryStore), - Dispatch: runtimeCoreDispatcher(req.Dispatch), ShouldRun: req.ShouldRun, + DeliveryStore: runtimeCoreDeliveryStore(req.DeliveryStore), + SubscriptionStore: runtimeCoreSubscriptionRejectionStore(req.DeliveryStore), + Dispatch: runtimeCoreDispatcher(req.Dispatch), ShouldRun: req.ShouldRun, } if req.BeforeStart != nil { hook := req.BeforeStart diff --git a/third_party/vowifi-go/runtimehost/start.go b/third_party/vowifi-go/runtimehost/start.go index 972e819f..84f1ab32 100644 --- a/third_party/vowifi-go/runtimehost/start.go +++ b/third_party/vowifi-go/runtimehost/start.go @@ -491,6 +491,9 @@ func imscoreFromPrepared(req StartRequest, tunnel Tunnel) (*imscore.Service, err } if req.DeliveryStore != nil { cfg.DeliveryStore = newDeliveryStoreAdapter(req.DeliveryStore) + cfg.SubscriptionRegistrations = imscore.NewPersistentSubscriptionRegistrationStore( + runtimeCoreSubscriptionRejectionStore(req.DeliveryStore), + ) } svc, err := imscore.New(cfg) if err != nil {