diff --git a/third_party/vowifi-go/engine/swu/rekey.go b/third_party/vowifi-go/engine/swu/rekey.go index 745f74ae..360cc85a 100644 --- a/third_party/vowifi-go/engine/swu/rekey.go +++ b/third_party/vowifi-go/engine/swu/rekey.go @@ -413,9 +413,10 @@ func (s *Session) failEstablishedControl(err error) { if err == nil || errors.Is(err, context.Canceled) { return } + s.cancel() s.stopTimers() s.setTerminalError(err) - s.cancel() + s.signalDone() } // ensureIKEDispatcher ensures the IKE dispatcher is running. diff --git a/third_party/vowifi-go/engine/swu/session.go b/third_party/vowifi-go/engine/swu/session.go index 66b86c0c..bb87f6cd 100644 --- a/third_party/vowifi-go/engine/swu/session.go +++ b/third_party/vowifi-go/engine/swu/session.go @@ -184,9 +184,10 @@ type Session struct { remotePort uint16 // --- lifecycle --- - ctx context.Context - cancel context.CancelFunc - done chan struct{} + ctx context.Context + cancel context.CancelFunc + done chan struct{} + doneOnce sync.Once mu sync.RWMutex childSAMu sync.RWMutex @@ -209,6 +210,7 @@ type Session struct { nextOutboundID uint32 // --- timers --- + timersMu sync.Mutex ikeReauthTimer *time.Timer ikeRekeyTimer *time.Timer childRekeyTimer *time.Timer @@ -277,13 +279,17 @@ func (s *Session) setTerminalError(err error) { s.setState(stateError) } -// terminalError returns the recorded terminal error, if any. -func (s *Session) terminalError() error { +// TerminalError returns the error that ended an established session, if any. +func (s *Session) TerminalError() error { s.mu.RLock() defer s.mu.RUnlock() return s.terminalErr } +func (s *Session) signalDone() { + s.doneOnce.Do(func() { close(s.done) }) +} + // Connect establishes the SWu tunnel: IKE_SA_INIT → IKE_AUTH (EAP-AKA) → // CREATE_CHILD_SA. It retries on redirect (RFC 5685) and returns once the data // plane is up or the session fails terminally. @@ -506,17 +512,13 @@ func (s *Session) Shutdown() { s.state = stateShutdown s.mu.Unlock() - s.stopTimers() s.cancel() + s.stopTimers() s.controlWG.Wait() s.dataPlaneWG.Wait() s.stopDataPlane() s.stopTransport() - select { - case <-s.done: - default: - close(s.done) - } + s.signalDone() } // WaitDone blocks until the session is shut down. @@ -628,11 +630,28 @@ func (s *Session) startTimers() { // stopTimers stops all timers. func (s *Session) stopTimers() { - for _, t := range []*time.Timer{s.ikeReauthTimer, s.ikeRekeyTimer, s.childRekeyTimer, s.natKeepalive, s.dpdTimer} { + s.timersMu.Lock() + defer s.timersMu.Unlock() + timers := []*time.Timer{s.ikeReauthTimer, s.ikeRekeyTimer, s.childRekeyTimer, s.natKeepalive, s.dpdTimer} + for _, t := range timers { if t != nil { t.Stop() } } + s.ikeReauthTimer = nil + s.ikeRekeyTimer = nil + s.childRekeyTimer = nil + s.natKeepalive = nil + s.dpdTimer = nil +} + +func (s *Session) armTimer(target **time.Timer, delay time.Duration, callback func()) { + s.timersMu.Lock() + defer s.timersMu.Unlock() + if s.ctx.Err() != nil { + return + } + *target = time.AfterFunc(delay, callback) } // startIKEReauthTimer arms the periodic re-authentication timer. @@ -641,7 +660,7 @@ func (s *Session) startIKEReauthTimer() { if every <= 0 { every = 24 * time.Hour } - s.ikeReauthTimer = time.AfterFunc(every, func() { + s.armTimer(&s.ikeReauthTimer, every, func() { if err := s.Reauthenticate(); err != nil { s.failEstablishedControl(fmt.Errorf("swu: IKE reauthentication failed: %w", err)) return @@ -656,7 +675,7 @@ func (s *Session) startIKESARekeyTimer() { if every <= 0 { every = 8 * time.Hour } - s.ikeRekeyTimer = time.AfterFunc(every, func() { + s.armTimer(&s.ikeRekeyTimer, every, func() { if err := s.RekeyIKESA(); err != nil { s.failEstablishedControl(fmt.Errorf("swu: IKE SA rekey failed: %w", err)) return @@ -671,7 +690,7 @@ func (s *Session) startChildSARekeyTimer() { if every <= 0 { every = 1 * time.Hour } - s.childRekeyTimer = time.AfterFunc(every, func() { + s.armTimer(&s.childRekeyTimer, every, func() { if err := s.RekeyChildSA(); err != nil { s.failEstablishedControl(fmt.Errorf("swu: CHILD_SA rekey failed: %w", err)) return @@ -686,7 +705,7 @@ func (s *Session) startNATKeepalive() { if every <= 0 { every = 20 * time.Second } - s.natKeepalive = time.AfterFunc(every, func() { + s.armTimer(&s.natKeepalive, every, func() { s.sendNATKeepalive() s.startNATKeepalive() }) @@ -709,7 +728,7 @@ func (s *Session) startDPD() { if every <= 0 { every = 30 * time.Second } - s.dpdTimer = time.AfterFunc(every, func() { + s.armTimer(&s.dpdTimer, every, func() { if err := s.DPDProbe(); err != nil { s.failEstablishedControl(fmt.Errorf("swu: DPD failed: %w", err)) return diff --git a/third_party/vowifi-go/engine/swu/session_test.go b/third_party/vowifi-go/engine/swu/session_test.go index c21991fb..46a39a44 100644 --- a/third_party/vowifi-go/engine/swu/session_test.go +++ b/third_party/vowifi-go/engine/swu/session_test.go @@ -193,7 +193,7 @@ func TestSessionStateTransitions(t *testing.T) { if s.State() != stateError { t.Errorf("state = %q", s.State()) } - if s.terminalError() == nil { + if s.TerminalError() == nil { t.Error("terminal error not recorded") } s.Shutdown() @@ -204,6 +204,25 @@ func TestSessionStateTransitions(t *testing.T) { } } +func TestIKEReauthTimerSignalsFreshRuntimeRequirement(t *testing.T) { + s := NewSession(&Config{ReauthSeconds: time.Millisecond}) + s.setState(stateEstablished) + s.startIKEReauthTimer() + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := s.WaitDoneContext(ctx); err != nil { + t.Fatalf("WaitDoneContext: %v", err) + } + if s.State() != stateError { + t.Fatalf("state = %q, want error", s.State()) + } + if err := s.TerminalError(); err == nil || !strings.Contains(err.Error(), "fresh runtime session") { + t.Fatalf("terminal error = %v, want fresh runtime requirement", err) + } + s.Shutdown() +} + func TestNewSessionInitializesDefaultAlgorithms(t *testing.T) { s := NewSession(&Config{}) if s.initErr != nil { diff --git a/third_party/vowifi-go/runtimehost/start.go b/third_party/vowifi-go/runtimehost/start.go index cfb7f20e..678be8a0 100644 --- a/third_party/vowifi-go/runtimehost/start.go +++ b/third_party/vowifi-go/runtimehost/start.go @@ -131,11 +131,31 @@ func Start(ctx context.Context, req StartRequest) (*Instance, error) { if err := attachVoiceAgent(req, inst, ims); err != nil { return failIMSStart(inst, fmt.Errorf("runtimehost: attach voice agent: %w", err)) } + go monitorTunnelFailure(runCtx, inst, tunnel) go monitorRegistrationFailures(runCtx, inst, ims) go stopRuntimeOnContext(runCtx, inst) return inst, nil } +func monitorTunnelFailure(ctx context.Context, inst *Instance, tunnel Tunnel) { + waitErr := tunnel.WaitDoneContext(ctx) + if ctx.Err() != nil { + return + } + failureErr := waitErr + if source, ok := tunnel.(tunnelFailureSource); ok { + if terminalErr := source.TerminalError(); terminalErr != nil { + failureErr = terminalErr + } + } + if failureErr == nil { + failureErr = errors.New("SWu tunnel stopped unexpectedly") + } + wrapped := fmt.Errorf("runtimehost: SWu tunnel control failed: %w", failureErr) + logger.Error("SWu tunnel control failed", "device", inst.State().DeviceID, "err", wrapped) + inst.setTunnelControlFailure(wrapped) +} + func wireSMSReadiness(inst *Instance, ims IMSLifecycle) { source, ok := ims.(smsReadinessSource) if !ok { diff --git a/third_party/vowifi-go/runtimehost/start_test.go b/third_party/vowifi-go/runtimehost/start_test.go index 504893f2..f9b89b1d 100644 --- a/third_party/vowifi-go/runtimehost/start_test.go +++ b/third_party/vowifi-go/runtimehost/start_test.go @@ -53,6 +53,7 @@ type lifecycleTunnel struct { onStateChange func(string) packetIO *lifecyclePacketIO updateErr error + terminalErr error oldIP net.IP newIP net.IP } @@ -163,6 +164,20 @@ func (t *lifecycleTunnel) WaitDoneContext(ctx context.Context) error { } } +func (t *lifecycleTunnel) TerminalError() error { + t.mu.Lock() + defer t.mu.Unlock() + return t.terminalErr +} + +func (t *lifecycleTunnel) fail(err error) { + t.mu.Lock() + t.terminalErr = err + t.mu.Unlock() + t.setState("error") + t.shutdownOnce.Do(func() { close(t.done) }) +} + func (t *lifecycleTunnel) InnerNetwork() swu.InnerNetworkConfig { return swu.InnerNetworkConfig{ IPv4: net.IPv4(10, 0, 0, 2), PrefixLen: 32, DNS: []net.IP{net.IPv4(10, 0, 0, 1)}, @@ -376,6 +391,38 @@ func TestStartClearsIMSReadyWhenRegistrationRefreshFails(t *testing.T) { } } +func TestStartSurfacesEstablishedTunnelFailure(t *testing.T) { + prepared := &identity.PreparedSession{ + Profile: identity.Profile{IMSI: "310260123456789", MCC: "310", MNC: "260"}, + IMSIdentity: identity.IMSIdentity{IMPI: "310260123456789@ims.example", IMPU: "sip:310260123456789@ims.example", Domain: "ims.example"}, + EPDGAddr: "epdg.example.com", + } + tunnel := newLifecycleTunnel(nil) + inst, err := Start(context.Background(), runtimeTestRequest(prepared, tunnel)) + if err != nil { + t.Fatalf("Start: %v", err) + } + tunnel.fail(errors.New("full reauthentication requires a fresh runtime session")) + + deadline := time.After(time.Second) + for inst.State().LastError == "" { + select { + case <-deadline: + t.Fatal("runtime did not expose terminal tunnel failure") + default: + time.Sleep(time.Millisecond) + } + } + state := inst.State() + if state.SessionState != "error" || state.TunnelReady || state.IMSReady || state.SMSReady { + t.Fatalf("terminal tunnel state = %+v", state) + } + if state.LastReason != "SWu tunnel control failed" || !strings.Contains(state.LastError, "fresh runtime session") { + t.Fatalf("terminal tunnel error = %+v", state) + } + _ = inst.Stop(context.Background()) +} + func TestStartReturnsFailedInstanceWhenTunnelConnectFails(t *testing.T) { connectErr := errors.New("IKE_AUTH rejected") tunnel := newLifecycleTunnel(connectErr) diff --git a/third_party/vowifi-go/runtimehost/types.go b/third_party/vowifi-go/runtimehost/types.go index cc51ef45..7e375836 100644 --- a/third_party/vowifi-go/runtimehost/types.go +++ b/third_party/vowifi-go/runtimehost/types.go @@ -155,6 +155,10 @@ type Tunnel interface { UpdateAddresses(oldIP, newIP net.IP) error } +type tunnelFailureSource interface { + TerminalError() error +} + // IMSLifecycle is the registered IMS service owned by the runtime Instance. type IMSLifecycle interface { Service