Merge pull request #89 from BFNOC/pr-port-s-timeout-await

This commit is contained in:
yibaiba committed 2026-10-29 13:57:16 +08:00
commit 443c7e8308
13 files changed
+739 -3

No files matched your search

@@ -69,6 +69,7 @@ func (s *Service) recordCurrentDownlinkRequest(peer net.Conn, checkpoint downlin
if _, datagram := peer.(*protectedUDPPeer); datagram {
s.udpDownlinkProven.Store(true)
s.portSRecoveryAwaitingFlow.Store(false)
s.portSTimeoutAwaitEntered.Store(false)
s.portSReconnectWaiting.Store(false)
s.resetPortSRecoveryBackoff()
s.recordPortSInbound(time.Now())
@@ -191,6 +191,7 @@ func (s *Service) resetRegistrationForPCSCFSwitch() error {
s.mwiSubscriptionDialog = registrationSubscriptionDialog{}
s.sipOutboundKeepalive = false
s.sipOutbound = false
s.sipOutboundFlow.Store(false)
s.sipOutboundRequired = false
s.outboundContactOffered = false
s.outboundContactRegistered = false
@@ -104,6 +104,46 @@ func (s *Service) clearPortSRecoveryDeadline() {
s.portSWatchMu.Unlock()
}
// enterPortSTimeoutAwait stops REGISTER-driven recovery after a timed-out
// port-s once canAwaitPeerAfterTimeout holds. Periodic refreshes continue.
// generation is the port-s generation when the recovery REGISTER was sent; a
// reopen since then belongs to a newer episode whose recovery must not be
// cancelled by this older completion.
// protectedConnMu serializes this with handleProtectedServerPushClosed.
func (s *Service) enterPortSTimeoutAwait(generation uint64) bool {
s.protectedConnMu.Lock()
session := s.capturePortSSession()
if len(s.protectedConns) > 0 || session.generation != generation || !s.canAwaitPeerAfterTimeout() {
s.protectedConnMu.Unlock()
return false
}
s.portSWatchMu.Lock()
failures := s.portSBackoff.failures
s.portSWatchMu.Unlock()
s.resetPortSRecoveryBackoff()
s.portSMissingAfterRegister.Store(false)
first := !s.portSTimeoutAwaitEntered.Swap(true)
s.protectedConnMu.Unlock()
if first {
logging.Info("IMS port-s timed out; REGISTER succeeded, awaiting peer reconnect",
"device", s.DeviceID(), "pcscf", s.currentPortSRecoveryRegistrar(),
"close_kind", session.lastCloseKind, "since_close", time.Since(session.closedAt).Round(time.Second),
"port_s_generation", session.generation,
"peer_reconnect_observed", s.portSOnDemandObserved.Load(),
"backoff_failures", failures,
"outbound", s.sipOutboundFlow.Load(),
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
} else {
logging.Info("IMS REGISTER succeeded while awaiting peer port-s after timeout; still awaiting",
"device", s.DeviceID(), "cseq", s.cseq.Load(), "status", s.lastSIPCode.Load(),
"since_close", time.Since(session.closedAt).Round(time.Second),
"port_s_generation", session.generation,
"peer_reconnect_observed", s.portSOnDemandObserved.Load(),
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
}
return true
}
// generation is the port-s generation the caller saw with no connection open.
func (s *Service) backoffMissingPortSAfterRegister(generation uint64) {
if s.capturePortSSession().generation != generation {
@@ -109,6 +109,7 @@ func (s *Service) recordPortSClosed(conn net.Conn, err error, now time.Time) boo
return false
}
// Order close evidence against accepted UDP requests and failover commits.
var probe *portSTimeoutProbeEpisode
s.mu.Lock()
currentRegistrar := strings.TrimSpace(s.registrar)
s.portSSessionMu.Lock()
@@ -141,6 +142,10 @@ func (s *Service) recordPortSClosed(conn net.Conn, err error, now time.Time) boo
s.portSSession.lastCloseReason = errorText(err)
s.portSSession.closedRegistrar = registrar
s.recordPortSTimeoutLocked(registrar, kind)
if kind == portSCloseTimeout && s.timeoutAwaitPreset() && !s.sipOutboundFlow.Load() {
probe = &portSTimeoutProbeEpisode{generation: s.portSSession.generation, registrar: currentRegistrar}
s.portSTimeoutProbe.Store(probe)
}
}
startFailover := false
if current && kind == portSClosePeerReset {
@@ -157,6 +162,11 @@ func (s *Service) recordPortSClosed(conn net.Conn, err error, now time.Time) boo
"close_kind", kind, "reason", errorText(err),
"lifetime", elapsedSince(connection.openedAt, now),
"last_inbound_at", lastInboundAt)
if probe != nil {
logging.Info("IMS port-s timed out; SMS reception stays ready until the probe REGISTER answers",
"device", s.DeviceID(), "pcscf", probe.registrar, "port_s_generation", probe.generation,
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
}
if startFailover {
s.startPendingPortSResetFailover()
}
@@ -0,0 +1,444 @@
package imscore
import (
"errors"
"net"
"sync"
"syscall"
"testing"
"time"
)
// TS 33.203 §7.1 item 1 (TCP case): the P-CSCF sets up a connection to
// port_us before sending a request, and NOTE 6 does not require keeping it.
// Once a REGISTER after the timeout succeeds on a carrier known to reopen a
// timed-out port-s (Lebara UK), the UE waits for it instead of re-registering;
// that list is our choice. peerSeen marks an earlier peer reconnect, which a
// timeout does not rely on. timedOutPortS closes port-s by timeout and waits
// for the recovery REGISTER request.
func timedOutPortS(t *testing.T, preset string, peerSeen bool) *Service {
t.Helper()
service := newProtectedKeepaliveTestService(t)
service.cfg.CarrierPresetID = preset
registration, peer := net.Pipe()
t.Cleanup(func() { registration.Close(); peer.Close() })
service.registrationTCP, service.registrationTCPProtected = registration, true
service.portSOnDemandObserved.Store(peerSeen)
closeTestPortS(t, service, syscall.ETIMEDOUT)
service.handleProtectedServerPushClosed()
waitForPortSCondition(t, func() bool { return service.reRegisterPending.Load() })
if !service.portSRecoveryPending.Load() {
t.Fatal("timeout did not request a REGISTER first")
}
return service
}
func TestTimedOutPortSAwaitsPeerAfterSuccessfulRegister(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, true)
service.completePortSRecovery(nil, true)
if !service.canAwaitPeerAfterTimeout() || !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("successful REGISTER after timeout did not await the peer")
}
service.portSWatchMu.Lock()
timer := service.portSWatchTimer
service.portSWatchMu.Unlock()
if timer != nil {
t.Fatal("awaiting the peer still scheduled REGISTER recovery")
}
if _, waiting := service.portSRecoveryDeadline(time.Now()); waiting {
t.Fatal("awaiting the peer kept a recovery backoff")
}
if got := service.SMSReadiness(); !got.Ready || !got.HealthReady || got.Reason != smsReadyReasonAwaitingPeerPortS {
t.Fatalf("readiness while awaiting = %+v", got)
}
// A periodic refresh during the await neither re-arms recovery nor
// re-enters the await.
service.completePortSRecovery(nil, true)
service.portSWatchMu.Lock()
timer = service.portSWatchTimer
service.portSWatchMu.Unlock()
if timer != nil || !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("periodic refresh during the await restarted recovery")
}
reopenTestPortS(t, service)
if service.portSTimeoutAwaitEntered.Load() || service.portSReconnectWaiting.Load() {
t.Fatal("peer reopen did not end the await")
}
}
func TestTimedOutPortSAwaitNeedsRegisterAfterThisClose(t *testing.T) {
service := newProtectedKeepaliveTestService(t)
service.cfg.CarrierPresetID = lebaraUKCarrierPresetID
service.portSOnDemandObserved.Store(true)
client, peer := net.Pipe()
t.Cleanup(func() { client.Close(); peer.Close() })
service.recordPortSOpened(client, time.Now())
if !service.trackProtectedConnection(client) {
t.Fatal("track port-s")
}
// A REGISTER completion that raced the reopen left this behind.
service.portSRecoveryAwaitingFlow.Store(true)
service.recordPortSClosed(client, syscall.ETIMEDOUT, time.Now())
service.untrackProtectedConnection(client)
service.handleProtectedServerPushClosed()
if service.canAwaitPeerAfterTimeout() {
t.Fatal("stale REGISTER success skipped the REGISTER for this timeout")
}
waitForPortSCondition(t, func() bool { return service.reRegisterPending.Load() })
}
func TestTimedOutPortSAwaitEndsWhenRegisterFails(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, true)
service.completePortSRecovery(nil, true)
if !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("did not enter the await")
}
service.completePortSRecovery(errors.New("503"), true)
if service.canAwaitPeerAfterTimeout() || service.portSTimeoutAwaitEntered.Load() {
t.Fatal("failed REGISTER kept awaiting the peer")
}
if _, waiting := service.portSRecoveryDeadline(time.Now()); !waiting {
t.Fatal("failed REGISTER during the await did not resume recovery")
}
// The recovery REGISTER after the backoff succeeds: wait again.
service.portSWatchMu.Lock()
service.portSBackoff.retryAt = time.Now()
service.portSWatchMu.Unlock()
fireTestPortSWatch(t, service)
if !service.portSRecoveryPending.Load() {
t.Fatal("backoff did not send the recovery REGISTER")
}
service.completePortSRecovery(nil, true)
if !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("successful recovery REGISTER did not resume the await")
}
}
func TestTimedOutPortSAwaitSkipsVodafoneValidation(t *testing.T) {
service := newProtectedKeepaliveTestService(t)
service.cfg.CarrierPresetID = vodafoneUKCarrierPresetID
service.portSOnDemandObserved.Store(true)
closeTestPortS(t, service, syscall.ETIMEDOUT)
service.handleProtectedServerPushClosed()
fireTestPortSWatch(t, service)
if !service.portSRecoveryPending.Load() {
t.Fatal("Vodafone UK timeout did not request a REGISTER")
}
service.completePortSRecovery(nil, true)
if service.canAwaitPeerAfterTimeout() || service.portSTimeoutAwaitEntered.Load() {
t.Fatal("Vodafone UK timeout bypassed its downlink validation")
}
fireTestPortSWatch(t, service)
if _, waiting := service.portSRecoveryDeadline(time.Now()); !waiting {
t.Fatal("Vodafone UK missing downlink did not back off toward failover")
}
}
func reopenTestPortS(t *testing.T, service *Service) {
t.Helper()
client, peer := net.Pipe()
t.Cleanup(func() { client.Close(); peer.Close() })
if !service.trackProtectedPortSConnection(client, time.Now()) {
t.Fatal("track reopened port-s")
}
}
func TestOlderRegisterCompletionKeepsNewerTimeoutRecovery(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, true)
// Before the REGISTER completes, the peer reopens port-s and that
// connection times out too.
closeTestPortS(t, service, syscall.ETIMEDOUT)
service.handleProtectedServerPushClosed()
service.completePortSRecovery(nil, true)
if service.portSTimeoutAwaitEntered.Load() {
t.Fatal("an older REGISTER completion entered the await for a newer timeout")
}
if service.awaitingPeerAfterTimeout() || !service.protectedSMSPushRequiredLocked() {
t.Fatal("a refused await still suppressed recovery or readiness checks")
}
// Lebara UK probes the newer timeout with another REGISTER; the watch
// for it fires at once.
waitForPortSCondition(t, func() bool { return service.portSRecoveryPending.Load() })
}
func TestClearingStaleAwaitRepublishesReadiness(t *testing.T) {
service := newProtectedKeepaliveTestService(t)
registration, peer := net.Pipe()
t.Cleanup(func() { registration.Close(); peer.Close() })
service.registrationTCP = registration
service.registrationTCPProtected = true
service.portSOnDemandObserved.Store(true)
client, other := net.Pipe()
t.Cleanup(func() { client.Close(); other.Close() })
service.recordPortSOpened(client, time.Now())
if !service.trackProtectedConnection(client) {
t.Fatal("track port-s")
}
// A reopen that raced the await entry left the await marked.
service.portSTimeoutAwaitEntered.Store(true)
service.recordPortSClosed(client, syscall.ETIMEDOUT, time.Now())
service.untrackProtectedConnection(client)
var last SMSReadiness
service.SetOnSMSReadinessChanged(func(readiness SMSReadiness) { last = readiness })
if !last.Ready {
t.Fatal("test setup: stale await should still report ready before the close is handled")
}
service.handleProtectedServerPushClosed()
if last.Ready {
t.Fatalf("clearing the stale await did not republish readiness: %+v", last)
}
}
func TestTimedOutPortSAwaitSkipsOutboundFlow(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, true)
service.sipOutboundFlow.Store(true)
service.completePortSRecovery(nil, true)
if service.canAwaitPeerAfterTimeout() || service.portSTimeoutAwaitEntered.Load() {
t.Fatal("an RFC 5626 outbound flow skipped its flow recovery")
}
}
func TestLebaraFirstTimedOutPortSAwaitsPeerAfterSuccessfulRegister(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, false)
if got := service.SMSReadiness(); !got.Ready || !got.HealthReady || got.Reason != smsReadyReasonProbingPortS {
t.Fatalf("readiness before the probe REGISTER answered = %+v", got)
}
service.completePortSRecovery(nil, true)
if !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("first timeout on Lebara UK did not await the peer after REGISTER 200")
}
if got := service.SMSReadiness(); !got.Ready || got.Reason != smsReadyReasonAwaitingPeerPortS {
t.Fatalf("readiness while awaiting = %+v", got)
}
reopenTestPortS(t, service)
if service.portSTimeoutAwaitEntered.Load() || !service.portSOnDemandObserved.Load() {
t.Fatal("peer reopen during the await was not recorded as on-demand")
}
}
// Regression guard, not a spec requirement: carriers outside the list keep
// main's validation after a timeout, even after an earlier peer reconnect.
func TestTimedOutPortSOutsideTheListKeepsValidation(t *testing.T) {
for _, preset := range []string{"", oneNZCarrierPresetID, twoDegreesNZCarrierPresetID} {
for _, peerSeen := range []bool{false, true} {
service := timedOutPortS(t, preset, peerSeen)
if got := service.SMSReadiness(); got.Ready || got.HealthReady {
t.Fatalf("%q peer seen %t: timeout reported ready before REGISTER answered: %+v", preset, peerSeen, got)
}
service.completePortSRecovery(nil, true)
if service.canAwaitPeerAfterTimeout() || service.portSTimeoutAwaitEntered.Load() {
t.Fatalf("%q peer seen %t: timeout awaited the peer", preset, peerSeen)
}
service.portSWatchMu.Lock()
timer := service.portSWatchTimer
service.portSWatchMu.Unlock()
if timer == nil {
t.Fatalf("%q peer seen %t: no port-s validation scheduled after REGISTER", preset, peerSeen)
}
}
}
}
func TestLebaraFirstTimeoutReportsFailedRegister(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, false)
service.completePortSRecovery(errors.New("503"), true)
if service.portSTimeoutAwaitEntered.Load() {
t.Fatal("failed REGISTER entered the await")
}
if got := service.SMSReadiness(); got.Ready || got.HealthReady {
t.Fatalf("failed REGISTER after the timeout still reported ready: %+v", got)
}
}
func TestTimedOutPortSAwaitRevokedWhenRefreshNegotiatesOutbound(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, true)
service.completePortSRecovery(nil, true)
if !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("did not enter the await")
}
service.sipOutboundFlow.Store(true)
service.completePortSRecovery(nil, true)
if service.portSTimeoutAwaitEntered.Load() {
t.Fatal("await survived a refresh that negotiated an outbound flow")
}
service.portSWatchMu.Lock()
timer := service.portSWatchTimer
service.portSWatchMu.Unlock()
if timer == nil {
t.Fatal("revoked await did not schedule port-s validation")
}
if got := service.SMSReadiness(); got.Reason == smsReadyReasonAwaitingPeerPortS {
t.Fatalf("readiness still reports the await: %+v", got)
}
}
// lebaraTimeoutDuringRefresh leaves Lebara UK awaiting the peer, then times
// port-s out again while a periodic REGISTER of the live binding is in flight
// (registerMu held, regRegistering).
func lebaraTimeoutDuringRefresh(t *testing.T) *Service {
t.Helper()
service := timedOutPortS(t, lebaraUKCarrierPresetID, false)
service.completePortSRecovery(nil, true)
if !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("did not enter the await")
}
service.registerMu.Lock()
service.mu.Lock()
service.regSession.expires = time.Hour
service.lastRegisterOKAt = time.Now()
service.regState = regRegistering
service.mu.Unlock()
closeTestPortS(t, service, syscall.ETIMEDOUT)
service.handleProtectedServerPushClosed()
if got := service.SMSReadiness(); !got.Ready || got.Reason != smsReadyReasonProbingPortS {
service.registerMu.Unlock()
t.Fatalf("readiness after a timeout during a REGISTER = %+v", got)
}
return service
}
func TestLebaraTimeoutDuringRefreshProbesBeforeAwaiting(t *testing.T) {
service := lebaraTimeoutDuringRefresh(t)
service.portSRecoveryPending.Store(false)
// The periodic REGISTER answers 200, but it was sent before this close.
service.completePortSRecovery(nil, true)
setTestRegState(service, regRegistered)
service.registerMu.Unlock()
if service.portSTimeoutAwaitEntered.Load() || service.portSMissingAfterRegister.Load() {
t.Fatal("a REGISTER sent before the close entered the await or failed validation")
}
waitForPortSCondition(t, func() bool { return service.portSRecoveryPending.Load() })
if got := service.SMSReadiness(); !got.Ready {
t.Fatalf("readiness while the probe REGISTER is in flight = %+v", got)
}
service.completePortSRecovery(nil, true)
if !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("the probe REGISTER after the close did not enter the await")
}
}
func TestLebaraTimeoutDuringRefreshEndsGraceWhenRefreshFails(t *testing.T) {
service := lebaraTimeoutDuringRefresh(t)
// A failed refresh that keeps the binding returns to registered first.
setTestRegState(service, regRegistered)
service.completePortSRecovery(errors.New("503"), true)
service.registerMu.Unlock()
if got := service.SMSReadiness(); got.Ready || got.HealthReady {
t.Fatalf("failed REGISTER after the timeout still reported ready: %+v", got)
}
}
func TestPeerReopenDuringRegisterEndsAwaitWithoutOnDemandEvidence(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, false)
service.completePortSRecovery(nil, true)
if !service.portSTimeoutAwaitEntered.Load() {
t.Fatal("did not enter the await")
}
setTestRegState(service, regReregister)
reopenTestPortS(t, service)
if service.portSTimeoutAwaitEntered.Load() {
t.Fatal("peer reopen did not end the await")
}
if service.portSOnDemandObserved.Load() {
t.Fatal("a reopen during a REGISTER counted as on-demand evidence")
}
}
// Regression guard, not a spec requirement: an RFC 5626 outbound flow on
// Lebara UK keeps its earlier readiness and recovery after a timeout.
func TestLebaraOutboundTimeoutKeepsRecovery(t *testing.T) {
service := newProtectedKeepaliveTestService(t)
service.cfg.CarrierPresetID = lebaraUKCarrierPresetID
registration, peer := net.Pipe()
t.Cleanup(func() { registration.Close(); peer.Close() })
service.registrationTCP, service.registrationTCPProtected = registration, true
service.sipOutboundFlow.Store(true)
closeTestPortS(t, service, syscall.ETIMEDOUT)
service.handleProtectedServerPushClosed()
waitForPortSCondition(t, func() bool { return service.reRegisterPending.Load() })
if got := service.SMSReadiness(); got.Ready || got.HealthReady {
t.Fatalf("outbound timeout reported ready: %+v", got)
}
service.completePortSRecovery(nil, true)
if service.portSTimeoutAwaitEntered.Load() {
t.Fatal("outbound timeout awaited the peer")
}
service.portSWatchMu.Lock()
timer := service.portSWatchTimer
service.portSWatchMu.Unlock()
if timer == nil {
t.Fatal("outbound timeout did not schedule port-s validation")
}
}
func TestLebaraTimeoutDuringRecoveryBackoffGetsNoGrace(t *testing.T) {
service := timedOutPortS(t, lebaraUKCarrierPresetID, false)
service.completePortSRecovery(errors.New("503"), true)
if _, waiting := service.portSRecoveryDeadline(time.Now()); !waiting {
t.Fatal("failed probe REGISTER did not back off")
}
// The peer reopens port-s during a REGISTER, which keeps the backoff, and
// it times out again before the backoff ends.
var (
publishedMu sync.Mutex
published SMSReadiness
)
service.SetOnSMSReadinessChanged(func(readiness SMSReadiness) {
publishedMu.Lock()
published = readiness
publishedMu.Unlock()
})
setTestRegState(service, regReregister)
client, peer := net.Pipe()
t.Cleanup(func() { client.Close(); peer.Close() })
service.recordPortSOpened(client, time.Now())
if !service.trackProtectedConnection(client) {
t.Fatal("track port-s")
}
setTestRegState(service, regRegistered)
service.recordPortSClosed(client, syscall.ETIMEDOUT, time.Now())
service.untrackProtectedConnection(client)
publishedMu.Lock()
got := published
publishedMu.Unlock()
if !got.Ready {
t.Fatalf("the close itself did not publish the timeout grace: %+v", got)
}
service.handleProtectedServerPushClosed()
publishedMu.Lock()
got = published
publishedMu.Unlock()
if got.Ready || got.HealthReady {
t.Fatalf("timeout during the backoff published ready with no probe REGISTER: %+v", got)
}
}
func setTestRegState(service *Service, state string) {
service.mu.Lock()
service.regState = state
service.mu.Unlock()
}
func TestLebaraTimeoutGraceEndsOnAnotherRegistrationPath(t *testing.T) {
// A new registration on the same P-CSCF, after the await, before port-s.
service := timedOutPortS(t, lebaraUKCarrierPresetID, false)
service.completePortSRecovery(nil, true)
service.resetPortSRecoveryKnowledge()
if got := service.SMSReadiness(); got.Ready || got.Reason == smsReadyReasonProbingPortS {
t.Fatalf("new registration kept the old timeout grace: %+v", got)
}
// Another P-CSCF while the probe REGISTER is still in flight.
service = timedOutPortS(t, lebaraUKCarrierPresetID, false)
if got := service.SMSReadiness(); !got.Ready {
t.Fatalf("readiness before the probe answered = %+v", got)
}
service.mu.Lock()
service.registrar = "pcscf-b.ims.example"
service.mu.Unlock()
if got := service.SMSReadiness(); got.Ready || got.Reason == smsReadyReasonProbingPortS {
t.Fatalf("another P-CSCF kept the old timeout grace: %+v", got)
}
}
@@ -140,6 +140,7 @@ func (s *Service) confirmPortSTimeoutDownlinkLocked(peer net.Conn) bool {
state.downlinkProven = true
state.validationFailed = false
s.portSRecoveryAwaitingFlow.Store(false)
s.portSTimeoutAwaitEntered.Store(false)
s.portSReconnectWaiting.Store(false)
s.resetPortSRecoveryBackoff()
}
@@ -161,6 +161,7 @@ func (s *Service) registerLocked(ctx context.Context) error {
s.signalingFailureReason = err.Error()
s.sipOutboundKeepalive = false
s.sipOutbound = false
s.sipOutboundFlow.Store(false)
s.sipOutboundRequired = false
s.outboundContactOffered = false
s.outboundContactRegistered = false
@@ -31,6 +31,7 @@ func (s *Service) logRegisterFlowNegotiation(response *sipResponse) {
// Supported and 503s the extra REGISTER (hideck#8 / #6).
s.sipOutboundRequired = requiredOutbound
s.sipOutbound = requiredOutbound || pathOB || contactRegID
s.sipOutboundFlow.Store(s.sipOutbound)
if s.outboundContactOffered {
s.outboundContactRegistered = true
}
@@ -299,6 +299,8 @@ func (s *Service) serveProtectedSIPConnection(conn net.Conn) {
// falls back to a REGISTER refresh if it does not. A failed refresh is not
// evidence of an on-demand flow. A later peer reconnect permits waiting after
// clean EOF only; it does not establish reachability after transport errors.
// A timeout on a listed carrier waits only after a successful REGISTER
// (canAwaitPeerAfterTimeout).
func (s *Service) handleProtectedServerPushClosed() {
if s == nil || s.stopped() {
return
@@ -313,7 +315,18 @@ func (s *Service) handleProtectedServerPushClosed() {
return
}
s.portSReconnectWaiting.Store(true)
// A new close starts a new episode: only a REGISTER response after this
// close can show the P-CSCF is still there (canAwaitPeerAfterTimeout).
s.portSRecoveryAwaitingFlow.Store(false)
staleAwait := s.portSTimeoutAwaitEntered.Swap(false)
s.protectedConnMu.Unlock()
if staleAwait {
// The close was published while the await still reported ready.
s.notifySMSReadiness()
logging.WarnRate("ims-ports-stale-await-"+s.DeviceID(), 30*time.Second,
"IMS port-s closed while still marked awaiting peer after timeout; restart recovery",
"device", s.DeviceID(), "close_kind", s.capturePortSSession().lastCloseKind)
}
if s.canAwaitOnDemandPortS() {
logging.Info("IMS protected server push closed; await peer port-s reconnect",
"device", s.DeviceID(), "since_last_read", s.portSSinceLastRead(),
@@ -327,6 +340,10 @@ func (s *Service) handleProtectedServerPushClosed() {
logging.Info("IMS protected server push closed during recovery backoff",
"device", s.DeviceID(), "since_last_read", s.portSSinceLastRead(),
"retry_in", retryAt.Sub(now))
// No probe REGISTER follows this close until the backoff ends.
if s.endTimeoutProbeGrace("recovery backoff", nil) {
s.notifySMSReadiness()
}
s.schedulePortSReconnectWatchAt(retryAt)
return
}
@@ -417,6 +434,15 @@ func (s *Service) portSReconnectWatchFired(generation uint64, registrar string)
s.protectedConnMu.Unlock()
return
}
if s.awaitingPeerAfterTimeout() {
s.protectedConnMu.Unlock()
// enterPortSTimeoutAwait bumps the watch generation via
// resetPortSRecoveryBackoff, so this is a bug.
logging.WarnRate("ims-ports-await-watch-"+s.DeviceID(), 30*time.Second,
"IMS port-s watch fired while awaiting peer after timeout; ignored",
"device", s.DeviceID(), "generation", generation, "registrar", registrar)
return
}
portSGeneration := s.capturePortSSession().generation
s.protectedConnMu.Unlock()
if s.portSRecoveryAwaitingFlow.Swap(false) {
@@ -433,6 +459,7 @@ func (s *Service) portSReconnectWatchFired(generation uint64, registrar string)
if !s.portSRecoveryPending.CompareAndSwap(false, true) {
return
}
s.portSRecoveryRegisterGen.Store(portSGeneration)
s.markPortSResetRecoveryAttempt(registrar)
s.triggerRegisterImmediate("port-s flow failed")
}
@@ -487,6 +514,100 @@ func (s *Service) awaitPortSAfterRegister() bool {
return s.canAwaitOnDemandPortS()
}
// canAwaitPeerAfterTimeout reports whether a timed-out port-s can be left
// for the P-CSCF to reopen. TS 33.203 §7.1 item 1 (TCP case) makes the P-CSCF
// set up a connection to port_us before sending a request, and §7.1 NOTE 6
// does not require keeping it open. The REGISTER after the close must have
// succeeded (portSRecoveryAwaitingFlow) so a dead P-CSCF is still caught.
// A timeout does not show the P-CSCF chose to close, and a past peer reconnect
// is only a hint for a clean EOF (canAwaitOnDemandPortS), so only carriers
// seen reopening a timed-out port-s for MT requests wait (timeoutAwaitPreset).
// Other carriers, Vodafone UK's validation and failover, and RFC 5626 outbound
// flows keep their recovery.
func (s *Service) canAwaitPeerAfterTimeout() bool {
if s == nil || usesVodafoneUKPortSResetRecovery(s.cfg) || s.sipOutboundFlow.Load() {
return false
}
return s.capturePortSSession().lastCloseKind == portSCloseTimeout &&
s.timeoutAwaitPreset() && s.portSRecoveryAwaitingFlow.Load()
}
// timeoutAwaitPreset reports a carrier whose P-CSCF lets an idle port-s time
// out and reopens it only to deliver a request. Lebara UK: port-s timed out
// after 2-14 hours idle on 10-06, 10-08 and 10-09, REGISTER 200 never reopened
// it, and an MT SMS reopened it each time (10-24: after 21m48s closed; 10-28:
// after 9m51s and 4m27s, the second for an A2P SMS).
func (s *Service) timeoutAwaitPreset() bool {
return s != nil && s.cfg != nil && strings.TrimSpace(s.cfg.CarrierPresetID) == lebaraUKCarrierPresetID
}
// timeoutProbeGraceLocked keeps SMS reception ready from a port-s timeout on
// a timeoutAwaitPreset carrier until the probe REGISTER after it answers. The
// timeout itself is not a fault: either side may close the TCP connection
// (TS 24.229 §4.2A NOTE 2) and this P-CSCF reopens it on demand. The probe
// takes about one REGISTER round trip; its failure (endTimeoutProbeGrace), a
// validation after its success, another P-CSCF or a new registration
// (resetPortSRecoveryKnowledge) ends the grace. Outbound flows keep their
// RFC 5626 recovery and readiness. The caller holds mu.
func (s *Service) timeoutProbeGraceLocked(portS portSSessionSnapshot) bool {
probe := s.portSTimeoutProbe.Load()
return probe != nil && probe.generation == portS.generation &&
strings.EqualFold(probe.registrar, strings.TrimSpace(s.registrar)) &&
s.timeoutAwaitPreset() && !s.sipOutboundFlow.Load() &&
portS.lastCloseKind == portSCloseTimeout && !portS.connected &&
!s.portSRecoveryAwaitingFlow.Load() && !s.portSMissingAfterRegister.Load()
}
// endTimeoutProbeGrace ends the reception grace of the current timed-out
// port-s; it reports whether a grace was ended. Callers publish readiness.
func (s *Service) endTimeoutProbeGrace(reason string, err error) bool {
probe := s.portSTimeoutProbe.Load()
session := s.capturePortSSession()
if probe == nil || probe.generation != session.generation ||
!s.portSTimeoutProbe.CompareAndSwap(probe, nil) {
return false
}
logging.Info("IMS port-s timeout reception grace ended",
"device", s.DeviceID(), "reason", reason, "err", err,
"port_s_generation", session.generation, "cseq", s.cseq.Load(), "status", s.lastSIPCode.Load(),
"since_close", time.Since(session.closedAt).Round(time.Second),
"pcscf", probe.registrar, "carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
return true
}
// probeTimedOutPortSAgain sends the probe REGISTER for a timeout that closed
// port-s while another REGISTER was in flight: that REGISTER's success belongs
// to an older port-s generation, so it does not show the P-CSCF answered after
// this close. The watch sends the probe once this REGISTER releases registerMu.
func (s *Service) probeTimedOutPortSAgain() bool {
if !s.timeoutAwaitPreset() || s.sipOutboundFlow.Load() {
return false
}
s.protectedConnMu.Lock()
session := s.capturePortSSession()
registerGen := s.portSRecoveryRegisterGen.Load()
stale := len(s.protectedConns) == 0 && session.lastCloseKind == portSCloseTimeout &&
session.generation != registerGen
s.protectedConnMu.Unlock()
if !stale {
return false
}
s.portSRecoveryAwaitingFlow.Store(false)
logging.Info("IMS port-s timed out during a REGISTER; probing with another REGISTER",
"device", s.DeviceID(), "port_s_generation", session.generation,
"register_port_s_generation", registerGen, "cseq", s.cseq.Load(), "status", s.lastSIPCode.Load(),
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
s.schedulePortSReconnectWatchAt(time.Now())
return true
}
// awaitingPeerAfterTimeout reports an await that enterPortSTimeoutAwait
// accepted for the current episode. Recovery and readiness follow this, not
// eligibility, so a refused entry keeps the normal validation path.
func (s *Service) awaitingPeerAfterTimeout() bool {
return s != nil && s.portSTimeoutAwaitEntered.Load()
}
func portSClosedFor(session portSSessionSnapshot) time.Duration {
if session.closedAt.IsZero() || session.openedAt.Before(session.closedAt) {
return 0
@@ -499,6 +620,7 @@ const (
globePHCarrierPresetID = "globe_ph_51502"
ditoPHCarrierPresetID = "dito_51566"
twoDegreesNZCarrierPresetID = "2degrees_nz_53024"
lebaraUKCarrierPresetID = "lebara_uk_23487"
)
func (s *Service) consumePortSReconnectWatch(generation uint64, registrar string) bool {
@@ -542,6 +664,32 @@ func (s *Service) completePortSRecovery(err error, bindingPreserved bool) {
s.clearPortSRecoveryDeadline()
s.portSRecoveryAwaitingFlow.Store(true)
s.portSReconnectWaiting.Store(true)
if s.canAwaitPeerAfterTimeout() && s.enterPortSTimeoutAwait(s.portSRecoveryRegisterGen.Load()) {
return
}
if s.portSTimeoutAwaitEntered.Swap(false) {
// The await no longer qualifies (for example this refresh
// negotiated an outbound flow), so validate port-s again.
logging.Info("IMS port-s await after timeout revoked; validating port-s",
"device", s.DeviceID(), "peer_reconnect_observed", s.portSOnDemandObserved.Load(),
"carrier_preset_await", s.timeoutAwaitPreset(),
"vodafone_uk", usesVodafoneUKPortSResetRecovery(s.cfg), "outbound", s.sipOutboundFlow.Load(),
"close_kind", s.capturePortSSession().lastCloseKind,
"register_port_s_generation", s.portSRecoveryRegisterGen.Load(),
"port_s_generation", s.capturePortSSession().generation,
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
}
if s.probeTimedOutPortSAgain() {
return
}
if pending && s.capturePortSSession().lastCloseKind == portSCloseTimeout {
logging.Info("IMS port-s timed out; REGISTER succeeded, validating port-s",
"device", s.DeviceID(), "peer_reconnect_observed", s.portSOnDemandObserved.Load(),
"vodafone_uk", usesVodafoneUKPortSResetRecovery(s.cfg), "outbound", s.sipOutboundFlow.Load(),
"register_port_s_generation", s.portSRecoveryRegisterGen.Load(),
"port_s_generation", s.capturePortSSession().generation,
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
}
s.schedulePortSReconnectWatchAt(time.Now().Add(s.portSRecoveryValidationWait()))
}
return
@@ -549,6 +697,19 @@ func (s *Service) completePortSRecovery(err error, bindingPreserved bool) {
// A failed REGISTER supersedes any earlier post-success validation wait.
s.retainReplacementRegisterRetryAfter(err)
s.portSRecoveryAwaitingFlow.Store(false)
s.endTimeoutProbeGrace("REGISTER failed", err)
if s.portSTimeoutAwaitEntered.Swap(false) {
next := "resume port-s recovery"
if !bindingPreserved {
next = "binding lost; registration restarts"
}
logging.Info("IMS REGISTER failed while awaiting peer port-s after timeout",
"device", s.DeviceID(), "err", err, "binding_preserved", bindingPreserved,
"canceled", isRegisterOperationCanceled(err), "next", next,
"since_close", time.Since(s.capturePortSSession().closedAt).Round(time.Second),
"peer_reconnect_observed", s.portSOnDemandObserved.Load(),
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
}
if !bindingPreserved {
s.portSReconnectWaiting.Store(false)
s.resetPortSRecoveryBackoff()
@@ -580,8 +741,29 @@ func (s *Service) recordOnDemandPortSReconnect() {
return
}
timeout := s.clearPortSTimeoutRecovery()
awaitedAfterTimeout := s.portSTimeoutAwaitEntered.Swap(false)
awaitingFlow := s.portSRecoveryAwaitingFlow.Swap(false)
session := s.capturePortSSession()
if awaitedAfterTimeout {
s.portSReconnectWaiting.Store(false)
s.resetPortSRecoveryBackoff()
if s.portSRecoveryPending.Load() || s.registrationInProgress() {
// A REGISTER in flight may have prompted this reopen, so it is
// not on-demand evidence, as below.
logging.Info("IMS peer reopened port-s while awaited after timeout during a REGISTER; not counted as on-demand",
"device", s.DeviceID(), "close_kind", session.lastCloseKind, "closed_for", portSClosedFor(session),
"port_s_generation", session.generation, "cseq", s.cseq.Load(), "status", s.lastSIPCode.Load(),
"peer_reconnect_observed", s.portSOnDemandObserved.Load(),
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
return
}
s.portSOnDemandObserved.Store(true)
logging.Info("IMS peer reopened port-s while awaited after timeout", "device", s.DeviceID(),
"close_kind", session.lastCloseKind, "closed_for", portSClosedFor(session),
"peer_reconnect_observed", s.portSOnDemandObserved.Load(),
"carrier_preset", strings.TrimSpace(s.cfg.CarrierPresetID))
return
}
if awaitingFlow || timeout.validationFailed {
s.portSReconnectWaiting.Store(false)
s.resetPortSRecoveryBackoff()
@@ -636,6 +818,8 @@ func (s *Service) resetPortSRecoveryKnowledge() {
s.portSRecoveryAwaitingFlow.Store(false)
s.portSOnDemandObserved.Store(false)
s.portSMissingAfterRegister.Store(false)
s.portSTimeoutAwaitEntered.Store(false)
s.portSTimeoutProbe.Store(nil)
s.clearPortSResetRecovery("")
s.clearPortSTimeoutRecovery()
}
@@ -2,6 +2,7 @@ package imscore
import (
"strings"
"time"
"github.com/iniwex5/vowifi-go/internal/vowifi/logging"
)
@@ -16,6 +17,8 @@ const (
smsReadyReasonAwaitingDownlink = "IMS registered; SMS reception awaiting downlink verification"
smsReadyReasonRegistrationFlow = "IMS SMS receiver verified on registered TCP flow"
smsReadyReasonPortSAwaitingPeer = "IMS registered; port-s closed or timed out, awaiting the P-CSCF reconnect"
smsReadyReasonAwaitingPeerPortS = "IMS SMS receiver ready; port-s timed out, P-CSCF reconnects on demand"
smsReadyReasonProbingPortS = "IMS SMS receiver ready; port-s timed out, REGISTER probing the P-CSCF"
)
type smsHealthInput struct {
@@ -33,16 +36,23 @@ func (s *Service) SMSReadiness() SMSReadiness {
s.mu.RLock()
defer s.mu.RUnlock()
registered := s.regState == regRegistered
protectedPushRequired := s.protectedSMSPushRequiredLocked()
portS := s.capturePortSSession()
// A periodic REGISTER in flight keeps the binding it refreshes.
probeGrace := protectedPushRequired && s.timeoutProbeGraceLocked(portS) &&
(registered || s.bindingLiveDuringRegisterLocked(time.Now()))
if probeGrace {
registered = true
}
profileReady := registered && s.regSession != nil &&
strings.TrimSpace(s.regSession.publicID) != "" &&
strings.TrimSpace(s.regSession.contactUser) != ""
transportReady := registered && s.registeredSIPTransportReadyLocked()
baseReceiverReady := s.smsReceiverReady
receiverReady := baseReceiverReady
protectedPushRequired := s.protectedSMSPushRequiredLocked()
registrationSMSProven := s.registrationSMSProvenLocked()
awaitingEvidence := !s.smsReception.failed && s.smsReception.peer == nil
if protectedPushRequired {
if protectedPushRequired && !probeGrace {
receiverReady = receiverReady && (s.portSPushReady.Load() || registrationSMSProven)
}
smsc := ""
@@ -50,7 +60,6 @@ func (s *Service) SMSReadiness() SMSReadiness {
smsc = s.cfg.SMSC
}
readiness := evaluateSMSReadiness(registered, profileReady, transportReady, receiverReady, smsc)
portS := s.capturePortSSession()
readiness.HealthReady = readiness.Ready || smsReceiverHealthReady(smsHealthInput{
readiness: readiness, baseReceiverReady: baseReceiverReady,
protectedPushRequired: protectedPushRequired, portS: portS,
@@ -63,6 +72,10 @@ func (s *Service) SMSReadiness() SMSReadiness {
}
if readiness.Ready && registrationSMSProven {
readiness.Reason = smsReadyReasonRegistrationFlow
} else if readiness.Ready && !s.portSPushReady.Load() && s.awaitingPeerAfterTimeout() {
readiness.Reason = smsReadyReasonAwaitingPeerPortS
} else if readiness.Ready && probeGrace {
readiness.Reason = smsReadyReasonProbingPortS
}
if !readiness.Ready && readiness.SMSCPresent && !s.smsReception.reportFailed &&
strings.EqualFold(portS.closedRegistrar, strings.TrimSpace(s.registrar)) && portSAwaitingPeer(smsHealthInput{
@@ -87,6 +100,14 @@ func portSAwaitingPeer(input smsHealthInput) bool {
!input.portS.closedAt.Before(input.portS.openedAt) && !input.portS.timeoutValidationFailed
}
// bindingLiveDuringRegisterLocked reports a REGISTER in flight on a binding
// that has not expired yet. The caller holds mu.
func (s *Service) bindingLiveDuringRegisterLocked(now time.Time) bool {
return (s.regState == regRegistering || s.regState == regReregister) &&
s.regSession != nil && s.regSession.expires > 0 && !s.lastRegisterOKAt.IsZero() &&
now.Before(s.lastRegisterOKAt.Add(s.regSession.expires))
}
func smsReceiverHealthReady(input smsHealthInput) bool {
return input.readiness.Registered && input.readiness.ProfileReady &&
input.readiness.TransportReady && input.baseReceiverReady &&
@@ -97,6 +118,7 @@ func smsReceiverHealthReady(input smsHealthInput) bool {
func (s *Service) protectedSMSPushRequiredLocked() bool {
return !s.externalTransport && !s.canAwaitOnDemandPortS() && !s.portSTimeoutDownlinkProven() &&
!s.awaitingPeerAfterTimeout() &&
s.regSession != nil &&
s.regSession.security != nil &&
strings.TrimSpace(s.regSession.security.verifyHeader) != ""
+17
View File
@@ -213,6 +213,16 @@ type Service struct {
protectedUDPRetiring *protectedUDPTransport
saRetirement atomic.Pointer[saRetirement]
// Set once per port-s timeout when recovery switches to awaiting the
// peer; drives the one-shot log and the reopen attribution.
portSTimeoutAwaitEntered atomic.Bool
// Port-s generation when the last recovery REGISTER was sent.
portSRecoveryRegisterGen atomic.Uint64
// The timed-out port-s whose probe REGISTER has not failed yet
// (timeoutProbeGraceLocked); nil when there is none.
portSTimeoutProbe atomic.Pointer[portSTimeoutProbeEpisode]
// Mirrors sipOutbound for readers that cannot take mu.
sipOutboundFlow atomic.Bool
portSWatchMu sync.Mutex
portSWatchTimer *time.Timer
portSWatchGeneration uint64
@@ -492,3 +502,10 @@ type SMSDeliveryIdentityStore = smsdelivery.IdentityStore
// DeliveryPartStatus is one delivery part.
type DeliveryPartStatus = smsdelivery.DeliveryPartStatus
// portSTimeoutProbeEpisode is a port-s timeout on a timeoutAwaitPreset carrier,
// bound to the port-s generation and P-CSCF it closed on.
type portSTimeoutProbeEpisode struct {
generation uint64
registrar string
}
@@ -20,5 +20,9 @@ export function smsReceptionDetail(runtime?: VoWiFiRuntimeState): string {
if (runtime?.sms_ready && runtime.sms_ready_reason === 'IMS SMS receiver verified on registered TCP flow') {
return '短信接收已验证,复用注册连接'
}
if (runtime?.sms_ready && (runtime.sms_ready_reason === 'IMS SMS receiver ready; port-s timed out, P-CSCF reconnects on demand' ||
runtime.sms_ready_reason === 'IMS SMS receiver ready; port-s timed out, REGISTER probing the P-CSCF')) {
return '端口已断,等运营商按需连入'
}
return ''
}
@@ -33,3 +33,13 @@ test('verified registered-flow reception describes its actual route', () => {
assert.equal(createDashboardStages(runtime)[5]?.ready, true)
assert.equal(smsReceptionDetail(runtime), '短信接收已验证,复用注册连接')
})
test('reception awaiting an on-demand port-s says so', () => {
const runtime = { ims_ready: true, sms_ready: true, sms_rx_pending: false,
sms_ready_reason: 'IMS SMS receiver ready; port-s timed out, P-CSCF reconnects on demand' }
assert.equal(createDashboardStages(runtime)[5]?.ready, true)
assert.equal(smsReceptionDetail(runtime), '端口已断,等运营商按需连入')
const probing = { ...runtime, sms_ready_reason: 'IMS SMS receiver ready; port-s timed out, REGISTER probing the P-CSCF' }
assert.equal(createDashboardStages(probing)[5]?.ready, true)
assert.equal(smsReceptionDetail(probing), '端口已断,等运营商按需连入')
})