From de3b95faacf82592fd56e819f9bbf884308e2012 Mon Sep 17 00:00:00 2001 From: yibaiba <946100224@qq.com> Date: Mon, 10 Aug 2026 16:56:28 +0800 Subject: [PATCH] [restore-vowifi-25.11] restore IMS maintenance loop --- .../internal/vowifi/imscore/helpers.go | 11 + .../internal/vowifi/imscore/helpers_test.go | 5 + .../internal/vowifi/imscore/inbound_stats.go | 124 ++++++++ .../internal/vowifi/imscore/keepalive.go | 54 +++- .../internal/vowifi/imscore/keepalive_test.go | 10 +- .../vowifi/imscore/maintenance_stats_test.go | 268 ++++++++++++++++++ .../internal/vowifi/imscore/network.go | 31 +- .../internal/vowifi/imscore/register.go | 1 + .../imscore/register_initial_transport.go | 7 + .../vowifi/imscore/register_transport.go | 17 +- .../internal/vowifi/imscore/service.go | 20 +- .../vowifi/imscore/service_methods.go | 7 +- .../vowifi/imscore/service_trigger.go | 28 ++ .../vowifi/imscore/signaling_failure.go | 28 +- .../vowifi/imscore/sms_delivery_report.go | 33 ++- .../internal/vowifi/imscore/sms_runtime.go | 1 + .../internal/vowifi/imscore/subscribe_reg.go | 5 + .../vowifi/imscore/transport_runtime.go | 9 + .../internal/vowifi/imscore/types.go | 4 +- 19 files changed, 628 insertions(+), 35 deletions(-) create mode 100644 third_party/vowifi-go/internal/vowifi/imscore/inbound_stats.go create mode 100644 third_party/vowifi-go/internal/vowifi/imscore/maintenance_stats_test.go create mode 100644 third_party/vowifi-go/internal/vowifi/imscore/service_trigger.go diff --git a/third_party/vowifi-go/internal/vowifi/imscore/helpers.go b/third_party/vowifi-go/internal/vowifi/imscore/helpers.go index c478c9b7..1aaad4a1 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/helpers.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/helpers.go @@ -3,9 +3,13 @@ package imscore import ( "crypto/rand" "crypto/sha256" + "errors" "fmt" + "io" + "net" "strconv" "strings" + "syscall" "time" "github.com/iniwex5/vowifi-go/internal/vowifi/common" @@ -213,6 +217,13 @@ func IsFatalNetworkError(err error) bool { if err == nil { return false } + for _, target := range []error{ + io.EOF, net.ErrClosed, syscall.ECONNREFUSED, syscall.ECONNRESET, syscall.EPIPE, + } { + if errors.Is(err, target) { + return true + } + } message := strings.ToLower(err.Error()) for _, fatal := range []string{ "network is unreachable", diff --git a/third_party/vowifi-go/internal/vowifi/imscore/helpers_test.go b/third_party/vowifi-go/internal/vowifi/imscore/helpers_test.go index 584ebb40..9f5b3bb1 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/helpers_test.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/helpers_test.go @@ -2,7 +2,11 @@ package imscore import ( "errors" + "fmt" + "io" + "net" "strings" + "syscall" "testing" "time" @@ -43,6 +47,7 @@ func TestIsFatalNetworkError(t *testing.T) { errors.New("connection refused"), errors.New("network is unreachable"), errors.New("use of closed network connection"), errors.New("no route to host"), errors.New("connection reset by peer"), errors.New("broken pipe"), + io.EOF, net.ErrClosed, fmt.Errorf("wrapped reset: %w", syscall.ECONNRESET), } for _, e := range fatal { if !IsFatalNetworkError(e) { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/inbound_stats.go b/third_party/vowifi-go/internal/vowifi/imscore/inbound_stats.go new file mode 100644 index 00000000..932e7d82 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/imscore/inbound_stats.go @@ -0,0 +1,124 @@ +package imscore + +import ( + "context" + "time" + + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" +) + +const defaultInboundStatsInterval = 30 * time.Second + +type inboundStatsLoggerOptions struct { + Interval time.Duration +} + +type inboundStatsSnapshot struct { + UDPSocketReads uint64 + UDPSocketBytes uint64 + TCPAccepts uint64 + TCPSocketReads uint64 + TCPSocketBytes uint64 + SIPParsedMessages uint64 + SIPParsedRequests uint64 + SIPParsedResponses uint64 +} + +func (s *Service) startInboundStatsLogger(ctx context.Context, options inboundStatsLoggerOptions) { + if s == nil || ctx == nil || options.Interval <= 0 { + return + } + s.inboundStatsMu.Lock() + defer s.inboundStatsMu.Unlock() + s.stopInboundStatsLoggerLocked() + if s.stopped() { + return + } + loggerCtx, cancel := context.WithCancel(ctx) + done := make(chan struct{}) + s.inboundStatsCancel = cancel + s.inboundStatsDone = done + go func() { + defer close(done) + s.logInboundStats(loggerCtx, options.Interval) + }() +} + +func (s *Service) stopInboundStatsLogger() { + if s == nil { + return + } + s.inboundStatsMu.Lock() + defer s.inboundStatsMu.Unlock() + s.stopInboundStatsLoggerLocked() +} + +func (s *Service) stopInboundStatsLoggerLocked() { + cancel := s.inboundStatsCancel + done := s.inboundStatsDone + s.inboundStatsCancel = nil + s.inboundStatsDone = nil + if cancel != nil { + cancel() + } + if done != nil { + <-done + } +} + +func (s *Service) logInboundStats(ctx context.Context, interval time.Duration) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-s.stop: + return + case <-ticker.C: + s.logInboundStatsSnapshot(s.captureInboundStats()) + } + } +} + +func (s *Service) logInboundStatsSnapshot(stats inboundStatsSnapshot) { + status := s.receiverStatus() + logging.Debug("IMS inbound stats", + "device", s.DeviceID(), "transport", status.Transport, + "local_address", status.LocalAddress, "local_port", s.cfg.LocalPort, + "udp_socket_reads", stats.UDPSocketReads, "udp_socket_bytes", stats.UDPSocketBytes, + "tcp_accepts", stats.TCPAccepts, "tcp_socket_reads", stats.TCPSocketReads, + "tcp_socket_bytes", stats.TCPSocketBytes, + "sip_parsed_messages", stats.SIPParsedMessages, + "sip_parsed_requests", stats.SIPParsedRequests, + "sip_parsed_responses", stats.SIPParsedResponses) +} + +func (s *Service) captureInboundStats() inboundStatsSnapshot { + if s == nil { + return inboundStatsSnapshot{} + } + return inboundStatsSnapshot{ + UDPSocketReads: s.inboundUDPSocketRead.Load(), + UDPSocketBytes: s.inboundUDPSocketBytes.Load(), + TCPAccepts: s.inboundTCPAccept.Load(), + TCPSocketReads: s.inboundTCPSocketRead.Load(), + TCPSocketBytes: s.inboundTCPSocketBytes.Load(), + SIPParsedMessages: s.inboundSIPParsedMessage.Load(), + SIPParsedRequests: s.inboundSIPParsedRequest.Load(), + SIPParsedResponses: s.inboundSIPParsedResp.Load(), + } +} + +func (stats inboundStatsSnapshot) diagnostics() map[string]interface{} { + return map[string]interface{}{ + "inbound_udp_socket_reads": stats.UDPSocketReads, + "inbound_udp_socket_bytes": stats.UDPSocketBytes, + "inbound_tcp_accepts": stats.TCPAccepts, + "inbound_tcp_socket_reads": stats.TCPSocketReads, + "inbound_tcp_socket_bytes": stats.TCPSocketBytes, + "inbound_sip_parsed_messages": stats.SIPParsedMessages, + "inbound_sip_parsed_requests": stats.SIPParsedRequests, + "inbound_sip_parsed_responses": stats.SIPParsedResponses, + } +} diff --git a/third_party/vowifi-go/internal/vowifi/imscore/keepalive.go b/third_party/vowifi-go/internal/vowifi/imscore/keepalive.go index 4ebe281a..2a54db11 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/keepalive.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/keepalive.go @@ -2,11 +2,13 @@ package imscore import ( "context" + "errors" "fmt" "strings" "time" "github.com/emiago/sipgo/sip" + enginesim "github.com/iniwex5/vowifi-go/engine/sim" "github.com/iniwex5/vowifi-go/internal/vowifi/common" "github.com/iniwex5/vowifi-go/internal/vowifi/imsheaders" "github.com/iniwex5/vowifi-go/internal/vowifi/logging" @@ -38,18 +40,18 @@ func (s *Service) startIMSKeepalive() { if s == nil { return } + s.UpdateLastPingAt(time.Now()) s.keepaliveOnce.Do(func() { - s.UpdateLastPingAt(time.Now()) s.networkDone.Add(1) - go s.runIMSMaintenance() + go s.keepaliveLoop() }) s.signalIMSMaintenance() } -func (s *Service) runIMSMaintenance() { +func (s *Service) keepaliveLoop() { defer s.networkDone.Done() for { - if !s.waitForIMSMaintenance(s.computeNextIMSWakeTime(time.Now())) { + if !s.waitForIMSMaintenance(s.computeNextWakeTime(time.Now())) { return } switch s.nextIMSMaintenanceAction(time.Now()) { @@ -80,7 +82,7 @@ func (s *Service) waitForIMSMaintenance(wakeAt time.Time) bool { } } -func (s *Service) computeNextIMSWakeTime(now time.Time) time.Time { +func (s *Service) computeNextWakeTime(now time.Time) time.Time { s.mu.RLock() registered := s.regState == regRegistered subscriptionEligible := s.subscriptionEligibleLocked() @@ -133,26 +135,35 @@ func (s *Service) handleIMSKeepaliveTick() { if !s.IsRegistered() { return } - s.recordIMSKeepaliveResult(s.sendIMSKeepalive(), time.Now()) + _, _ = s.sendPing() +} + +func (s *Service) sendPing() (bool, error) { + if !s.pingSending.CompareAndSwap(false, true) { + return false, nil + } + defer s.pingSending.Store(false) + err := s.sendIMSKeepalive() + s.recordIMSKeepaliveResult(err, time.Now()) + return true, err } func (s *Service) recordIMSKeepaliveResult(err error, completedAt time.Time) { s.mu.Lock() s.lastPingAt = completedAt - if err == nil { - s.keepaliveFailures = 0 - } else { - s.keepaliveFailures++ - } - failures := s.keepaliveFailures limit := s.keepaliveFailureLimit - s.mu.Unlock() if err == nil { + s.pingFailCount.Store(0) + s.lastPingOK.Store(true) + s.mu.Unlock() s.keepaliveSuccessOnce.Do(func() { logging.Info("IMS SIP keepalive established", "device", s.DeviceID()) }) return } + s.lastPingOK.Store(false) + failures := int(s.pingFailCount.Add(1)) + s.mu.Unlock() logging.WarnRate("ims-keepalive", "IMS SIP keepalive failed", "device", s.DeviceID(), "attempt", failures, "err", err) if failures >= limit { @@ -169,7 +180,6 @@ func (s *Service) requestRuntimeReconnect(keepaliveErr error) { s.regState = regFailed s.registrationRefreshAt = time.Time{} s.subscriptionRefreshAt = time.Time{} - s.keepaliveFailures = 0 s.mu.Unlock() s.transitionRegStatus(registrationRejectedTemporary) s.notifySMSReadiness() @@ -177,6 +187,7 @@ func (s *Service) requestRuntimeReconnect(keepaliveErr error) { s.keepaliveFailureLimit, keepaliveErr) logging.WarnRate("ims-fast-reconnect", "IMS SIP keepalive requested runtime rebuild", "device", s.DeviceID(), "err", err) + s.triggerRegisterReconnect() s.reportRegistrationRuntimeError(err) } @@ -195,6 +206,20 @@ func (s *Service) refreshRegistrationSubscription() { } } +func logRegisterRetryAttemptFailure(device, phase string, err error) { + if err == nil { + return + } + if errors.Is(err, enginesim.ErrAPDUBusy) { + logging.Info("IMS REGISTER retry deferred because SIM is busy", + "device", device, "phase", strings.TrimSpace(phase), "err", err) + return + } + logging.WarnRate("ims-register-retry-"+device, 30*time.Second, + "IMS REGISTER retry failed", + "device", device, "phase", strings.TrimSpace(phase), "err", err) +} + func registrationRefreshDelay(expires time.Duration) time.Duration { if expires > imsRegistrationRefreshAdvance { return expires - imsRegistrationRefreshAdvance @@ -223,7 +248,6 @@ func (s *Service) sendIMSKeepalive() error { if response.StatusCode < 200 || response.StatusCode >= 300 { return fmt.Errorf("OPTIONS rejected with status %d (%s)", response.StatusCode, response.Reason) } - s.UpdateLastPingAt(time.Now()) return nil } diff --git a/third_party/vowifi-go/internal/vowifi/imscore/keepalive_test.go b/third_party/vowifi-go/internal/vowifi/imscore/keepalive_test.go index 1985bc65..7cae4565 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/keepalive_test.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/keepalive_test.go @@ -139,7 +139,7 @@ func TestIMSMaintenanceChoosesEarliestRegistrationOrKeepaliveDeadline(t *testing service.keepaliveInterval = time.Minute service.mu.Unlock() - if got, want := service.computeNextIMSWakeTime(now), now.Add(5*time.Second); !got.Equal(want) { + if got, want := service.computeNextWakeTime(now), now.Add(5*time.Second); !got.Equal(want) { t.Fatalf("next poll wake = %s, want %s", got, want) } if got := service.nextIMSMaintenanceAction(now.Add(15 * time.Second)); got != imsMaintenanceKeepalive { @@ -170,8 +170,9 @@ func TestInboundSIPTrafficDefersKeepaliveAndResetsFailures(t *testing.T) { service := newProtectedKeepaliveTestService(t) service.mu.Lock() service.lastPingAt = time.Now().Add(-time.Minute) - service.keepaliveFailures = 2 service.mu.Unlock() + service.pingFailCount.Store(2) + service.lastPingOK.Store(false) raw := "SIP/2.0 200 OK\r\nCall-ID: traffic\r\nCSeq: 9 OPTIONS\r\nContent-Length: 0\r\n\r\n" before := time.Now() @@ -180,13 +181,12 @@ func TestInboundSIPTrafficDefersKeepaliveAndResetsFailures(t *testing.T) { } service.mu.RLock() lastTrafficAt := service.lastPingAt - failures := service.keepaliveFailures service.mu.RUnlock() if lastTrafficAt.Before(before) { t.Fatalf("last traffic = %s, want at or after %s", lastTrafficAt, before) } - if failures != 0 { - t.Fatalf("keepalive failures = %d, want 0", failures) + if status := service.Status(); status.PingFailCount != 0 || !status.LastPingOK { + t.Fatalf("ping status = count %d ok %v, want count 0 and ok", status.PingFailCount, status.LastPingOK) } } diff --git a/third_party/vowifi-go/internal/vowifi/imscore/maintenance_stats_test.go b/third_party/vowifi-go/internal/vowifi/imscore/maintenance_stats_test.go new file mode 100644 index 00000000..82a32c23 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/imscore/maintenance_stats_test.go @@ -0,0 +1,268 @@ +package imscore + +import ( + "bufio" + "context" + "errors" + "io" + "net" + "strings" + "testing" + "time" +) + +func TestInboundCountingPacketConnProjectsSocketStats(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + reader, writer := packetConnPair(t) + counted := &inboundCountingPacketConn{conn: reader, service: service} + payload := []byte("SIP/2.0 200 OK\r\nContent-Length: 0\r\n\r\n") + go func() { _, _ = writer.WriteTo(payload, reader.LocalAddr()) }() + + buffer := make([]byte, 256) + n, _, err := counted.ReadFrom(buffer) + if err != nil { + t.Fatal(err) + } + stats := service.captureInboundStats() + if stats.UDPSocketReads != 1 || stats.UDPSocketBytes != uint64(n) { + t.Fatalf("UDP stats = reads %d bytes %d, want 1/%d", stats.UDPSocketReads, stats.UDPSocketBytes, n) + } +} + +func TestInboundCountingConnRecordsTrafficBeforeSIPParsing(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + service.pingFailCount.Store(2) + service.lastPingOK.Store(false) + client, server := net.Pipe() + counted := service.newInboundCountingConn(client) + payload := []byte("partial") + go func() { _, _ = server.Write(payload) }() + + buffer := make([]byte, len(payload)) + if _, err := io.ReadFull(counted, buffer); err != nil { + t.Fatal(err) + } + stats := service.captureInboundStats() + if stats.TCPSocketReads != 1 || stats.TCPSocketBytes != uint64(len(payload)) { + t.Fatalf("TCP stats = reads %d bytes %d", stats.TCPSocketReads, stats.TCPSocketBytes) + } + status := service.Status() + if status.PingFailCount != 0 || !status.LastPingOK { + t.Fatalf("ping status = count %d ok %v", status.PingFailCount, status.LastPingOK) + } +} + +func TestDispatchInboundSIPProjectsParsedMessageStats(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + response := "SIP/2.0 200 OK\r\nCall-ID: response\r\nCSeq: 1 OPTIONS\r\nContent-Length: 0\r\n\r\n" + if err := service.dispatchInboundSIP(response, nil); err != nil { + t.Fatal(err) + } + request := "OPTIONS sip:user@example.test SIP/2.0\r\nVia: SIP/2.0/UDP host;branch=z9hG4bK-a\r\nFrom: ;tag=a\r\nTo: \r\nCall-ID: request\r\nCSeq: 1 OPTIONS\r\nContent-Length: 0\r\n\r\n" + if err := service.dispatchInboundSIP(request, func(string) error { return nil }); err != nil { + t.Fatal(err) + } + stats := service.captureInboundStats() + if stats.SIPParsedMessages != 2 || stats.SIPParsedRequests != 1 || stats.SIPParsedResponses != 1 { + t.Fatalf("parsed stats = %+v", stats) + } + if got := service.Status().Diagnostics["inbound_sip_parsed_messages"]; got != uint64(2) { + t.Fatalf("status parsed messages = %#v, want 2", got) + } +} + +func TestSendPingAllowsOnlyOneInFlightTransaction(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + client, server := net.Pipe() + service.activateProtectedRegistrationTCP(client) + received := make(chan string, 1) + release := make(chan struct{}) + go holdKeepaliveResponse(server, received, release) + + firstDone := make(chan error, 1) + go func() { + _, err := service.sendPing() + firstDone <- err + }() + select { + case <-received: + case <-time.After(time.Second): + t.Fatal("first ping was not sent") + } + if sent, err := service.sendPing(); sent || err != nil { + t.Fatalf("second ping = sent %v err %v, want skipped", sent, err) + } + close(release) + if err := <-firstDone; err != nil { + t.Fatal(err) + } + if reads := service.captureInboundStats().TCPSocketReads; reads == 0 { + t.Fatal("protected registration TCP response bypassed the production counting wrapper") + } +} + +func holdKeepaliveResponse(conn net.Conn, received chan<- string, release <-chan struct{}) { + request, err := readSIPStreamMessage(bufio.NewReader(conn)) + if err != nil { + return + } + received <- request + <-release + _, _ = io.WriteString(conn, registerWireResponse(request, 200, "")) +} + +func TestInboundStatsLoggerStopsWithReceiverLifecycle(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + service.startInboundStatsLogger(context.Background(), inboundStatsLoggerOptions{Interval: time.Millisecond}) + service.inboundStatsMu.Lock() + done := service.inboundStatsDone + service.inboundStatsMu.Unlock() + service.stopInboundStatsLogger() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("inbound stats logger did not stop") + } +} + +func TestServiceStopCancelsInboundStatsLogger(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + service.startInboundStatsLogger(context.Background(), inboundStatsLoggerOptions{Interval: time.Hour}) + service.inboundStatsMu.Lock() + done := service.inboundStatsDone + service.inboundStatsMu.Unlock() + service.Stop() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Service.Stop did not join the inbound stats logger") + } +} + +func TestRegistrationPacketReadFailureMarksSignalingDead(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + packet, peer := packetConnPair(t) + service.mu.Lock() + service.signalingReady = true + service.registrationIO = packet + service.registrationRefreshAt = time.Now().Add(time.Hour) + service.mu.Unlock() + service.handleRegistrationPacketReadError(packet, errors.New("read failed")) + status := service.Status() + if status.SignalingReady || status.RegState != regFailed { + t.Fatalf("status after packet read failure = ready %v state %s", status.SignalingReady, status.RegState) + } + if status.SignalingFailureReason == "" { + t.Fatal("packet read failure reason was not projected") + } + _ = peer +} + +func TestStaleRegistrationPacketReadFailureCannotDetachReplacement(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + stale, _ := packetConnPair(t) + current, _ := packetConnPair(t) + service.mu.Lock() + service.registrationIO = current + service.signalingReady = true + service.mu.Unlock() + service.handleRegistrationPacketReadError(stale, errors.New("stale socket closed")) + service.mu.RLock() + got := service.registrationIO + ready := service.signalingReady + service.mu.RUnlock() + if got != current || !ready { + t.Fatalf("stale read detached current packet: current=%v ready=%v", got == current, ready) + } +} + +func TestMORPErrorCause30SchedulesRateLimitedRegistration(t *testing.T) { + service := newProtectedKeepaliveTestService(t) + service.mu.Lock() + service.registrationRefreshAt = time.Now().Add(time.Hour) + service.mu.Unlock() + + service.handleMORPError(30, "SM absent") + service.mu.RLock() + firstDeadline := service.registrationRefreshAt + service.mu.RUnlock() + if firstDeadline.After(time.Now()) || !service.reRegisterPending.Load() { + t.Fatalf("cause 30 deadline = %s pending = %v", firstDeadline, service.reRegisterPending.Load()) + } + if action := service.nextIMSMaintenanceAction(time.Now()); action != imsMaintenanceRefresh { + t.Fatalf("maintenance action = %d, want refresh", action) + } + + service.mu.Lock() + service.registrationRefreshAt = time.Now().Add(time.Hour) + service.mu.Unlock() + service.handleMORPError(30, "duplicate") + service.mu.RLock() + secondDeadline := service.registrationRefreshAt + service.mu.RUnlock() + if !secondDeadline.After(time.Now().Add(59 * time.Minute)) { + t.Fatalf("rate-limited cause 30 changed deadline to %s", secondDeadline) + } + if got := service.moRPErrorCause30.Load(); got != 2 { + t.Fatalf("cause 30 count = %d, want 2", got) + } +} + +func TestMORPErrorCause30WakesProductionRegistrationLoop(t *testing.T) { + registrar, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)}) + if err != nil { + t.Fatal(err) + } + defer registrar.Close() + seen := make(chan string, 2) + go serveMaintenanceRegistrationSequence(registrar, seen, 2) + service, err := New(registerTransportTestConfig("udp", registrar.LocalAddr().String())) + if err != nil { + t.Fatal(err) + } + defer service.Stop() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + if err := service.Register(ctx); err != nil { + t.Fatal(err) + } + <-seen + service.handleMORPError(30, "SM absent") + select { + case request := <-seen: + if !strings.HasPrefix(request, "REGISTER ") { + t.Fatalf("maintenance request = %q", request) + } + case <-time.After(time.Second): + t.Fatal("cause 30 did not wake the production REGISTER loop") + } +} + +func serveMaintenanceRegistrationSequence(conn *net.UDPConn, seen chan<- string, count int) { + buffer := make([]byte, 64*1024) + for attempt := 0; attempt < count; attempt++ { + n, remote, err := conn.ReadFromUDP(buffer) + if err != nil { + return + } + request := string(buffer[:n]) + seen <- request + response := registerWireResponse(request, 200, "Expires: 3600\r\n") + _, _ = conn.WriteToUDP([]byte(response), remote) + } +} + +func packetConnPair(t *testing.T) (net.PacketConn, net.PacketConn) { + t.Helper() + reader, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + writer, err := net.ListenPacket("udp", "127.0.0.1:0") + if err != nil { + reader.Close() + t.Fatal(err) + } + t.Cleanup(func() { reader.Close(); writer.Close() }) + return reader, writer +} diff --git a/third_party/vowifi-go/internal/vowifi/imscore/network.go b/third_party/vowifi-go/internal/vowifi/imscore/network.go index 9d1b8878..b0f657a8 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/network.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/network.go @@ -241,7 +241,19 @@ func (c *sipFramingConn) LocalAddr() net.Addr { // inboundCountingConn counts inbound bytes/conns. type inboundCountingConn struct { - conn net.Conn + conn net.Conn + service *Service + onRead func() +} + +func (s *Service) newInboundCountingConn(conn net.Conn) net.Conn { + if conn == nil { + return nil + } + if _, counted := conn.(*inboundCountingConn); counted { + return conn + } + return &inboundCountingConn{conn: conn, service: s, onRead: s.handleTCPTraffic} } // Read reads and counts. @@ -250,6 +262,13 @@ func (c *inboundCountingConn) Read(b []byte) (int, error) { return 0, errors.New("imscore: nil conn") } n, err := c.conn.Read(b) + if n > 0 && c.service != nil { + c.service.inboundTCPSocketRead.Add(1) + c.service.inboundTCPSocketBytes.Add(uint64(n)) + if c.onRead != nil { + c.onRead() + } + } return n, err } @@ -287,7 +306,8 @@ func (c *inboundCountingConn) RemoteAddr() net.Addr { // inboundCountingPacketConn counts inbound packets. type inboundCountingPacketConn struct { - conn net.PacketConn + conn net.PacketConn + service *Service } // ReadFrom reads a packet. @@ -295,7 +315,12 @@ func (c *inboundCountingPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { if c == nil || c.conn == nil { return 0, nil, errors.New("imscore: nil packet conn") } - return c.conn.ReadFrom(b) + n, address, err := c.conn.ReadFrom(b) + if n > 0 && c.service != nil { + c.service.inboundUDPSocketRead.Add(1) + c.service.inboundUDPSocketBytes.Add(uint64(n)) + } + return n, address, err } // WriteTo writes a packet. diff --git a/third_party/vowifi-go/internal/vowifi/imscore/register.go b/third_party/vowifi-go/internal/vowifi/imscore/register.go index c4878dba..441cdc18 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/register.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/register.go @@ -830,6 +830,7 @@ func (s *Service) refreshRegistration() { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := s.Register(ctx); err != nil { + logRegisterRetryAttemptFailure(s.DeviceID(), "periodic", err) s.reportRegistrationRuntimeError(fmt.Errorf("imscore: registration refresh failed: %w", err)) } } diff --git a/third_party/vowifi-go/internal/vowifi/imscore/register_initial_transport.go b/third_party/vowifi-go/internal/vowifi/imscore/register_initial_transport.go index c4e8b67f..66372d86 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/register_initial_transport.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/register_initial_transport.go @@ -87,6 +87,13 @@ func (s *Service) activateInitialRegistrationTransport( opened *initialRegistrationTransport, serverListener, clientReservation net.Listener, ) { + if opened.packet != nil { + opened.packet = &inboundCountingPacketConn{conn: opened.packet, service: s} + } + if opened.stream != nil { + configureTCPKeepalive(opened.stream) + opened.stream = s.newInboundCountingConn(opened.stream) + } s.cfg.LocalPort = opened.port s.mu.Lock() s.registrationIO = opened.packet diff --git a/third_party/vowifi-go/internal/vowifi/imscore/register_transport.go b/third_party/vowifi-go/internal/vowifi/imscore/register_transport.go index a364580a..290524d9 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/register_transport.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/register_transport.go @@ -166,6 +166,7 @@ func (s *Service) protectedTransportState() (external, connected bool) { func (s *Service) activateProtectedRegistrationTCP(conn net.Conn) { configureTCPKeepalive(conn) + conn = s.newInboundCountingConn(conn) s.mu.Lock() previous := s.registrationTCP s.registrationTCP = conn @@ -200,6 +201,7 @@ func (s *Service) readRegistrationResponses(conn net.PacketConn) { for { n, remote, err := conn.ReadFrom(buffer) if err != nil { + s.handleRegistrationPacketReadError(conn, err) return } err = s.dispatchInboundSIP(string(buffer[:n]), func(response string) error { @@ -214,6 +216,17 @@ func (s *Service) readRegistrationResponses(conn net.PacketConn) { } } +func (s *Service) handleRegistrationPacketReadError(conn net.PacketConn, readErr error) { + if s.stopped() { + return + } + err := fmt.Errorf("imscore: registration SIP packet socket closed: %w", readErr) + if !s.markRegistrationPacketSignalingDead(conn, err) { + return + } + logging.WarnRate("ims-registration-packet", "IMS registration SIP packet socket closed", "err", err) +} + func (s *Service) acceptProtectedSIP(listener net.Listener) { defer s.networkDone.Done() s.receiverStarted() @@ -223,11 +236,13 @@ func (s *Service) acceptProtectedSIP(listener net.Listener) { if err != nil { return } + s.inboundTCPAccept.Add(1) + configureTCPKeepalive(conn) + conn = s.newInboundCountingConn(conn) if !s.trackProtectedConnection(conn) { _ = conn.Close() return } - configureTCPKeepalive(conn) s.networkDone.Add(1) go s.serveProtectedSIPConnection(conn) } diff --git a/third_party/vowifi-go/internal/vowifi/imscore/service.go b/third_party/vowifi-go/internal/vowifi/imscore/service.go index c7ac575c..9ecf50e4 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/service.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/service.go @@ -103,17 +103,23 @@ func (s *Service) RegState() string { // Status returns a status snapshot. func (s *Service) Status() *ServiceStatus { + status := s.captureStatusSnapshot() + return &status +} + +func (s *Service) captureStatusSnapshot() ServiceStatus { if s == nil || s.cfg == nil { - return &ServiceStatus{} + return ServiceStatus{} } lastSMSTrace, lastSMSAt, lastSMSErr := s.smsSendStatus() + inboundStats := s.captureInboundStats() s.receiverMu.Lock() rxRunning := s.activeReceivers > 0 s.receiverMu.Unlock() s.mu.RLock() defer s.mu.RUnlock() identities := s.cfg.publicIdentities() - status := &ServiceStatus{ + status := ServiceStatus{ Enabled: s.cfg.Enabled, DeviceID: s.cfg.DeviceID, Registered: s.regState == regRegistered || s.regStatus.Load() == registrationRegistered, RegStatus: registrationStatusText(s.regStatus.Load()), @@ -134,14 +140,17 @@ func (s *Service) Status() *ServiceStatus { SignalingFailureReason: s.signalingFailureReason, RegFailCount: int(s.regFailCount.Load()), ReRegisterPending: s.reRegisterPending.Load() || s.notifyReconnectPending.Load(), - LastPingAt: s.lastPingAt, ServiceRoute: currentServiceRoute(s.regSession), - Path: s.path, SecurityVerify: s.securityVerify, AssociatedMSISDN: s.assocMSISDN, + PingFailCount: int(s.pingFailCount.Load()), + LastPingAt: s.lastPingAt, LastPingOK: s.lastPingOK.Load(), + ServiceRoute: currentServiceRoute(s.regSession), + Path: s.path, SecurityVerify: s.securityVerify, AssociatedMSISDN: s.assocMSISDN, LastError: s.lastError, LastRegisterTraceID: s.lastRegisterTraceID, LastRegisterAttemptAt: s.lastRegisterAttemptAt, LastRegisterOKAt: s.lastRegisterOKAt, LastRegisterErr: s.lastRegisterErr, LastSMSSendTraceID: lastSMSTrace, LastSMSSendAt: lastSMSAt, LastSMSSendErr: lastSMSErr, FragmentAudit: s.fragmentAuditSnapshot(), - State: s.state, RegState: s.regState, IMPUs: identities, + Diagnostics: inboundStats.diagnostics(), + State: s.state, RegState: s.regState, IMPUs: identities, } ready, reason := s.evaluateSignalingReadyLocked(status.Registered) status.SignalingReady = status.SignalingReady && ready @@ -360,6 +369,7 @@ func (s *Service) Stop() { s.transitionRegStatus(registrationStopping) close(s.stop) } + s.stopInboundStatsLogger() s.clearPendingSMS() s.mu.Lock() registrationIO := s.registrationIO diff --git a/third_party/vowifi-go/internal/vowifi/imscore/service_methods.go b/third_party/vowifi-go/internal/vowifi/imscore/service_methods.go index 8deb13b6..c73a80a3 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/service_methods.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/service_methods.go @@ -248,6 +248,11 @@ func (s *Service) UpdateLastPingAt(t time.Time) { if s.lastPingAt.IsZero() || t.After(s.lastPingAt) { s.lastPingAt = t } - s.keepaliveFailures = 0 + s.pingFailCount.Store(0) + s.lastPingOK.Store(true) s.mu.Unlock() } + +func (s *Service) handleTCPTraffic() { + s.UpdateLastPingAt(time.Now()) +} diff --git a/third_party/vowifi-go/internal/vowifi/imscore/service_trigger.go b/third_party/vowifi-go/internal/vowifi/imscore/service_trigger.go new file mode 100644 index 00000000..faf6bf5e --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/imscore/service_trigger.go @@ -0,0 +1,28 @@ +package imscore + +import ( + "strings" + "time" + + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" +) + +func (s *Service) triggerRegisterImmediate(reason string) { + if s == nil || s.stopped() { + return + } + now := time.Now() + s.mu.Lock() + if s.regState != regRegistered { + s.mu.Unlock() + return + } + s.registrationRefreshAt = now + s.nextRegister = now + s.mu.Unlock() + s.reRegisterPending.Store(true) + logging.WarnRate("ims-register-immediate-"+s.DeviceID(), 30*time.Second, + "IMS immediate re-registration scheduled", + "device", s.DeviceID(), "reason", strings.TrimSpace(reason)) + s.signalIMSMaintenance() +} diff --git a/third_party/vowifi-go/internal/vowifi/imscore/signaling_failure.go b/third_party/vowifi-go/internal/vowifi/imscore/signaling_failure.go index 5f2c42dd..91a356f5 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/signaling_failure.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/signaling_failure.go @@ -5,6 +5,7 @@ import ( "fmt" "net" "strings" + "time" ) func (s *Service) handleFatalTransactionError(err error) { @@ -22,10 +23,26 @@ func (s *Service) markSignalingDead(err error) { if s == nil || err == nil { return } - packet, stream, marked := s.detachDeadSignaling(err) + packet, stream, marked := s.detachDeadSignaling(err, nil) if !marked { return } + s.finishSignalingFailure(packet, stream, err) +} + +func (s *Service) markRegistrationPacketSignalingDead(expected net.PacketConn, err error) bool { + if s == nil || expected == nil || err == nil { + return false + } + packet, stream, marked := s.detachDeadSignaling(err, expected) + if !marked { + return false + } + s.finishSignalingFailure(packet, stream, err) + return true +} + +func (s *Service) finishSignalingFailure(packet net.PacketConn, stream net.Conn, err error) { closeDeadSignaling(packet, stream) s.transport.terminateClientTransactions(transactionTransportError(err)) s.transitionRegStatus(registrationRejectedTemporary) @@ -33,9 +50,12 @@ func (s *Service) markSignalingDead(err error) { s.reportRegistrationRuntimeError(err) } -func (s *Service) detachDeadSignaling(err error) (net.PacketConn, net.Conn, bool) { +func (s *Service) detachDeadSignaling(err error, expectedPacket net.PacketConn) (net.PacketConn, net.Conn, bool) { s.mu.Lock() defer s.mu.Unlock() + if expectedPacket != nil && s.registrationIO != expectedPacket { + return nil, nil, false + } if !s.signalingReady && strings.TrimSpace(s.signalingFailureReason) != "" { return nil, nil, false } @@ -45,10 +65,14 @@ func (s *Service) detachDeadSignaling(err error) (net.PacketConn, net.Conn, bool s.registrationTCP = nil s.registrationTCPProtected = false s.registrationTransport = "" + s.registrationRefreshAt = time.Time{} + s.subscriptionRefreshAt = time.Time{} + s.nextRegister = time.Time{} s.signalingGeneration++ s.signalingReady = false s.signalingFailureReason = err.Error() s.regState = regFailed + s.lastPingOK.Store(false) s.transport.SetSendFn(func(string) error { return errors.New("imscore: registered SIP transport is not connected") }) diff --git a/third_party/vowifi-go/internal/vowifi/imscore/sms_delivery_report.go b/third_party/vowifi-go/internal/vowifi/imscore/sms_delivery_report.go index 7dcaebe4..8d632931 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/sms_delivery_report.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/sms_delivery_report.go @@ -9,6 +9,7 @@ import ( "github.com/iniwex5/vowifi-go/internal/smscodec" "github.com/iniwex5/vowifi-go/internal/vowifi/events" + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" "github.com/warthog618/sms/encoding/tpdu" ) @@ -84,7 +85,7 @@ func parseTPStatusReport(payload []byte) (smsDeliveryReport, error) { } func (s *Service) recordSMSDeliveryReport(raw string, report smsDeliveryReport) error { - s.recordMORPErrorCause(report.rpCause) + s.handleMORPError(report.rpCause, report.errorText) inReplyTo := rawSIPHeaderValue(raw, "In-Reply-To") callID := rawSIPHeaderValue(raw, "Call-ID") if s.delivery == nil { @@ -118,14 +119,42 @@ func (s *Service) recordSMSDeliveryReport(raw string, report smsDeliveryReport) return nil } -func (s *Service) recordMORPErrorCause(cause int) { +func (s *Service) handleMORPError(cause int, reason string) { switch cause { case 28: s.moRPErrorCause28.Add(1) + logging.WarnRate("sms-mo-rp-cause-28-"+s.DeviceID(), 30*time.Second, + "IMS MO SMS RP-ERROR", "device", s.DeviceID(), "cause", cause, "reason", reason) case 30: s.moRPErrorCause30.Add(1) + s.handleMORPErrorCause30(reason, time.Now()) case 38: s.moRPErrorCause38.Add(1) + logging.WarnRate("sms-mo-rp-cause-38-"+s.DeviceID(), 30*time.Second, + "IMS MO SMS RP-ERROR", "device", s.DeviceID(), "cause", cause, "reason", reason) + } +} + +func (s *Service) handleMORPErrorCause30(reason string, now time.Time) { + if !s.claimMORPErrorCause30(now) { + return + } + logging.WarnRate("sms-mo-rp-cause-30-"+s.DeviceID(), 30*time.Second, + "IMS MO SMS RP-ERROR requires re-registration", + "device", s.DeviceID(), "cause", 30, "reason", reason) + s.triggerRegisterImmediate("RP-ERROR cause=30") +} + +func (s *Service) claimMORPErrorCause30(now time.Time) bool { + const cooldown = 30 * time.Second + for { + previous := s.lastMORPErrorCause30At.Load() + if previous > 0 && now.Sub(time.Unix(0, previous)) < cooldown { + return false + } + if s.lastMORPErrorCause30At.CompareAndSwap(previous, now.UnixNano()) { + return true + } } } diff --git a/third_party/vowifi-go/internal/vowifi/imscore/sms_runtime.go b/third_party/vowifi-go/internal/vowifi/imscore/sms_runtime.go index 14a1ee72..8de4fcc3 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/sms_runtime.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/sms_runtime.go @@ -121,6 +121,7 @@ type observability struct { moRPErrorCause28 atomic.Int64 moRPErrorCause30 atomic.Int64 moRPErrorCause38 atomic.Int64 + lastMORPErrorCause30At atomic.Int64 outboundQueueReject atomic.Int64 bypassSuppressedSMS atomic.Int64 inboundUDPSocketRead atomic.Uint64 diff --git a/third_party/vowifi-go/internal/vowifi/imscore/subscribe_reg.go b/third_party/vowifi-go/internal/vowifi/imscore/subscribe_reg.go index 0797a020..75f112c6 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/subscribe_reg.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/subscribe_reg.go @@ -56,9 +56,14 @@ func (s *Service) stopped() bool { } func (s *Service) reportRegistrationRuntimeError(err error) { + if err == nil || s == nil || s.stopped() { + return + } select { case s.registerErrors <- err: default: + logging.WarnRate("ims-runtime-error-overflow-"+s.DeviceID(), time.Minute, + "IMS runtime error channel is full", "device", s.DeviceID(), "err", err) } } 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 ab3eb03b..dff76e3f 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go @@ -28,8 +28,14 @@ func (s *Service) receiverStarted() { s.receiverMu.Lock() s.activeReceivers++ active := s.activeReceivers > 0 + startStats := s.activeReceivers == 1 s.receiverMu.Unlock() s.setSMSReceiverReady(active) + if startStats { + s.startInboundStatsLogger(context.Background(), inboundStatsLoggerOptions{ + Interval: defaultInboundStatsInterval, + }) + } } func (s *Service) receiverStopped() { @@ -132,11 +138,14 @@ func (s *Service) dispatchInboundSIP(raw string, reply func(string) error) error func (s *Service) dispatchInboundSIPMessage(message sip.Message, raw string, reply func(string) error) error { s.UpdateLastPingAt(time.Now()) + s.inboundSIPParsedMessage.Add(1) switch parsed := message.(type) { case *sip.Response: + s.inboundSIPParsedResp.Add(1) s.transport.DeliverResponse(newSIPResponse(parsed)) return nil case *sip.Request: + s.inboundSIPParsedRequest.Add(1) return s.dispatchInboundSIPRequest(parsed, raw, reply) default: return errors.New("imscore: unsupported inbound SIP message") diff --git a/third_party/vowifi-go/internal/vowifi/imscore/types.go b/third_party/vowifi-go/internal/vowifi/imscore/types.go index 60f1361e..25325071 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/types.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/types.go @@ -185,6 +185,9 @@ type Service struct { sipWriteMu sync.Mutex receiverMu sync.Mutex activeReceivers int + inboundStatsMu sync.Mutex + inboundStatsCancel context.CancelFunc + inboundStatsDone chan struct{} networkDone sync.WaitGroup registerErrors chan error keepaliveOnce sync.Once @@ -201,7 +204,6 @@ type Service struct { keepaliveInterval time.Duration keepaliveTimeout time.Duration keepaliveFailureLimit int - keepaliveFailures int // Dialogs. dialogRegistry *dialogRegistry