diff --git a/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_events.go b/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_events.go index b00bfd1a..067f105c 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_events.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_events.go @@ -53,6 +53,17 @@ type imsEventBus struct { publishCounts map[string]uint64 } +type imsEventPublishReceipt struct { + matched int + enqueued int + queueFull int + subscriptions map[string]int +} + +func (r imsEventPublishReceipt) enqueuedFor(name string) bool { + return r.subscriptions[strings.TrimSpace(name)] > 0 +} + func newIMSEventBus(device string) *imsEventBus { return &imsEventBus{ device: strings.TrimSpace(device), @@ -137,13 +148,18 @@ func (b *imsEventBus) unsubscribe(id uint64) { } func (b *imsEventBus) publish(event imsendpoint.Event) (matched, enqueued, queueFull int) { + receipt := b.publishWithReceipt(event) + return receipt.matched, receipt.enqueued, receipt.queueFull +} + +func (b *imsEventBus) publishWithReceipt(event imsendpoint.Event) imsEventPublishReceipt { if b == nil { - return 0, 0, 0 + return imsEventPublishReceipt{} } b.mu.Lock() if b.closed { b.mu.Unlock() - return 0, 0, 0 + return imsEventPublishReceipt{} } b.publishCounts[imsEventCounterKey(event)]++ subscribers := make([]*imsEventSubscriber, 0, len(b.subscribers)) @@ -151,18 +167,20 @@ func (b *imsEventBus) publish(event imsendpoint.Event) (matched, enqueued, queue subscribers = append(subscribers, subscriber) } b.mu.Unlock() + receipt := imsEventPublishReceipt{subscriptions: make(map[string]int)} for _, subscriber := range subscribers { if !subscriber.matches(event) { continue } - matched++ + receipt.matched++ if subscriber.enqueue(event) { - enqueued++ + receipt.enqueued++ + receipt.subscriptions[subscriber.spec.Name]++ continue } - queueFull++ + receipt.queueFull++ } - return matched, enqueued, queueFull + return receipt } func (b *imsEventBus) close() { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_projection.go b/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_projection.go index 9ab8a56b..95791551 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_projection.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/ims_endpoint_projection.go @@ -25,14 +25,14 @@ func (s *Service) getIMSEventBus() *imsEventBus { return s.imsEventBus } -func (s *Service) publishIMSEvent(event imsendpoint.Event) { +func (s *Service) publishIMSEvent(event imsendpoint.Event) imsEventPublishReceipt { if s == nil { - return + return imsEventPublishReceipt{} } if strings.TrimSpace(event.DeviceID) == "" { event.DeviceID = s.DeviceID() } - s.getIMSEventBus().publish(event) + return s.getIMSEventBus().publishWithReceipt(event) } func (s *Service) buildIMSEventFromRequest(request *sip.Request) imsendpoint.Event { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/inbound_voice_event_ownership_test.go b/third_party/vowifi-go/internal/vowifi/imscore/inbound_voice_event_ownership_test.go new file mode 100644 index 00000000..5b02c9c5 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/imscore/inbound_voice_event_ownership_test.go @@ -0,0 +1,87 @@ +package imscore + +import ( + "context" + "strings" + "sync/atomic" + "testing" + + "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" +) + +const testVoiceEventSubscription = "voice_ims_dispatch" + +type eventOwnedVoiceHandler struct { + calls atomic.Int32 +} + +func (h *eventOwnedVoiceHandler) HandleInboundVoiceRequest( + InboundVoiceRequest, +) (InboundVoiceResult, error) { + h.calls.Add(1) + return InboundVoiceResult{Handled: true, StatusCode: 200}, nil +} + +func (*eventOwnedVoiceHandler) OwnsInboundVoiceMethod(method string) bool { + return strings.EqualFold(strings.TrimSpace(method), "INVITE") +} + +func (*eventOwnedVoiceHandler) InboundVoiceEventSubscription() string { + return testVoiceEventSubscription +} + +func TestEventOwnedVoiceRequestFallsBackWhenEventWasNotDelivered(t *testing.T) { + service := mustEventTestService(t) + handler := &eventOwnedVoiceHandler{} + service.SetVoiceRequestHandler(handler) + result, err := service.handleInboundSIPTransaction( + context.Background(), testInboundVoiceInvite(), func(string) error { return nil }, nil, + ) + if err != nil { + t.Fatal(err) + } + if handler.calls.Load() != 1 || !strings.HasPrefix(result.response, "SIP/2.0 200 ") { + t.Fatalf("fallback calls=%d response=%q", handler.calls.Load(), result.response) + } +} + +func TestEventOwnedVoiceRequestSkipsSyncHandlerOnlyAfterNamedDelivery(t *testing.T) { + service := mustEventTestService(t) + handler := &eventOwnedVoiceHandler{} + service.SetVoiceRequestHandler(handler) + receipt := imsEventPublishReceipt{subscriptions: map[string]int{testVoiceEventSubscription: 1}} + result, err := service.handleInboundSIPDispatch(context.Background(), inboundSIPDispatch{ + raw: testInboundVoiceInvite(), reply: func(string) error { return nil }, events: receipt, + }) + if err != nil { + t.Fatal(err) + } + if handler.calls.Load() != 0 || result.response != "" { + t.Fatalf("event-owned calls=%d response=%q", handler.calls.Load(), result.response) + } +} + +func TestIMSEventPublishReceiptNamesAcceptedSubscription(t *testing.T) { + bus := newIMSEventBus("receipt-device") + delivered := make(chan struct{}, 1) + unsubscribe := bus.subscribe(imsendpoint.EventSubscription{ + Name: testVoiceEventSubscription, + }, func(imsendpoint.Event) { delivered <- struct{}{} }) + t.Cleanup(unsubscribe) + receipt := bus.publishWithReceipt(imsendpoint.Event{Kind: "request", Method: "INVITE"}) + if !receipt.enqueuedFor(testVoiceEventSubscription) || receipt.enqueued != 1 { + t.Fatalf("publish receipt = %+v", receipt) + } + <-delivered +} + +func testInboundVoiceInvite() string { + return "INVITE sip:user@ims.example SIP/2.0\r\n" + + "Via: SIP/2.0/UDP 192.0.2.1:5060;branch=z9hG4bK-voice-owner\r\n" + + "From: ;tag=caller\r\n" + + "To: \r\n" + + "Call-ID: voice-owner-call\r\n" + + "CSeq: 1 INVITE\r\n" + + "Content-Type: application/sdp\r\n" + + "Content-Length: 3\r\n\r\nv=0" +} 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 b890c5cc..40ea9b24 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/transport_runtime.go @@ -23,6 +23,13 @@ type inboundSIPResult struct { afterReply func() } +type inboundSIPDispatch struct { + raw string + reply func(string) error + transaction *serverSIPTransaction + events imsEventPublishReceipt +} + func (s *Service) receiverStarted() { s.receiverMu.Lock() s.activeReceivers++ @@ -73,6 +80,15 @@ func (s *Service) handleInboundSIPTransaction( raw string, reply func(string) error, transaction *serverSIPTransaction, +) (inboundSIPResult, error) { + return s.handleInboundSIPDispatch(ctx, inboundSIPDispatch{ + raw: raw, reply: reply, transaction: transaction, + }) +} + +func (s *Service) handleInboundSIPDispatch( + ctx context.Context, + dispatch inboundSIPDispatch, ) (inboundSIPResult, error) { if ctx == nil { ctx = context.Background() @@ -82,47 +98,48 @@ func (s *Service) handleInboundSIPTransaction( return inboundSIPResult{}, ctx.Err() default: } - method := strings.ToUpper(sipRequestMethod(raw)) + method := strings.ToUpper(sipRequestMethod(dispatch.raw)) if method == "" { return inboundSIPResult{}, errors.New("imscore: invalid inbound SIP message") } switch method { case "NOTIFY": - response, err := buildSIPRequestResponse(raw, 200) + response, err := buildSIPRequestResponse(dispatch.raw, 200) return inboundSIPResult{response: response, afterReply: func() { - s.handleRegistrationNotification(raw) + s.handleRegistrationNotification(dispatch.raw) }}, err case "OPTIONS": - response, err := buildSIPRequestResponse(raw, 200) + response, err := buildSIPRequestResponse(dispatch.raw, 200) return inboundSIPResult{response: response}, err case "MESSAGE": - return s.handleInboundSMS(raw) + return s.handleInboundSMS(dispatch.raw) case "INFO", "BYE": - result, handled, err := s.handleInboundUSSI(raw) + result, handled, err := s.handleInboundUSSI(dispatch.raw) if handled { return result, err } - result, handled, err = s.handleInboundVoice(raw, reply, transaction) + result, handled, err = s.handleInboundVoice(dispatch) if handled { return result, err } - response, responseErr := buildSIPRequestResponse(raw, 405) + response, responseErr := buildSIPRequestResponse(dispatch.raw, 405) return inboundSIPResult{response: response}, responseErr case "INVITE", "CANCEL", "PRACK", "UPDATE": - result, handled, err := s.handleInboundVoice(raw, reply, transaction) + result, handled, err := s.handleInboundVoice(dispatch) if handled { return result, err } - response, responseErr := buildSIPRequestResponse(raw, 405) + response, responseErr := buildSIPRequestResponse(dispatch.raw, 405) return inboundSIPResult{response: response}, responseErr case "ACK": - result, handled, err := s.handleInboundVoice(raw, reply, nil) + dispatch.transaction = nil + result, handled, err := s.handleInboundVoice(dispatch) if handled { return result, err } return inboundSIPResult{}, err default: - response, err := buildSIPRequestResponse(raw, 405) + response, err := buildSIPRequestResponse(dispatch.raw, 405) return inboundSIPResult{response: response}, err } } @@ -162,14 +179,14 @@ func (s *Service) dispatchInboundSIPRequest( if handled || err != nil { return err } - s.publishIMSEvent(s.buildInboundRequestEvent(request, transaction)) + events := s.publishIMSEvent(s.buildInboundRequestEvent(request, transaction)) responseWriter := reply if transaction != nil { responseWriter = transaction.respondRaw } - result, err := s.handleInboundSIPTransaction( - context.Background(), raw, responseWriter, transaction, - ) + result, err := s.handleInboundSIPDispatch(context.Background(), inboundSIPDispatch{ + raw: raw, reply: responseWriter, transaction: transaction, events: events, + }) if result.response == "" { if err != nil && transaction != nil { transaction.fail(err, true) diff --git a/third_party/vowifi-go/internal/vowifi/imscore/voice_runtime.go b/third_party/vowifi-go/internal/vowifi/imscore/voice_runtime.go index 35d9793c..ce51a4b8 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/voice_runtime.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/voice_runtime.go @@ -47,6 +47,7 @@ type InboundVoiceRequest struct { DialogMatched bool DialogResponded bool DialogTerminated bool + Session *imsendpoint.Session } // InboundVoiceResponse is one provisional or final response to an inbound @@ -78,6 +79,13 @@ type VoiceRequestHandler interface { HandleInboundVoiceRequest(InboundVoiceRequest) (InboundVoiceResult, error) } +// EventOwnedVoiceRequestHandler lets the v1.5.5 endpoint event consumer own +// selected methods without racing the additive synchronous handler. +type EventOwnedVoiceRequestHandler interface { + OwnsInboundVoiceMethod(method string) bool + InboundVoiceEventSubscription() string +} + // SetVoiceRequestHandler installs or removes the active voice router. func (s *Service) SetVoiceRequestHandler(handler VoiceRequestHandler) { if s == nil { @@ -182,37 +190,39 @@ func (s *Service) EventBus() *EventBus { return s.bus } -func (s *Service) handleInboundVoice( - raw string, - reply func(string) error, - transaction *serverSIPTransaction, -) (inboundSIPResult, bool, error) { +func (s *Service) handleInboundVoice(dispatch inboundSIPDispatch) (inboundSIPResult, bool, error) { s.mu.RLock() handler := s.voiceHandler s.mu.RUnlock() if handler == nil { return inboundSIPResult{}, false, nil } - dialogRead := s.readInboundVoiceDialog(raw, transaction) - body, err := rawSIPBody(raw) + method := strings.ToUpper(strings.TrimSpace(sipRequestMethod(dispatch.raw))) + owner, eventOwned := handler.(EventOwnedVoiceRequestHandler) + if eventOwned && owner.OwnsInboundVoiceMethod(method) && + dispatch.events.enqueuedFor(owner.InboundVoiceEventSubscription()) { + return inboundSIPResult{}, true, nil + } + dialogRead := s.readInboundVoiceDialog(dispatch.raw, dispatch.transaction) + body, err := rawSIPBody(dispatch.raw) if err != nil { return inboundSIPResult{}, true, err } request := InboundVoiceRequest{ - Method: sipRequestMethod(raw), CallID: rawSIPHeaderValue(raw, "Call-ID"), - From: rawSIPHeaderValue(raw, "From"), To: rawSIPHeaderValue(raw, "To"), - Contact: rawSIPHeaderValue(raw, "Contact"), RecordRoute: rawSIPHeaderValue(raw, "Record-Route"), - CSeq: rawSIPHeaderValue(raw, "CSeq"), ContentType: rawSIPHeaderValue(raw, "Content-Type"), - SessionExpires: rawSIPHeaderValue(raw, "Session-Expires"), - Body: body, Responder: newInboundVoiceResponder(raw, reply), + Method: sipRequestMethod(dispatch.raw), CallID: rawSIPHeaderValue(dispatch.raw, "Call-ID"), + From: rawSIPHeaderValue(dispatch.raw, "From"), To: rawSIPHeaderValue(dispatch.raw, "To"), + Contact: rawSIPHeaderValue(dispatch.raw, "Contact"), RecordRoute: rawSIPHeaderValue(dispatch.raw, "Record-Route"), + CSeq: rawSIPHeaderValue(dispatch.raw, "CSeq"), ContentType: rawSIPHeaderValue(dispatch.raw, "Content-Type"), + SessionExpires: rawSIPHeaderValue(dispatch.raw, "Session-Expires"), + Body: body, Responder: newInboundVoiceResponder(dispatch.raw, dispatch.reply), Dialog: dialogRead.handle, DialogMatched: dialogRead.matched, DialogResponded: dialogRead.responded, DialogTerminated: dialogRead.terminated, } - if transaction != nil && transaction.request != nil { - request.Request = transaction.request.Clone() - request.InboundRequest = newInboundRequestHandle(transaction.request, transaction) - if transaction.request.IsInvite() { - request.ServerInvite = newServerInviteHandle(transaction.request, transaction) + if dispatch.transaction != nil && dispatch.transaction.request != nil { + request.Request = dispatch.transaction.request.Clone() + request.InboundRequest = newInboundRequestHandle(dispatch.transaction.request, dispatch.transaction) + if dispatch.transaction.request.IsInvite() { + request.ServerInvite = newServerInviteHandle(dispatch.transaction.request, dispatch.transaction) } } result, handlerErr := handler.HandleInboundVoiceRequest(request) @@ -226,7 +236,7 @@ func (s *Service) handleInboundVoice( if result.StatusCode == 0 { return inboundSIPResult{}, true, err } - response, responseErr := buildSIPRequestResponse(raw, result.StatusCode) + response, responseErr := buildSIPRequestResponse(dispatch.raw, result.StatusCode) if responseErr != nil { return inboundSIPResult{}, true, responseErr } diff --git a/third_party/vowifi-go/internal/vowifi/voice/agent.go b/third_party/vowifi-go/internal/vowifi/voice/agent.go index 692a9c01..38913673 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/agent.go +++ b/third_party/vowifi-go/internal/vowifi/voice/agent.go @@ -20,6 +20,8 @@ const ( voiceInviteTimeout = 30 * time.Second voiceHangupTimeout = 10 * time.Second voiceActorEventLogInterval = 10 * time.Second + inboundClientWaitTimeout = 120 * time.Second + inboundClientTxTimeout = 32 * time.Second ) // NewAgent creates a voice agent for a device. @@ -66,6 +68,7 @@ func (a *Agent) Start() error { a.actor.Start(a.ctx) if a.ims != nil { a.ims.SetVoiceRequestHandler(a) + a.imsUnsubscribe = a.subscribeIMSEvents() } if a.clientAdapter != nil { a.clientBridge = client.NewBridge(a.deviceID, a.clientAdapter) @@ -91,6 +94,8 @@ func (a *Agent) Stop() error { a.cancel = nil a.ctx = nil clientBridge := a.clientBridge + unsubscribe := a.imsUnsubscribe + a.imsUnsubscribe = nil var activeCall *Call if a.activeCall != nil && !a.activeCall.IsTerminalState() { activeCall = a.activeCall @@ -99,6 +104,9 @@ func (a *Agent) Stop() error { if cancel != nil { cancel() } + if unsubscribe != nil { + unsubscribe() + } if clientBridge != nil { clientBridge.Stop() } diff --git a/third_party/vowifi-go/internal/vowifi/voice/gateway.go b/third_party/vowifi-go/internal/vowifi/voice/gateway.go index 7285ecbf..bae1688c 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/gateway.go +++ b/third_party/vowifi-go/internal/vowifi/voice/gateway.go @@ -3,8 +3,11 @@ package voice import ( "context" "errors" + "strings" "github.com/iniwex5/vowifi-go/internal/vowifi/events" + "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" "github.com/iniwex5/vowifi-go/internal/vowifi/voiceclient" ) @@ -135,6 +138,28 @@ func (g *Gateway) DeviceStatus() map[string]interface{} { return g.agent.deviceStatus() } +// OnIMSInvite retains the v1.5.5 raw compatibility entry point. Production +// endpoint delivery uses Agent.OnIMSInvite with a retained server handle. +func (g *Gateway) OnIMSInvite(deviceID string, raw []byte, session *imsendpoint.Session) { + if g == nil || g.agent == nil { + logging.WarnRate("voice-gateway-invite:"+strings.TrimSpace(deviceID), + voiceActorEventLogInterval, "voice gateway has no agent", "device", deviceID) + return + } + if deviceID = strings.TrimSpace(deviceID); deviceID != "" && deviceID != g.agent.DeviceID() { + logging.WarnRate("voice-gateway-invite:"+deviceID, voiceActorEventLogInterval, + "voice gateway agent does not match device", "device", deviceID) + return + } + request, err := parseVoiceRequest(string(raw)) + if err != nil { + logging.WarnRate("voice-gateway-invite-parse:"+deviceID, voiceActorEventLogInterval, + "voice gateway INVITE parse failed", "device", deviceID, "err", err) + return + } + g.agent.OnIMSInvite(request, session, nil) +} + // SimulateCall runs the recovered device-scoped timed-call workflow. func (g *Gateway) SimulateCall( ctx context.Context, diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_actions.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_actions.go index 0434a688..118f7107 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/inbound_actions.go +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_actions.go @@ -23,7 +23,7 @@ func (a *Agent) AnswerWithSDP(callID, clientSDP string) (InboundAnswer, error) { return InboundAnswer{}, errors.New("voice: inbound call is not alerting") } responder := call.inboundResponseWriter() - if responder == nil { + if responder == nil && !call.hasServerInvite() { return InboundAnswer{}, errors.New("voice: inbound INVITE response context is unavailable") } answer, err := a.applyInboundAnswer(call, clientSDP) @@ -83,7 +83,7 @@ func (a *Agent) rejectInboundCall(call *Call, statusCode int) error { return errors.New("voice: inbound call is not alerting") } responder := call.inboundResponseWriter() - if responder == nil { + if responder == nil && !call.hasServerInvite() { return errors.New("voice: inbound INVITE response context is unavailable") } structured, err := a.rejectStoredServerInvite(call, statusCode) @@ -121,7 +121,7 @@ func (a *Agent) notifyIncomingCall(call *Call) { func (a *Agent) startInboundNoAnswerTimer(call *Call) { call.mu.Lock() - call.noAnswerTimer = time.AfterFunc(voiceInviteTimeout, func() { + call.noAnswerTimer = time.AfterFunc(inboundClientWaitTimeout, func() { call.inboundDecisionMu.Lock() defer call.inboundDecisionMu.Unlock() if call.CallState() != callstate.StateAlerting { @@ -136,14 +136,14 @@ func (a *Agent) startInboundNoAnswerTimer(call *Call) { func (a *Agent) sendInboundTimeout(call *Call) error { cause := errors.New("voice: inbound call timed out") responder := call.inboundResponseWriter() - if responder == nil { + if responder == nil && !call.hasServerInvite() { return cause } structured, err := a.rejectStoredServerInvite(call, 480) if err != nil { return errors.Join(cause, err) } - if !structured { + if !structured && responder != nil { if err := responder.Respond(imscore.InboundVoiceResponse{StatusCode: 480}); err != nil { return errors.Join(cause, fmt.Errorf("send 480 response: %w", err)) } diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_call.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_call.go index faab7003..264d2f05 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/inbound_call.go +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_call.go @@ -5,6 +5,7 @@ import ( "github.com/iniwex5/vowifi-go/internal/vowifi/imscore" "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" "github.com/iniwex5/vowifi-go/internal/vowifi/voice/callstate" + "github.com/iniwex5/vowifi-go/internal/vowifi/voice/client" ) func (c *Call) setServerInvite(handle imsendpoint.ServerInviteHandle, request *sip.Request) { @@ -18,6 +19,133 @@ func (c *Call) setServerInvite(handle imsendpoint.ServerInviteHandle, request *s c.mu.Unlock() } +func (c *Call) hasServerInvite() bool { + if c == nil { + return false + } + c.mu.RLock() + defer c.mu.RUnlock() + return c.imsServerInvite != nil && c.imsInviteRequest != nil +} + +func (c *Call) markInboundPrepared() { + if c == nil { + return + } + c.mu.Lock() + c.inboundPrepared = true + c.mu.Unlock() +} + +func (c *Call) startInboundClientOnce() bool { + if c == nil { + return false + } + c.mu.Lock() + defer c.mu.Unlock() + if !c.inboundPrepared || c.inboundClientStarted || callstate.IsTerminal(callstate.State(c.State)) { + return false + } + c.inboundClientStarted = true + return true +} + +type clientRequestContext struct { + request *sip.Request + destination string + localIP string + fromTag string +} + +func (c *Call) storeClientRequestContext(value clientRequestContext) { + c.mu.Lock() + c.clientInviteRequest = value.request.Clone() + c.DialogState.ClientDest = value.destination + c.DialogState.ClientLocalIP = value.localIP + c.DialogState.ClientFromTag = value.fromTag + c.mu.Unlock() +} + +func (c *Call) setInboundClientBridge(bridge *client.Bridge) { + if c == nil { + return + } + c.mu.Lock() + c.inboundClientBridge = bridge + c.mu.Unlock() +} + +func (c *Call) inboundBridge() *client.Bridge { + if c == nil { + return nil + } + c.mu.RLock() + defer c.mu.RUnlock() + return c.inboundClientBridge +} + +func (c *Call) storeClientInvite(request *sip.Request) { + if c == nil || request == nil { + return + } + c.mu.Lock() + c.clientInviteRequest = request.Clone() + c.mu.Unlock() +} + +func (c *Call) storeClientInviteResponse(response *sip.Response) { + if c == nil || response == nil { + return + } + c.mu.Lock() + c.clientInviteResponse = response.Clone() + c.DialogState.ClientToTag = sipHeaderTag(response.To()) + c.mu.Unlock() +} + +func (c *Call) clientDialogContext() (*sip.Request, *sip.Response) { + if c == nil { + return nil, nil + } + c.mu.RLock() + defer c.mu.RUnlock() + var request *sip.Request + var response *sip.Response + if c.clientInviteRequest != nil { + request = c.clientInviteRequest.Clone() + } + if c.clientInviteResponse != nil { + response = c.clientInviteResponse.Clone() + } + return request, response +} + +func (c *Call) takeClientCancelRequest() *sip.Request { + if c == nil { + return nil + } + c.mu.Lock() + defer c.mu.Unlock() + if c.clientCancelSent || c.clientInviteRequest == nil { + return nil + } + c.clientCancelSent = true + return c.clientInviteRequest.Clone() +} + +func (c *Call) takeClientByeContext() (*sip.Request, *sip.Response) { + if c == nil { + return nil, nil + } + c.mu.Lock() + defer c.mu.Unlock() + if c.clientByeSent || c.clientInviteRequest == nil || c.clientInviteResponse == nil { + return nil, nil + } + c.clientByeSent = true + return c.clientInviteRequest.Clone(), c.clientInviteResponse.Clone() +} + func (c *Call) serverInviteContext() (imsendpoint.ServerInviteHandle, *sip.Request) { c.mu.RLock() defer c.mu.RUnlock() @@ -40,6 +168,15 @@ func (c *Call) inboundResponseWriter() imscore.InboundVoiceResponder { return c.inboundResponder } +func (c *Call) inboundLocalTagValue() string { + if c == nil { + return "" + } + c.mu.RLock() + defer c.mu.RUnlock() + return c.DialogState.ToTag +} + func (c *Call) setRemoteSDP(remote, clientRemote string) { c.mu.Lock() c.remoteSDP = remote diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_client_requests.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_client_requests.go new file mode 100644 index 00000000..6625ff96 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_client_requests.go @@ -0,0 +1,201 @@ +package voice + +import ( + "context" + "errors" + "fmt" + "net" + "strings" + + "github.com/emiago/sipgo/sip" + "github.com/iniwex5/vowifi-go/internal/vowifi/sipkit" + "github.com/iniwex5/vowifi-go/internal/vowifi/voice/client" +) + +type clientInviteBuildConfig struct { + recipient sip.Uri + localIP string + username string + fromTag string +} + +type clientDialogHeaderConfig struct { + method sip.RequestMethod + cseq uint32 +} + +func (a *Agent) buildClientInviteReq( + call *Call, + bridge *client.Bridge, + target inboundClientTarget, +) (*sip.Request, error) { + if a == nil || call == nil || bridge == nil { + return nil, errors.New("voice: client bridge is unavailable") + } + var recipient sip.Uri + if err := sip.ParseUri(strings.TrimSpace(target.contactURI), &recipient); err != nil { + return nil, fmt.Errorf("voice: parse client Contact: %w", err) + } + if target.username = strings.TrimSpace(target.username); target.username != "" { + recipient.User = target.username + } + destination, err := clientDestination(recipient, target.destination) + if err != nil { + return nil, err + } + localIP := strings.TrimSpace(bridge.LocalIP()) + if localIP == "" { + return nil, errors.New("voice: client bridge local IP is unavailable") + } + fromTag := voiceTag() + request := buildClientInviteMessage(call, bridge, clientInviteBuildConfig{ + recipient: recipient, localIP: localIP, username: target.username, fromTag: fromTag, + }) + request.SetDestination(destination) + request.SetTransport("UDP") + call.storeClientRequestContext(clientRequestContext{ + request: request, destination: destination, localIP: localIP, fromTag: fromTag, + }) + return request, nil +} + +func buildClientInviteMessage( + call *Call, + bridge *client.Bridge, + cfg clientInviteBuildConfig, +) *sip.Request { + request := sip.NewRequest(sip.INVITE, cfg.recipient) + fromParams := sip.NewParams() + fromParams.Add("tag", cfg.fromTag) + request.AppendHeader(&sip.FromHeader{Address: sip.Uri{Scheme: "sip", User: call.CallerID, Host: cfg.localIP}, Params: fromParams}) + request.AppendHeader(&sip.ToHeader{Address: sip.Uri{Scheme: "sip", User: cfg.username, Host: cfg.localIP}, Params: sip.NewParams()}) + callID := sip.CallIDHeader(call.ClientCallID()) + request.AppendHeader(&callID) + request.AppendHeader(&sip.CSeqHeader{SeqNo: 1, MethodName: sip.INVITE}) + maxForwards := sip.MaxForwardsHeader(70) + request.AppendHeader(&maxForwards) + host, port := bridge.ListenHostPort() + request.AppendHeader(&sip.ContactHeader{Address: sip.Uri{Scheme: "sip", User: "vohive", Host: host, Port: port}}) + if call.agent != nil && call.agent.dialog != nil { + if userAgent := strings.TrimSpace(call.agent.dialog.UserAgent()); userAgent != "" { + request.AppendHeader(sip.NewHeader("User-Agent", userAgent)) + } + } + request.AppendHeader(sip.NewHeader("Content-Type", "application/sdp")) + request.SetBody([]byte(call.ClientSDP())) + return request +} + +func clientDestination(recipient sip.Uri, configured string) (string, error) { + configured = strings.TrimSpace(configured) + if configured != "" { + if _, _, err := net.SplitHostPort(configured); err == nil { + return configured, nil + } + if net.ParseIP(strings.Trim(configured, "[]")) != nil || validClientHost(configured) { + return net.JoinHostPort(strings.Trim(configured, "[]"), "5060"), nil + } + return "", fmt.Errorf("voice: invalid client destination %q", configured) + } + if strings.TrimSpace(recipient.Host) == "" { + return "", errors.New("voice: client Contact host is empty") + } + port := recipient.Port + if port == 0 { + port = 5060 + } + return net.JoinHostPort(recipient.Host, fmt.Sprint(port)), nil +} + +func validClientHost(value string) bool { + return !strings.ContainsAny(value, " :/\\@") && strings.TrimSpace(value) != "" +} + +func (a *Agent) sendClientACK(call *Call) error { + invite, response := call.clientDialogContext() + if invite == nil || response == nil { + return errors.New("voice: client dialog context is unavailable") + } + request := buildClientDialogRequest(sip.ACK, invite, response, invite.CSeq().SeqNo) + return writeInboundClientRequest(call, "inbound_client_ack", request) +} + +func (a *Agent) sendClientCancel(call *Call) error { + return sendClientCancelRequest(call.inboundBridge(), call.takeClientCancelRequest()) +} + +func sendClientCancelRequest(bridge *client.Bridge, invite *sip.Request) error { + if invite == nil { + return nil + } + if bridge == nil { + return errors.New("voice: client bridge is unavailable") + } + request, err := sipkit.BuildCancelFromInvite(invite) + if err != nil { + return err + } + return bridge.WriteRequest(context.Background(), "inbound_client_cancel", request) +} + +func (a *Agent) sendClientBye(call *Call) error { + invite, response := call.takeClientByeContext() + if invite == nil || response == nil { + return nil + } + request := buildClientDialogRequest(sip.BYE, invite, response, invite.CSeq().SeqNo+1) + return writeInboundClientRequest(call, "inbound_client_bye", request) +} + +func writeInboundClientRequest(call *Call, flow string, request *sip.Request) error { + bridge := call.inboundBridge() + if bridge == nil { + return errors.New("voice: client bridge is unavailable") + } + return bridge.WriteRequest(context.Background(), flow, request) +} + +func buildClientDialogRequest( + method sip.RequestMethod, + invite *sip.Request, + response *sip.Response, + cseq uint32, +) *sip.Request { + recipient := invite.Recipient + if contact := response.Contact(); contact != nil { + recipient = *contact.Address.Clone() + } + request := sip.NewRequest(method, recipient) + appendClientDialogHeaders(request, invite, response, clientDialogHeaderConfig{ + method: method, cseq: cseq, + }) + request.SetDestination(invite.Destination()) + request.SetTransport(invite.Transport()) + return request +} + +func appendClientDialogHeaders( + request *sip.Request, + invite *sip.Request, + response *sip.Response, + cfg clientDialogHeaderConfig, +) { + maxForwards := sip.MaxForwardsHeader(70) + request.AppendHeader(&maxForwards) + if header := invite.From(); header != nil { + request.AppendHeader(sip.HeaderClone(header)) + } + if header := response.To(); header != nil { + request.AppendHeader(sip.HeaderClone(header)) + } + if header := invite.CallID(); header != nil { + request.AppendHeader(sip.HeaderClone(header)) + } + request.AppendHeader(&sip.CSeqHeader{SeqNo: cfg.cseq, MethodName: cfg.method}) + if header := invite.Contact(); header != nil { + request.AppendHeader(sip.HeaderClone(header)) + } + for _, header := range response.GetHeaders("Record-Route") { + request.PrependHeader(sip.NewHeader("Route", header.Value())) + } +} diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog.go index dd17e6e4..375851cd 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog.go +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog.go @@ -28,26 +28,61 @@ func (a *Agent) prepareInboundVoiceDialog(call *Call, request imscore.InboundVoi localURI: voiceHeaderURI(request.To), remoteURI: remoteURI, remoteTarget: remoteTarget, contactURI: profile.ContactURI, localAddress: profile.LocalAddress, transport: profile.Transport, serviceRoute: splitVoiceHeaderValues(request.RecordRoute), securityVerify: profile.SecurityVerify, - pani: profile.PANI, userAgent: profile.UserAgent, localTag: request.Responder.LocalTag(), + pani: profile.PANI, userAgent: profile.UserAgent, localTag: inboundLocalTag(call, request.Responder), remoteTag: voiceHeaderTag(request.From), cseq: cseq, }) return nil } -func (a *Agent) reserveInboundCall(request imscore.InboundVoiceRequest) (*Call, error) { - call := NewCall(a, callstate.DirectionInbound, request.CallID, voiceHeaderURI(request.From)) - call.callee = voiceHeaderURI(request.To) +func (a *Agent) reserveInboundCall(request imscore.InboundVoiceRequest) (*Call, bool, error) { + call := a.newInboundCall(request) if err := call.TransitionChecked(callstate.StateAlerting); err != nil { - return nil, err + return nil, false, err } a.mu.Lock() defer a.mu.Unlock() + if existing := a.calls[request.CallID]; existing != nil && !existing.IsTerminalState() { + call.CloseDone() + return existing, false, nil + } if a.activeCall != nil && !a.activeCall.IsTerminalState() { - return nil, errors.New("voice: busy") + call.CloseDone() + return nil, false, errors.New("voice: busy") } a.calls[request.CallID] = call a.activeCall = call - return call, nil + return call, true, nil +} + +func (a *Agent) newInboundCall(request imscore.InboundVoiceRequest) *Call { + if request.Request == nil { + call := NewCall(a, callstate.DirectionInbound, request.CallID, voiceHeaderURI(request.From)) + call.callee = voiceHeaderURI(request.To) + return call + } + call := NewCallFromRequest(a.deviceID, request.Request, request.Session) + call.agent = a + if call.callID == "" { + call.callID = request.CallID + call.DialogState.CallID = request.CallID + } + return call +} + +func inboundLocalTag(call *Call, responder imscore.InboundVoiceResponder) string { + tag := "" + if responder != nil { + tag = strings.TrimSpace(responder.LocalTag()) + } + call.mu.Lock() + defer call.mu.Unlock() + if tag != "" { + call.DialogState.ToTag = tag + } + if strings.TrimSpace(call.DialogState.ToTag) == "" { + call.DialogState.ToTag = voiceTag() + } + return call.DialogState.ToTag } func inboundVoiceCSeq(value string) (int, error) { diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog_signaling.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog_signaling.go index 527e3c9f..0f5b5caf 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog_signaling.go +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_dialog_signaling.go @@ -12,7 +12,22 @@ import ( "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" ) +type serverInviteAnswer struct { + status int + reason string + sdp string +} + func (a *Agent) answerStoredServerInvite(call *Call, sdp string) (bool, error) { + return a.answerStoredServerInviteResult(call, serverInviteAnswer{ + status: 200, reason: "OK", sdp: sdp, + }) +} + +func (a *Agent) answerStoredServerInviteResult( + call *Call, + answer serverInviteAnswer, +) (bool, error) { if a == nil || a.dialog == nil || call == nil { return false, errors.New("voice: dialog controller is unavailable") } @@ -24,14 +39,10 @@ func (a *Agent) answerStoredServerInvite(call *Call, sdp string) (bool, error) { if contact == nil { return true, errors.New("voice: inbound answer Contact is unavailable") } - response := sip.NewResponseFromRequest(request, 200, "OK", []byte(sdp)) - response.AppendHeader(sip.NewHeader("Content-Type", "application/sdp")) + response := call.BuildResponseWithSDP(answer.status, answer.reason, []byte(answer.sdp)) if expires := call.voiceSessionExpires(); expires > 0 { response.AppendHeader(sip.NewHeader("Session-Expires", strconv.FormatInt(int64(expires/time.Second), 10))) } - if responder := call.inboundResponseWriter(); responder != nil && response.To() != nil { - response.To().Params.Add("tag", responder.LocalTag()) - } dialog, err := a.dialog.AnswerServerInvite( context.Background(), a.deviceID, invite, imsendpoint.ServerInviteAnswerOptions{Response: response, Contact: contact.Clone()}, @@ -43,6 +54,14 @@ func (a *Agent) answerStoredServerInvite(call *Call, sdp string) (bool, error) { } func (a *Agent) rejectStoredServerInvite(call *Call, statusCode int) (bool, error) { + return a.rejectStoredServerInviteWithReason(call, statusCode, imscore.SIPStatusText(statusCode)) +} + +func (a *Agent) rejectStoredServerInviteWithReason( + call *Call, + statusCode int, + reason string, +) (bool, error) { if a == nil || a.dialog == nil || call == nil { return false, errors.New("voice: dialog controller is unavailable") } @@ -50,10 +69,14 @@ func (a *Agent) rejectStoredServerInvite(call *Call, statusCode int) (bool, erro if invite == nil || request == nil { return false, nil } - reason := strings.TrimSpace(imscore.SIPStatusText(statusCode)) + reason = strings.TrimSpace(reason) + if reason == "" { + reason = strings.TrimSpace(imscore.SIPStatusText(statusCode)) + } + response := call.BuildResponse(statusCode, reason) err := a.dialog.RejectServerInvite( context.Background(), a.deviceID, invite, - imsendpoint.ServerInviteRejectOptions{Code: statusCode, Reason: reason}, + imsendpoint.ServerInviteRejectOptions{Response: response, Code: statusCode, Reason: reason}, ) return true, err } diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_events.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_events.go new file mode 100644 index 00000000..1a516c64 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_events.go @@ -0,0 +1,297 @@ +package voice + +import ( + "context" + "errors" + "strings" + + "github.com/emiago/sipgo/sip" + "github.com/iniwex5/vowifi-go/internal/vowifi/imscore" + "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" + "github.com/iniwex5/vowifi-go/internal/vowifi/voice/callstate" +) + +const ( + voiceIMSEventSubscription = "voice_ims_dispatch" + voiceIMSEventQueueSize = 64 +) + +func (a *Agent) subscribeIMSEvents() func() { + if a == nil || a.ims == nil { + return nil + } + return a.ims.Subscribe(imsendpoint.EventSubscription{ + Name: voiceIMSEventSubscription, QueueSize: voiceIMSEventQueueSize, + Workers: 1, Match: isVoiceIMSEvent, + }, a.handleIMSEvent) +} + +func isVoiceIMSEvent(event imsendpoint.Event) bool { + method := strings.ToUpper(strings.TrimSpace(event.Method)) + if method == "" { + method = strings.ToUpper(strings.TrimSpace(event.CSeqMethod)) + } + switch strings.ToLower(strings.TrimSpace(event.Kind)) { + case "request": + return method == "INVITE" || method == "BYE" || method == "CANCEL" || method == "UPDATE" + case "response": + return method == "INVITE" || method == "PRACK" + default: + return false + } +} + +// OwnsInboundVoiceMethod prevents the synchronous compatibility router from +// consuming the same request as the restored endpoint event path. +func (a *Agent) OwnsInboundVoiceMethod(method string) bool { + switch strings.ToUpper(strings.TrimSpace(method)) { + case "INVITE", "BYE", "CANCEL", "UPDATE": + return true + default: + return false + } +} + +// InboundVoiceEventSubscription identifies the queue that must accept an +// event before imscore transfers ownership from its synchronous router. +func (a *Agent) InboundVoiceEventSubscription() string { + return voiceIMSEventSubscription +} + +func (a *Agent) handleIMSEvent(event imsendpoint.Event) { + if !strings.EqualFold(strings.TrimSpace(event.Kind), "request") { + return + } + switch strings.ToUpper(strings.TrimSpace(event.Method)) { + case "INVITE": + a.OnIMSInvite(event.Request, event.Session, event.ServerInvite) + case "BYE": + a.HandleIMSByeEvent(event) + case "CANCEL": + a.HandleIMSCancelEvent(event) + case "UPDATE": + a.HandleIMSUpdateEvent(event) + } +} + +// OnIMSInvite retains the v1.5.5 inbound server-INVITE entry point. +func (a *Agent) OnIMSInvite( + request *sip.Request, + session *imsendpoint.Session, + handle imsendpoint.ServerInviteHandle, +) { + if a == nil || request == nil { + logging.WarnRate("voice-inbound-invite-nil", voiceActorEventLogInterval, + "voice inbound INVITE is nil") + return + } + method := strings.ToUpper(strings.TrimSpace(string(request.Method))) + if method == "CANCEL" { + a.HandleIMSCancelEvent(imsendpoint.Event{ + Kind: "request", Method: method, CallID: requestCallID(request), + Session: session, Request: request, ServerInvite: handle, + }) + return + } + if method != "" && method != "INVITE" { + return + } + inbound := inboundRequestFromEvent(request, session, handle) + result, err := a.HandleInboundVoiceRequest(inbound) + if err != nil { + logging.WarnRate("voice-inbound-invite:"+inbound.CallID, voiceActorEventLogInterval, + "voice inbound INVITE failed", "device", a.deviceID, "call_id", inbound.CallID, "err", err) + } + if result.StatusCode != 0 { + if result.StatusCode == 486 { + a.rejectBusy(request, session, handle) + return + } + a.rejectUnownedServerInvite(request, session, handle, result.StatusCode) + } +} + +func inboundRequestFromEvent( + request *sip.Request, + session *imsendpoint.Session, + handle imsendpoint.ServerInviteHandle, +) imscore.InboundVoiceRequest { + return imscore.InboundVoiceRequest{ + Method: string(request.Method), CallID: requestCallID(request), + From: requestHeaderValue(request, "From"), To: requestHeaderValue(request, "To"), + Contact: requestHeaderValue(request, "Contact"), + RecordRoute: joinedRequestHeaders(request, "Record-Route"), + CSeq: requestHeaderValue(request, "CSeq"), + ContentType: requestHeaderValue(request, "Content-Type"), + SessionExpires: requestHeaderValue(request, "Session-Expires"), + Body: append([]byte(nil), request.Body()...), Request: request.Clone(), + ServerInvite: handle, Session: session, + } +} + +func (a *Agent) inboundRequestFromEndpointEvent(event imsendpoint.Event) imscore.InboundVoiceRequest { + request := event.Request + if request == nil { + return imscore.InboundVoiceRequest{Method: event.Method, CallID: event.CallID} + } + inbound := inboundRequestFromEvent(request, event.Session, event.ServerInvite) + inbound.InboundRequest = event.InboundRequest + if event.InboundRequest != nil { + inbound.Responder = a.newEndpointEventResponder(event) + } + return inbound +} + +func (a *Agent) newEndpointEventResponder(event imsendpoint.Event) imscore.InboundVoiceResponder { + localTag := "" + if call := a.callForIMSEvent(event); call != nil { + call.mu.RLock() + localTag = call.DialogState.ToTag + call.mu.RUnlock() + } + return &endpointEventResponder{ + agent: a, handle: event.InboundRequest, localTag: localTag, + } +} + +type endpointEventResponder struct { + agent *Agent + handle imsendpoint.InboundRequestHandle + localTag string +} + +func (r *endpointEventResponder) LocalTag() string { + if r == nil { + return "" + } + return r.localTag +} + +func (r *endpointEventResponder) Respond(response imscore.InboundVoiceResponse) error { + if r == nil || r.agent == nil || r.agent.ims == nil || r.handle == nil { + return errors.New("voice: IMS inbound response path is unavailable") + } + headers := endpointResponseHeaders(response) + return r.agent.ims.RespondInboundRequest(context.Background(), r.agent.deviceID, r.handle, + imsendpoint.InboundResponseOptions{ + Code: response.StatusCode, Body: append([]byte(nil), response.Body...), Headers: headers, + }) +} + +func endpointResponseHeaders(response imscore.InboundVoiceResponse) []sip.Header { + headers := make([]sip.Header, 0, 3) + if value := strings.TrimSpace(response.ContentType); value != "" { + headers = append(headers, sip.NewHeader("Content-Type", value)) + } + if value := strings.TrimSpace(response.Contact); value != "" { + headers = append(headers, sip.NewHeader("Contact", "<"+strings.Trim(value, "<>")+">")) + } + if value := strings.TrimSpace(response.SessionExpires); value != "" { + headers = append(headers, sip.NewHeader("Session-Expires", value)) + } + return headers +} + +func joinedRequestHeaders(request *sip.Request, name string) string { + if request == nil { + return "" + } + values := make([]string, 0, len(request.GetHeaders(name))) + for _, header := range request.GetHeaders(name) { + if value := strings.TrimSpace(header.Value()); value != "" { + values = append(values, value) + } + } + return strings.Join(values, ", ") +} + +func (a *Agent) rejectUnownedServerInvite( + request *sip.Request, + session *imsendpoint.Session, + handle imsendpoint.ServerInviteHandle, + status int, +) { + if a == nil || a.dialog == nil || request == nil || handle == nil { + return + } + call := NewCallFromRequest(a.deviceID, request, session) + defer call.CloseDone() + response := call.BuildResponse(status, imscore.SIPStatusText(status)) + err := a.dialog.RejectServerInvite(context.Background(), a.deviceID, handle, + imsendpoint.ServerInviteRejectOptions{Response: response}) + if err != nil { + logging.WarnRate("voice-inbound-reject:"+requestCallID(request), voiceActorEventLogInterval, + "voice inbound INVITE rejection failed", "device", a.deviceID, + "call_id", requestCallID(request), "status", status, "err", err) + } +} + +// HandleIMSByeEvent retains the v1.5.5 endpoint event entry point. +func (a *Agent) HandleIMSByeEvent(event imsendpoint.Event) { + a.handleIMSRequestEvent(event) +} + +// HandleIMSCancelEvent retains the v1.5.5 endpoint event entry point. +func (a *Agent) HandleIMSCancelEvent(event imsendpoint.Event) { + a.handleIMSRequestEvent(event) +} + +// HandleIMSUpdateEvent retains the v1.5.5 endpoint event entry point. +func (a *Agent) HandleIMSUpdateEvent(event imsendpoint.Event) { + a.handleIMSRequestEvent(event) +} + +func (a *Agent) handleIMSRequestEvent(event imsendpoint.Event) { + inbound := a.inboundRequestFromEndpointEvent(event) + responded, responseErr := a.respondBeforeIMSRequest(event, inbound) + result, handlerErr := a.HandleInboundVoiceRequest(inbound) + err := errors.Join(responseErr, handlerErr) + if err != nil { + logging.WarnRate("voice-ims-request:"+inbound.CallID+":"+inbound.Method, voiceActorEventLogInterval, + "voice IMS request failed", "device", a.deviceID, "call_id", inbound.CallID, + "method", inbound.Method, "err", err) + } + if responded || result.StatusCode == 0 || inbound.Responder == nil { + return + } + if err := inbound.Responder.Respond(imscore.InboundVoiceResponse{StatusCode: result.StatusCode}); err != nil { + logging.WarnRate("voice-ims-response:"+inbound.CallID+":"+inbound.Method, voiceActorEventLogInterval, + "voice IMS response failed", "device", a.deviceID, "call_id", inbound.CallID, + "method", inbound.Method, "status", result.StatusCode, "err", err) + } +} + +func (a *Agent) respondBeforeIMSRequest( + event imsendpoint.Event, + inbound imscore.InboundVoiceRequest, +) (bool, error) { + if !strings.EqualFold(strings.TrimSpace(inbound.Method), "BYE") || inbound.Responder == nil { + return false, nil + } + call := a.callForIMSEvent(event) + if call == nil || call.CallState() != callstate.StateConnected { + return false, nil + } + return true, inbound.Responder.Respond(imscore.InboundVoiceResponse{StatusCode: 200}) +} + +func (a *Agent) callForIMSEvent(event imsendpoint.Event) *Call { + if a == nil { + return nil + } + callID := strings.TrimSpace(event.CallID) + if callID == "" && event.Request != nil { + callID = requestCallID(event.Request) + } + if call := a.callByID(callID); call != nil { + return call + } + a.mu.RLock() + active := a.activeCall + a.mu.RUnlock() + if callMatchesID(active, callID) { + return active + } + return nil +} diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_forward.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_forward.go new file mode 100644 index 00000000..9ebc83cd --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_forward.go @@ -0,0 +1,206 @@ +package voice + +import ( + "context" + "errors" + "strings" + "time" + + "github.com/emiago/sipgo/sip" + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" + "github.com/iniwex5/vowifi-go/internal/vowifi/voice/callstate" + "github.com/iniwex5/vowifi-go/internal/vowifi/voice/client" + "github.com/iniwex5/vowifi-go/internal/vowifi/voiceclient" +) + +type inboundClientTarget struct { + contactURI string + destination string + username string +} + +func (a *Agent) maybeStartInboundClient(call *Call) { + if a == nil || call == nil { + return + } + bridge, adapter := a.inboundClientDependencies() + if bridge == nil || adapter == nil { + return + } + if !call.startInboundClientOnce() { + return + } + call.setInboundClientBridge(bridge) + go a.deliverInboundCall(call, bridge, adapter) +} + +func (a *Agent) inboundClientDependencies() (*client.Bridge, voiceclient.Adapter) { + a.mu.RLock() + defer a.mu.RUnlock() + return a.clientBridge, a.clientAdapter +} + +func (a *Agent) deliverInboundCall(call *Call, bridge *client.Bridge, adapter voiceclient.Adapter) { + online := adapter.SubscribeDeviceOnline(a.deviceID) + if a.tryForwardInboundCall(call, bridge) { + return + } + if err := bridge.SendPush(a.deviceID, call.ClientCallID(), call.CallerID, call.CalleeID); err != nil { + logging.WarnRate("voice-inbound-push:"+call.CallID(), voiceActorEventLogInterval, + "voice inbound push failed", "device", a.deviceID, "call_id", call.CallID(), "err", err) + } + timer := time.NewTimer(inboundClientWaitTimeout) + defer timer.Stop() + for { + select { + case <-call.Done: + return + case <-timer.C: + return + case _, open := <-online: + if !open { + online = nil + continue + } + if a.tryForwardInboundCall(call, bridge) { + return + } + } + } +} + +func (a *Agent) tryForwardInboundCall(call *Call, bridge *client.Bridge) bool { + if call == nil || call.IsTerminalState() { + return true + } + contactURI, destination, username, err := bridge.Contact(nil) + if err != nil || strings.TrimSpace(contactURI) == "" { + if err != nil { + logging.WarnRate("voice-inbound-contact:"+call.CallID(), voiceActorEventLogInterval, + "voice client contact lookup failed", "device", a.deviceID, "call_id", call.CallID(), "err", err) + } + return false + } + return a.forwardToClient(call, bridge, inboundClientTarget{ + contactURI: contactURI, destination: destination, username: username, + }) +} + +// forwardToClient runs the retained local UAC transaction for one IMS call. +func (a *Agent) forwardToClient( + call *Call, + bridge *client.Bridge, + target inboundClientTarget, +) bool { + ctx, cancel := context.WithTimeout(call.Ctx, inboundClientTxTimeout) + defer cancel() + request, err := a.buildClientInviteReq(call, bridge, target) + if err != nil { + a.failInboundClientDelivery(call, 500, err) + return true + } + transaction, err := bridge.StartTransaction(ctx, "inbound_client_invite", request) + if err != nil { + logging.WarnRate("voice-inbound-client-tx:"+call.CallID(), voiceActorEventLogInterval, + "voice client INVITE transaction failed", "device", a.deviceID, "call_id", call.CallID(), "err", err) + return false + } + if transaction == nil { + a.failInboundClientDelivery(call, 500, + errors.New("voice: client INVITE transaction is unavailable")) + return true + } + call.storeClientInvite(request) + defer transaction.Terminate() + response, err := a.waitFinalResponse(ctx, call, transaction) + if err != nil { + a.handleInboundClientTransactionError(call, err) + return true + } + return a.handleInboundClientFinal(call, response) +} + +func (a *Agent) waitFinalResponse( + ctx context.Context, + call *Call, + transaction sip.ClientTransaction, +) (*sip.Response, error) { + for { + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-call.Done: + return nil, context.Canceled + case response, open := <-transaction.Responses(): + if !open { + return nil, transactionError(transaction) + } + if response != nil && response.StatusCode >= 200 { + return response, nil + } + case <-transaction.Done(): + return nil, transactionError(transaction) + } + } +} + +func transactionError(transaction sip.ClientTransaction) error { + if transaction != nil && transaction.Err() != nil { + return transaction.Err() + } + return errors.New("voice: client INVITE transaction ended without a final response") +} + +func (a *Agent) handleInboundClientFinal(call *Call, response *sip.Response) bool { + if response == nil { + a.failInboundClientDelivery(call, 500, errors.New("voice: client returned an empty INVITE response")) + return true + } + if response.StatusCode >= 200 && response.StatusCode < 300 { + return a.handleClientAnswer(call, response) + } + if response.StatusCode == 408 || response.StatusCode == 480 || response.StatusCode == 503 { + return false + } + a.failInboundClientDelivery(call, response.StatusCode, errors.New("voice: client rejected inbound call")) + return true +} + +func (a *Agent) handleClientAnswer(call *Call, response *sip.Response) bool { + call.storeClientInviteResponse(response) + if err := a.sendClientACK(call); err != nil { + a.failInboundClientDelivery(call, 500, err) + return true + } + if _, err := a.AnswerWithSDP(call.CallID(), string(response.Body())); err != nil { + _ = a.sendClientBye(call) + a.failInboundClientDelivery(call, 500, err) + } + return true +} + +func (a *Agent) handleInboundClientTransactionError(call *Call, cause error) { + if call == nil || call.IsTerminalState() { + return + } + _ = a.sendClientCancel(call) + status := 408 + if errors.Is(cause, context.Canceled) && call.CallState() != callstate.StateAlerting { + return + } + a.failInboundClientDelivery(call, status, cause) +} + +func (a *Agent) failInboundClientDelivery(call *Call, status int, cause error) { + if call == nil || call.IsTerminalState() { + return + } + if status < 300 || status > 699 { + status = 500 + } + if err := a.Reject(call.CallID(), status); err != nil { + logging.WarnRate("voice-inbound-client-failure:"+call.CallID(), voiceActorEventLogInterval, + "voice inbound client failure response failed", "device", a.deviceID, + "call_id", call.CallID(), "status", status, "cause", cause, "err", err) + } +} diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_forward_production_test.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_forward_production_test.go new file mode 100644 index 00000000..ca21038c --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_forward_production_test.go @@ -0,0 +1,253 @@ +package voice + +import ( + "context" + "fmt" + "net" + "strings" + "sync" + "testing" + "time" + + "github.com/emiago/sipgo" + "github.com/emiago/sipgo/sip" + "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" + "github.com/iniwex5/vowifi-go/internal/vowifi/voiceclient" +) + +type inboundLocalTransaction struct { + responses chan *sip.Response + done chan struct{} + once sync.Once +} + +func (t *inboundLocalTransaction) Terminate() { + t.once.Do(func() { close(t.done) }) +} + +func (t *inboundLocalTransaction) OnTerminate(sip.FnTxTerminate) bool { return true } +func (t *inboundLocalTransaction) Done() <-chan struct{} { return t.done } +func (t *inboundLocalTransaction) Err() error { return nil } +func (t *inboundLocalTransaction) Responses() <-chan *sip.Response { return t.responses } +func (t *inboundLocalTransaction) OnRetransmission(sip.FnTxResponse) bool { + return true +} + +type inboundLocalRequest struct { + request *sip.Request + transaction *inboundLocalTransaction +} + +type inboundLocalRequester struct { + requests chan inboundLocalRequest +} + +func (r *inboundLocalRequester) Request( + _ context.Context, + request *sip.Request, +) (sip.ClientTransaction, error) { + captured := inboundLocalRequest{request: request.Clone()} + if request.Method == sip.INVITE { + captured.transaction = &inboundLocalTransaction{ + responses: make(chan *sip.Response, 4), done: make(chan struct{}), + } + } + r.requests <- captured + return captured.transaction, nil +} + +type inboundLocalAdapter struct { + client *sipgo.Client + ua *sipgo.UserAgent + online chan struct{} +} + +var _ voiceclient.Adapter = (*inboundLocalAdapter)(nil) + +func (a *inboundLocalAdapter) GetClient() *sipgo.Client { return a.client } +func (a *inboundLocalAdapter) GetClientContact(string) (string, string, string, error) { + return "sip:placeholder@127.0.0.1:5072", "127.0.0.1:5072", "client", nil +} +func (a *inboundLocalAdapter) GetExternalIP() string { return "127.0.0.1" } +func (a *inboundLocalAdapter) GetListenAddr() string { return "127.0.0.1:5070" } +func (a *inboundLocalAdapter) GetUA() *sipgo.UserAgent { return a.ua } +func (a *inboundLocalAdapter) RTPPortRange() (int, int) { return 10000, 20000 } +func (a *inboundLocalAdapter) SendPushNotification(string, string, string, string) error { + return nil +} +func (a *inboundLocalAdapter) SubscribeDeviceOnline(string) <-chan struct{} { return a.online } + +type originalInboundAgentAPI interface { + OnIMSInvite(*sip.Request, *imsendpoint.Session, imsendpoint.ServerInviteHandle) + HandleIMSByeEvent(imsendpoint.Event) + HandleIMSCancelEvent(imsendpoint.Event) + HandleIMSUpdateEvent(imsendpoint.Event) +} + +type originalInboundGatewayAPI interface { + OnIMSInvite(string, []byte, *imsendpoint.Session) +} + +var _ originalInboundAgentAPI = (*Agent)(nil) +var _ originalInboundGatewayAPI = (*Gateway)(nil) + +func TestInboundNetworkCallForwardsToLocalClientAndClosesBothDialogs(t *testing.T) { + registrar := startInboundDialogRegistrar(t) + agent := newVoiceTestAgent(t, registrar.conn) + requester := installInboundLocalAdapter(t, agent) + if err := agent.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = agent.Stop() }) + + clientAddr := registrar.waitClient(t) + imsPeer := listenVoiceUDP(t) + clientPeer := listenVoiceUDP(t) + callID := "inbound-local-forward" + sendInboundWireRequest(t, registrar, clientAddr, + inboundNetworkInvite(registrar.conn.LocalAddr().String(), callID, + voiceSDP(imsPeer.LocalAddr().(*net.UDPAddr).Port))) + _ = registrar.waitStatus(t, 100) + provisional := registrar.waitStatus(t, 180) + + invite := waitInboundLocalRequest(t, requester, sip.INVITE) + assertInboundLocalInvite(t, invite.request, callID) + response := sip.NewResponseFromRequest(invite.request, 200, "OK", + []byte(voiceSDP(clientPeer.LocalAddr().(*net.UDPAddr).Port))) + response.To().Params.Add("tag", "local-client") + response.AppendHeader(&sip.ContactHeader{Address: sip.Uri{ + Scheme: "sip", User: "client", Host: "127.0.0.1", Port: 5072, + }}) + response.AppendHeader(sip.NewHeader("Content-Type", "application/sdp")) + invite.transaction.responses <- response + + ack := waitInboundLocalRequest(t, requester, sip.ACK) + if ack.request.CSeq() == nil || ack.request.CSeq().SeqNo != 1 { + t.Fatalf("local ACK CSeq = %#v", ack.request.CSeq()) + } + accepted := registrar.waitStatus(t, 200) + if voiceHeaderTag(voiceTestHeader(accepted, "To")) != + voiceHeaderTag(voiceTestHeader(provisional, "To")) { + t.Fatal("IMS provisional and accepted responses used different To tags") + } + sendInboundWireRequest(t, registrar, clientAddr, + inboundNetworkACK(registrar.conn.LocalAddr().String(), callID, voiceTestHeader(accepted, "To"))) + sendInboundWireRequest(t, registrar, clientAddr, + inboundNetworkBYE(registrar.conn.LocalAddr().String(), callID, voiceTestHeader(accepted, "To"))) + _ = registrar.waitResponse(t, func(raw string) bool { + return strings.HasPrefix(raw, "SIP/2.0 200 ") && + strings.HasSuffix(voiceTestHeader(raw, "CSeq"), " BYE") + }, "BYE 200") + bye := waitInboundLocalRequest(t, requester, sip.BYE) + if bye.request.CSeq() == nil || bye.request.CSeq().SeqNo != 2 { + t.Fatalf("local BYE CSeq = %#v", bye.request.CSeq()) + } + waitForAgentIdle(t, agent) +} + +func TestInboundNetworkCancelForwardsToLocalClient(t *testing.T) { + registrar := startInboundDialogRegistrar(t) + agent := newVoiceTestAgent(t, registrar.conn) + requester := installInboundLocalAdapter(t, agent) + if err := agent.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = agent.Stop() }) + + clientAddr := registrar.waitClient(t) + imsPeer := listenVoiceUDP(t) + callID := "inbound-local-cancel" + sendInboundWireRequest(t, registrar, clientAddr, + inboundNetworkInvite(registrar.conn.LocalAddr().String(), callID, + voiceSDP(imsPeer.LocalAddr().(*net.UDPAddr).Port))) + _ = registrar.waitStatus(t, 100) + provisional := registrar.waitStatus(t, 180) + invite := waitInboundLocalRequest(t, requester, sip.INVITE) + + sendInboundWireRequest(t, registrar, clientAddr, + inboundNetworkCancel(registrar.conn.LocalAddr().String(), callID, voiceTestHeader(provisional, "To"))) + cancel := waitInboundLocalRequest(t, requester, sip.CANCEL) + if cancel.request.CSeq() == nil || invite.request.CSeq() == nil || + cancel.request.CSeq().SeqNo != invite.request.CSeq().SeqNo { + t.Fatalf("local CANCEL CSeq=%#v INVITE CSeq=%#v", cancel.request.CSeq(), invite.request.CSeq()) + } + _ = registrar.waitResponse(t, func(raw string) bool { + return strings.HasPrefix(raw, "SIP/2.0 200 ") && + strings.HasSuffix(voiceTestHeader(raw, "CSeq"), " CANCEL") + }, "CANCEL 200") + _ = registrar.waitStatus(t, 487) + waitForAgentIdle(t, agent) +} + +func installInboundLocalAdapter(t *testing.T, agent *Agent) *inboundLocalRequester { + t.Helper() + ua, err := sipgo.NewUA(sipgo.WithUserAgent("inbound-local-test")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ua.Close() }) + client, err := sipgo.NewClient(ua) + if err != nil { + t.Fatal(err) + } + requester := &inboundLocalRequester{requests: make(chan inboundLocalRequest, 8)} + client.TxRequester = requester + agent.SetClientAdapter(&inboundLocalAdapter{ + client: client, ua: ua, online: make(chan struct{}), + }) + return requester +} + +func waitInboundLocalRequest( + t *testing.T, + requester *inboundLocalRequester, + method sip.RequestMethod, +) inboundLocalRequest { + t.Helper() + deadline := time.After(2 * time.Second) + for { + select { + case request := <-requester.requests: + if request.request != nil && request.request.Method == method { + return request + } + case <-deadline: + t.Fatalf("local client did not receive %s", method) + } + } +} + +func assertInboundLocalInvite(t *testing.T, request *sip.Request, imsCallID string) { + t.Helper() + if request == nil || request.Method != sip.INVITE { + t.Fatalf("local INVITE = %#v", request) + } + if request.Recipient.User != "client" || request.Destination() != "127.0.0.1:5072" { + t.Fatalf("local target = %s destination=%q", request.Recipient.String(), request.Destination()) + } + if request.CallID() == nil || !strings.HasPrefix(request.CallID().Value(), imsCallID+"-") { + t.Fatalf("local Call-ID = %#v", request.CallID()) + } + if request.ContentType() == nil || request.ContentType().Value() != "application/sdp" || len(request.Body()) == 0 { + t.Fatal("local INVITE is missing the relayed SDP offer") + } +} + +func sendInboundWireRequest( + t *testing.T, + registrar *inboundDialogRegistrar, + destination *net.UDPAddr, + request string, +) { + t.Helper() + if _, err := registrar.conn.WriteToUDP([]byte(request), destination); err != nil { + t.Fatal(err) + } +} + +func inboundNetworkBYE(localAddr, callID, to string) string { + return fmt.Sprintf( + "BYE sip:user@ims.example.com SIP/2.0\r\nVia: SIP/2.0/UDP %s;rport;branch=z9hG4bK-bye-28\r\nFrom: ;tag=remote-28\r\nTo: %s\r\nCall-ID: %s\r\nCSeq: 2 BYE\r\nContent-Length: 0\r\n\r\n", + localAddr, to, callID, + ) +} diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_legacy_helpers.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_legacy_helpers.go new file mode 100644 index 00000000..81976462 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_legacy_helpers.go @@ -0,0 +1,102 @@ +package voice + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/emiago/sipgo/sip" + "github.com/iniwex5/vowifi-go/internal/vowifi/imscore" + "github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint" + "github.com/iniwex5/vowifi-go/internal/vowifi/logging" +) + +var ( + errInboundCallUnavailable = errors.New("voice: inbound call is unavailable") + errInboundResponseUnavailable = errors.New("voice: inbound INVITE response context is unavailable") +) + +func (a *Agent) rejectBusy( + request *sip.Request, + session *imsendpoint.Session, + handle imsendpoint.ServerInviteHandle, +) { + if a == nil || request == nil || handle == nil { + return + } + call := NewCallFromRequest(a.deviceID, request, session) + call.agent = a + call.setServerInvite(handle, request) + call.DialogState.ToTag = voiceTag() + a.sendStatusResponse(486, "Busy Here", call) +} + +func (a *Agent) sendStatusResponse(status int, reason string, call *Call) { + if err := a.sendStatusResponseResult(status, reason, call); err != nil { + logging.WarnRate("voice-status-response:"+callIDValue(call), voiceActorEventLogInterval, + "voice status response failed", "device", a.DeviceID(), "call_id", callIDValue(call), + "status", status, "err", err) + } +} + +func (a *Agent) sendStatusResponseResult(status int, reason string, call *Call) error { + if call == nil { + return errInboundCallUnavailable + } + structured, err := a.rejectStoredServerInviteWithReason(call, status, reason) + if structured || err != nil { + return err + } + responder := call.inboundResponseWriter() + if responder == nil { + return errInboundResponseUnavailable + } + return responder.Respond(imscore.InboundVoiceResponse{ + StatusCode: status, ToTag: call.inboundLocalTagValue(), + }) +} + +func (a *Agent) sendStatusResponseWithSDP( + status int, + reason string, + call *Call, + sdp string, +) { + if status < 200 || status >= 300 { + a.sendStatusResponse(status, reason, call) + return + } + if _, err := a.answerStoredServerInviteResult(call, serverInviteAnswer{ + status: status, reason: reason, sdp: sdp, + }); err != nil { + logging.WarnRate("voice-sdp-response:"+callIDValue(call), voiceActorEventLogInterval, + "voice SDP response failed", "device", a.DeviceID(), "call_id", callIDValue(call), + "status", status, "err", err) + } +} + +func (a *Agent) sendIMSBye(call *Call) { + if a == nil || call == nil || call.IMSDialogValue() == nil { + return + } + go func() { + ctx, cancel := context.WithTimeout(context.Background(), voiceHangupTimeout) + defer cancel() + response, err := a.sendCallDialogRequest(ctx, call, BuildIMSBye(a, call)) + if err == nil && (response.StatusCode < 200 || response.StatusCode >= 300) { + err = fmt.Errorf("voice: IMS BYE rejected: %d %s", response.StatusCode, response.Reason) + } + if err != nil { + logging.WarnRate("voice-ims-bye:"+call.CallID(), voiceActorEventLogInterval, + "voice IMS BYE failed", "device", a.DeviceID(), "call_id", call.CallID(), "err", err) + } + }() +} + +func callIDValue(call *Call) string { + if call == nil { + return "" + } + return strings.TrimSpace(call.CallID()) +} diff --git a/third_party/vowifi-go/internal/vowifi/voice/inbound_runtime.go b/third_party/vowifi-go/internal/vowifi/voice/inbound_runtime.go index 61a869b1..df5f3aa5 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/inbound_runtime.go +++ b/third_party/vowifi-go/internal/vowifi/voice/inbound_runtime.go @@ -75,6 +75,10 @@ func (a *Agent) HandleInboundVoiceRequest(request imscore.InboundVoiceRequest) ( func (a *Agent) handleInboundInvite(request imscore.InboundVoiceRequest, call *Call) (imscore.InboundVoiceResult, error) { if call != nil { + if call.CallDirection() == callstate.DirectionInbound && call.CallState() == callstate.StateAlerting { + a.maybeStartInboundClient(call) + return voiceResult(0), nil + } return a.handleReinvite(request, call) } if strings.TrimSpace(request.CallID) == "" || voiceHeaderURI(request.From) == "" || voiceHeaderURI(request.To) == "" { @@ -83,14 +87,19 @@ func (a *Agent) handleInboundInvite(request imscore.InboundVoiceRequest, call *C if !isVoiceSDPContentType(request.ContentType) { return voiceResult(415), nil } - if request.Responder == nil { + if request.Responder == nil && request.ServerInvite == nil { return voiceResult(500), errors.New("voice: inbound INVITE reply path is unavailable") } + var created bool var err error - call, err = a.reserveInboundCall(request) + call, created, err = a.reserveInboundCall(request) if err != nil { return voiceResult(486), nil } + if !created { + a.maybeStartInboundClient(call) + return voiceResult(0), nil + } status, err := a.beginInboundInvite(call, request) if status != 0 || err != nil { return voiceResult(status), err @@ -98,6 +107,7 @@ func (a *Agent) handleInboundInvite(request imscore.InboundVoiceRequest, call *C a.emitIncomingCall(call) a.emitCallRinging(call) a.notifyIncomingCall(call) + a.maybeStartInboundClient(call) return voiceResult(0), nil } @@ -107,7 +117,16 @@ func (a *Agent) beginInboundInvite(call *Call, request imscore.InboundVoiceReque call.SetStartTime(time.Now()) call.setInboundRequest(request.Responder) call.setServerInvite(request.ServerInvite, request.Request) + if call.ClientCallID() == "" { + call.SetClientCallID(call.CallID() + "-" + voiceHex(16)) + } call.applyVoiceSessionExpires(request.SessionExpires) + if request.ServerInvite != nil { + if _, err := a.rejectStoredServerInvite(call, 100); err != nil { + a.releaseInboundCall(call, err, false) + return 0, err + } + } if err := a.prepareInboundVoiceDialog(call, request); err != nil { a.releaseInboundCall(call, err, false) return 500, err @@ -116,14 +135,22 @@ func (a *Agent) beginInboundInvite(call *Call, request imscore.InboundVoiceReque a.releaseInboundCall(call, err, false) return 488, nil } - if err := request.Responder.Respond(imscore.InboundVoiceResponse{StatusCode: 180}); err != nil { + if err := a.respondInboundProvisional(call, 180); err != nil { a.releaseInboundCall(call, err, false) return 0, err } + call.markInboundPrepared() a.startInboundNoAnswerTimer(call) return 0, nil } +func (a *Agent) respondInboundProvisional(call *Call, status int) error { + if call == nil { + return errInboundCallUnavailable + } + return a.sendStatusResponseResult(status, imscore.SIPStatusText(status), call) +} + func (a *Agent) handleInboundCancel(request imscore.InboundVoiceRequest, call *Call) (imscore.InboundVoiceResult, error) { if call == nil { return voiceResult(481), nil @@ -134,21 +161,22 @@ func (a *Agent) handleInboundCancel(request imscore.InboundVoiceRequest, call *C return voiceResult(481), nil } responder := call.inboundResponseWriter() - if responder == nil { + if responder == nil && !call.hasServerInvite() { return voiceResult(500), errors.New("voice: inbound INVITE response context is unavailable") } if request.Responder == nil { return voiceResult(500), errors.New("voice: CANCEL reply path is unavailable") } cancelErr := request.Responder.Respond(imscore.InboundVoiceResponse{ - StatusCode: 200, ToTag: responder.LocalTag(), + StatusCode: 200, ToTag: call.inboundLocalTagValue(), }) structured, inviteErr := a.rejectStoredServerInvite(call, 487) - if !structured { + if !structured && responder != nil { inviteErr = responder.Respond(imscore.InboundVoiceResponse{StatusCode: 487}) } + clientErr := a.sendClientCancel(call) a.releaseInboundCall(call, errors.New("voice: call canceled by IMS"), true) - return voiceResult(0), errors.Join(cancelErr, inviteErr) + return voiceResult(0), errors.Join(cancelErr, inviteErr, clientErr) } func (a *Agent) handleInboundUpdate(request imscore.InboundVoiceRequest, call *Call) (imscore.InboundVoiceResult, error) { diff --git a/third_party/vowifi-go/internal/vowifi/voice/methods.go b/third_party/vowifi-go/internal/vowifi/voice/methods.go index 079bdbfb..1f06daf8 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/methods.go +++ b/third_party/vowifi-go/internal/vowifi/voice/methods.go @@ -257,17 +257,6 @@ func (a *Agent) HandleClientPrack(callID string) error { return errors.New("voice: PRACK requires the reliable provisional response context") } -// --- IMS event handlers --- - -// OnIMSInvite handles an incoming INVITE from the IMS network. -func (a *Agent) OnIMSInvite(peer, callID string, sdp string) *Call { - call := NewCallFromRequestForAgent(a, peer, callID) - _, _ = ProcessIncomingIMSSDP(sdp) - a.emitIncomingCall(call) - a.emitCallRinging(call) - return call -} - // OnIMSBye handles a BYE from the IMS network. func (a *Agent) OnIMSBye(callID string) error { if a == nil { @@ -288,15 +277,16 @@ func (a *Agent) OnIMSBye(callID string) error { } func (a *Agent) finishRemoteBye(call *Call) error { + clientErr := a.sendClientBye(call) _ = call.TransitionChecked(callstate.StateDisconnected) _ = call.TransitionChecked(callstate.StateEnded) _ = call.StopMedia() _ = call.EnsureTimerStopped() - call.SetIMSDialog(nil) + closeErr := a.closeCallDialog(context.Background(), call) call.CloseDone() a.emitCallEnded(call, "remote_bye") a.finalizeActiveCall(call) - return nil + return errors.Join(clientErr, closeErr) } // OnIMSCancel handles a CANCEL from the IMS network. @@ -310,13 +300,9 @@ func (a *Agent) OnIMSCancel(callID string) error { if call == nil { return errors.New("voice: call not found") } - _ = call.TransitionChecked(callstate.StateFailed) - _ = call.StopMedia() - _ = call.EnsureTimerStopped() - call.CloseDone() - a.emitCallCanceled(call, "remote_cancel") - a.finalizeActiveCall(call) - return nil + clientErr := a.sendClientCancel(call) + a.releaseInboundCall(call, errors.New("voice: call canceled by IMS"), true) + return clientErr } // OnIMSUpdate handles a re-INVITE/UPDATE from the IMS network. @@ -349,15 +335,6 @@ func (a *Agent) applyIMSUpdate(call *Call) error { return nil } -// HandleIMSByeEvent handles an IMS BYE event. -func (a *Agent) HandleIMSByeEvent(callID string) error { return a.OnIMSBye(callID) } - -// HandleIMSCancelEvent handles an IMS CANCEL event. -func (a *Agent) HandleIMSCancelEvent(callID string) error { return a.OnIMSCancel(callID) } - -// HandleIMSUpdateEvent handles an IMS UPDATE event. -func (a *Agent) HandleIMSUpdateEvent(callID string) error { return a.OnIMSUpdate(callID) } - // --- Wiring --- // ReplaceIMSProvider swaps the IMS service. diff --git a/third_party/vowifi-go/internal/vowifi/voice/types.go b/third_party/vowifi-go/internal/vowifi/voice/types.go index 8f6454da..2ade124c 100644 --- a/third_party/vowifi-go/internal/vowifi/voice/types.go +++ b/third_party/vowifi-go/internal/vowifi/voice/types.go @@ -44,6 +44,7 @@ type Agent struct { clientAdapter voiceclient.Adapter clientBridge *client.Bridge eventDispatcher interface{ Dispatch(interface{}) } + imsUnsubscribe func() } // Call is one voice call (inbound or outbound). @@ -105,6 +106,13 @@ type Call struct { localCancelSent bool reliableProvisional bool outboundCancelReason string + clientInviteRequest *sip.Request + clientInviteResponse *sip.Response + inboundClientStarted bool + inboundPrepared bool + inboundClientBridge *client.Bridge + clientCancelSent bool + clientByeSent bool } // Gateway bridges the local client (LAN side) to the IMS network. It owns