From ca0ddedcdf559b513becbd6e50700ef5290683ce Mon Sep 17 00:00:00 2001 From: yibaiba <946100224@qq.com> Date: Mon, 10 Aug 2026 10:24:48 +0800 Subject: [PATCH] [restore-vowifi-25.08] restore outbound mode execution --- .../internal/vowifi/imscore/outbound_mode.go | 219 ++++++++++++++++++ .../vowifi/imscore/outbound_mode_context.go | 47 ++-- .../vowifi/imscore/outbound_mode_test.go | 161 +++++++++++++ .../imscore/outbound_request_dispatcher.go | 4 +- .../internal/vowifi/imscore/retry.go | 33 ++- 5 files changed, 437 insertions(+), 27 deletions(-) create mode 100644 third_party/vowifi-go/internal/vowifi/imscore/outbound_mode.go create mode 100644 third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_test.go diff --git a/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode.go b/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode.go new file mode 100644 index 00000000..2c46a286 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode.go @@ -0,0 +1,219 @@ +package imscore + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "strconv" + "strings" + "time" + + "github.com/emiago/sipgo/sip" + "github.com/iniwex5/vowifi-go/internal/vowifi/policy" +) + +const outboundDirectWriteTimeout = 5 * time.Second + +var errIMSSignalingRuntimeNotReady = errors.New("IMS signaling runtime not ready") + +type directTCPWriteOptions struct { + Context context.Context + Conn net.Conn + Payload []byte + Timeout time.Duration +} + +type outboundSendOperation struct { + Context context.Context + Mode outboundModeContext + Request *sip.Request + Timeout time.Duration +} + +func transportForRequest(configuredTransport, securityMode string, method sip.RequestMethod) string { + transport := strings.ToUpper(policy.NormalizeIMSTransport(configuredTransport)) + protected := normalizeSecurityMode(securityMode) == securityModeIPSec + if transport == "AUTO" { + if protected { + return "TCP" + } + return "UDP" + } + if protected && (method == sip.OPTIONS || method == sip.SUBSCRIBE) { + return "TCP" + } + if transport == "" { + return "TCP" + } + return transport +} + +func signalingRuntimeNotReadyError(reason string) error { + reason = strings.TrimSpace(reason) + if reason == "" { + reason = "unknown" + } + return fmt.Errorf("%w: %s", errIMSSignalingRuntimeNotReady, reason) +} + +func destinationFromContext(modeCtx outboundModeContext) string { + if modeCtx.TCPConn != nil && modeCtx.TCPConn.RemoteAddr() != nil { + return modeCtx.TCPConn.RemoteAddr().String() + } + host := strings.Trim(strings.TrimSpace(modeCtx.RemoteIP), "[]") + if host == "" || modeCtx.RemotePortS < 1 { + return "" + } + return net.JoinHostPort(host, strconv.Itoa(modeCtx.RemotePortS)) +} + +func modeContextErrorFields(err error) (code, message string) { + if err == nil { + return "", "" + } + code = outboundResolveErrorCode(err) + if code == "" { + code = "unknown" + } + return code, strings.TrimSpace(err.Error()) +} + +func sendDirectTCPSafe(options directTCPWriteOptions) error { + if options.Conn == nil { + return errors.New("TCPConn is nil for direct write") + } + deadline, err := outboundWriteDeadline(options.Context, options.Timeout) + if err != nil { + return err + } + if err := options.Conn.SetWriteDeadline(deadline); err != nil { + return err + } + defer func() { _ = options.Conn.SetWriteDeadline(time.Time{}) }() + written, err := options.Conn.Write(options.Payload) + if err != nil { + return outboundWriteError(options.Context, err) + } + if written != len(options.Payload) { + return io.ErrShortWrite + } + return nil +} + +func sendDirectWrite(ctx context.Context, modeCtx outboundModeContext, raw string) error { + payload := []byte(raw) + if modeCtx.TCPConn != nil { + return sendDirectTCPSafe(directTCPWriteOptions{ + Context: ctx, Conn: modeCtx.TCPConn, Payload: payload, Timeout: outboundDirectWriteTimeout, + }) + } + if modeCtx.UDPConn == nil { + return errors.New("no direct write channel available") + } + destination := destinationFromContext(modeCtx) + remote, err := net.ResolveUDPAddr("udp", destination) + if err != nil { + return err + } + deadline, err := outboundWriteDeadline(ctx, outboundDirectWriteTimeout) + if err != nil { + return err + } + if err := modeCtx.UDPConn.SetWriteDeadline(deadline); err != nil { + return err + } + defer func() { _ = modeCtx.UDPConn.SetWriteDeadline(time.Time{}) }() + _, err = modeCtx.UDPConn.WriteTo(payload, remote) + return outboundWriteError(ctx, err) +} + +func outboundWriteDeadline(ctx context.Context, timeout time.Duration) (time.Time, error) { + if timeout <= 0 { + timeout = outboundDirectWriteTimeout + } + deadline := time.Now().Add(timeout) + if ctx == nil { + return deadline, nil + } + if err := ctx.Err(); err != nil { + return time.Time{}, fmt.Errorf("%w: %v", err, err) + } + if contextDeadline, ok := ctx.Deadline(); ok && contextDeadline.Before(deadline) { + deadline = contextDeadline + } + return deadline, nil +} + +func outboundWriteError(ctx context.Context, err error) error { + if err == nil { + return nil + } + if ctx != nil && ctx.Err() != nil { + return fmt.Errorf("%w: %v", ctx.Err(), err) + } + return err +} + +func (s *Service) writeStatelessWithSipgo( + ctx context.Context, + modeCtx outboundModeContext, + req *sip.Request, +) error { + if req == nil { + return errors.New("request 为空") + } + if !modeCtx.SignalingReady && modeCtx.Mode != "external" { + return signalingRuntimeNotReadyError(modeCtx.SignalingNotReadyReason) + } + built, err := s.buildOutboundRequest(req) + if err != nil { + return err + } + setOutboundDestination(built, modeCtx) + if modeCtx.Client != nil { + return modeCtx.Client.WriteRequest(built) + } + if modeCtx.send == nil { + return errors.New("outbound client 为空") + } + return modeCtx.send(ctx, built.String()) +} + +func (s *Service) sendByMode(operation outboundSendOperation) (*sipResponse, error) { + if operation.Request == nil { + return nil, errors.New("request 为空") + } + if operation.Timeout <= 0 && operation.Request.Method == sip.MESSAGE { + return nil, s.writeStatelessWithSipgo(operation.Context, operation.Mode, operation.Request) + } + built, err := s.buildOutboundRequest(operation.Request) + if err != nil { + return nil, err + } + setOutboundDestination(built, operation.Mode) + if operation.Mode.Client != nil { + response, err := operation.Mode.Client.Do(operation.Context, built) + if err != nil { + return nil, err + } + return newSIPResponse(response), nil + } + if operation.Mode.send == nil { + return nil, newOutboundModeResolveError( + "missing_direct_sender", "no direct sender for %s", destinationFromContext(operation.Mode), + ) + } + sender := func(raw string) error { return operation.Mode.send(operation.Context, raw) } + return s.transport.roundTripWithSender(operation.Context, built.String(), sender) +} + +func setOutboundDestination(request *sip.Request, modeCtx outboundModeContext) { + if request == nil { + return + } + if destination := destinationFromContext(modeCtx); destination != "" { + request.SetDestination(destination) + } +} diff --git a/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_context.go b/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_context.go index 9a296671..a2ff3303 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_context.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_context.go @@ -1,8 +1,8 @@ package imscore import ( + "context" "errors" - "fmt" "net" "strconv" "strings" @@ -39,7 +39,7 @@ type outboundModeContext struct { UDPConn net.PacketConn Client *sipgo.Client SkipGenericRawLog bool - send func(string) error + send func(context.Context, string) error } func (s *Service) resolveOutboundModeContext( @@ -47,7 +47,9 @@ func (s *Service) resolveOutboundModeContext( req *sip.Request, ) (outboundModeContext, error) { if s == nil || s.transport == nil { - return outboundModeContext{}, newOutboundModeResolveError("missing_sip_transport") + return outboundModeContext{}, newOutboundModeResolveError( + "missing_sip_transport", "outbound transport layer 为空", + ) } if req == nil { return outboundModeContext{}, errors.New("imscore: nil outbound request") @@ -56,19 +58,25 @@ func (s *Service) resolveOutboundModeContext( s.mu.RLock() defer s.mu.RUnlock() if s.cfg == nil { - return outboundModeContext{}, newOutboundModeResolveError("missing_ims_config") + return outboundModeContext{}, newOutboundModeResolveError( + "missing_ims_config", "IMS config 为空", + ) } modeCtx := s.outboundModeSnapshotLocked(flow, req, pani) sender := s.outboundSenderLocked(&modeCtx) if sender == nil { - return outboundModeContext{}, newOutboundModeResolveError("missing_direct_sender") + return outboundModeContext{}, newOutboundModeResolveError( + "missing_direct_sender", "no direct sender for %s", destinationFromContext(modeCtx), + ) } if modeCtx.IPSec3GPP && !modeCtx.SignalingReady && modeCtx.Mode != "external" { reason := strings.TrimSpace(modeCtx.SignalingNotReadyReason) if reason == "" { reason = "signaling_not_ready" } - return outboundModeContext{}, newOutboundModeResolveError(reason) + return outboundModeContext{}, newOutboundModeResolveError( + "signaling_not_ready", "resolve outbound mode: %w", signalingRuntimeNotReadyError(reason), + ) } modeCtx.send = sender return modeCtx, nil @@ -93,7 +101,7 @@ func (s *Service) outboundModeSnapshotLocked( LocalPortC: s.protectedClientPort, LocalPortS: s.protectedServerPort, Registrar: strings.TrimSpace(s.registrar), ServiceRoute: route.serviceRoute, RouteHeader: route.serviceRoute, SecVerify: route.securityVerify, - PANI: pani, Transport: strings.ToLower(strings.TrimSpace(req.Transport())), + PANI: pani, Transport: transportForRequest(cfg.Transport, s.effectiveSecurityModeLocked(), req.Method), TCPConn: s.registrationTCP, UDPConn: s.registrationIO, } if modeCtx.LocalHost == "" { @@ -130,25 +138,26 @@ func (s *Service) populateOutboundRemoteLocked(modeCtx *outboundModeContext) { modeCtx.Mode = "external" } -func (s *Service) outboundSenderLocked(modeCtx *outboundModeContext) func(string) error { +func (s *Service) outboundSenderLocked(modeCtx *outboundModeContext) func(context.Context, string) error { if modeCtx.TCPConn != nil { - conn := modeCtx.TCPConn - return func(raw string) error { return s.writeSIPStream(conn, raw) } + snapshot := *modeCtx + return func(ctx context.Context, raw string) error { + s.sipWriteMu.Lock() + defer s.sipWriteMu.Unlock() + return sendDirectWrite(ctx, snapshot, raw) + } } if modeCtx.UDPConn != nil && s.registrationRemote != nil { - packet := modeCtx.UDPConn - remote := cloneUDPAddr(s.registrationRemote) - return func(raw string) error { - if _, err := packet.WriteTo([]byte(raw), remote); err != nil { - return fmt.Errorf("imscore: write SIP datagram: %w", err) - } - return nil - } + snapshot := *modeCtx + return func(ctx context.Context, raw string) error { return sendDirectWrite(ctx, snapshot, raw) } } s.transport.mu.Lock() sender := s.transport.sendFn s.transport.mu.Unlock() - return sender + if sender == nil { + return nil + } + return func(_ context.Context, raw string) error { return sender(raw) } } func cloneOutboundIMSConfig(source *IMSConfig) IMSConfig { diff --git a/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_test.go b/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_test.go new file mode 100644 index 00000000..a210a045 --- /dev/null +++ b/third_party/vowifi-go/internal/vowifi/imscore/outbound_mode_test.go @@ -0,0 +1,161 @@ +package imscore + +import ( + "context" + "errors" + "io" + "net" + "strings" + "sync" + "testing" + "time" + + "github.com/emiago/sipgo/sip" +) + +func TestOutboundModeResolveErrorPreservesCodeAndCause(t *testing.T) { + cause := errors.New("transport unavailable") + err := newOutboundModeResolveError("missing_transport", "resolve mode: %w", cause) + if got := outboundResolveErrorCode(err); got != "missing_transport" { + t.Fatalf("resolve code = %q", got) + } + if !errors.Is(err, cause) || err.Error() != "resolve mode: transport unavailable" { + t.Fatalf("resolve error = %v", err) + } + code, message := modeContextErrorFields(err) + if code != "missing_transport" || message != err.Error() { + t.Fatalf("error fields = %q, %q", code, message) + } +} + +func TestTransportForRequestMatchesRecoveredSelection(t *testing.T) { + tests := []struct { + configured string + security string + method sip.RequestMethod + want string + }{ + {configured: "auto", security: securityModePlain, method: sip.MESSAGE, want: "UDP"}, + {configured: "auto", security: securityModeIPSec, method: sip.MESSAGE, want: "TCP"}, + {configured: "udp", security: securityModeIPSec, method: sip.OPTIONS, want: "TCP"}, + {configured: "udp", security: securityModeIPSec, method: sip.SUBSCRIBE, want: "TCP"}, + {configured: "udp", security: securityModeIPSec, method: sip.MESSAGE, want: "UDP"}, + {configured: "tcp", security: securityModePlain, method: sip.MESSAGE, want: "TCP"}, + } + for _, test := range tests { + if got := transportForRequest(test.configured, test.security, test.method); got != test.want { + t.Errorf("transportForRequest(%q, %q, %s) = %q, want %q", + test.configured, test.security, test.method, got, test.want) + } + } +} + +func TestSendDirectTCPSafeUsesContextDeadlineAndClearsIt(t *testing.T) { + client, peer := net.Pipe() + t.Cleanup(func() { _ = client.Close() }) + t.Cleanup(func() { _ = peer.Close() }) + tracked := &writeDeadlineConn{Conn: client} + payload := []byte("OPTIONS sip:ims.example SIP/2.0\r\n\r\n") + readDone := make(chan error, 1) + go func() { + received := make([]byte, len(payload)) + _, err := io.ReadFull(peer, received) + if err == nil && string(received) != string(payload) { + err = errors.New("direct TCP payload mismatch") + } + readDone <- err + }() + + ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) + defer cancel() + if err := sendDirectTCPSafe(directTCPWriteOptions{ + Context: ctx, Conn: tracked, Payload: payload, Timeout: outboundDirectWriteTimeout, + }); err != nil { + t.Fatal(err) + } + if err := <-readDone; err != nil { + t.Fatal(err) + } + deadlines := tracked.snapshotDeadlines() + if len(deadlines) != 2 || deadlines[0].IsZero() || !deadlines[1].IsZero() { + t.Fatalf("write deadlines = %v", deadlines) + } + contextDeadline, _ := ctx.Deadline() + if deadlines[0].After(contextDeadline) { + t.Fatalf("write deadline %s exceeds context deadline %s", deadlines[0], contextDeadline) + } +} + +func TestSendDirectWriteExposesMissingChannelAndCanceledContext(t *testing.T) { + err := sendDirectWrite(context.Background(), outboundModeContext{}, "MESSAGE sip:x SIP/2.0\r\n\r\n") + if err == nil || err.Error() != "no direct write channel available" { + t.Fatalf("missing channel error = %v", err) + } + client, peer := net.Pipe() + defer client.Close() + defer peer.Close() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + err = sendDirectWrite(ctx, outboundModeContext{TCPConn: client}, "MESSAGE sip:x SIP/2.0\r\n\r\n") + if !errors.Is(err, context.Canceled) { + t.Fatalf("canceled direct write error = %v", err) + } +} + +func TestWriteStatelessWithSipgoUsesResolvedExternalSender(t *testing.T) { + service, err := New(&IMSConfig{}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(service.Stop) + request := parsedDispatchRequest(t, "stateless-message", 1) + originalDestination := request.Destination() + var sent string + modeCtx := outboundModeContext{ + Mode: "external", SignalingReady: true, RemoteIP: "192.0.2.44", RemotePortS: 5060, + send: func(_ context.Context, raw string) error { + sent = raw + return nil + }, + } + if err := service.writeStatelessWithSipgo(context.Background(), modeCtx, request); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(sent, "MESSAGE ") || rawSIPHeaderValue(sent, "Call-ID") != "stateless-message" { + t.Fatalf("stateless request = %q", sent) + } + if request.Destination() != originalDestination { + t.Fatalf("source request destination changed from %q to %q", originalDestination, request.Destination()) + } +} + +func TestSetOutboundDestinationUsesSnapshotWithoutMutatingEmptyDestination(t *testing.T) { + request := parsedDispatchRequest(t, "destination-snapshot", 1) + setOutboundDestination(request, outboundModeContext{RemoteIP: "2001:db8::44", RemotePortS: 5070}) + if got := request.Destination(); got != "[2001:db8::44]:5070" { + t.Fatalf("destination = %q", got) + } + setOutboundDestination(request, outboundModeContext{}) + if got := request.Destination(); got != "[2001:db8::44]:5070" { + t.Fatalf("empty snapshot changed destination to %q", got) + } +} + +type writeDeadlineConn struct { + net.Conn + mu sync.Mutex + deadlines []time.Time +} + +func (conn *writeDeadlineConn) SetWriteDeadline(deadline time.Time) error { + conn.mu.Lock() + conn.deadlines = append(conn.deadlines, deadline) + conn.mu.Unlock() + return conn.Conn.SetWriteDeadline(deadline) +} + +func (conn *writeDeadlineConn) snapshotDeadlines() []time.Time { + conn.mu.Lock() + defer conn.mu.Unlock() + return append([]time.Time(nil), conn.deadlines...) +} diff --git a/third_party/vowifi-go/internal/vowifi/imscore/outbound_request_dispatcher.go b/third_party/vowifi-go/internal/vowifi/imscore/outbound_request_dispatcher.go index 5a025742..c99cb0b2 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/outbound_request_dispatcher.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/outbound_request_dispatcher.go @@ -96,7 +96,9 @@ func (s *Service) executeOutboundRequest( ctx, cancel = context.WithTimeout(ctx, timeout) defer cancel() } - response, err := s.transport.roundTripWithSender(ctx, req.String(), modeCtx.send) + response, err := s.sendByMode(outboundSendOperation{ + Context: ctx, Mode: modeCtx, Request: req, Timeout: timeout, + }) if err != nil { s.handleOutboundRequestError(req, err) return nil, err diff --git a/third_party/vowifi-go/internal/vowifi/imscore/retry.go b/third_party/vowifi-go/internal/vowifi/imscore/retry.go index 97892241..af8c1667 100644 --- a/third_party/vowifi-go/internal/vowifi/imscore/retry.go +++ b/third_party/vowifi-go/internal/vowifi/imscore/retry.go @@ -1,6 +1,10 @@ package imscore -import "strings" +import ( + "errors" + "fmt" + "strings" +) // RequestID returns the inbound request ID. func (h *imscoreInboundRequestHandle) RequestID() string { @@ -26,23 +30,38 @@ func (m *inboundRequestResponseMemo) Sanitize() (int, string) { // outboundModeResolveError is returned when the outbound mode cannot be // resolved for a registration. type outboundModeResolveError struct { - reason string + code string + err error } // Error implements error. func (e *outboundModeResolveError) Error() string { if e == nil { - return "imscore: cannot resolve outbound mode" + return "" } - return "imscore: cannot resolve outbound mode: " + e.reason + if e.err != nil { + return e.err.Error() + } + return e.code } // Unwrap returns the wrapped error, if any. func (e *outboundModeResolveError) Unwrap() error { - return nil + if e == nil { + return nil + } + return e.err } // newOutboundModeResolveError builds an outbound mode resolution error. -func newOutboundModeResolveError(reason string) error { - return &outboundModeResolveError{reason: reason} +func newOutboundModeResolveError(code, format string, args ...interface{}) error { + return &outboundModeResolveError{code: strings.TrimSpace(code), err: fmt.Errorf(format, args...)} +} + +func outboundResolveErrorCode(err error) string { + var resolveErr *outboundModeResolveError + if !errors.As(err, &resolveErr) || resolveErr == nil { + return "" + } + return strings.TrimSpace(resolveErr.code) }