fix(ims): leave the registrar binding alone on shutdown

Shutdown removed its Contact binding with a REGISTER Expires=0 and fell back
to Contact:* when that timed out. Measured on 2026-09-03, 3 of 11 shutdown
de-registrations took that fallback, and Contact:* also third-party
de-registers the IP-SM-GW, after which Vodafone stopped pushing MT MESSAGE
even following a clean re-REGISTER. So every restart carried a 27% chance of
breaking MT SMS on purpose.

The binding it removed is not worth that. It expires on its own, the next
registration replaces it, and a leftover one showed up in only 3 of 46
registrations as a second Contact, which is logged and left alone. The
reg-event path that would answer duplicates with a wildcard cannot even run
here: SUBSCRIBE for reg was rejected 489 Bad Event 26 times that day.

Shutdown now ends the event subscriptions and stops there.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
yibaibaandCursor committed 2026-09-03 11:56:16 +08:00
1 parent 05daedbe0b
commit de4005e080
5 files changed
+50 -72

No files matched your search

@@ -191,6 +191,29 @@ func (s *Service) UnregisterAll(ctx context.Context) error {
return s.unregisterBindings(ctx, true)
}
// releaseSubscriptionsForShutdown ends the event subscriptions on the way out
// but leaves the registrar binding alone. RFC 5626 5.3.1 keys the binding by
// instance-id and reg-id, both stable across a restart here (instance-id is
// the IMEI, and the P-CSCF offers Path;ob), so the next REGISTER replaces it
// rather than adding to it: 43 of 46 registrations reported a single Contact.
// De-registering bought nothing and cost two things. It told the S-CSCF we
// were gone for the whole ~18s a restart needs to rebuild the flow, and its
// Contact expires=0 timed out three times in one day and fell back to
// Contact:*, which third-party de-registers the IP-SM-GW and stopped Vodafone
// pushing MT MESSAGE even after a clean re-REGISTER.
func (s *Service) releaseSubscriptionsForShutdown(ctx context.Context) {
if s == nil {
return
}
if ctx == nil {
ctx = context.Background()
}
unsubCtx, cancel := context.WithTimeout(ctx, shutdownUnsubscribeTimeout)
defer cancel()
s.unsubscribeMWI(unsubCtx)
s.unsubscribeRegistration(unsubCtx)
}
func (s *Service) unregisterBindings(ctx context.Context, allBindings bool) error {
if s == nil {
return nil
@@ -831,7 +831,12 @@ func TestUnregisterDoesNotWildcardAfterContextDeadline(t *testing.T) {
}
}
func TestStopUnregistersBeforeClosingRegisteredTransport(t *testing.T) {
// Shutdown leaves the registrar binding alone. Measured on 2026-09-03, 3 of 11
// shutdown de-registrations timed out on the Contact expires=0 and escalated to
// Contact:*, which third-party de-registers the IP-SM-GW and stopped Vodafone
// pushing MT MESSAGE even after a clean re-REGISTER. The binding it would have
// removed expires on its own and is replaced by the next registration.
func TestStopLeavesTheRegistrarBindingInPlace(t *testing.T) {
service, err := New(registerTransportTestConfig("udp", "127.0.0.1:5060"))
if err != nil {
t.Fatal(err)
@@ -841,7 +846,7 @@ func TestStopUnregistersBeforeClosingRegisteredTransport(t *testing.T) {
callID: "call-1", fromTag: "tag-1", contactUser: "contact-1",
cseq: 3, authHeader: "Digest username=\"user\"", expires: time.Hour,
}
requests := make(chan string, 1)
requests := make(chan string, 4)
service.transport.SetSendFn(func(request string) error {
requests <- request
service.transport.DeliverResponse(registerResponseForRequest(request, 200, nil))
@@ -851,20 +856,12 @@ func TestStopUnregistersBeforeClosingRegisteredTransport(t *testing.T) {
if err := service.Stop(context.Background()); err != nil {
t.Fatalf("Stop: %v", err)
}
select {
case request := <-requests:
if sipHeaderValue(request, "Expires") != "0" {
t.Fatalf("shutdown REGISTER Expires = %q", sipHeaderValue(request, "Expires"))
close(requests)
for request := range requests {
if strings.EqualFold(sipRequestMethod(request), "REGISTER") {
t.Fatalf("shutdown sent a REGISTER with Contact = %q",
sipHeaderValue(request, "Contact"))
}
contact := sipHeaderValue(request, "Contact")
if contact == "*" {
t.Fatal("shutdown used wildcard Contact")
}
if !strings.Contains(strings.ToLower(contact), "expires=0") {
t.Fatalf("shutdown Contact = %q, want current Contact with expires=0", contact)
}
default:
t.Fatal("Stop closed the transport without deregistering")
}
}
@@ -13,7 +13,6 @@ import (
)
const (
gracefulUnregisterTimeout = 12 * time.Second
shutdownUnsubscribeTimeout = 2 * time.Second
stopCurrentReserve = 500 * time.Millisecond
)
@@ -41,25 +40,6 @@ func deregisterAttemptTimeout(ctx context.Context) time.Duration {
}
return timeout
}
func unregisterTimeoutFor(ctx context.Context) time.Duration {
if ctx == nil {
return gracefulUnregisterTimeout
}
deadline, ok := ctx.Deadline()
if !ok {
return gracefulUnregisterTimeout
}
remaining := time.Until(deadline)
if remaining <= 0 {
return time.Millisecond
}
if remaining > stopCurrentReserve+time.Second {
return remaining - stopCurrentReserve
}
return remaining
}
// Status restores the v1.5.5 map status API.
func (s *Service) Status() map[string]interface{} {
return s.captureStatusSnapshot().ToMap()
@@ -262,14 +242,9 @@ func (s *Service) Stop(ctx context.Context) error {
s.StopCurrent()
return err
}
unregisterCtx, cancel := context.WithTimeout(ctx, unregisterTimeoutFor(ctx))
// Contact-specific Expires=0 first. Contact:* also third-party
// deregisters IP-SM-GW; Vodafone then stopped pushing MT MESSAGE
// even after a clean re-REGISTER.
unregisterErr := s.Unregister(unregisterCtx)
cancel()
s.releaseSubscriptionsForShutdown(ctx)
s.StopCurrent()
return unregisterErr
return nil
}
// TriggerRegisterImmediate schedules production maintenance to REGISTER now.
@@ -97,20 +97,3 @@ func TestRecoveredListenPacketHonorsCanceledContext(t *testing.T) {
}
}
func TestUnregisterTimeoutForHonorsParentDeadline(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
got := unregisterTimeoutFor(ctx)
if got < 7*time.Second || got > 8*time.Second {
t.Fatalf("timeout = %s", got)
}
}
func TestUnregisterTimeoutForDefaultsWithoutDeadline(t *testing.T) {
if got := unregisterTimeoutFor(context.Background()); got != gracefulUnregisterTimeout {
t.Fatalf("timeout = %s, want %s", got, gracefulUnregisterTimeout)
}
if gracefulUnregisterTimeout < 10*time.Second {
t.Fatalf("graceful unregister timeout %s is too short for IMS deregister", gracefulUnregisterTimeout)
}
}
@@ -413,7 +413,12 @@ func TestReginfoAORPrefersTelephoneIdentityAndSummaryIsBounded(t *testing.T) {
}
}
func TestStopUnsubscribesRegistrationBeforeDeregister(t *testing.T) {
// Shutdown ends the reg-event subscription and stops there. Measured on
// 2026-09-03, 3 of 11 shutdown de-registrations timed out on the Contact
// expires=0 and escalated to Contact:*, which third-party de-registers the
// IP-SM-GW and stopped Vodafone pushing MT MESSAGE even after a clean
// re-REGISTER, so the binding is left to expire instead.
func TestStopUnsubscribesRegistrationWithoutDeregistering(t *testing.T) {
service := newProtectedKeepaliveTestService(t)
service.mu.Lock()
service.regSession.callID = "reg-call"
@@ -423,23 +428,19 @@ func TestStopUnsubscribesRegistrationBeforeDeregister(t *testing.T) {
service.activateProtectedRegistrationTCP(client)
t.Cleanup(func() { _ = server.Close() })
seen := make(chan string, 3)
errorsSeen := make(chan error, 1)
seen := make(chan string, 4)
go func() {
reader := bufio.NewReader(server)
for i := 0; i < 3; i++ {
for {
request, err := readSIPStreamMessage(reader)
if err != nil {
errorsSeen <- err
return
}
seen <- request
if _, err = io.WriteString(server, subscriptionWireResponse(request, 200, "Expires: 0\r\n")); err != nil {
errorsSeen <- err
return
}
}
errorsSeen <- nil
}()
if err := service.sendSubscribeReg(context.Background()); err != nil {
t.Fatalf("sendSubscribeReg: %v", err)
@@ -449,16 +450,15 @@ func TestStopUnsubscribesRegistrationBeforeDeregister(t *testing.T) {
t.Fatalf("Stop: %v", err)
}
unsubscribe := <-seen
deregister := <-seen
if err := <-errorsSeen; err != nil {
t.Fatal(err)
}
assertRegistrationSubscription(t, unsubscribe, 6, 0, "reg-notifier")
if rawSIPHeaderValue(unsubscribe, "Call-ID") != rawSIPHeaderValue(initial, "Call-ID") {
t.Fatal("unsubscribe used a different Call-ID")
}
if sipHeaderValue(deregister, "Expires") != "0" || !strings.HasPrefix(deregister, "REGISTER ") {
t.Fatalf("deregister = %q", strings.SplitN(deregister, "\r\n", 2)[0])
select {
case extra := <-seen:
t.Fatalf("shutdown sent %q after unsubscribing",
strings.SplitN(extra, "\r\n", 2)[0])
case <-time.After(200 * time.Millisecond):
}
if service.hasSubscriptionDialog() || !service.subscriptionClosed {
t.Fatalf("subscription after stop dialog=%v closed=%v",