mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-05 16:02:17 +00:00
feat(imscore): align remaining Via, Route, and dialog SIP packing
Keep UDP IPsec Via sent-by on port-s, TCP Via on the configured local port, and originating requests on P-CSCF then Service-Route. Preserve Record-Route across 18x/2xx, close MWI SUBSCRIBE after a permanent 405, and default inbound Session-Expires to 1800 when timer is advertised.
This commit is contained in:
1 parent
94b5ad8d66
commit
cb32b5c139
34 files changed
+1572
-56
No files matched your search
@@ -0,0 +1,181 @@
|
||||
package imscore
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/emiago/sipgo/sip"
|
||||
)
|
||||
|
||||
var dialogLongDigitPattern = regexp.MustCompile(`\d{8,}`)
|
||||
|
||||
type dialogTokenFingerprint struct {
|
||||
Kind string
|
||||
Length int
|
||||
Suffix string
|
||||
}
|
||||
|
||||
func dialogTokenOf(value string) dialogTokenFingerprint {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return dialogTokenFingerprint{Kind: "empty"}
|
||||
}
|
||||
if dialogLongDigitPattern.MatchString(value) {
|
||||
return dialogTokenFingerprint{Kind: "redacted", Length: len(value)}
|
||||
}
|
||||
suffix := value
|
||||
if len(value) > 4 {
|
||||
suffix = value[len(value)-4:]
|
||||
}
|
||||
return dialogTokenFingerprint{Kind: "opaque", Length: len(value), Suffix: suffix}
|
||||
}
|
||||
|
||||
func appendDialogTokenFields(fields []any, prefix string, token dialogTokenFingerprint) []any {
|
||||
fields = append(fields, prefix+"_kind", token.Kind, prefix+"_len", token.Length)
|
||||
if token.Kind == "opaque" && token.Suffix != "" {
|
||||
fields = append(fields, prefix+"_suffix", token.Suffix)
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func dialogURIUserFields(prefix string, uri sip.Uri) []any {
|
||||
return []any{
|
||||
prefix + "_user_kind", dialogRequestURIUserKind(uri),
|
||||
prefix + "_user_shape", dialogContactUserShape(uri.User),
|
||||
prefix + "_user_len", len(strings.TrimSpace(uri.User)),
|
||||
prefix + "_host", strings.ToLower(strings.Trim(uri.Host, "[]")),
|
||||
prefix + "_port", uri.Port,
|
||||
}
|
||||
}
|
||||
|
||||
func dialogRequestToTag(request *sip.Request) string {
|
||||
if request == nil || request.To() == nil {
|
||||
return ""
|
||||
}
|
||||
return toHeaderTag(request.To())
|
||||
}
|
||||
|
||||
func dialogRequestFromTag(request *sip.Request) string {
|
||||
if request == nil || request.From() == nil {
|
||||
return ""
|
||||
}
|
||||
return fromHeaderTag(request.From())
|
||||
}
|
||||
|
||||
func sipURISameTarget(left, right sip.Uri) bool {
|
||||
if strings.ToLower(strings.Trim(left.Host, "[]")) != strings.ToLower(strings.Trim(right.Host, "[]")) {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(left.User) != strings.TrimSpace(right.User) {
|
||||
return false
|
||||
}
|
||||
return left.Port == right.Port
|
||||
}
|
||||
|
||||
func dialogInviteIdentityFields(request *sip.Request, handle *imscoreDialogHandle) []any {
|
||||
fields := []any{}
|
||||
if request != nil {
|
||||
fields = append(fields,
|
||||
"ruri_user_shape", dialogContactUserShape(request.Recipient.User),
|
||||
"ruri_user_len", len(strings.TrimSpace(request.Recipient.User)),
|
||||
)
|
||||
if request.To() != nil {
|
||||
fields = append(fields, dialogURIUserFields("to", request.To().Address)...)
|
||||
}
|
||||
fields = appendDialogTokenFields(fields, "call_id", dialogTokenOf(requestCallID(request)))
|
||||
fields = appendDialogTokenFields(fields, "from_tag", dialogTokenOf(dialogRequestFromTag(request)))
|
||||
fields = appendDialogTokenFields(fields, "to_tag", dialogTokenOf(dialogRequestToTag(request)))
|
||||
fields = append(fields, "to_has_tag", dialogRequestToTag(request) != "")
|
||||
}
|
||||
if handle == nil {
|
||||
return fields
|
||||
}
|
||||
handle.mu.Lock()
|
||||
callID := handle.callID
|
||||
fromTag := handle.fromTag
|
||||
toTag := handle.toTag
|
||||
confirmed := handle.confirmed
|
||||
remote := *handle.remoteTarget.Clone()
|
||||
responseToTag := ""
|
||||
responseTo := sip.Uri{}
|
||||
if handle.inviteResponse != nil && handle.inviteResponse.To() != nil {
|
||||
responseToTag = toHeaderTag(handle.inviteResponse.To())
|
||||
responseTo = handle.inviteResponse.To().Address
|
||||
}
|
||||
inviteFromTag := ""
|
||||
if handle.inviteRequest != nil && handle.inviteRequest.From() != nil {
|
||||
inviteFromTag = fromHeaderTag(handle.inviteRequest.From())
|
||||
}
|
||||
handle.mu.Unlock()
|
||||
|
||||
fields = append(fields, "handle_confirmed", confirmed)
|
||||
fields = append(fields, dialogURIUserFields("remote_target", remote)...)
|
||||
fields = appendDialogTokenFields(fields, "handle_call_id", dialogTokenOf(callID))
|
||||
fields = appendDialogTokenFields(fields, "handle_from_tag", dialogTokenOf(fromTag))
|
||||
fields = appendDialogTokenFields(fields, "handle_to_tag", dialogTokenOf(toTag))
|
||||
if request != nil {
|
||||
fields = append(fields,
|
||||
"call_id_eq_handle", requestCallID(request) == callID,
|
||||
"from_tag_eq_handle", dialogRequestFromTag(request) == fromTag,
|
||||
"to_tag_eq_handle", dialogRequestToTag(request) == toTag,
|
||||
"to_tag_eq_response", dialogRequestToTag(request) == responseToTag,
|
||||
"from_tag_eq_invite", dialogRequestFromTag(request) == inviteFromTag,
|
||||
"ruri_eq_remote_target", sipURISameTarget(request.Recipient, remote),
|
||||
)
|
||||
if request.To() != nil {
|
||||
fields = append(fields, "to_uri_eq_response", sipURISameTarget(request.To().Address, responseTo))
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
func learnedDialogIdentityFields(response *sip.Response, dialog *imscoreDialogHandle) []any {
|
||||
fields := []any{}
|
||||
if response != nil {
|
||||
if response.CallID() != nil {
|
||||
fields = appendDialogTokenFields(fields, "call_id", dialogTokenOf(response.CallID().Value()))
|
||||
}
|
||||
if response.From() != nil {
|
||||
fields = append(fields, dialogURIUserFields("from", response.From().Address)...)
|
||||
fields = appendDialogTokenFields(fields, "from_tag", dialogTokenOf(fromHeaderTag(response.From())))
|
||||
}
|
||||
if response.To() != nil {
|
||||
fields = append(fields, dialogURIUserFields("to", response.To().Address)...)
|
||||
fields = appendDialogTokenFields(fields, "to_tag", dialogTokenOf(toHeaderTag(response.To())))
|
||||
fields = append(fields, "to_has_tag", toHeaderTag(response.To()) != "")
|
||||
}
|
||||
}
|
||||
if dialog == nil {
|
||||
return fields
|
||||
}
|
||||
dialog.mu.Lock()
|
||||
handleToTag := dialog.toTag
|
||||
confirmed := dialog.confirmed
|
||||
dialog.mu.Unlock()
|
||||
responseToTag := ""
|
||||
if response != nil && response.To() != nil {
|
||||
responseToTag = toHeaderTag(response.To())
|
||||
}
|
||||
fields = append(fields,
|
||||
"handle_confirmed", confirmed,
|
||||
"to_tag_eq_handle", responseToTag == handleToTag,
|
||||
)
|
||||
fields = appendDialogTokenFields(fields, "handle_to_tag", dialogTokenOf(handleToTag))
|
||||
return fields
|
||||
}
|
||||
|
||||
func unmatchedResponseIdentityFields(response *sipResponse) []any {
|
||||
if response == nil {
|
||||
return nil
|
||||
}
|
||||
fields := []any{"status", response.StatusCode, "cseq", response.CSeq}
|
||||
fields = appendDialogTokenFields(fields, "call_id", dialogTokenOf(response.CallID))
|
||||
if response.parsed != nil && response.parsed.To() != nil {
|
||||
fields = appendDialogTokenFields(fields, "to_tag", dialogTokenOf(toHeaderTag(response.parsed.To())))
|
||||
fields = append(fields, "to_has_tag", toHeaderTag(response.parsed.To()) != "")
|
||||
}
|
||||
if response.parsed != nil && response.parsed.From() != nil {
|
||||
fields = appendDialogTokenFields(fields, "from_tag", dialogTokenOf(fromHeaderTag(response.parsed.From())))
|
||||
}
|
||||
return fields
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package imscore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/emiago/sipgo/sip"
|
||||
)
|
||||
|
||||
func TestDialogTokenOfRedactsLongDigits(t *testing.T) {
|
||||
got := dialogTokenOf("vohive-447840844894-abc")
|
||||
if got.Kind != "redacted" || got.Suffix != "" {
|
||||
t.Fatalf("digit-bearing token = %+v", got)
|
||||
}
|
||||
if got.Length != len("vohive-447840844894-abc") {
|
||||
t.Fatalf("redacted length = %d", got.Length)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialogTokenOfKeepsOpaqueSuffix(t *testing.T) {
|
||||
got := dialogTokenOf("a5df1a60")
|
||||
if got.Kind != "opaque" || got.Length != 8 || got.Suffix != "1a60" {
|
||||
t.Fatalf("opaque token = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDialogInviteIdentityFieldsMatchHandleAndHideNumbers(t *testing.T) {
|
||||
invite := mustClientInviteRequest(t, "vohive-59b005c9505fb58eeda840acee2f0b52")
|
||||
response := mustTransactionResponse(t, invite.String(), 200).parsed
|
||||
response.AppendHeader(testContactHeader(t, "sip:ab@10.128.120.163:50600;transport=tcp"))
|
||||
dialog := newClientDialogHandle(invite, response)
|
||||
request := testDialogTemplate(t, sip.INVITE)
|
||||
applyDialogRecipient(request, dialog)
|
||||
applyDialogCoreHeaders(nil, request, dialog)
|
||||
|
||||
fields := dialogInviteIdentityFields(request, dialog)
|
||||
if !dialogIdentityFieldBool(fields, "call_id_eq_handle") ||
|
||||
!dialogIdentityFieldBool(fields, "from_tag_eq_handle") ||
|
||||
!dialogIdentityFieldBool(fields, "to_tag_eq_handle") ||
|
||||
!dialogIdentityFieldBool(fields, "to_tag_eq_response") ||
|
||||
!dialogIdentityFieldBool(fields, "ruri_eq_remote_target") {
|
||||
t.Fatalf("match fields = %#v", fieldsToMap(fields))
|
||||
}
|
||||
longDigits := regexp.MustCompile(`\d{8,}`)
|
||||
for key, value := range fieldsToMap(fields) {
|
||||
if longDigits.MatchString(fmt.Sprint(value)) {
|
||||
t.Fatalf("identity field %s leaked digits: %v", key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLearnedDialogIdentityFieldsCompareResponseTag(t *testing.T) {
|
||||
invite := mustClientInviteRequest(t, "dialog-learn-id")
|
||||
response := mustTransactionResponse(t, invite.String(), 183).parsed
|
||||
dialog := newClientDialogHandle(invite, response)
|
||||
fields := learnedDialogIdentityFields(response, dialog)
|
||||
if !dialogIdentityFieldBool(fields, "to_has_tag") || !dialogIdentityFieldBool(fields, "to_tag_eq_handle") {
|
||||
t.Fatalf("learned fields = %#v", fieldsToMap(fields))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnmatchedResponseIdentityFieldsIncludeToTag(t *testing.T) {
|
||||
invite := mustClientInviteRequest(t, "unmatched-481")
|
||||
response := mustTransactionResponse(t, invite.String(), 481)
|
||||
fields := unmatchedResponseIdentityFields(response)
|
||||
if !dialogIdentityFieldBool(fields, "to_has_tag") {
|
||||
t.Fatalf("unmatched fields = %#v", fieldsToMap(fields))
|
||||
}
|
||||
}
|
||||
|
||||
func fieldsToMap(fields []any) map[string]any {
|
||||
out := make(map[string]any, len(fields)/2)
|
||||
for index := 0; index+1 < len(fields); index += 2 {
|
||||
key, _ := fields[index].(string)
|
||||
out[key] = fields[index+1]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func dialogIdentityFieldBool(fields []any, name string) bool {
|
||||
value, ok := fieldsToMap(fields)[name].(bool)
|
||||
return ok && value
|
||||
}
|
||||
|
||||
func TestDialogTokenFieldsNeverPrintMSISDN(t *testing.T) {
|
||||
fields := appendDialogTokenFields(nil, "call_id", dialogTokenOf("+447840844894"))
|
||||
for _, value := range fields {
|
||||
if strings.Contains(fmt.Sprint(value), "447840844894") || strings.Contains(fmt.Sprint(value), "4894") {
|
||||
t.Fatalf("token fields leaked number: %#v", fields)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package imscore
|
||||
|
||||
import (
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/imsheaders"
|
||||
)
|
||||
|
||||
func recordRouteSetFromMessage(message sip.Message) []string {
|
||||
if message == nil {
|
||||
return nil
|
||||
}
|
||||
headers := message.GetHeaders("Record-Route")
|
||||
values := make([]string, 0, len(headers))
|
||||
for _, header := range headers {
|
||||
if value := header.Value(); value != "" {
|
||||
values = append(values, value)
|
||||
}
|
||||
}
|
||||
return imsheaders.RecordRouteSet(values)
|
||||
}
|
||||
|
||||
func applyClientDialogRouteSetLocked(dialog *imscoreDialogHandle, response *sip.Response) {
|
||||
if dialog == nil {
|
||||
return
|
||||
}
|
||||
if routes := recordRouteSetFromMessage(response); len(routes) > 0 {
|
||||
dialog.routeSet = routes
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,13 @@ package imscore
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"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/logging"
|
||||
)
|
||||
|
||||
const dialogMaxForwards = 70
|
||||
@@ -135,6 +137,9 @@ func (s *Service) sendDialogRequestByMode(
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if request.IsInvite() {
|
||||
logDialogInviteRequest(request, handle)
|
||||
}
|
||||
if request.IsAck() {
|
||||
return nil, s.writeDialogACK(ctx, request, sender)
|
||||
}
|
||||
@@ -237,3 +242,142 @@ func (s *Service) prepareDialogRequest(
|
||||
request.SetTransport(handle.inviteRequest.Transport())
|
||||
return request, s.dialogSenderLocked(handle), handle.server != nil, nil
|
||||
}
|
||||
|
||||
func logDialogInviteRequest(request *sip.Request, handle *imscoreDialogHandle) {
|
||||
if request == nil {
|
||||
return
|
||||
}
|
||||
body := request.Body()
|
||||
contact := ""
|
||||
if request.Contact() != nil {
|
||||
contact = request.Contact().Value()
|
||||
}
|
||||
fields := []any{
|
||||
"ruri_host", strings.ToLower(strings.Trim(request.Recipient.Host, "[]")),
|
||||
"ruri_port", request.Recipient.Port,
|
||||
"ruri_user_kind", dialogRequestURIUserKind(request.Recipient),
|
||||
"ruri_params", strings.Join(dialogURIParamKeys(request.Recipient), ","),
|
||||
"via", dialogHeaderValue(request, "Via"),
|
||||
"via_port", sipSentByPort(dialogHeaderValue(request, "Via")),
|
||||
"route", strings.Join(dialogHeaderValues(request, "Route"), ","),
|
||||
"cseq", dialogHeaderValue(request, "CSeq"),
|
||||
"contact_has_ob", strings.Contains(strings.ToLower(contact), ";ob"),
|
||||
"contact_has_instance", strings.Contains(strings.ToLower(contact), "+sip.instance"),
|
||||
"session_expires_present", strings.TrimSpace(dialogHeaderValue(request, "Session-Expires")) != "",
|
||||
"body_bytes", len(body),
|
||||
"qos_remote", sdpCurrentQoSRemote(body),
|
||||
}
|
||||
fields = append(fields, dialogInviteIdentityFields(request, handle)...)
|
||||
logging.Info("IMS dialog INVITE outbound", fields...)
|
||||
}
|
||||
|
||||
func dialogURIParamKeys(uri sip.Uri) []string {
|
||||
if uri.UriParams == nil {
|
||||
return nil
|
||||
}
|
||||
return append([]string(nil), uri.UriParams.Keys()...)
|
||||
}
|
||||
|
||||
func dialogContactUserShape(user string) string {
|
||||
user = strings.ToLower(strings.TrimSpace(user))
|
||||
switch {
|
||||
case user == "":
|
||||
return "empty"
|
||||
case user == "orig" || user == "term":
|
||||
return user
|
||||
case strings.HasPrefix(user, "+"):
|
||||
return "e164"
|
||||
case isDialogDigits(user):
|
||||
return "digits"
|
||||
case len(user) >= 8:
|
||||
return "token"
|
||||
default:
|
||||
return "short"
|
||||
}
|
||||
}
|
||||
|
||||
func dialogRequestURIUserKind(uri sip.Uri) string {
|
||||
user := strings.TrimSpace(uri.User)
|
||||
switch {
|
||||
case user == "":
|
||||
return "empty"
|
||||
case strings.HasPrefix(user, "+"):
|
||||
return "e164"
|
||||
case isDialogDigits(user) && len(user) <= 6:
|
||||
return "shortcode"
|
||||
case isDialogDigits(user):
|
||||
return "digits"
|
||||
default:
|
||||
return "other"
|
||||
}
|
||||
}
|
||||
|
||||
func isDialogDigits(value string) bool {
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
if character < '0' || character > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func dialogHeaderValue(request *sip.Request, name string) string {
|
||||
values := dialogHeaderValues(request, name)
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
return values[0]
|
||||
}
|
||||
|
||||
func dialogHeaderValues(request *sip.Request, name string) []string {
|
||||
if request == nil {
|
||||
return nil
|
||||
}
|
||||
var values []string
|
||||
for _, header := range request.GetHeaders(name) {
|
||||
if value := strings.TrimSpace(header.Value()); value != "" {
|
||||
values = append(values, value)
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func logLearnedDialogTarget(response *sip.Response, dialog *imscoreDialogHandle) {
|
||||
if dialog == nil {
|
||||
return
|
||||
}
|
||||
dialog.mu.Lock()
|
||||
target := *dialog.remoteTarget.Clone()
|
||||
routes := append([]string(nil), dialog.routeSet...)
|
||||
dialog.mu.Unlock()
|
||||
status := 0
|
||||
if response != nil {
|
||||
status = response.StatusCode
|
||||
}
|
||||
fields := []any{
|
||||
"status", status,
|
||||
"contact_host", strings.ToLower(strings.Trim(target.Host, "[]")),
|
||||
"contact_port", target.Port,
|
||||
"contact_user_kind", dialogRequestURIUserKind(target),
|
||||
"contact_user_shape", dialogContactUserShape(target.User),
|
||||
"contact_params", strings.Join(dialogURIParamKeys(target), ","),
|
||||
"route_count", len(routes),
|
||||
"route", strings.Join(routes, ","),
|
||||
}
|
||||
fields = append(fields, learnedDialogIdentityFields(response, dialog)...)
|
||||
logging.Info("IMS dialog target learned", fields...)
|
||||
}
|
||||
|
||||
func sdpCurrentQoSRemote(body []byte) string {
|
||||
const prefix = "a=curr:qos remote "
|
||||
for _, line := range strings.Split(string(body), "\n") {
|
||||
line = strings.ToLower(strings.TrimSpace(strings.TrimSuffix(line, "\r")))
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
return strings.TrimSpace(strings.TrimPrefix(line, prefix))
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -113,7 +113,7 @@ func (t *sipTransport) DeliverResponse(r *sipResponse) {
|
||||
}
|
||||
if r != nil {
|
||||
logging.WarnRate("ims-unmatched-sip-response", "IMS response did not match an active transaction",
|
||||
"status", r.StatusCode, "cseq", r.CSeq)
|
||||
unmatchedResponseIdentityFields(r)...)
|
||||
}
|
||||
select {
|
||||
case t.responses <- r:
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package imscore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/imsheaders"
|
||||
)
|
||||
|
||||
func (s *Service) originatingRouteSetLocked(serviceRoute string) string {
|
||||
pcscf := s.pcscfPreloadedRouteLocked()
|
||||
if pcscf == "" {
|
||||
return strings.TrimSpace(serviceRoute)
|
||||
}
|
||||
return imsheaders.PreloadedOriginatingRoute(pcscf, serviceRoute)
|
||||
}
|
||||
|
||||
func (s *Service) pcscfPreloadedRouteLocked() string {
|
||||
host := ""
|
||||
port := 0
|
||||
if s.registrationTCP != nil {
|
||||
host, port = splitOutboundAddress(s.registrationTCP.RemoteAddr())
|
||||
}
|
||||
if (host == "" || net.ParseIP(strings.Trim(host, "[]")) == nil) &&
|
||||
s.registrationRemote != nil && s.registrationRemote.IP != nil {
|
||||
host = s.registrationRemote.IP.String()
|
||||
if port < 1 {
|
||||
port = s.registrationRemote.Port
|
||||
}
|
||||
}
|
||||
if s.regSession != nil && s.regSession.security != nil && s.regSession.security.server != nil {
|
||||
if negotiated := int(s.regSession.security.server.PortS); negotiated > 0 {
|
||||
port = negotiated
|
||||
}
|
||||
}
|
||||
transport := "tcp"
|
||||
if s.registrationTCP == nil && s.cfg != nil {
|
||||
transport = strings.ToLower(strings.TrimSpace(s.cfg.Transport))
|
||||
if transport == "" {
|
||||
transport = "udp"
|
||||
}
|
||||
}
|
||||
return formatPCSCFRoute(host, port, transport)
|
||||
}
|
||||
|
||||
func formatPCSCFRoute(host string, port int, transport string) string {
|
||||
host = strings.Trim(strings.TrimSpace(host), "[]")
|
||||
if net.ParseIP(host) == nil || port < 1 {
|
||||
return ""
|
||||
}
|
||||
addr := net.JoinHostPort(host, strconv.Itoa(port))
|
||||
if transport = strings.ToLower(strings.TrimSpace(transport)); transport != "" {
|
||||
return fmt.Sprintf("<sip:%s;transport=%s;lr>", addr, transport)
|
||||
}
|
||||
return fmt.Sprintf("<sip:%s;lr>", addr)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package imscore
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestPCSCFPreloadedRouteUsesProtectedServerPort(t *testing.T) {
|
||||
service := &Service{
|
||||
cfg: &IMSConfig{Transport: "udp"},
|
||||
registrationRemote: &net.UDPAddr{IP: net.ParseIP("10.128.120.17"), Port: 5060},
|
||||
regSession: ®isterSession{
|
||||
security: &securityAgreement{server: &securityMechanism{PortS: 50600}},
|
||||
},
|
||||
}
|
||||
service.registrationTCP = nil
|
||||
got := service.pcscfPreloadedRouteLocked()
|
||||
want := "<sip:10.128.120.17:50600;transport=udp;lr>"
|
||||
if got != want {
|
||||
t.Fatalf("P-CSCF Route = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterResponseKeepsServiceRouteList(t *testing.T) {
|
||||
raw := "SIP/2.0 200 OK\r\n" +
|
||||
"Via: SIP/2.0/TCP 192.0.2.10:5060;branch=z9hG4bK1\r\n" +
|
||||
"From: <sip:user@ims.example>;tag=local\r\n" +
|
||||
"To: <sip:user@ims.example>;tag=remote\r\n" +
|
||||
"Call-ID: call-1\r\nCSeq: 2 REGISTER\r\n" +
|
||||
"Service-Route: <sip:orig@scscf.ims.example;lr>\r\n" +
|
||||
"Service-Route: <sip:icscf.ims.example;lr>\r\n" +
|
||||
"Content-Length: 0\r\n\r\n"
|
||||
response, err := parseSIPResponse(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := strings.Join(response.HeaderValues("Service-Route"), ",")
|
||||
want := "<sip:orig@scscf.ims.example;lr>,<sip:icscf.ims.example;lr>"
|
||||
if got != want {
|
||||
t.Fatalf("Service-Route list = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
+60
-4
@@ -71,6 +71,10 @@ func (s *Service) Register(ctx context.Context) error {
|
||||
ctx = common.WithTraceID(ctx, common.TraceID(ctx))
|
||||
s.registerMu.Lock()
|
||||
defer s.registerMu.Unlock()
|
||||
return s.registerLocked(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) registerLocked(ctx context.Context) error {
|
||||
select {
|
||||
case <-s.stop:
|
||||
return errors.New("imscore: service stopped")
|
||||
@@ -319,7 +323,7 @@ func (s *Service) commitRegisterSuccess(resp *sipResponse, session *registerSess
|
||||
s.learnedAOR = session.publicID
|
||||
s.mu.Unlock()
|
||||
}
|
||||
if serviceRoute := imsheaders.FirstRoute(resp.Header("Service-Route"), ""); serviceRoute != "" {
|
||||
if serviceRoute := strings.Join(resp.HeaderValues("Service-Route"), ","); strings.TrimSpace(serviceRoute) != "" {
|
||||
session.serviceRoute = serviceRoute
|
||||
s.mu.Lock()
|
||||
s.serviceRoute = serviceRoute
|
||||
@@ -436,6 +440,7 @@ func (s *Service) exchangeRegister(ctx context.Context, session *registerSession
|
||||
"authenticated", strings.TrimSpace(authorization) != "",
|
||||
"security_client_mechanisms", securityClientMechanismCount(rawSIPHeaderValue(request, "Security-Client")),
|
||||
"sip", logging.RedactSIPRaw(request))
|
||||
s.logRegisterViaPorts(session, request)
|
||||
response, err := s.transport.RoundTrip(ctx, request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("imscore: REGISTER CSeq %d transaction: %w", session.cseq, err)
|
||||
@@ -610,7 +615,7 @@ func (s *Service) buildRegisterRequest(
|
||||
transport := s.registerRequestTransport(protected)
|
||||
var b strings.Builder
|
||||
b.WriteString(fmt.Sprintf("REGISTER sip:%s SIP/2.0\r\n", cfg.Domain))
|
||||
localAddress := s.registerLocalAddress(session)
|
||||
localAddress := s.registerLocalAddress(session, transport)
|
||||
b.WriteString(fmt.Sprintf("Via: SIP/2.0/%s %s;rport;branch=%s%s\r\n",
|
||||
transportUpper(transport), localAddress, session.branch, registerViaAlias(protected)))
|
||||
publicIdentity := primaryPublicIdentity(cfg)
|
||||
@@ -861,8 +866,59 @@ func associatedPublicIdentity(header string) string {
|
||||
return identity
|
||||
}
|
||||
|
||||
func (s *Service) registerLocalAddress(_ *registerSession) string {
|
||||
return net.JoinHostPort(s.cfg.LocalIP.String(), strconv.Itoa(s.cfg.LocalPort))
|
||||
func (s *Service) registerLocalAddress(session *registerSession, transport string) string {
|
||||
port := s.cfg.LocalPort
|
||||
if registerUsesProtectedTransport(session) && session != nil && session.security != nil {
|
||||
// TCP after SA keeps cfg.LocalPort (24.229 5.1.1.2.2 (c) is UDP-only;
|
||||
// K.2.1.2.2.2 TCP Via is IP/FQDN). UDP IPsec uses port-s.
|
||||
port = protectedViaSentByPort(transport, int(session.security.client.PortS), s.cfg.LocalPort)
|
||||
}
|
||||
return net.JoinHostPort(s.cfg.LocalIP.String(), strconv.Itoa(port))
|
||||
}
|
||||
|
||||
func (s *Service) logRegisterViaPorts(session *registerSession, request string) {
|
||||
if s == nil {
|
||||
return
|
||||
}
|
||||
viaPort := sipSentByPort(rawSIPHeaderValue(request, "Via"))
|
||||
portC, portS := 0, 0
|
||||
if session != nil && session.security != nil {
|
||||
portC = int(session.security.client.PortC)
|
||||
portS = int(session.security.client.PortS)
|
||||
}
|
||||
localPort := 0
|
||||
if s.cfg != nil {
|
||||
localPort = s.cfg.LocalPort
|
||||
}
|
||||
transport := s.registerRequestTransport(registerUsesProtectedTransport(session))
|
||||
logging.Info("IMS REGISTER via ports",
|
||||
"device", s.DeviceID(),
|
||||
"transport", transport,
|
||||
"via_port", viaPort,
|
||||
"cfg_local_port", localPort,
|
||||
"port_c", portC,
|
||||
"port_s", portS,
|
||||
"via_eq_port_c", viaPort > 0 && viaPort == portC,
|
||||
"via_eq_port_s", viaPort > 0 && viaPort == portS,
|
||||
"udp_via_uses_port_s", sipTransportIsUDP(transport),
|
||||
"protected", registerUsesProtectedTransport(session))
|
||||
}
|
||||
|
||||
func sipSentByPort(via string) int {
|
||||
fields := strings.Fields(via)
|
||||
if len(fields) < 2 {
|
||||
return 0
|
||||
}
|
||||
sentBy, _, _ := strings.Cut(fields[1], ";")
|
||||
_, portText, err := net.SplitHostPort(strings.TrimSpace(sentBy))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil || port < 1 {
|
||||
return 0
|
||||
}
|
||||
return port
|
||||
}
|
||||
|
||||
func (s *Service) registerRequestTransport(protected bool) string {
|
||||
|
||||
@@ -341,6 +341,62 @@ func TestRefreshRegisterPrefersServiceRouteOverPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedRegisterViaKeepsConfiguredSentByNotPortC(t *testing.T) {
|
||||
service := &Service{cfg: &IMSConfig{
|
||||
IMPI: "user@ims.example", IMPU: "sip:user@ims.example", Domain: "ims.example",
|
||||
LocalIP: net.ParseIP("192.0.2.10"), LocalPort: 5060, Transport: "udp",
|
||||
}}
|
||||
request := service.buildRegister(®isterSession{
|
||||
callID: "call-1", fromTag: "tag-1", contactUser: "contact-1", cseq: 2,
|
||||
security: &securityAgreement{
|
||||
verifyHeader: "ipsec-3gpp;alg=hmac-sha-1-96",
|
||||
client: securityMechanism{PortC: 50309, PortS: 48554},
|
||||
},
|
||||
}, "Digest response")
|
||||
via := sipHeaderValue(request, "Via")
|
||||
if !strings.HasPrefix(via, "SIP/2.0/TCP ") {
|
||||
t.Fatalf("protected REGISTER transport = %q, want TCP after SA", via)
|
||||
}
|
||||
if sipViaSentBy(via) != "192.0.2.10:5060" {
|
||||
t.Fatalf("TCP REGISTER Via sent-by = %q, want configured local port", sipViaSentBy(via))
|
||||
}
|
||||
if sipSentByPort(via) == 50309 || sipSentByPort(via) == 48554 {
|
||||
t.Fatalf("TCP REGISTER Via used an IPsec port: %q", via)
|
||||
}
|
||||
contact := sipHeaderValue(request, "Contact")
|
||||
if !strings.Contains(contact, ":48554") {
|
||||
t.Fatalf("REGISTER Contact = %q, want port-s", contact)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProtectedUDPRegisterViaUsesPortS(t *testing.T) {
|
||||
service := &Service{cfg: &IMSConfig{
|
||||
IMPI: "user@ims.example", IMPU: "sip:user@ims.example", Domain: "ims.example",
|
||||
LocalIP: net.ParseIP("192.0.2.10"), LocalPort: 5060, Transport: "udp",
|
||||
}}
|
||||
session := ®isterSession{
|
||||
security: &securityAgreement{
|
||||
verifyHeader: "ipsec-3gpp;alg=hmac-sha-1-96",
|
||||
client: securityMechanism{PortC: 50309, PortS: 48554},
|
||||
},
|
||||
}
|
||||
if got := service.registerLocalAddress(session, "udp"); got != "192.0.2.10:48554" {
|
||||
t.Fatalf("UDP protected REGISTER Via = %q, want port-s", got)
|
||||
}
|
||||
if got := service.registerLocalAddress(session, "tcp"); got != "192.0.2.10:5060" {
|
||||
t.Fatalf("TCP protected REGISTER Via = %q, want configured local port", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSipSentByPortParsesIPv4AndIPv6(t *testing.T) {
|
||||
if got := sipSentByPort("SIP/2.0/TCP 192.0.2.10:5060;rport;branch=z9hG4bK"); got != 5060 {
|
||||
t.Fatalf("IPv4 via port = %d", got)
|
||||
}
|
||||
if got := sipSentByPort("SIP/2.0/TCP [2001:db8::10]:50309;rport;branch=z9hG4bK"); got != 50309 {
|
||||
t.Fatalf("IPv6 via port = %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRefreshRegisterAddsOutboundContactAfterNegotiation(t *testing.T) {
|
||||
service := &Service{cfg: &IMSConfig{
|
||||
IMPI: "user@ims.example", IMPU: "sip:user@ims.example", Domain: "ims.example",
|
||||
|
||||
+3
-7
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint"
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/imsheaders"
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/sipkit"
|
||||
)
|
||||
|
||||
@@ -94,15 +95,10 @@ func concreteReliableDialog(value imsendpoint.DialogHandle) (*imscoreDialogHandl
|
||||
}
|
||||
|
||||
func applyReliableProvisionalRouteSet(dialog *imscoreDialogHandle, routes []string) {
|
||||
if dialog == nil || len(routes) == 0 {
|
||||
if dialog == nil {
|
||||
return
|
||||
}
|
||||
cleaned := make([]string, 0, len(routes))
|
||||
for index := len(routes) - 1; index >= 0; index-- {
|
||||
if route := strings.TrimSpace(routes[index]); route != "" {
|
||||
cleaned = append(cleaned, route)
|
||||
}
|
||||
}
|
||||
cleaned := imsheaders.RecordRouteSet(routes)
|
||||
if len(cleaned) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -441,7 +441,6 @@ func assertRecoveredRegistrationSubscription(request, securityVerify string, cli
|
||||
return fmt.Errorf("unexpected SUBSCRIBE request line: %q", strings.SplitN(request, "\r\n", 2)[0])
|
||||
}
|
||||
checks := map[string]string{
|
||||
"Route": "<sip:pcscf.example;lr>",
|
||||
"Event": "reg",
|
||||
"Accept": "application/reginfo+xml",
|
||||
"P-Preferred-Identity": "<sip:+447840844894@o2.co.uk>",
|
||||
@@ -454,9 +453,13 @@ func assertRecoveredRegistrationSubscription(request, securityVerify string, cli
|
||||
return fmt.Errorf("SUBSCRIBE %s = %q, want %q", name, got, want)
|
||||
}
|
||||
}
|
||||
route := sipHeaderValue(request, "Route")
|
||||
if !strings.Contains(route, "<sip:pcscf.example;lr>") || !strings.Contains(route, ";transport=tcp;lr>") {
|
||||
return fmt.Errorf("SUBSCRIBE Route = %q, want P-CSCF then Service-Route", route)
|
||||
}
|
||||
if !strings.Contains(sipHeaderValue(request, "Via"), fmt.Sprintf(":%d;", client.PortC)) ||
|
||||
!strings.Contains(sipHeaderValue(request, "Contact"),
|
||||
fmt.Sprintf(":%d;transport=tcp>", client.PortS)) {
|
||||
fmt.Sprintf(":%d;ob;transport=tcp>", client.PortS)) {
|
||||
return errors.New("SUBSCRIBE did not advertise the negotiated protected ports")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/emiago/sipgo"
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/imsendpoint"
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/logging"
|
||||
)
|
||||
|
||||
// StartClientInvite starts a v1.5.5 client-side INVITE transaction.
|
||||
@@ -52,7 +53,11 @@ func (s *Service) StartClientInvite(
|
||||
}
|
||||
}
|
||||
response, err := s.transport.waitClientTransaction(ctx, transaction)
|
||||
return s.completeClientInviteResult(handle, result, response, options.OnResponse, err)
|
||||
completed, completeErr := s.completeClientInviteResult(handle, result, response, options.OnResponse, err)
|
||||
if completed != nil && completed.Response != nil {
|
||||
s.observeInitialInvite503(newSIPResponse(completed.Response))
|
||||
}
|
||||
return completed, completeErr
|
||||
}
|
||||
|
||||
// StartClientInviteForCurrentDevice retains the additive device-implicit API.
|
||||
@@ -226,6 +231,14 @@ func (s *Service) closeReplacedEarlyDialog(previousID, currentID string) {
|
||||
return
|
||||
}
|
||||
if previous := s.dialogs().load(previousID); previous != nil {
|
||||
previous.mu.Lock()
|
||||
previousToTag := previous.toTag
|
||||
previous.mu.Unlock()
|
||||
fields := []any{"phase", "early_replaced"}
|
||||
fields = appendDialogTokenFields(fields, "prev_dialog", dialogTokenOf(previousID))
|
||||
fields = appendDialogTokenFields(fields, "next_dialog", dialogTokenOf(currentID))
|
||||
fields = appendDialogTokenFields(fields, "prev_to_tag", dialogTokenOf(previousToTag))
|
||||
logging.Info("IMS dialog early replaced", fields...)
|
||||
_ = s.closeDialogHandle(previous)
|
||||
}
|
||||
}
|
||||
@@ -257,11 +270,14 @@ func (s *Service) retainClientInviteEarlyDialog(
|
||||
if response.parsed.To() == nil || toHeaderTag(response.parsed.To()) == "" {
|
||||
return
|
||||
}
|
||||
dialog := newClientDialogHandle(invite.initialRequest, response.parsed)
|
||||
dialog.client.Init()
|
||||
dialog.confirmed = false
|
||||
dialog.sender = invite.transaction.send
|
||||
s.storeClientDialog(dialog, invite.initialRequest, response.parsed)
|
||||
dialog := s.retainMatchingEarlyDialog(invite, response.parsed)
|
||||
if dialog == nil {
|
||||
dialog = newClientDialogHandle(invite.initialRequest, response.parsed)
|
||||
dialog.client.Init()
|
||||
dialog.confirmed = false
|
||||
dialog.sender = invite.transaction.send
|
||||
s.storeClientDialog(dialog, invite.initialRequest, response.parsed)
|
||||
}
|
||||
invite.mu.Lock()
|
||||
previous := invite.dialog
|
||||
invite.dialog = dialog.client
|
||||
@@ -271,6 +287,42 @@ func (s *Service) retainClientInviteEarlyDialog(
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) retainMatchingEarlyDialog(
|
||||
invite *imscoreInviteHandle,
|
||||
response *sip.Response,
|
||||
) *imscoreDialogHandle {
|
||||
id, err := sip.DialogIDFromResponse(response)
|
||||
if err != nil && invite != nil && invite.initialRequest != nil && invite.initialRequest.From() != nil {
|
||||
id = sip.DialogIDMake(
|
||||
invite.initialRequest.CallID().Value(),
|
||||
toHeaderTag(response.To()),
|
||||
fromHeaderTag(invite.initialRequest.From()),
|
||||
)
|
||||
}
|
||||
if id == "" {
|
||||
return nil
|
||||
}
|
||||
dialog := s.dialogs().load(id)
|
||||
if dialog == nil {
|
||||
return nil
|
||||
}
|
||||
dialog.mu.Lock()
|
||||
dialog.inviteResponse = response.Clone()
|
||||
if dialog.client != nil {
|
||||
dialog.client.InviteResponse = response.Clone()
|
||||
}
|
||||
if response.Contact() != nil {
|
||||
dialog.remoteTarget = *response.Contact().Address.Clone()
|
||||
}
|
||||
applyClientDialogRouteSetLocked(dialog, response)
|
||||
if invite != nil && invite.transaction != nil {
|
||||
dialog.sender = invite.transaction.send
|
||||
}
|
||||
dialog.mu.Unlock()
|
||||
s.dialogs().store(dialog)
|
||||
return dialog
|
||||
}
|
||||
|
||||
func retainedClientInviteFinal(handle *imscoreInviteHandle) *sipResponse {
|
||||
if handle == nil || handle.transaction == nil {
|
||||
return nil
|
||||
@@ -305,6 +357,7 @@ func initializeClientDialogTarget(
|
||||
) {
|
||||
if request.CSeq() != nil {
|
||||
handle.localCSeq = request.CSeq().SeqNo
|
||||
handle.localInviteCSeq = request.CSeq().SeqNo
|
||||
handle.remoteCSeq = request.CSeq().SeqNo
|
||||
}
|
||||
if request.Contact() != nil {
|
||||
@@ -341,15 +394,15 @@ func (s *Service) storeClientDialog(
|
||||
if s == nil || dialog == nil {
|
||||
return
|
||||
}
|
||||
routes := response.GetHeaders("Record-Route")
|
||||
routeSet := make([]string, 0, len(routes))
|
||||
for index := len(routes) - 1; index >= 0; index-- {
|
||||
routeSet = append(routeSet, routes[index].Value())
|
||||
}
|
||||
dialog.mu.Lock()
|
||||
dialog.routeSet = routeSet
|
||||
// RFC 3261 12.1.2: the UAC route set comes from the dialog-creating
|
||||
// Record-Route. A later 2xx that omits Record-Route must not wipe the
|
||||
// 18x set; VoWiFi still has to loose-route through the P-CSCF
|
||||
// (TS 24.229 5.1.2A). A 2xx that repeats Record-Route recomputes it.
|
||||
applyClientDialogRouteSetLocked(dialog, response)
|
||||
dialog.mu.Unlock()
|
||||
s.dialogs().store(dialog)
|
||||
logLearnedDialogTarget(response, dialog)
|
||||
}
|
||||
|
||||
func (s *Service) cancelClientInviteWithContext(
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/imsheaders"
|
||||
)
|
||||
|
||||
const smsSupportedHeader = "path, 100rel, replaces, gruu"
|
||||
@@ -139,25 +138,31 @@ func (s *Service) registeredSIPRouteLocked() registeredSIPRoute {
|
||||
serverPort := s.protectedServerPort
|
||||
transport := "tcp"
|
||||
if s.registrationTCP == nil {
|
||||
clientPort, serverPort = s.cfg.LocalPort, s.cfg.LocalPort
|
||||
transport = strings.ToLower(strings.TrimSpace(s.cfg.Transport))
|
||||
if transport == "" {
|
||||
transport = "udp"
|
||||
}
|
||||
// TCP/TLS after SA keep the configured local ports when the
|
||||
// protected TCP socket is not up. UDP IPsec keeps port-s so Via
|
||||
// sent-by can follow 24.229 5.1.2A.1.1 / 5.1.1.2.2 (c).
|
||||
if !sipTransportIsUDP(transport) || serverPort < 1 {
|
||||
clientPort, serverPort = s.cfg.LocalPort, s.cfg.LocalPort
|
||||
}
|
||||
}
|
||||
route := registeredSIPRoute{transport: transport}
|
||||
if clientPort > 0 {
|
||||
route.clientAddress = net.JoinHostPort(s.cfg.LocalIP.String(), fmt.Sprint(clientPort))
|
||||
viaPort := clientPort
|
||||
if sipTransportIsUDP(transport) {
|
||||
viaPort = protectedViaSentByPort(transport, serverPort, clientPort)
|
||||
}
|
||||
route.clientAddress = net.JoinHostPort(s.cfg.LocalIP.String(), fmt.Sprint(viaPort))
|
||||
}
|
||||
if serverPort > 0 {
|
||||
route.serverAddress = net.JoinHostPort(s.cfg.LocalIP.String(), fmt.Sprint(serverPort))
|
||||
}
|
||||
route.remoteAddress = s.registeredRemoteAddressLocked()
|
||||
if s.regSession != nil {
|
||||
route.serviceRoute = imsheaders.EffectiveRoute(s.regSession.serviceRoute, s.regSession.path)
|
||||
if route.serviceRoute == "" {
|
||||
route.serviceRoute = strings.TrimSpace(s.path)
|
||||
}
|
||||
route.serviceRoute = s.originatingRouteSetLocked(s.regSession.serviceRoute)
|
||||
if s.regSession.security != nil {
|
||||
route.securityVerify = strings.TrimSpace(s.regSession.security.verifyHeader)
|
||||
}
|
||||
|
||||
@@ -579,7 +579,7 @@ func assertOutboundSMSRequest(t *testing.T, request, recipient, smsc string) {
|
||||
}
|
||||
wantHeaders := map[string]string{
|
||||
"From": "<sip:+447840844894@o2.co.uk>",
|
||||
"Contact": "<sip:registered-contact@10.0.0.2:5060>",
|
||||
"Contact": "<sip:registered-contact@10.0.0.2:5060;ob>",
|
||||
"Route": "<sip:pcscf.ims.example;lr>",
|
||||
"P-Preferred-Identity": "<sip:+447840844894@o2.co.uk>",
|
||||
"Security-Verify": "ipsec-3gpp;alg=hmac-sha-1-96",
|
||||
|
||||
@@ -274,6 +274,12 @@ func (s *Service) recordMWISubscriptionResult(
|
||||
s.mu.Lock()
|
||||
if resultErr != nil {
|
||||
s.mwiSubscriptionLastErr = resultErr.Error()
|
||||
if subscriptionPermanentlyRejected(response) {
|
||||
s.mwiSubscriptionClosed = true
|
||||
s.mwiSubscriptionDialog = registrationSubscriptionDialog{}
|
||||
s.mwiSubscriptionExpires = 0
|
||||
s.mwiSubscriptionRefreshAt = time.Time{}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return resultErr
|
||||
}
|
||||
|
||||
@@ -3,12 +3,15 @@ package imscore
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/emiago/sipgo/sip"
|
||||
)
|
||||
|
||||
func TestParseMWISummary(t *testing.T) {
|
||||
@@ -200,3 +203,67 @@ func TestMWISubscribe481RetriesAsInitial(t *testing.T) {
|
||||
t.Fatalf("481 retry kept To tag: %q", rawSIPHeaderValue(second, "To"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordMWISubscriptionResultClosesOnPermanentReject(t *testing.T) {
|
||||
for _, status := range []int{405, 489} {
|
||||
t.Run(strconv.Itoa(status), func(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
service.recordMWISubscriptionAttempt(time.Now(), time.Hour)
|
||||
err := service.recordMWISubscriptionResult(
|
||||
&sip.Response{StatusCode: status, Reason: "rejected"},
|
||||
time.Hour, false, fmt.Errorf("SUBSCRIBE rejected with status %d", status),
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected permanent reject error")
|
||||
}
|
||||
service.mu.RLock()
|
||||
closed := service.mwiSubscriptionClosed
|
||||
refresh := service.mwiSubscriptionRefreshAt
|
||||
service.mu.RUnlock()
|
||||
if !closed || !refresh.IsZero() {
|
||||
t.Fatalf("closed=%t refresh=%v", closed, refresh)
|
||||
}
|
||||
now := time.Now()
|
||||
service.mu.Lock()
|
||||
service.registrationRefreshAt = now.Add(time.Hour)
|
||||
service.subscriptionRefreshAt = now.Add(time.Hour)
|
||||
service.lastPingAt = now
|
||||
service.mu.Unlock()
|
||||
if got := service.nextIMSMaintenanceAction(now); got == imsMaintenanceSubscribeMWI {
|
||||
t.Fatal("permanent MWI reject still scheduled SUBSCRIBE")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeMWI405StopsPeriodicRefresh(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
client, server := net.Pipe()
|
||||
service.activateProtectedRegistrationTCP(client)
|
||||
t.Cleanup(func() { _ = server.Close() })
|
||||
errorsSeen := make(chan error, 1)
|
||||
go func() {
|
||||
reader := bufio.NewReader(server)
|
||||
request, err := readSIPStreamMessage(reader)
|
||||
if err != nil {
|
||||
errorsSeen <- err
|
||||
return
|
||||
}
|
||||
_, err = io.WriteString(server, subscriptionWireResponse(request, 405, ""))
|
||||
errorsSeen <- err
|
||||
}()
|
||||
err := service.sendSubscribeMWI(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "405") {
|
||||
t.Fatalf("sendSubscribeMWI error = %v", err)
|
||||
}
|
||||
if err := <-errorsSeen; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.mu.RLock()
|
||||
closed := service.mwiSubscriptionClosed
|
||||
refresh := service.mwiSubscriptionRefreshAt
|
||||
service.mu.RUnlock()
|
||||
if !closed || !refresh.IsZero() {
|
||||
t.Fatalf("closed=%t refresh=%v", closed, refresh)
|
||||
}
|
||||
}
|
||||
@@ -393,6 +393,18 @@ func (s *Service) recordSubscriptionAttempt(at time.Time, expires time.Duration)
|
||||
s.signalIMSMaintenance()
|
||||
}
|
||||
|
||||
func subscriptionPermanentlyRejected(response *sip.Response) bool {
|
||||
if response == nil {
|
||||
return false
|
||||
}
|
||||
switch response.StatusCode {
|
||||
case 403, 405, 489:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) recordSubscriptionResult(
|
||||
response *sip.Response,
|
||||
requestedExpires time.Duration,
|
||||
@@ -403,6 +415,12 @@ func (s *Service) recordSubscriptionResult(
|
||||
s.mu.Lock()
|
||||
if resultErr != nil {
|
||||
s.subscriptionLastErr = resultErr.Error()
|
||||
if subscriptionPermanentlyRejected(response) {
|
||||
s.subscriptionClosed = true
|
||||
s.subscriptionDialog = registrationSubscriptionDialog{}
|
||||
s.subscriptionExpires = 0
|
||||
s.subscriptionRefreshAt = time.Time{}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return resultErr
|
||||
}
|
||||
|
||||
@@ -4,12 +4,15 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/emiago/sipgo/sip"
|
||||
)
|
||||
|
||||
func TestFirstSIPHeaderURI(t *testing.T) {
|
||||
@@ -141,8 +144,8 @@ func assertRegistrationSubscription(t *testing.T, request string, wantCSeq, expi
|
||||
t.Fatalf("To = %q, want tag %s", to, toTag)
|
||||
}
|
||||
contact := rawSIPHeaderValue(request, "Contact")
|
||||
if !strings.Contains(contact, ":16083;transport=tcp>") {
|
||||
t.Fatalf("Contact = %q, want protected server port and transport", contact)
|
||||
if !strings.Contains(contact, ":16083;ob;transport=tcp>") {
|
||||
t.Fatalf("Contact = %q, want protected server port, ob, and transport", contact)
|
||||
}
|
||||
viaBranch, err := parseTopViaBranch(rawSIPHeaderValue(request, "Via"))
|
||||
if err != nil || !strings.HasPrefix(viaBranch, "z9hG4bK") || len(viaBranch) != len("z9hG4bK")+36 {
|
||||
@@ -618,3 +621,86 @@ func waitForReginfoAOR(t *testing.T, service *Service, want string) {
|
||||
}
|
||||
t.Fatalf("reginfo AOR was not updated to %q", want)
|
||||
}
|
||||
|
||||
func TestRecordSubscriptionResultClosesOnPermanentReject(t *testing.T) {
|
||||
for _, status := range []int{403, 405, 489} {
|
||||
t.Run(strconv.Itoa(status), func(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
service.recordSubscriptionAttempt(time.Now(), time.Hour)
|
||||
err := service.recordSubscriptionResult(
|
||||
&sip.Response{StatusCode: status, Reason: "rejected"},
|
||||
time.Hour, false, fmt.Errorf("SUBSCRIBE rejected with status %d", status),
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected permanent reject error")
|
||||
}
|
||||
service.mu.RLock()
|
||||
closed := service.subscriptionClosed
|
||||
refresh := service.subscriptionRefreshAt
|
||||
service.mu.RUnlock()
|
||||
if !closed || !refresh.IsZero() {
|
||||
t.Fatalf("closed=%t refresh=%v", closed, refresh)
|
||||
}
|
||||
now := time.Now()
|
||||
service.mu.Lock()
|
||||
service.registrationRefreshAt = now.Add(time.Hour)
|
||||
service.lastPingAt = now
|
||||
service.mu.Unlock()
|
||||
if got := service.nextIMSMaintenanceAction(now); got == imsMaintenanceSubscribe {
|
||||
t.Fatal("permanent reject still scheduled SUBSCRIBE")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordSubscriptionResultKeepsRetryOnTemporaryReject(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
service.recordSubscriptionAttempt(time.Now(), time.Hour)
|
||||
before := service.subscriptionRefreshAt
|
||||
err := service.recordSubscriptionResult(
|
||||
&sip.Response{StatusCode: 503, Reason: "Service Unavailable"},
|
||||
time.Hour, false, errors.New("SUBSCRIBE rejected with status 503"),
|
||||
)
|
||||
if err == nil {
|
||||
t.Fatal("expected 503 error")
|
||||
}
|
||||
service.mu.RLock()
|
||||
closed := service.subscriptionClosed
|
||||
refresh := service.subscriptionRefreshAt
|
||||
service.mu.RUnlock()
|
||||
if closed || refresh.IsZero() || !refresh.Equal(before) {
|
||||
t.Fatalf("temporary reject closed=%t refresh=%v before=%v", closed, refresh, before)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeReg405StopsPeriodicRefresh(t *testing.T) {
|
||||
service := newProtectedKeepaliveTestService(t)
|
||||
client, server := net.Pipe()
|
||||
service.activateProtectedRegistrationTCP(client)
|
||||
t.Cleanup(func() { _ = server.Close() })
|
||||
errorsSeen := make(chan error, 1)
|
||||
go func() {
|
||||
reader := bufio.NewReader(server)
|
||||
request, err := readSIPStreamMessage(reader)
|
||||
if err != nil {
|
||||
errorsSeen <- err
|
||||
return
|
||||
}
|
||||
_, err = io.WriteString(server, subscriptionWireResponse(request, 405, ""))
|
||||
errorsSeen <- err
|
||||
}()
|
||||
err := service.sendSubscribeReg(context.Background())
|
||||
if err == nil || !strings.Contains(err.Error(), "405") {
|
||||
t.Fatalf("sendSubscribeReg error = %v", err)
|
||||
}
|
||||
if err := <-errorsSeen; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.mu.RLock()
|
||||
closed := service.subscriptionClosed
|
||||
refresh := service.subscriptionRefreshAt
|
||||
service.mu.RUnlock()
|
||||
if !closed || !refresh.IsZero() {
|
||||
t.Fatalf("closed=%t refresh=%v", closed, refresh)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package imscore
|
||||
|
||||
import "strings"
|
||||
|
||||
// sipTransportIsUDP reports an explicit SIP/UDP hop. Empty and TCP/TLS
|
||||
// stay on the connection-oriented family so a missing token cannot flip a
|
||||
// live TCP Via onto the UDP port-s rule.
|
||||
func sipTransportIsUDP(transport string) bool {
|
||||
return strings.EqualFold(strings.TrimSpace(transport), "udp")
|
||||
}
|
||||
|
||||
// protectedViaSentByPort picks the Via sent-by port for an IMS AKA
|
||||
// security association. RFC 3329 only negotiates port-c / port-s; it
|
||||
// does not set Via.
|
||||
//
|
||||
// UDP IPsec — TS 24.229 5.1.1.2.2 (c) and 5.1.1.4.2 (c): a protected
|
||||
// REGISTER Via sent-by includes the protected server port. 5.1.2A.1.1
|
||||
// (IMS AKA) (b) says the same for non-REGISTER. Annex K.2.1.2.2.2 /
|
||||
// K.2.1.4.1 repeat port-s for UDP. TS 33.203 7.1 UDP: the UE still
|
||||
// transmits from port-c and receives on port-s; 24.229 5.2.2.2 NOTE 3
|
||||
// says the P-CSCF replies to a different UE port than the request
|
||||
// source. Annex M SM7 (UDP-enc-tun) also puts port-s in Via.
|
||||
//
|
||||
// TCP / TLS — 5.1.1.2.2 (c) is written "for UDP" only. K.2.1.2.2.2 and
|
||||
// K.2.1.4.1 say a protected TCP Via carries the public IP or FQDN, not
|
||||
// port-s. 5.2.2.2 NOTE 3, TS 33.203 7.1 TCP, and RFC 3261 §18 send the
|
||||
// response on the same connection (UE port-c → P-CSCF port-s). There
|
||||
// is no TCP/TLS clause that requires rewriting a working sent-by to
|
||||
// port-s; fallback stays the actual TCP source or configured local
|
||||
// port.
|
||||
func protectedViaSentByPort(transport string, portS, fallback int) int {
|
||||
if sipTransportIsUDP(transport) && portS > 0 {
|
||||
return portS
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package imscore
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestProtectedViaSentByPortByTransportFamily(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
transport string
|
||||
portS int
|
||||
fallback int
|
||||
want int
|
||||
}{
|
||||
{name: "udp uses port-s", transport: "udp", portS: 48554, fallback: 5060, want: 48554},
|
||||
{name: "UDP token is case-insensitive", transport: "UDP", portS: 48554, fallback: 5060, want: 48554},
|
||||
{name: "udp without port-s keeps fallback", transport: "udp", portS: 0, fallback: 5060, want: 5060},
|
||||
{name: "tcp keeps fallback not port-s", transport: "tcp", portS: 48554, fallback: 5060, want: 5060},
|
||||
{name: "tls keeps fallback not port-s", transport: "tls", portS: 48554, fallback: 50309, want: 50309},
|
||||
{name: "empty transport does not take UDP rule", transport: "", portS: 48554, fallback: 5060, want: 5060},
|
||||
}
|
||||
for _, test := range tests {
|
||||
if got := protectedViaSentByPort(test.transport, test.portS, test.fallback); got != test.want {
|
||||
t.Fatalf("%s: sent-by = %d, want %d", test.name, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSipTransportIsUDPRequiresExplicitUDP(t *testing.T) {
|
||||
if !sipTransportIsUDP("udp") || !sipTransportIsUDP("UDP") {
|
||||
t.Fatal("udp was not recognized")
|
||||
}
|
||||
for _, transport := range []string{"", "tcp", "tls", "auto"} {
|
||||
if sipTransportIsUDP(transport) {
|
||||
t.Fatalf("%q was treated as UDP", transport)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,8 @@ type InboundVoiceRequest struct {
|
||||
Session *imsendpoint.Session
|
||||
ReferTo string
|
||||
ReferSub string
|
||||
Supported string
|
||||
MinSE string
|
||||
}
|
||||
|
||||
// InboundVoiceResponse is one provisional or final response to an inbound
|
||||
@@ -144,6 +146,8 @@ func (s *Service) registeredSIPDialogProfile(reserveCSeq bool) (SIPDialogProfile
|
||||
initialCSeq = s.reserveSIPCSeqLocked(session, route.securityVerify != "")
|
||||
}
|
||||
contactURI, contactHeader := registeredVoiceContact(s.cfg, registeredContactUser, route.serverAddress)
|
||||
// LocalAddress is the Via sent-by: TCP/TLS keeps the actual source
|
||||
// (port-c); UDP IPsec uses port-s. Contact stays on port-s.
|
||||
return SIPDialogProfile{
|
||||
LocalURI: localURI, Domain: strings.TrimSpace(s.cfg.Domain),
|
||||
FromTag: session.fromTag, LocalAddress: route.clientAddress, RemoteAddress: route.remoteAddress,
|
||||
@@ -168,22 +172,36 @@ func (s *Service) reserveSIPCSeqLocked(session *registerSession, subscriptionCon
|
||||
}
|
||||
|
||||
func registeredVoiceContact(cfg *IMSConfig, user, address string) (string, string) {
|
||||
uri := fmt.Sprintf("sip:%s@%s", user, address)
|
||||
// TS 24.229 5.1.2A.1.1: dialog Contact uses the registered address and
|
||||
// the "ob" URI parameter so subsequent in-dialog requests stay on this
|
||||
// flow. Registration-only parameters such as +sip.instance, expires and
|
||||
// reg-id are not copied onto non-REGISTER requests.
|
||||
uri := fmt.Sprintf("sip:%s@%s;ob", user, address)
|
||||
template := cfg.RegisterTemplate
|
||||
if len(template.ContactOrder) == 0 {
|
||||
return uri, "<" + uri + ">"
|
||||
}
|
||||
instance := strings.TrimSpace(cfg.IMEI)
|
||||
if instance == "" {
|
||||
instance = strings.TrimSpace(cfg.DeviceID)
|
||||
}
|
||||
header := imsheaders.IMSContactURI(uri, imsheaders.IMSContactOptions{
|
||||
AccessType: template.AccessType, Instance: instance,
|
||||
ICSIRef: template.ICSIRef, ParamOrder: template.ContactOrder,
|
||||
AccessType: template.AccessType,
|
||||
ICSIRef: template.ICSIRef,
|
||||
ParamOrder: dialogContactParamOrder(template.ContactOrder),
|
||||
})
|
||||
return uri, header
|
||||
}
|
||||
|
||||
func dialogContactParamOrder(order []string) []string {
|
||||
filtered := make([]string, 0, len(order))
|
||||
for _, name := range order {
|
||||
switch strings.ToLower(strings.TrimSpace(name)) {
|
||||
case "sip_instance", "reg_id", "expires", "ob":
|
||||
continue
|
||||
default:
|
||||
filtered = append(filtered, name)
|
||||
}
|
||||
}
|
||||
return filtered
|
||||
}
|
||||
|
||||
// EventBus returns the service event bus used by lifecycle consumers.
|
||||
func (s *Service) EventBus() *EventBus {
|
||||
if s == nil {
|
||||
@@ -218,6 +236,8 @@ func (s *Service) handleInboundVoice(dispatch inboundSIPDispatch) (inboundSIPRes
|
||||
SessionExpires: rawSIPHeaderValue(dispatch.raw, "Session-Expires"),
|
||||
ReferTo: rawSIPHeaderValue(dispatch.raw, "Refer-To"),
|
||||
ReferSub: rawSIPHeaderValue(dispatch.raw, "Refer-Sub"),
|
||||
Supported: rawSIPHeaderValue(dispatch.raw, "Supported"),
|
||||
MinSE: rawSIPHeaderValue(dispatch.raw, "Min-SE"),
|
||||
Body: body, Responder: newInboundVoiceResponder(dispatch.raw, dispatch.reply),
|
||||
Dialog: dialogRead.handle, DialogMatched: dialogRead.matched,
|
||||
DialogResponded: dialogRead.responded, DialogTerminated: dialogRead.terminated,
|
||||
|
||||
@@ -35,13 +35,21 @@ func TestRegisteredSIPDialogProfileUsesNegotiatedIdentityAndBinding(t *testing.T
|
||||
if profile.LocalURI != "sip:+447840844894@o2.co.uk" || profile.InitialCSeq != 6 {
|
||||
t.Fatalf("registered identity/CSeq = %q/%d", profile.LocalURI, profile.InitialCSeq)
|
||||
}
|
||||
if profile.LocalAddress != "[2001:db8::10]:50309" || profile.ContactURI != "sip:binding-uuid@[2001:db8::10]:48554" {
|
||||
t.Fatalf("registered addresses = local %q contact %q", profile.LocalAddress, profile.ContactURI)
|
||||
if profile.Transport != "tcp" {
|
||||
t.Fatalf("TCP IPsec transport = %q", profile.Transport)
|
||||
}
|
||||
wantContact := `<sip:binding-uuid@[2001:db8::10]:48554>;+g.3gpp.accesstype="wlan1";+sip.instance="<urn:gsma:imei:86034905-044531-1>";audio`
|
||||
if profile.LocalAddress != "[2001:db8::10]:50309" || profile.ContactURI != "sip:binding-uuid@[2001:db8::10]:48554;ob" {
|
||||
t.Fatalf("TCP Via/Contact = local %q contact %q, want Via=port-c Contact=port-s", profile.LocalAddress, profile.ContactURI)
|
||||
}
|
||||
wantContact := `<sip:binding-uuid@[2001:db8::10]:48554;ob>;+g.3gpp.accesstype="wlan1";audio`
|
||||
if profile.ContactHeader != wantContact {
|
||||
t.Fatalf("Contact = %q, want %q", profile.ContactHeader, wantContact)
|
||||
}
|
||||
for _, unwanted := range []string{"+sip.instance", "reg-id=", ";expires="} {
|
||||
if strings.Contains(profile.ContactHeader, unwanted) {
|
||||
t.Fatalf("dialog Contact copied registration param %q: %q", unwanted, profile.ContactHeader)
|
||||
}
|
||||
}
|
||||
nextProfile, err := service.RegisteredSIPDialogProfile()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -51,6 +59,65 @@ func TestRegisteredSIPDialogProfileUsesNegotiatedIdentityAndBinding(t *testing.T
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisteredSIPDialogProfileUDPViaUsesPortS(t *testing.T) {
|
||||
service := &Service{
|
||||
cfg: &IMSConfig{
|
||||
Domain: "ims.example", LocalIP: net.ParseIP("192.0.2.10"), LocalPort: 5060, Transport: "udp",
|
||||
RegisterTemplate: IMSRegisterTemplate{ContactOrder: []string{"audio"}},
|
||||
},
|
||||
regState: regRegistered, externalTransport: true,
|
||||
protectedClientPort: 50309, protectedServerPort: 48554,
|
||||
regSession: ®isterSession{
|
||||
contactUser: "binding", cseq: 3,
|
||||
publicID: "sip:user@ims.example",
|
||||
security: &securityAgreement{verifyHeader: "ipsec-3gpp;alg=hmac-sha-1-96"},
|
||||
},
|
||||
}
|
||||
profile, err := service.RegisteredSIPDialogProfile()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if profile.Transport != "udp" {
|
||||
t.Fatalf("UDP IPsec transport = %q", profile.Transport)
|
||||
}
|
||||
if profile.LocalAddress != "192.0.2.10:48554" {
|
||||
t.Fatalf("UDP Via sent-by = %q, want port-s", profile.LocalAddress)
|
||||
}
|
||||
if profile.ContactURI != "sip:binding@192.0.2.10:48554;ob" {
|
||||
t.Fatalf("UDP Contact = %q, want port-s", profile.ContactURI)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisteredSIPDialogProfilePreloadsPCSCFThenServiceRoute(t *testing.T) {
|
||||
client, server := net.Pipe()
|
||||
t.Cleanup(func() { _ = client.Close(); _ = server.Close() })
|
||||
service := &Service{
|
||||
cfg: &IMSConfig{
|
||||
Domain: "ims.example", LocalIP: net.ParseIP("192.0.2.10"),
|
||||
RegisterTemplate: IMSRegisterTemplate{ContactOrder: []string{"audio"}},
|
||||
},
|
||||
regState: regRegistered, registrationTCP: client, registrationTCPProtected: true,
|
||||
protectedClientPort: 49939, protectedServerPort: 18105,
|
||||
registrationRemote: &net.UDPAddr{IP: net.ParseIP("10.128.120.17"), Port: 50600},
|
||||
regSession: ®isterSession{
|
||||
contactUser: "binding", cseq: 3,
|
||||
publicID: "sip:user@ims.example", serviceRoute: "<sip:orig@scscf.ims.example;lr>",
|
||||
security: &securityAgreement{
|
||||
verifyHeader: "ipsec-3gpp;alg=hmac-sha-1-96",
|
||||
server: &securityMechanism{PortS: 50600},
|
||||
},
|
||||
},
|
||||
}
|
||||
profile, err := service.RegisteredSIPDialogProfile()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "<sip:10.128.120.17:50600;transport=tcp;lr>,<sip:orig@scscf.ims.example;lr>"
|
||||
if profile.ServiceRoute != want {
|
||||
t.Fatalf("ServiceRoute = %q, want %q", profile.ServiceRoute, want)
|
||||
}
|
||||
}
|
||||
|
||||
type recordingVoiceHandler struct {
|
||||
request InboundVoiceRequest
|
||||
result InboundVoiceResult
|
||||
@@ -153,6 +220,9 @@ func TestInboundVoiceResponderRetainsReplyPathForFinalSDPResponse(t *testing.T)
|
||||
if handler.request.SessionExpires != "120;refresher=uas" || rawSIPHeaderValue(responses[1], "Session-Expires") != "120" {
|
||||
t.Fatalf("Session-Expires request/response = %q / %q", handler.request.SessionExpires, responses[1])
|
||||
}
|
||||
if handler.request.Supported != "timer" || handler.request.MinSE != "90" {
|
||||
t.Fatalf("Supported/Min-SE = %q / %q", handler.request.Supported, handler.request.MinSE)
|
||||
}
|
||||
if err := handler.request.Responder.Respond(InboundVoiceResponse{StatusCode: 486}); err == nil {
|
||||
t.Fatal("second final response unexpectedly succeeded")
|
||||
}
|
||||
@@ -166,6 +236,7 @@ func inboundVoiceInvite(callID string) string {
|
||||
"To: <sip:user@ims.example>\r\n"+
|
||||
"Call-ID: %s\r\nCSeq: 1 INVITE\r\n"+
|
||||
"Session-Expires: 120;refresher=uas\r\n"+
|
||||
"Supported: timer\r\nMin-SE: 90\r\n"+
|
||||
"Content-Type: application/sdp\r\nContent-Length: %d\r\n\r\n%s", callID, len(body), body)
|
||||
}
|
||||
|
||||
|
||||
+88
-1
@@ -1,6 +1,11 @@
|
||||
package imsheaders
|
||||
|
||||
import "strings"
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/emiago/sipgo/sip"
|
||||
)
|
||||
|
||||
// EffectiveRoute prefers Service-Route and falls back to Path. The two are
|
||||
// never stacked: RFC 3608 Service-Route is the outbound route set, and Path
|
||||
@@ -24,6 +29,31 @@ func RouteSet(serviceRoute, outboundProxy string) []string {
|
||||
return routes
|
||||
}
|
||||
|
||||
// SplitRouteValues splits a stored Route / Service-Route list on commas.
|
||||
func SplitRouteValues(value string) []string {
|
||||
var routes []string
|
||||
for _, item := range strings.Split(value, ",") {
|
||||
if item = strings.TrimSpace(item); item != "" {
|
||||
routes = append(routes, item)
|
||||
}
|
||||
}
|
||||
return routes
|
||||
}
|
||||
|
||||
// RecordRouteSet builds the RFC 3261 12.1.2 UAC route set from Record-Route
|
||||
// header values. Each value may itself be a comma-separated URI list. The
|
||||
// resulting URIs are taken in reverse order, preserving parameters.
|
||||
func RecordRouteSet(values []string) []string {
|
||||
var uris []string
|
||||
for _, value := range values {
|
||||
uris = append(uris, SplitRouteValues(value)...)
|
||||
}
|
||||
for left, right := 0, len(uris)-1; left < right; left, right = left+1, right-1 {
|
||||
uris[left], uris[right] = uris[right], uris[left]
|
||||
}
|
||||
return uris
|
||||
}
|
||||
|
||||
// FirstRoute returns the first effective route.
|
||||
func FirstRoute(serviceRoute, outboundProxy string) string {
|
||||
routes := RouteSet(serviceRoute, outboundProxy)
|
||||
@@ -32,3 +62,60 @@ func FirstRoute(serviceRoute, outboundProxy string) string {
|
||||
}
|
||||
return routes[0]
|
||||
}
|
||||
|
||||
// PreloadedOriginatingRoute builds the TS 24.229 5.1.2A.1.1 preloaded Route
|
||||
// set: P-CSCF (discovery IP and protected server port) first, then the saved
|
||||
// Service-Route list. Path is not a substitute for Service-Route. A Service-
|
||||
// Route hop that is already the same URI as the P-CSCF is not duplicated.
|
||||
func PreloadedOriginatingRoute(pcscf, serviceRoute string) string {
|
||||
pcscf = strings.TrimSpace(pcscf)
|
||||
routes := make([]string, 0, 4)
|
||||
if pcscf != "" {
|
||||
routes = append(routes, pcscf)
|
||||
}
|
||||
for _, item := range SplitRouteValues(serviceRoute) {
|
||||
if pcscf != "" && sameRouteHop(item, pcscf) {
|
||||
continue
|
||||
}
|
||||
routes = append(routes, item)
|
||||
}
|
||||
return strings.Join(routes, ",")
|
||||
}
|
||||
|
||||
func sameRouteHop(left, right string) bool {
|
||||
leftURI, leftOK := ParseRouteURI(left)
|
||||
rightURI, rightOK := ParseRouteURI(right)
|
||||
if !leftOK || !rightOK {
|
||||
return strings.EqualFold(strings.TrimSpace(left), strings.TrimSpace(right))
|
||||
}
|
||||
return strings.EqualFold(leftURI.Host, rightURI.Host) &&
|
||||
routePort(leftURI) == routePort(rightURI) &&
|
||||
strings.EqualFold(leftURI.User, rightURI.User)
|
||||
}
|
||||
|
||||
// ParseRouteURI extracts a SIP URI from a Route / Record-Route / Contact value.
|
||||
func ParseRouteURI(value string) (sip.Uri, bool) {
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return sip.Uri{}, false
|
||||
}
|
||||
if start, end := strings.IndexByte(value, '<'), strings.IndexByte(value, '>'); start >= 0 && end > start {
|
||||
value = strings.TrimSpace(value[start+1 : end])
|
||||
}
|
||||
var uri sip.Uri
|
||||
if err := sip.ParseUri(value, &uri); err != nil {
|
||||
return sip.Uri{}, false
|
||||
}
|
||||
uri.Host = strings.Trim(strings.TrimSpace(uri.Host), "[]")
|
||||
return uri, uri.Host != ""
|
||||
}
|
||||
|
||||
func routePort(uri sip.Uri) int {
|
||||
if uri.Port > 0 {
|
||||
return uri.Port
|
||||
}
|
||||
if net.ParseIP(uri.Host) != nil {
|
||||
return 5060
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -22,3 +22,45 @@ func TestRouteSetDoesNotStackEmptyProxy(t *testing.T) {
|
||||
t.Fatalf("RouteSet = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreloadedOriginatingRouteStacksPCSCFThenServiceRoute(t *testing.T) {
|
||||
got := PreloadedOriginatingRoute(
|
||||
"<sip:10.128.120.17:50600;transport=tcp;lr>",
|
||||
"<sip:orig@scscf.ims.example;lr>,<sip:icscf.ims.example;lr>",
|
||||
)
|
||||
want := "<sip:10.128.120.17:50600;transport=tcp;lr>,<sip:orig@scscf.ims.example;lr>,<sip:icscf.ims.example;lr>"
|
||||
if got != want {
|
||||
t.Fatalf("PreloadedOriginatingRoute = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreloadedOriginatingRouteDoesNotDuplicatePCSCF(t *testing.T) {
|
||||
got := PreloadedOriginatingRoute(
|
||||
"<sip:10.128.120.17:50600;transport=tcp;lr>",
|
||||
"<sip:10.128.120.17:50600;lr>,<sip:orig@scscf.ims.example;lr>",
|
||||
)
|
||||
want := "<sip:10.128.120.17:50600;transport=tcp;lr>,<sip:orig@scscf.ims.example;lr>"
|
||||
if got != want {
|
||||
t.Fatalf("deduped Route = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordRouteSetReversesCommaSeparatedValues(t *testing.T) {
|
||||
got := RecordRouteSet([]string{"<sip:edge-one.example;lr>, <sip:edge-two.example;lr>"})
|
||||
want := []string{"<sip:edge-two.example;lr>", "<sip:edge-one.example;lr>"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("RecordRouteSet = %#v, want %#v", got, want)
|
||||
}
|
||||
got = RecordRouteSet([]string{"<sip:edge-a.example;lr>", "<sip:edge-b.example;lr>"})
|
||||
want = []string{"<sip:edge-b.example;lr>", "<sip:edge-a.example;lr>"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("multi-header RecordRouteSet = %#v, want %#v", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreloadedOriginatingRouteWithoutServiceRouteIsPCSCF(t *testing.T) {
|
||||
got := PreloadedOriginatingRoute("<sip:10.128.120.17:50600;transport=tcp;lr>", "")
|
||||
if got != "<sip:10.128.120.17:50600;transport=tcp;lr>" {
|
||||
t.Fatalf("P-CSCF-only Route = %q", got)
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -318,7 +318,7 @@ func (a *Agent) executeOutboundCall(
|
||||
if err := call.StartOutboundNoAnswerTimerCurrent(voiceInviteTimeout); err != nil {
|
||||
return imscore.SIPResponse{}, a.handleOutboundInviteRuntimeError(call, err)
|
||||
}
|
||||
logging.RunDebug("IMS INVITE outbound", "sip", logging.RedactSIPRaw(invite))
|
||||
logOutboundInviteRequest(invite)
|
||||
response, err := a.startVoiceClientInvite(ctx, call, invite)
|
||||
call.StopOutboundNoAnswerTimer()
|
||||
if response.StatusCode >= 200 {
|
||||
|
||||
@@ -12,8 +12,11 @@ import (
|
||||
|
||||
const (
|
||||
voiceInviteSupported = "100rel, timer, replaces, norefersub, early-session, sec-agree, precondition"
|
||||
voiceInviteAllow = "INVITE, ACK, CANCEL, BYE, UPDATE, REFER, NOTIFY, MESSAGE, OPTIONS"
|
||||
voiceFeatureCaps = `*;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel"`
|
||||
// TS 24.229 5.1.3.1: initial INVITE Accept must include SDP and the 3GPP
|
||||
// IM CN subsystem XML body MIME type.
|
||||
voiceInviteAccept = "application/sdp, application/3gpp-ims+xml"
|
||||
voiceInviteAllow = "INVITE, ACK, CANCEL, BYE, UPDATE, REFER, NOTIFY, MESSAGE, OPTIONS"
|
||||
voiceFeatureCaps = `*;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel"`
|
||||
)
|
||||
|
||||
// BuildIMSInvite builds the initial IMS INVITE with the registered route.
|
||||
@@ -75,6 +78,7 @@ func voiceIMSRequestOptions(dialog voiceSIPDialog, input voiceInitialRequest) si
|
||||
if strings.TrimSpace(dialog.sessionID) != "" {
|
||||
headers = append(headers, sip.NewHeader("Session-ID", strings.TrimSpace(dialog.sessionID)))
|
||||
}
|
||||
headers = append(headers, sip.NewHeader("Accept", voiceInviteAccept))
|
||||
headers = append(headers, sip.NewHeader("P-Early-Media", "supported"))
|
||||
headers = append(headers, sip.NewHeader("Privacy", "none"))
|
||||
headers = append(headers, sip.NewHeader("Feature-Caps", voiceFeatureCaps))
|
||||
@@ -96,6 +100,9 @@ func voiceIMSRequestOptions(dialog voiceSIPDialog, input voiceInitialRequest) si
|
||||
PreferredService: "urn:urn-7:3gpp-service.ims.icsi.mmtel", AddAcceptContact: true,
|
||||
AcceptContact: `*;+g.3gpp.icsi-ref="urn%3Aurn-7%3A3gpp-service.ims.icsi.mmtel"`,
|
||||
AddUserAgent: strings.TrimSpace(dialog.userAgent) != "", UserAgent: dialog.userAgent,
|
||||
// IR.92 2.2.8 / RFC 4028: Supported: timer is required. Session-Expires
|
||||
// on the initial INVITE may be 1800 or omitted. Omitting it is allowed
|
||||
// by the spec, not a partial alignment. This UAC omits it.
|
||||
AddSupported: true, Supported: voiceInviteSupported, AddAllow: true, Allow: voiceInviteAllow,
|
||||
PreferredIdentity: "<" + dialog.localURI + ">", SecurityVerify: dialog.securityVerify,
|
||||
Runtime: sipkit.IMSRuntimeSnapshot{PAccessNetworkInfo: dialog.pani, LocalAddr: dialog.localAddress, Transport: dialog.transport},
|
||||
|
||||
@@ -133,6 +133,8 @@ func inboundRequestFromEvent(
|
||||
SessionExpires: requestHeaderValue(request, "Session-Expires"),
|
||||
ReferTo: requestHeaderValue(request, "Refer-To"),
|
||||
ReferSub: requestHeaderValue(request, "Refer-Sub"),
|
||||
Supported: requestHeaderValue(request, "Supported"),
|
||||
MinSE: requestHeaderValue(request, "Min-SE"),
|
||||
Body: append([]byte(nil), request.Body()...), Request: request.Clone(),
|
||||
ServerInvite: handle, Session: session,
|
||||
}
|
||||
|
||||
@@ -135,7 +135,7 @@ func (a *Agent) beginInboundInvite(call *Call, request imscore.InboundVoiceReque
|
||||
if call.ClientCallID() == "" {
|
||||
call.SetClientCallID(call.CallID() + "-" + voiceHex(16))
|
||||
}
|
||||
call.applyVoiceSessionExpires(request.SessionExpires)
|
||||
call.applyInboundSessionTimer(request.Supported, request.SessionExpires, request.MinSE)
|
||||
if request.ServerInvite != nil {
|
||||
if _, err := a.rejectStoredServerInvite(call, 100); err != nil {
|
||||
a.releaseInboundCall(call, err, false)
|
||||
|
||||
@@ -4,9 +4,12 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"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"
|
||||
@@ -68,7 +71,143 @@ func (a *Agent) handleIMS1xxResponse(
|
||||
return a.sendReliableProvisionalPRACK(ctx, call, rseq)
|
||||
}
|
||||
|
||||
func logOutboundInviteRequest(raw string) {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return
|
||||
}
|
||||
body := ""
|
||||
if index := strings.Index(raw, "\r\n\r\n"); index >= 0 {
|
||||
body = raw[index+4:]
|
||||
}
|
||||
fromTag := voiceHeaderTag(voiceRawHeader(raw, "From"))
|
||||
toTag := voiceHeaderTag(voiceRawHeader(raw, "To"))
|
||||
callID := voiceRawHeader(raw, "Call-ID")
|
||||
routes := voiceRawHeaders(raw, "Route")
|
||||
logging.Info("IMS INVITE outbound",
|
||||
"ruri_host", inviteRequestURIHost(raw),
|
||||
"ruri_user_kind", inviteRequestURIUserKind(raw),
|
||||
"via", voiceRawHeader(raw, "Via"),
|
||||
"via_port", sipHeaderSentByPort(voiceRawHeader(raw, "Via")),
|
||||
"route", strings.Join(routes, ","),
|
||||
"route_hops", len(routes),
|
||||
"route_orig", voiceRouteHasOrig(routes),
|
||||
"cseq", voiceRawHeader(raw, "CSeq"),
|
||||
"accept", voiceRawHeader(raw, "Accept"),
|
||||
"contact_has_ob", strings.Contains(strings.ToLower(voiceRawHeader(raw, "Contact")), ";ob"),
|
||||
"contact_has_instance", strings.Contains(strings.ToLower(voiceRawHeader(raw, "Contact")), "+sip.instance"),
|
||||
"session_expires_present", voiceRawHeader(raw, "Session-Expires") != "",
|
||||
"body_bytes", len(body),
|
||||
"content_length", voiceRawHeader(raw, "Content-Length"),
|
||||
"qos_remote", sdpQoSCurrent(body, "remote"),
|
||||
"to_has_tag", toTag != "",
|
||||
"call_id_kind", inviteTokenKind(callID),
|
||||
"call_id_len", len(strings.TrimSpace(callID)),
|
||||
"from_tag_kind", inviteTokenKind(fromTag),
|
||||
"from_tag_len", len(fromTag),
|
||||
"from_tag_suffix", inviteTokenSuffix(fromTag),
|
||||
)
|
||||
}
|
||||
|
||||
func sipHeaderSentByPort(via string) int {
|
||||
fields := strings.Fields(via)
|
||||
if len(fields) < 2 {
|
||||
return 0
|
||||
}
|
||||
sentBy, _, _ := strings.Cut(fields[1], ";")
|
||||
_, portText, err := net.SplitHostPort(strings.TrimSpace(sentBy))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
port, err := strconv.Atoi(portText)
|
||||
if err != nil || port < 1 {
|
||||
return 0
|
||||
}
|
||||
return port
|
||||
}
|
||||
|
||||
func inviteRequestURIHost(raw string) string {
|
||||
line, _, _ := strings.Cut(raw, "\r\n")
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 2 {
|
||||
return ""
|
||||
}
|
||||
var uri sip.Uri
|
||||
if err := sip.ParseUri(fields[1], &uri); err != nil {
|
||||
return ""
|
||||
}
|
||||
return strings.ToLower(strings.Trim(uri.Host, "[]"))
|
||||
}
|
||||
|
||||
func inviteRequestURIUserKind(raw string) string {
|
||||
line, _, _ := strings.Cut(raw, "\r\n")
|
||||
fields := strings.Fields(line)
|
||||
if len(fields) < 2 {
|
||||
return ""
|
||||
}
|
||||
var uri sip.Uri
|
||||
if err := sip.ParseUri(fields[1], &uri); err != nil {
|
||||
return ""
|
||||
}
|
||||
user := strings.TrimSpace(uri.User)
|
||||
switch {
|
||||
case user == "":
|
||||
return "empty"
|
||||
case strings.HasPrefix(user, "+"):
|
||||
return "e164"
|
||||
case isDigits(user) && len(user) <= 6:
|
||||
return "shortcode"
|
||||
case isDigits(user):
|
||||
return "digits"
|
||||
default:
|
||||
return "other"
|
||||
}
|
||||
}
|
||||
|
||||
func isDigits(value string) bool {
|
||||
if value == "" {
|
||||
return false
|
||||
}
|
||||
for _, character := range value {
|
||||
if character < '0' || character > '9' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func voiceRawHeader(raw, name string) string {
|
||||
values := voiceRawHeaders(raw, name)
|
||||
if len(values) == 0 {
|
||||
return ""
|
||||
}
|
||||
return values[0]
|
||||
}
|
||||
|
||||
func voiceRawHeaders(raw, name string) []string {
|
||||
prefix := strings.ToLower(name) + ":"
|
||||
var values []string
|
||||
for _, line := range strings.Split(raw, "\r\n") {
|
||||
if strings.HasPrefix(strings.ToLower(line), prefix) {
|
||||
values = append(values, strings.TrimSpace(line[len(name)+1:]))
|
||||
}
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func voiceRouteHasOrig(routes []string) bool {
|
||||
for _, route := range routes {
|
||||
for _, item := range strings.Split(route, ",") {
|
||||
item = strings.ToLower(strings.TrimSpace(item))
|
||||
if strings.Contains(item, "sip:orig@") || strings.Contains(item, "sip:orig;") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func logOutboundInviteResponse(message string, response imscore.SIPResponse) {
|
||||
toTag := voiceHeaderTag(voiceResponseHeader(response.Headers, "To"))
|
||||
logging.Info(message,
|
||||
"status", response.StatusCode,
|
||||
"reason", response.Reason,
|
||||
@@ -76,9 +215,37 @@ func logOutboundInviteResponse(message string, response imscore.SIPResponse) {
|
||||
"rseq", voiceResponseHeader(response.Headers, "RSeq"),
|
||||
"warning", logging.RedactSIPRaw(voiceResponseHeader(response.Headers, "Warning")),
|
||||
"network_reason", logging.RedactSIPRaw(voiceResponseHeader(response.Headers, "Reason")),
|
||||
"to_has_tag", toTag != "",
|
||||
"to_tag_kind", inviteTokenKind(toTag),
|
||||
"to_tag_len", len(toTag),
|
||||
"to_tag_suffix", inviteTokenSuffix(toTag),
|
||||
)
|
||||
}
|
||||
|
||||
func inviteTokenKind(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
switch {
|
||||
case value == "":
|
||||
return "empty"
|
||||
case inviteLongDigitPattern.MatchString(value):
|
||||
return "redacted"
|
||||
default:
|
||||
return "opaque"
|
||||
}
|
||||
}
|
||||
|
||||
func inviteTokenSuffix(value string) string {
|
||||
if inviteTokenKind(value) != "opaque" {
|
||||
return ""
|
||||
}
|
||||
if len(value) > 4 {
|
||||
return value[len(value)-4:]
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
var inviteLongDigitPattern = regexp.MustCompile(`\d{8,}`)
|
||||
|
||||
func (a *Agent) sendReliableProvisionalPRACK(ctx context.Context, call *Call, rseq uint32) error {
|
||||
options := reliableProvisionalPRACKOptions(
|
||||
call,
|
||||
|
||||
@@ -7,6 +7,15 @@ import (
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/voice/callstate"
|
||||
)
|
||||
|
||||
func TestReservedLocalOfferDoesNotNeedSegmentedUpdate(t *testing.T) {
|
||||
if !sdpPreconditionsSatisfied(sdpQoSReservedLocal) {
|
||||
t.Fatal("reserved-local first offer still waits for a segmented UPDATE")
|
||||
}
|
||||
if strings.Contains(sdpQoSReservedLocal, "a=curr:qos local none") {
|
||||
t.Fatal("reserved-local offer advertised unmet local qos")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSDPPreconditionsSatisfied(t *testing.T) {
|
||||
if !sdpPreconditionsSatisfied("v=0\r\nm=audio 9 RTP/AVP 0\r\n") {
|
||||
t.Fatal("SDP without qos should be vacuously met")
|
||||
|
||||
@@ -17,6 +17,10 @@ const (
|
||||
voiceSessionRefreshTimeout = 5 * time.Second
|
||||
sessionRefresherUAC = "uac"
|
||||
sessionRefresherUAS = "uas"
|
||||
// IR.92 2.2.8: inbound 2xx uses 1800 when the peer advertised timer
|
||||
// but omitted Session-Expires. Outbound INVITE may omit the header;
|
||||
// that is spec-complete, not a leftover.
|
||||
defaultIMSSessionExpires = 1800
|
||||
)
|
||||
|
||||
type sessionExpiresOffer struct {
|
||||
@@ -61,6 +65,38 @@ func parseMinSEHeader(value string) time.Duration {
|
||||
return time.Duration(seconds) * time.Second
|
||||
}
|
||||
|
||||
func containsTimerOption(supported string) bool {
|
||||
for _, token := range strings.Split(supported, ",") {
|
||||
if strings.EqualFold(strings.TrimSpace(token), "timer") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c *Call) applyInboundSessionTimer(supported, sessionExpires, minSE string) {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(sessionExpires) != "" {
|
||||
c.applyVoiceSessionExpires(sessionExpires)
|
||||
c.applySessionMinSE(parseMinSEHeader(minSE))
|
||||
return
|
||||
}
|
||||
if !containsTimerOption(supported) {
|
||||
c.applySessionMinSE(parseMinSEHeader(minSE))
|
||||
return
|
||||
}
|
||||
expires := defaultIMSSessionExpires
|
||||
if parsed := parseMinSEHeader(minSE); parsed > 0 {
|
||||
if seconds := int(parsed / time.Second); seconds > expires {
|
||||
expires = seconds
|
||||
}
|
||||
}
|
||||
c.applyVoiceSessionExpires(strconv.Itoa(expires))
|
||||
c.applySessionMinSE(parseMinSEHeader(minSE))
|
||||
}
|
||||
|
||||
func (c *Call) applyVoiceSessionExpires(value string) {
|
||||
offer := parseSessionExpiresOffer(value)
|
||||
if strings.TrimSpace(value) != "" && !offer.OK {
|
||||
|
||||
@@ -12,6 +12,57 @@ import (
|
||||
"github.com/iniwex5/vowifi-go/internal/vowifi/voice/callstate"
|
||||
)
|
||||
|
||||
func TestInitialInviteOmitsSessionExpiresPerIR92(t *testing.T) {
|
||||
agent := newTestAgent(t)
|
||||
call := NewCall(agent, callstate.DirectionOutbound, "call-se-omit", "+447700900001")
|
||||
invite := BuildIMSInvite(agent, call)
|
||||
if !strings.Contains(invite, "Supported: "+voiceInviteSupported) {
|
||||
t.Fatalf("initial INVITE missing Supported timer: %s", invite)
|
||||
}
|
||||
if voiceTestHeader(invite, "Session-Expires") != "" {
|
||||
t.Fatalf("IR.92 2.2.8 allows omitting Session-Expires; got %q", voiceTestHeader(invite, "Session-Expires"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundInviteWithoutSessionExpiresUsesIR92Default(t *testing.T) {
|
||||
agent := startedVoiceAgent(t)
|
||||
peer := listenVoiceUDP(t)
|
||||
responder := &capturedVoiceResponder{localTag: "local-tag"}
|
||||
invite := inboundAgentInvite("call-in-se-default", peer, responder)
|
||||
invite.Supported = "100rel, timer"
|
||||
if _, err := agent.HandleInboundVoiceRequest(invite); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client := listenVoiceUDP(t)
|
||||
if _, err := agent.AnswerWithSDP(invite.CallID, voiceSDP(client.LocalAddr().(*net.UDPAddr).Port)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := agent.callByID(invite.CallID)
|
||||
response := responder.lastResponse()
|
||||
if response.SessionExpires != "1800;refresher=uac" {
|
||||
t.Fatalf("IR.92 inbound 2xx Session-Expires = %q", response.SessionExpires)
|
||||
}
|
||||
if call.weAreSessionRefresher() || call.voiceSessionExpires() != 1800*time.Second {
|
||||
t.Fatalf("inbound default refresher=%t expires=%s", call.weAreSessionRefresher(), call.voiceSessionExpires())
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundInviteWithoutTimerDoesNotInventSessionExpires(t *testing.T) {
|
||||
call := NewCall(nil, callstate.DirectionInbound, "call-no-timer", "+447700900001")
|
||||
call.applyInboundSessionTimer("100rel", "", "")
|
||||
if got := formatSessionExpiresHeader(call); got != "" {
|
||||
t.Fatalf("invented Session-Expires = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInboundInviteWithoutSessionExpiresHonorsMinSE(t *testing.T) {
|
||||
call := NewCall(nil, callstate.DirectionInbound, "call-minse-default", "+447700900001")
|
||||
call.applyInboundSessionTimer("timer", "", "2400")
|
||||
if got := formatSessionExpiresHeader(call); got != "2400;refresher=uac" {
|
||||
t.Fatalf("greater of 1800 and Min-SE = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeAreSessionRefresher(t *testing.T) {
|
||||
tests := []struct {
|
||||
direction callstate.Direction
|
||||
|
||||
+53
-5
@@ -581,10 +581,15 @@ func TestBuildIMSInvite(t *testing.T) {
|
||||
if !strings.Contains(invite, "P-Early-Media: supported") {
|
||||
t.Errorf("INVITE missing P-Early-Media: %q", invite)
|
||||
}
|
||||
if !strings.Contains(invite, "Accept: "+voiceInviteAccept) {
|
||||
t.Errorf("INVITE missing Accept: %q", invite)
|
||||
}
|
||||
if !strings.Contains(invite, "a=curr:qos local sendrecv") ||
|
||||
strings.Contains(invite, "a=curr:qos local none") ||
|
||||
!strings.Contains(invite, "Supported: "+voiceInviteSupported) {
|
||||
t.Errorf("INVITE qos/precondition offer is not RFC 3312 reserved-local: %q", invite)
|
||||
!strings.Contains(invite, "Supported: "+voiceInviteSupported) ||
|
||||
strings.Contains(invite, "Require: precondition") ||
|
||||
voiceTestHeader(invite, "Session-Expires") != "" {
|
||||
t.Errorf("INVITE qos/precondition/session-timer offer is not IR.92 reserved-local: %q", invite)
|
||||
}
|
||||
if !strings.Contains(invite, "Privacy: none") ||
|
||||
!strings.Contains(invite, "Feature-Caps: "+voiceFeatureCaps) ||
|
||||
@@ -599,8 +604,8 @@ func TestBuildIMSInviteMatchesRegisteredCarrierProfile(t *testing.T) {
|
||||
call.setVoiceDialog(&voiceSIPDialog{
|
||||
localURI: "sip:+447840844894@o2.co.uk",
|
||||
remoteURI: "sip:+447942985429@o2.co.uk;user=phone", remoteTarget: "sip:+447942985429@o2.co.uk;user=phone",
|
||||
contactURI: "sip:binding@[2001:db8::10]:48554",
|
||||
contactHeader: `<sip:binding@[2001:db8::10]:48554>;+g.3gpp.accesstype="wlan1";audio`,
|
||||
contactURI: "sip:binding@[2001:db8::10]:48554;ob",
|
||||
contactHeader: `<sip:binding@[2001:db8::10]:48554;ob>;+g.3gpp.accesstype="wlan1";audio`,
|
||||
localAddress: "[2001:db8::10]:50309", transport: "tcp",
|
||||
serviceRoute: []string{"<sip:pcscf.example;lr>"},
|
||||
securityVerify: "ipsec-3gpp;alg=hmac-sha-1-96", pani: "IEEE-802.11;country=GB",
|
||||
@@ -612,7 +617,7 @@ func TestBuildIMSInviteMatchesRegisteredCarrierProfile(t *testing.T) {
|
||||
checks := []string{
|
||||
"INVITE sip:+447942985429@o2.co.uk;user=phone SIP/2.0",
|
||||
"CSeq: 10 INVITE",
|
||||
`Contact: <sip:binding@[2001:db8::10]:48554>;+g.3gpp.accesstype="wlan1";audio`,
|
||||
`Contact: <sip:binding@[2001:db8::10]:48554;ob>;+g.3gpp.accesstype="wlan1";audio`,
|
||||
"Require: sec-agree", "Proxy-Require: sec-agree",
|
||||
"Supported: " + voiceInviteSupported, "Allow: " + voiceInviteAllow,
|
||||
"P-Preferred-Identity: <sip:+447840844894@o2.co.uk>", "Session-ID: session-id",
|
||||
@@ -622,6 +627,18 @@ func TestBuildIMSInviteMatchesRegisteredCarrierProfile(t *testing.T) {
|
||||
t.Fatalf("INVITE missing %q: %s", value, invite)
|
||||
}
|
||||
}
|
||||
via := voiceTestHeader(invite, "Via")
|
||||
if !strings.Contains(via, "SIP/2.0/TCP") || !strings.Contains(via, "[2001:db8::10]:50309") {
|
||||
t.Fatalf("TCP INVITE Via = %q, want actual source port-c", via)
|
||||
}
|
||||
if strings.Contains(via, ":48554") {
|
||||
t.Fatalf("TCP INVITE Via used port-s: %q", via)
|
||||
}
|
||||
for _, unwanted := range []string{"+sip.instance", "reg-id=", ";expires="} {
|
||||
if strings.Contains(invite, unwanted) {
|
||||
t.Fatalf("dialog INVITE copied registration Contact param %q: %s", unwanted, invite)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildIMSCancelUsesStoredInitialInviteTransaction(t *testing.T) {
|
||||
@@ -686,6 +703,37 @@ func TestBuildIMSCalledPartyURIAddsPhoneContextForLocalNumber(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildIMSByeUsesLearnedContactAndRecordRoute(t *testing.T) {
|
||||
agent := &Agent{}
|
||||
call := NewCall(agent, callstate.DirectionOutbound, "bye-dialog", "+447700900001")
|
||||
call.setVoiceDialog(&voiceSIPDialog{
|
||||
localURI: "sip:local@ims.example", remoteURI: "sip:+447700900001@ims.example;user=phone",
|
||||
remoteTarget: "sip:+447700900001@ims.example;user=phone",
|
||||
contactHeader: "<sip:local@192.0.2.10:48554;ob>",
|
||||
localAddress: "192.0.2.10:50309", transport: "tcp",
|
||||
serviceRoute: []string{"<sip:orig@scscf.ims.example;lr>"},
|
||||
localTag: "local-tag", cseq: 1, inviteCSeq: 1,
|
||||
})
|
||||
call.learnVoiceDialog(imscore.SIPResponse{
|
||||
Headers: map[string]string{
|
||||
"To": "<sip:+447700900001@ims.example>;tag=remote",
|
||||
"Contact": "<sip:term@10.128.120.163:50600>",
|
||||
"Record-Route": "<sip:10.128.120.163:50600;transport=tcp;lr>,<sip:scscf.example;lr>",
|
||||
},
|
||||
})
|
||||
bye := BuildIMSBye(agent, call)
|
||||
if !strings.HasPrefix(bye, "BYE sip:term@10.128.120.163:50600 SIP/2.0") {
|
||||
t.Fatalf("BYE Request-URI = %q", strings.SplitN(bye, "\r\n", 2)[0])
|
||||
}
|
||||
if !strings.Contains(bye, "Route: <sip:scscf.example;lr>") ||
|
||||
!strings.Contains(bye, "Route: <sip:10.128.120.163:50600;transport=tcp;lr>") {
|
||||
t.Fatalf("BYE Route missing reversed Record-Route: %s", bye)
|
||||
}
|
||||
if strings.Contains(bye, "orig@scscf.ims.example") {
|
||||
t.Fatalf("BYE stacked REGISTER Service-Route: %s", bye)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildIMSBye(t *testing.T) {
|
||||
agent := newTestAgent(t)
|
||||
call := NewCall(agent, callstate.DirectionOutbound, "call-1", "+8613800000000")
|
||||
|
||||
@@ -143,6 +143,10 @@ func applyCallAuxiliaryEvent(result *CallEvent, event events.Event) bool {
|
||||
result.CallID, result.Caller, result.Callee, result.Time = value.CallID, value.Caller, value.Callee, eventTime(value.Time)
|
||||
case *events.EventCallBusy:
|
||||
result.CallID, result.Caller, result.Callee, result.Time = value.CallID, value.Caller, value.Callee, eventTime(value.Time)
|
||||
case events.EventCallWaiting:
|
||||
applyCallWaitingEvent(result, value)
|
||||
case *events.EventCallWaiting:
|
||||
applyCallWaitingEvent(result, *value)
|
||||
case events.EventCallFinalized:
|
||||
applyFinalizedEvent(result, value)
|
||||
case *events.EventCallFinalized:
|
||||
@@ -158,6 +162,11 @@ func applyIncomingEvent(result *CallEvent, value events.EventIncomingCall) {
|
||||
result.Time = eventTime(value.Time, value.ReceivedAt)
|
||||
}
|
||||
|
||||
func applyCallWaitingEvent(result *CallEvent, value events.EventCallWaiting) {
|
||||
result.CallID, result.Caller, result.Callee = value.CallID, value.Caller, value.Callee
|
||||
result.Time = eventTime(value.Time, value.ReceivedAt)
|
||||
}
|
||||
|
||||
func applyFinalizedEvent(result *CallEvent, value events.EventCallFinalized) {
|
||||
result.CallID, result.PCAPPath, result.AudioPath = value.CallID, value.PCAPPath, value.AudioPath
|
||||
result.AudioCodec, result.RecordingError = value.AudioCodec, value.RecordingError
|
||||
|
||||
Reference in new issue
Block a user