diff --git a/internal/db/ims_subscription_rejection.go b/internal/db/ims_subscription_rejection.go index de937cdd..41a88445 100644 --- a/internal/db/ims_subscription_rejection.go +++ b/internal/db/ims_subscription_rejection.go @@ -45,6 +45,12 @@ func LoadIMSSubscriptionRejection( err = DB.Delete(&row).Error return 0, time.Time{}, err } + if row.StatusCode == 405 { + if err := DB.Delete(&row).Error; err != nil { + return 0, time.Time{}, err + } + return 0, time.Time{}, nil + } if !validPersistentSubscriptionStatus(row.StatusCode) { return 0, time.Time{}, fmt.Errorf("invalid persisted IMS subscription status %d", row.StatusCode) } @@ -122,5 +128,5 @@ func normalizeIMSSubscriptionRejectionKey(identity, eventPackage string) (string } func validPersistentSubscriptionStatus(status int) bool { - return status == 405 || status == 489 + return status == 489 } diff --git a/internal/db/ims_subscription_rejection_test.go b/internal/db/ims_subscription_rejection_test.go index ef83295f..e5175aab 100644 --- a/internal/db/ims_subscription_rejection_test.go +++ b/internal/db/ims_subscription_rejection_test.go @@ -29,12 +29,8 @@ func TestIMSSubscriptionRejectionPersistence(t *testing.T) { 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 := SaveIMSSubscriptionRejection(identity, "reg", 405, now.Add(time.Minute)); err == nil { + t.Fatal("ambiguous 405 response was persisted") } if err := DeleteIMSSubscriptionRejections(identity); err != nil { t.Fatal(err) @@ -58,12 +54,26 @@ func TestIMSSubscriptionRejectionExpiresAndValidatesBoundary(t *testing.T) { }) now := time.Now().UTC().Truncate(time.Second) - if err := SaveIMSSubscriptionRejection("identity", "message-summary", 405, now.Add(-time.Second)); err != nil { + identityHash, eventPackage, err := normalizeIMSSubscriptionRejectionKey("identity", "message-summary") + if err != nil { + t.Fatal(err) + } + legacy := IMSSubscriptionRejection{ + IdentityHash: identityHash, EventPackage: eventPackage, + StatusCode: 405, ExpiresAt: now.Add(time.Hour), + } + if err := DB.Create(&legacy).Error; 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) + t.Fatalf("legacy 405 status=%d err=%v", status, err) + } + var count int64 + if err := DB.Model(&IMSSubscriptionRejection{}).Where( + "identity_hash = ? AND event_package = ?", identityHash, eventPackage, + ).Count(&count).Error; err != nil || count != 0 { + t.Fatalf("legacy 405 row count=%d err=%v", count, err) } if err := SaveIMSSubscriptionRejection("identity", "reg", 503, now.Add(time.Hour)); err == nil { t.Fatal("transient status was persisted") 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 70ada090..9efaa7cf 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_exchange.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_exchange.go @@ -25,6 +25,7 @@ func (s *Service) recordSubscriptionUsageAttempt(result subscriptionResult, mwi l := f.lifecycle l.context, l.started = result.context.subscriptionContext, true l.attemptKey, l.sentAt = key, time.Time{} + l.selfRouted = false l.notifyDeadline, l.retryAt = time.Time{}, time.Time{} l.notifyExpires, l.unsubscribing = false, result.unsubscribe *f.closed, *f.lastErr = false, "" @@ -121,13 +122,23 @@ func (s *Service) recordSubscriptionUsageResult(result subscriptionResult, mwi b func (s *Service) failSubscriptionUsageLocked(f subscriptionFields, result subscriptionResult) error { if subscriptionPermanentlyRejected(result.response) { + status := result.response.StatusCode + if f.lifecycle.selfRouted && status == 405 { + reason := fmt.Sprintf("SUBSCRIBE %s was routed back to the local contact", subscriptionEventPackage(f.mwi)) + f.terminate(reason) + f.lifecycle.blockedReason = reason + return fmt.Errorf("imscore: %s: %w", reason, result.err) + } f.terminate(result.err.Error()) - f.lifecycle.rejectedStatus = result.response.StatusCode - s.subscriptionRegistrations.reject( - result.context.binding, - subscriptionEventPackage(f.mwi), - result.response.StatusCode, - ) + if identityScopedSubscriptionRejection(status) { + s.subscriptionRegistrations.reject( + result.context.binding, + subscriptionEventPackage(f.mwi), + status, + ) + } else { + f.lifecycle.rejectedStatus = status + } 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 0c610dd6..1589b1e6 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_lifecycle.go @@ -33,6 +33,7 @@ type subscriptionLifecycle struct { notifyVersion uint64 notifications *subscriptionNotificationQueue usageGeneration uint64 + selfRouted bool } type subscriptionAttemptContext struct { 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 4a538122..d059b2e9 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 @@ -5,6 +5,7 @@ import ( "errors" "io" "net" + "strings" "testing" "time" @@ -91,6 +92,26 @@ func TestSubscriptionRejectionsSurviveOrdinaryRegisterRefresh(t *testing.T) { } } +func TestSubscriptionRejectionExpiryAllowsRetryWithoutServiceRestart(t *testing.T) { + service := newSubscriptionLifecycleTestService(t, nil) + rejectSubscriptionForTest(t, service, true) + service.subscriptionRegistrations.mu.Lock() + entry := service.subscriptionRegistrations.identities[service.subscriptionBinding.identity] + entry.rejections[mwiEventPackage] = subscriptionRejection{ + status: 405, expiresAt: time.Now().Add(-time.Second), + } + service.subscriptionRegistrations.mu.Unlock() + service.mu.Lock() + due := service.subscriptionDueLocked(true, time.Now()) + service.mu.Unlock() + if !due { + t.Fatal("expired rejection did not schedule an automatic MWI retry") + } + if start, reason := service.prepareSubscriptionStart(true); !start { + t.Fatalf("expired rejection still blocked MWI: %s", reason) + } +} + func TestRegisteredSubscriptionDialogSurvivesRegisterRefresh(t *testing.T) { s := newSubscriptionLifecycleTestService(t, nil) for _, mwi := range []bool{false, true} { @@ -232,3 +253,47 @@ func Test2degreesMWIRejectionDoesNotChangeOnDemandSMSReadiness(t *testing.T) { default: } } + +func TestSelfRoutedMWI405IsNotPersistedAsNetworkCapability(t *testing.T) { + persistence := &memorySubscriptionRejectionStore{ + values: make(map[string]persistedSubscriptionRejection), + } + registrations := NewPersistentSubscriptionRegistrationStore(persistence) + service := newSubscriptionLifecycleTestService(t, registrations) + attempt, err := service.beginSubscriptionAttempt(true, false) + if err != nil { + t.Fatal(err) + } + request, requestedExpires, err := service.buildMWISubscription(time.Hour) + if err != nil { + t.Fatal(err) + } + result := subscriptionResult{ + context: attempt, request: request, requestedExpires: requestedExpires, + } + if err := service.recordMWISubscriptionAttempt(result); err != nil { + t.Fatal(err) + } + service.markSelfRoutedSubscription(request) + result.response = &sip.Response{StatusCode: 405, Reason: "Method Not Allowed"} + result.err = errors.New("SUBSCRIBE rejected with status 405") + if err := service.recordMWISubscriptionResult(result); err == nil { + t.Fatal("self-routed rejection was hidden") + } + if got := registrations.rejected(service.subscriptionBinding, mwiEventPackage); got != 0 { + t.Fatalf("self-routed 405 became network rejection: %d", got) + } + if len(persistence.values) != 0 { + t.Fatalf("self-routed 405 was persisted: %#v", persistence.values) + } + if start, reason := service.prepareSubscriptionStart(true); start || !strings.Contains(reason, "routed back") { + t.Fatalf("current context retried self-routed MWI: start=%t reason=%q", start, reason) + } + service.mu.Lock() + service.subscriptionGeneration++ + service.trackSubscriptionRegistrationLocked(time.Hour) + service.mu.Unlock() + if start, reason := service.prepareSubscriptionStart(true); !start { + t.Fatalf("new registration context retained self-route result: %s", reason) + } +} 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 725b41c4..392712f4 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 @@ -7,9 +7,9 @@ import ( "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. +// SubscriptionRejectionPersistence stores explicit 489 Bad Event responses. +// Ambiguous 405 responses, transport failures, and timeouts are scoped to the +// current registration and are not durable 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 @@ -28,7 +28,12 @@ type SubscriptionRegistrationStore struct { type subscriptionRegistrationEntry struct { epoch uint64 bindings map[string]time.Time - rejections map[string]int + rejections map[string]subscriptionRejection +} + +type subscriptionRejection struct { + status int + expiresAt time.Time } type subscriptionRegistration struct { @@ -61,7 +66,6 @@ func (store *SubscriptionRegistrationStore) registered(binding subscriptionRegis store.identities[binding.identity] = entry } entry.bindings[binding.contact] = expiresAt - store.extendRejectionsLocked(binding.identity, entry, expiresAt) binding.epoch = entry.epoch return binding } @@ -72,12 +76,13 @@ func (store *SubscriptionRegistrationStore) newEntryLocked( ) *subscriptionRegistrationEntry { store.nextEpoch++ entry := &subscriptionRegistrationEntry{ - epoch: store.nextEpoch, bindings: make(map[string]time.Time), rejections: make(map[string]int), + epoch: store.nextEpoch, bindings: make(map[string]time.Time), + rejections: make(map[string]subscriptionRejection), } 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 + entry.rejections[eventPackage] = subscriptionRejection{status: status, expiresAt: expiresAt} } } return entry @@ -120,15 +125,18 @@ func (store *SubscriptionRegistrationStore) reject( eventPackage string, status int, ) { - if !persistentSubscriptionRejection(status) { + if !identityScopedSubscriptionRejection(status) { return } store.mu.Lock() defer store.mu.Unlock() entry := store.activeLocked(binding.identity, time.Now()) if entry != nil && entry.epoch == binding.epoch { - entry.rejections[eventPackage] = status - store.saveRejectionLocked(binding.identity, eventPackage, status, latestBindingExpiry(entry)) + expiresAt := latestBindingExpiry(entry) + entry.rejections[eventPackage] = subscriptionRejection{status: status, expiresAt: expiresAt} + if persistentSubscriptionRejection(status) { + store.saveRejectionLocked(binding.identity, eventPackage, status, expiresAt) + } } } @@ -142,7 +150,15 @@ func (store *SubscriptionRegistrationStore) rejected( if entry == nil || entry.epoch != binding.epoch { return 0 } - return entry.rejections[eventPackage] + rejection := entry.rejections[eventPackage] + if rejection.status == 0 { + return 0 + } + if !time.Now().Before(rejection.expiresAt) { + delete(entry.rejections, eventPackage) + return 0 + } + return rejection.status } func (store *SubscriptionRegistrationStore) deregistered(binding subscriptionRegistration, all bool) { @@ -159,16 +175,6 @@ func (store *SubscriptionRegistrationStore) deregistered(binding subscriptionReg } } -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, @@ -204,7 +210,11 @@ func latestBindingExpiry(entry *subscriptionRegistrationEntry) time.Time { } func persistentSubscriptionRejection(status int) bool { - return status == 405 || status == 489 + return status == 489 +} + +func identityScopedSubscriptionRejection(status int) bool { + return status == 405 || persistentSubscriptionRejection(status) } func subscriptionEventPackage(mwi bool) string { 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 0cab34f0..532389bc 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 @@ -76,6 +76,21 @@ func TestMWIRejectionExpiresWithLastKnownRegistration(t *testing.T) { } } +func TestSubscriptionRejectionExpiresWhileRegistrationIsRefreshed(t *testing.T) { + store := NewSubscriptionRegistrationStore() + ref := store.registered(subscriptionRegistration{identity: "sim/user", contact: "contact"}, time.Now().Add(time.Hour)) + store.reject(ref, registrationEventPackage, 489) + store.mu.Lock() + store.identities[ref.identity].rejections[registrationEventPackage] = subscriptionRejection{ + status: 489, expiresAt: time.Now().Add(-time.Second), + } + store.identities[ref.identity].bindings[ref.contact] = time.Now().Add(time.Hour) + store.mu.Unlock() + if got := store.rejected(ref, registrationEventPackage); got != 0 { + t.Fatalf("expired rejection survived live registration refresh: %d", got) + } +} + func TestMWITransientFailuresAreNotUnsupported(t *testing.T) { store := NewSubscriptionRegistrationStore() ref := store.registered(subscriptionRegistration{identity: "sim/user", contact: "contact"}, time.Now().Add(time.Hour)) @@ -87,7 +102,7 @@ func TestMWITransientFailuresAreNotUnsupported(t *testing.T) { } } -func TestExplicitRejectionsSurviveProcessStoreReplacement(t *testing.T) { +func TestBadEventRejectionsSurviveProcessWithoutExtendingExpiry(t *testing.T) { persistence := &memorySubscriptionRejectionStore{ values: make(map[string]persistedSubscriptionRejection), } @@ -98,7 +113,8 @@ func TestExplicitRejectionsSurviveProcessStoreReplacement(t *testing.T) { identity: identity, contact: "first", }, expiresAt) firstStore.reject(first, registrationEventPackage, 489) - firstStore.reject(first, mwiEventPackage, 405) + firstStore.reject(first, mwiEventPackage, 489) + firstStore.registered(first, expiresAt.Add(time.Hour)) restartedStore := NewPersistentSubscriptionRegistrationStore(persistence) restarted := restartedStore.registered(subscriptionRegistration{ @@ -107,17 +123,43 @@ func TestExplicitRejectionsSurviveProcessStoreReplacement(t *testing.T) { if got := restartedStore.rejected(restarted, registrationEventPackage); got != 489 { t.Fatalf("registration rejection after restart = %d", got) } - if got := restartedStore.rejected(restarted, mwiEventPackage); got != 405 { + if got := restartedStore.rejected(restarted, mwiEventPackage); got != 489 { 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) + if !value.expiresAt.Equal(expiresAt) { + t.Fatalf("%s expiration changed during REGISTER refresh: %s", eventPackage, value.expiresAt) } } } +func TestMethodNotAllowedRejectionDoesNotSurviveProcess(t *testing.T) { + persistence := &memorySubscriptionRejectionStore{ + values: make(map[string]persistedSubscriptionRejection), + } + identity := "device\x00impi\x00domain\x00impu" + firstStore := NewPersistentSubscriptionRegistrationStore(persistence) + first := firstStore.registered(subscriptionRegistration{ + identity: identity, contact: "first", + }, time.Now().Add(time.Hour)) + firstStore.reject(first, mwiEventPackage, 405) + if got := firstStore.rejected(first, mwiEventPackage); got != 405 { + t.Fatalf("current registration lost 405 rejection: %d", got) + } + if len(persistence.values) != 0 { + t.Fatalf("405 rejection was persisted: %#v", persistence.values) + } + + restartedStore := NewPersistentSubscriptionRegistrationStore(persistence) + restarted := restartedStore.registered(subscriptionRegistration{ + identity: identity, contact: "replacement", + }, time.Now().Add(time.Hour)) + if got := restartedStore.rejected(restarted, mwiEventPackage); got != 0 { + t.Fatalf("405 rejection survived process replacement: %d", got) + } +} + func TestExplicitDeregistrationClearsPersistedRejections(t *testing.T) { persistence := &memorySubscriptionRejectionStore{ values: make(map[string]persistedSubscriptionRejection), @@ -126,7 +168,7 @@ func TestExplicitDeregistrationClearsPersistedRejections(t *testing.T) { binding := store.registered(subscriptionRegistration{ identity: "sim/user", contact: "contact", }, time.Now().Add(time.Hour)) - store.reject(binding, mwiEventPackage, 405) + store.reject(binding, mwiEventPackage, 489) store.deregistered(binding, false) if len(persistence.values) != 0 { t.Fatalf("deregistration left persisted rejections: %#v", persistence.values) diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscription_self_route.go b/third_party/vowifi-go/internal/vowifi/imscore/subscription_self_route.go new file mode 100644 index 00000000..2a44c7c7 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_self_route.go @@ -0,0 +1,38 @@ +package imscore + +import ( + "strings" + + "github.com/emiago/sipgo/sip" + "github.com/iniwex5/vowifi-go/internal/vowifi/sipkit" +) + +func (s *Service) markSelfRoutedSubscription(request *sip.Request) { + if s == nil || request == nil || request.Method != sip.SUBSCRIBE || request.CallID() == nil || request.CSeq() == nil { + return + } + eventPackage := subscriptionRequestEventPackage(request) + if eventPackage != registrationEventPackage && eventPackage != mwiEventPackage { + return + } + s.mu.Lock() + defer s.mu.Unlock() + lifecycle := &s.subscriptionLifecycle + if eventPackage == mwiEventPackage { + lifecycle = &s.mwiSubscriptionLifecycle + } + key := lifecycle.attemptKey + if key.Method != string(sip.SUBSCRIBE) || key.CSeq != int(request.CSeq().SeqNo) { + return + } + if key.CallID != strings.TrimSpace(request.CallID().Value()) { + return + } + lifecycle.selfRouted = true +} + +func subscriptionRequestEventPackage(request *sip.Request) string { + value := sipkit.FirstHeaderValue(request, "Event", true) + eventPackage, _, _ := strings.Cut(strings.ToLower(strings.TrimSpace(value)), ";") + return strings.TrimSpace(eventPackage) +} 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 a1a7ee60..da2b98c9 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscription_timers.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscription_timers.go @@ -23,7 +23,10 @@ func (s *Service) subscriptionDueLocked(mwi bool, now time.Time) bool { return !now.Before(f.lifecycle.retryAt) } if *f.closed { - return false + // Identity-scoped 405/489 responses close the usage while their + // registration-lifetime cache is active. Once that cache expires, + // retry without requiring a process or IMS service restart. + return f.lifecycle.started && f.lifecycle.rejectedStatus == 0 } return (!mwi && f.refreshAt.IsZero()) || (!f.refreshAt.IsZero() && !now.Before(*f.refreshAt)) } diff --git a/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go b/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go index 94b2d0cf..e59d8ba6 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go @@ -225,6 +225,7 @@ func (s *Service) dispatchInboundSIPRequest( peer net.Conn, ) error { s.logInboundSIPRequest(request) + s.markSelfRoutedSubscription(request) s.transport.DeliverRequest(raw) transaction, handled, err := s.acceptServerRequest(request, raw, reply) if handled || err != nil { diff --git a/third_party/vowifi-go/runtimehost/messaging/types.go b/third_party/vowifi-go/runtimehost/messaging/types.go index 8a0e45e3..d29e11b3 100644 --- a/third_party/vowifi-go/runtimehost/messaging/types.go +++ b/third_party/vowifi-go/runtimehost/messaging/types.go @@ -151,8 +151,8 @@ 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 +// SubscriptionRejectionStore persists explicit 489 Bad Event responses 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)