mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-05 16:02:17 +00:00
[restore-vowifi-13] restore IMS DNS
This commit is contained in:
1 parent
8ee6abc993
commit
5568cd370e
14 files changed
+1408
-380
No files matched your search
@@ -0,0 +1,77 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ExpandRegistrarCandidates resolves host candidates and preserves their ports.
|
||||
func ExpandRegistrarCandidates(
|
||||
ctx context.Context,
|
||||
candidates string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
) string {
|
||||
candidates = strings.TrimSpace(candidates)
|
||||
if candidates == "" {
|
||||
return ""
|
||||
}
|
||||
result := make([]string, 0, strings.Count(candidates, ",")+1)
|
||||
seen := make(map[string]struct{})
|
||||
cache := make(map[string][]net.IP)
|
||||
for _, candidate := range strings.Split(candidates, ",") {
|
||||
host, port, ok := parserRegistrarHostPort(candidate, defaultRegistrarSIPPort)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
normalized := strings.Trim(strings.TrimSpace(host), "[]")
|
||||
if ip := net.ParseIP(normalized); ip != nil {
|
||||
appendUniqueEndpoints(&result, seen, []string{ip.String()}, port)
|
||||
continue
|
||||
}
|
||||
addresses, exists := cache[normalized]
|
||||
if !exists {
|
||||
addresses = LookupHostIPViaDNSServers(ctx, normalized, preferIPv6, bindIP, servers)
|
||||
cache[normalized] = addresses
|
||||
}
|
||||
if len(addresses) == 0 {
|
||||
appendUniqueEndpoints(&result, seen, []string{normalized}, port)
|
||||
continue
|
||||
}
|
||||
hosts := make([]string, 0, len(addresses))
|
||||
for _, address := range addresses {
|
||||
hosts = append(hosts, address.String())
|
||||
}
|
||||
appendUniqueEndpoints(&result, seen, hosts, port)
|
||||
}
|
||||
return strings.Join(result, ",")
|
||||
}
|
||||
|
||||
func parserRegistrarHostPort(candidate string, defaultPort int) (string, int, bool) {
|
||||
candidate = strings.TrimSpace(candidate)
|
||||
if strings.HasPrefix(candidate, "sip:") {
|
||||
candidate = candidate[len("sip:"):]
|
||||
}
|
||||
if strings.HasPrefix(candidate, "sips:") {
|
||||
candidate = candidate[len("sips:"):]
|
||||
}
|
||||
if index := strings.IndexByte(candidate, ';'); index >= 0 {
|
||||
candidate = candidate[:index]
|
||||
}
|
||||
if index := strings.IndexByte(candidate, '?'); index >= 0 {
|
||||
candidate = candidate[:index]
|
||||
}
|
||||
candidate = strings.TrimSpace(candidate)
|
||||
if candidate == "" {
|
||||
return "", 0, false
|
||||
}
|
||||
host, portText, err := net.SplitHostPort(candidate)
|
||||
if err != nil {
|
||||
return strings.TrimSpace(candidate), defaultPort, true
|
||||
}
|
||||
port, _ := strconv.Atoi(portText)
|
||||
return strings.TrimSpace(host), port, true
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RegistrarCandidate retains the structured candidate API added after v1.5.5.
|
||||
type RegistrarCandidate struct {
|
||||
Host string
|
||||
Port int
|
||||
Transport string
|
||||
Priority uint16
|
||||
Weight uint16
|
||||
}
|
||||
|
||||
// DiscoverOptions retains the post-v1.5.5 structured discovery options.
|
||||
type DiscoverOptions struct {
|
||||
Domain string
|
||||
DNSServers []string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// DiscoverRegistrarCandidatesAutoViaDNS is the structured counterpart of the legacy API.
|
||||
func DiscoverRegistrarCandidatesAutoViaDNS(domain string) ([]RegistrarCandidate, error) {
|
||||
return DiscoverRegistrarCandidatesAutoViaDNSWithOptions(domain, DiscoverOptions{})
|
||||
}
|
||||
|
||||
// DiscoverRegistrarCandidatesAutoViaDNSWithOptions discovers structured candidates.
|
||||
func DiscoverRegistrarCandidatesAutoViaDNSWithOptions(
|
||||
domain string,
|
||||
options DiscoverOptions,
|
||||
) ([]RegistrarCandidate, error) {
|
||||
servers := options.DNSServers
|
||||
if len(servers) == 0 {
|
||||
for _, server := range ReadSystemDNSServers() {
|
||||
servers = append(servers, server.String())
|
||||
}
|
||||
}
|
||||
if len(servers) == 0 {
|
||||
servers = []string{"1.1.1.1"}
|
||||
}
|
||||
return DiscoverRegistrarCandidatesViaDNS(domain, servers, options.Timeout)
|
||||
}
|
||||
|
||||
// DiscoverRegistrarCandidatesViaDNS performs structured SRV discovery.
|
||||
func DiscoverRegistrarCandidatesViaDNS(
|
||||
domain string,
|
||||
servers []string,
|
||||
timeout time.Duration,
|
||||
) ([]RegistrarCandidate, error) {
|
||||
domain = strings.TrimSpace(domain)
|
||||
if domain == "" {
|
||||
return nil, errors.New("dns: empty registrar domain")
|
||||
}
|
||||
if timeout <= 0 {
|
||||
timeout = 5 * time.Second
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
var candidates []RegistrarCandidate
|
||||
var failures []error
|
||||
for _, transport := range []string{"udp", "tcp", "tls"} {
|
||||
found, err := lookupStructuredSRV(ctx, domain, transport, servers)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, found...)
|
||||
}
|
||||
if len(candidates) > 0 {
|
||||
return candidates, nil
|
||||
}
|
||||
addresses, addressErr := lookupStructuredAddresses(ctx, domain, servers)
|
||||
if addressErr == nil {
|
||||
return addresses, nil
|
||||
}
|
||||
failures = append(failures, addressErr)
|
||||
if len(failures) == 0 {
|
||||
failures = append(failures, errors.New("no DNS servers configured"))
|
||||
}
|
||||
return nil, fmt.Errorf("dns: no registrar found for %s: %w", domain, errors.Join(failures...))
|
||||
}
|
||||
|
||||
func lookupStructuredSRV(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
servers []string,
|
||||
) ([]RegistrarCandidate, error) {
|
||||
var failures []error
|
||||
for _, endpoint := range servers {
|
||||
resolver, err := resolverForEndpoint(endpoint)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
continue
|
||||
}
|
||||
_, records, err := resolver.LookupSRV(ctx, "sip", transport, domain)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
continue
|
||||
}
|
||||
result := make([]RegistrarCandidate, 0, len(records))
|
||||
for _, record := range records {
|
||||
result = append(result, RegistrarCandidate{
|
||||
Host: strings.TrimSuffix(record.Target, "."), Port: int(record.Port),
|
||||
Transport: transport, Priority: record.Priority, Weight: record.Weight,
|
||||
})
|
||||
}
|
||||
if len(result) > 0 {
|
||||
return result, nil
|
||||
}
|
||||
}
|
||||
if len(failures) == 0 {
|
||||
return nil, errors.New("dns: no DNS servers configured")
|
||||
}
|
||||
return nil, errors.Join(failures...)
|
||||
}
|
||||
|
||||
func lookupStructuredAddresses(
|
||||
ctx context.Context,
|
||||
domain string,
|
||||
servers []string,
|
||||
) ([]RegistrarCandidate, error) {
|
||||
var failures []error
|
||||
for _, endpoint := range servers {
|
||||
resolver, err := resolverForEndpoint(endpoint)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
continue
|
||||
}
|
||||
addresses, err := resolver.LookupIPAddr(ctx, domain)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
continue
|
||||
}
|
||||
result := make([]RegistrarCandidate, 0, len(addresses))
|
||||
seen := make(map[string]struct{})
|
||||
for _, address := range addresses {
|
||||
host := address.IP.String()
|
||||
if address.IP == nil {
|
||||
continue
|
||||
}
|
||||
if _, exists := seen[host]; exists {
|
||||
continue
|
||||
}
|
||||
seen[host] = struct{}{}
|
||||
result = append(result, RegistrarCandidate{
|
||||
Host: host, Port: defaultRegistrarSIPPort, Transport: "udp",
|
||||
})
|
||||
}
|
||||
if len(result) > 0 {
|
||||
return result, nil
|
||||
}
|
||||
failures = append(failures, fmt.Errorf("dns: no address records for %s", domain))
|
||||
}
|
||||
if len(failures) == 0 {
|
||||
return nil, errors.New("dns: no DNS servers configured")
|
||||
}
|
||||
return nil, errors.Join(failures...)
|
||||
}
|
||||
|
||||
func resolverForEndpoint(endpoint string) (queryResolver, error) {
|
||||
endpoint = strings.TrimSpace(endpoint)
|
||||
host, port, err := net.SplitHostPort(endpoint)
|
||||
if err != nil {
|
||||
host, port = endpoint, defaultDNSPort
|
||||
}
|
||||
ip := net.ParseIP(strings.Trim(host, "[]"))
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("dns: DNS server must be an IP address: %q", endpoint)
|
||||
}
|
||||
return newServerResolverAt(nil, ip, port), nil
|
||||
}
|
||||
|
||||
// NormalizeRegistrarCandidates retains structured defaulting and deduplication.
|
||||
func NormalizeRegistrarCandidates(candidates []RegistrarCandidate) []RegistrarCandidate {
|
||||
seen := make(map[string]struct{})
|
||||
result := make([]RegistrarCandidate, 0, len(candidates))
|
||||
for _, candidate := range candidates {
|
||||
if candidate.Port == 0 {
|
||||
candidate.Port = defaultRegistrarSIPPort
|
||||
if candidate.Transport == "tls" {
|
||||
candidate.Port = 5061
|
||||
}
|
||||
}
|
||||
key := net.JoinHostPort(candidate.Host, strconv.Itoa(candidate.Port)) + ":" + candidate.Transport
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
result = append(result, candidate)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// LookupHostIP resolves through the system resolver.
|
||||
func LookupHostIP(ctx context.Context, host string) ([]net.IP, error) {
|
||||
return net.DefaultResolver.LookupIP(ctx, "ip", host)
|
||||
}
|
||||
-313
@@ -1,313 +0,0 @@
|
||||
// Package dns implements IMS registrar discovery via DNS (RFC 3263) and the
|
||||
// DNS-server selection helpers used by the IMS stack.
|
||||
//
|
||||
// Reconstructed from the decompiled internal/vowifi/dns.
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// RegistrarCandidate is one discovered registrar endpoint.
|
||||
type RegistrarCandidate struct {
|
||||
Host string
|
||||
Port int
|
||||
// Transport is "udp", "tcp" or "tls".
|
||||
Transport string
|
||||
// Priority / Weight from the SRV record (RFC 2782).
|
||||
Priority uint16
|
||||
Weight uint16
|
||||
}
|
||||
|
||||
// DiscoverOptions tunes registrar discovery.
|
||||
type DiscoverOptions struct {
|
||||
// Domain is the IMS domain (e.g. "ims.mnc026.mcc310.3gppnetwork.org").
|
||||
Domain string
|
||||
// DNSServers overrides the DNS servers used for the lookup.
|
||||
DNSServers []string
|
||||
// Timeout bounds each DNS query.
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// defaultRegistrarPublicDNSServers are the fallback public resolvers.
|
||||
func defaultRegistrarPublicDNSServers() []string {
|
||||
return []string{"8.8.8.8:53", "1.1.1.1:53"}
|
||||
}
|
||||
|
||||
// ReadSystemDNSServers reads the system DNS servers from /etc/resolv.conf.
|
||||
func ReadSystemDNSServers() []string {
|
||||
cfg, err := dns.ClientConfigFromFile("/etc/resolv.conf")
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
var out []string
|
||||
for _, s := range cfg.Servers {
|
||||
out = append(out, net.JoinHostPort(s, cfg.Port))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// FilterDNSServersForBind keeps only servers usable for binding (non-empty,
|
||||
// valid addresses).
|
||||
func FilterDNSServersForBind(servers []string) []string {
|
||||
var out []string
|
||||
for _, s := range servers {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
continue
|
||||
}
|
||||
host, _, err := net.SplitHostPort(s)
|
||||
if err != nil {
|
||||
host = s
|
||||
}
|
||||
if net.ParseIP(host) == nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// OrderDNSServersByPreference orders DNS servers, preferring loopback and
|
||||
// link-local resolvers first.
|
||||
func OrderDNSServersByPreference(servers []string) []string {
|
||||
scored := make([]struct {
|
||||
s string
|
||||
n int
|
||||
}, 0, len(servers))
|
||||
for _, s := range servers {
|
||||
host, _, err := net.SplitHostPort(s)
|
||||
if err != nil {
|
||||
host = s
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
n := 0
|
||||
if ip != nil && ip.IsLoopback() {
|
||||
n = 3
|
||||
} else if ip != nil && ip.IsLinkLocalUnicast() {
|
||||
n = 2
|
||||
} else if ip != nil && ip.IsPrivate() {
|
||||
n = 1
|
||||
}
|
||||
scored = append(scored, struct {
|
||||
s string
|
||||
n int
|
||||
}{s, n})
|
||||
}
|
||||
sort.SliceStable(scored, func(i, j int) bool { return scored[i].n > scored[j].n })
|
||||
out := make([]string, 0, len(scored))
|
||||
for _, e := range scored {
|
||||
out = append(out, e.s)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// registrarDiscoveryDNSServerStages returns the ordered DNS server stages:
|
||||
// system servers first, then the public fallbacks.
|
||||
func registrarDiscoveryDNSServerStages() [][]string {
|
||||
system := ReadSystemDNSServers()
|
||||
system = OrderDNSServersByPreference(FilterDNSServersForBind(system))
|
||||
return [][]string{system, defaultRegistrarPublicDNSServers()}
|
||||
}
|
||||
|
||||
// registrarTransportCandidates are the transport schemes probed in order.
|
||||
func registrarTransportCandidates() []string {
|
||||
return []string{"udp", "tcp", "tls"}
|
||||
}
|
||||
|
||||
// DiscoverRegistrarAutoViaDNS discovers the IMS registrar for the domain using
|
||||
// the system DNS servers, falling back to public resolvers.
|
||||
func DiscoverRegistrarAutoViaDNS(domain string) ([]RegistrarCandidate, error) {
|
||||
return DiscoverRegistrarAutoViaDNSWithOptions(domain, DiscoverOptions{})
|
||||
}
|
||||
|
||||
// DiscoverRegistrarAutoViaDNSWithOptions discovers the registrar with explicit
|
||||
// options.
|
||||
func DiscoverRegistrarAutoViaDNSWithOptions(domain string, opts DiscoverOptions) ([]RegistrarCandidate, error) {
|
||||
if opts.Timeout <= 0 {
|
||||
opts.Timeout = 5 * time.Second
|
||||
}
|
||||
var lastErr error
|
||||
for _, stage := range registrarDiscoveryDNSServerStages() {
|
||||
servers := opts.DNSServers
|
||||
if len(servers) == 0 {
|
||||
servers = stage
|
||||
}
|
||||
if len(servers) == 0 {
|
||||
continue
|
||||
}
|
||||
cands, err := DiscoverRegistrarViaDNS(domain, servers, opts.Timeout)
|
||||
if err == nil && len(cands) > 0 {
|
||||
return cands, nil
|
||||
}
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
}
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = fmt.Errorf("dns: no registrar found for %s", domain)
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// DiscoverRegistrarViaDNS performs the SRV/NAPTR lookup for the registrar.
|
||||
func DiscoverRegistrarViaDNS(domain string, servers []string, timeout time.Duration) ([]RegistrarCandidate, error) {
|
||||
if timeout <= 0 {
|
||||
timeout = 5 * time.Second
|
||||
}
|
||||
var out []RegistrarCandidate
|
||||
for _, transport := range registrarTransportCandidates() {
|
||||
srvName := fmt.Sprintf("_sip._%s.%s", transport, domain)
|
||||
cands, err := lookupSRV(srvName, servers, timeout)
|
||||
if err == nil && len(cands) > 0 {
|
||||
out = append(out, cands...)
|
||||
}
|
||||
}
|
||||
if len(out) == 0 {
|
||||
// Fall back to an A/AAAA lookup of the domain itself.
|
||||
ips, err := LookupHostIPViaDNSServers(domain, servers, timeout)
|
||||
if err == nil {
|
||||
for _, ip := range ips {
|
||||
out = append(out, RegistrarCandidate{Host: ip.String(), Port: 5060, Transport: "udp"})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// lookupSRV queries the SRV records for a name.
|
||||
func lookupSRV(name string, servers []string, timeout time.Duration) ([]RegistrarCandidate, error) {
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion(name, dns.TypeSRV)
|
||||
m.RecursionDesired = true
|
||||
var out []RegistrarCandidate
|
||||
var lastErr error
|
||||
for _, server := range servers {
|
||||
c := &dns.Client{Timeout: timeout}
|
||||
resp, _, err := c.Exchange(m, server)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
for _, rr := range resp.Answer {
|
||||
if srv, ok := rr.(*dns.SRV); ok {
|
||||
out = append(out, RegistrarCandidate{
|
||||
Host: strings.TrimSuffix(srv.Target, "."),
|
||||
Port: int(srv.Port),
|
||||
Transport: transportOf(name),
|
||||
Priority: srv.Priority,
|
||||
Weight: srv.Weight,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = fmt.Errorf("dns: no SRV records for %s", name)
|
||||
}
|
||||
return out, lastErr
|
||||
}
|
||||
|
||||
// transportOf extracts the transport from an SRV name like "_sip._udp.x".
|
||||
func transportOf(name string) string {
|
||||
parts := strings.Split(name, ".")
|
||||
if len(parts) >= 2 {
|
||||
return strings.TrimPrefix(parts[1], "_")
|
||||
}
|
||||
return "udp"
|
||||
}
|
||||
|
||||
// LookupHostIPViaDNSServers resolves a host to IPs using the given servers.
|
||||
func LookupHostIPViaDNSServers(host string, servers []string, timeout time.Duration) ([]net.IP, error) {
|
||||
if timeout <= 0 {
|
||||
timeout = 5 * time.Second
|
||||
}
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion(dns.Fqdn(host), dns.TypeA)
|
||||
m.RecursionDesired = true
|
||||
var out []net.IP
|
||||
var lastErr error
|
||||
for _, server := range servers {
|
||||
c := &dns.Client{Timeout: timeout}
|
||||
resp, _, err := c.Exchange(m, server)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
for _, rr := range resp.Answer {
|
||||
if a, ok := rr.(*dns.A); ok {
|
||||
out = append(out, a.A)
|
||||
}
|
||||
}
|
||||
if len(out) > 0 {
|
||||
return out, nil
|
||||
}
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = fmt.Errorf("dns: no A records for %s", host)
|
||||
}
|
||||
return out, lastErr
|
||||
}
|
||||
|
||||
// ExpandRegistrarCandidates expands a candidate list, adding default ports and
|
||||
// deduplicating.
|
||||
func ExpandRegistrarCandidates(cands []RegistrarCandidate) []RegistrarCandidate {
|
||||
seen := make(map[string]bool)
|
||||
var out []RegistrarCandidate
|
||||
for _, c := range cands {
|
||||
if c.Port == 0 {
|
||||
switch c.Transport {
|
||||
case "tls":
|
||||
c.Port = 5061
|
||||
default:
|
||||
c.Port = 5060
|
||||
}
|
||||
}
|
||||
key := fmt.Sprintf("%s:%d:%s", c.Host, c.Port, c.Transport)
|
||||
if seen[key] {
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
out = append(out, c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// parserRegistrarHostPort parses a "host:port" string into host and port.
|
||||
func parserRegistrarHostPort(s string) (string, int, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return "", 0, fmt.Errorf("dns: empty registrar")
|
||||
}
|
||||
host, portStr, err := net.SplitHostPort(s)
|
||||
if err != nil {
|
||||
// No port: default to 5060.
|
||||
return s, 5060, nil
|
||||
}
|
||||
var port int
|
||||
if _, err := fmt.Sscanf(portStr, "%d", &port); err != nil {
|
||||
return "", 0, fmt.Errorf("dns: bad port %q", portStr)
|
||||
}
|
||||
return host, port, nil
|
||||
}
|
||||
|
||||
// LookupHostIP is a convenience wrapper using the system resolver.
|
||||
func LookupHostIP(ctx context.Context, host string) ([]net.IP, error) {
|
||||
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ips, nil
|
||||
}
|
||||
|
||||
var _ = os.Getenv
|
||||
@@ -1,55 +0,0 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParserRegistrarHostPort(t *testing.T) {
|
||||
host, port, err := parserRegistrarHostPort("epdg.example.com:4500")
|
||||
if err != nil || host != "epdg.example.com" || port != 4500 {
|
||||
t.Errorf("parse = %q %d %v", host, port, err)
|
||||
}
|
||||
host, port, err = parserRegistrarHostPort("epdg.example.com")
|
||||
if err != nil || host != "epdg.example.com" || port != 5060 {
|
||||
t.Errorf("parse no port = %q %d %v", host, port, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandRegistrarCandidates(t *testing.T) {
|
||||
cands := []RegistrarCandidate{
|
||||
{Host: "a.example.com", Transport: "udp"},
|
||||
{Host: "a.example.com", Transport: "udp"}, // duplicate
|
||||
{Host: "b.example.com", Transport: "tls"},
|
||||
}
|
||||
got := ExpandRegistrarCandidates(cands)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expanded = %d, want 2", len(got))
|
||||
}
|
||||
if got[0].Port != 5060 {
|
||||
t.Errorf("udp default port = %d", got[0].Port)
|
||||
}
|
||||
if got[1].Port != 5061 {
|
||||
t.Errorf("tls default port = %d", got[1].Port)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderDNSServersByPreference(t *testing.T) {
|
||||
servers := []string{"8.8.8.8:53", "127.0.0.1:53", "192.168.1.1:53"}
|
||||
got := OrderDNSServersByPreference(servers)
|
||||
if got[0] != "127.0.0.1:53" {
|
||||
t.Errorf("loopback should be first: %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterDNSServersForBind(t *testing.T) {
|
||||
got := FilterDNSServersForBind([]string{"8.8.8.8:53", "", "not-an-ip", "1.1.1.1:53"})
|
||||
if len(got) != 2 {
|
||||
t.Errorf("filtered = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTransportOf(t *testing.T) {
|
||||
if got := transportOf("_sip._udp.example.com"); got != "udp" {
|
||||
t.Errorf("transport = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Package dns implements IMS registrar discovery and explicit DNS-server
|
||||
// selection for the VoWiFi runtime.
|
||||
package dns
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
miekgdns "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
type queryResolver interface {
|
||||
LookupIPAddr(context.Context, string) ([]net.IPAddr, error)
|
||||
LookupSRV(context.Context, string, string, string) (string, []*net.SRV, error)
|
||||
LookupNAPTR(context.Context, string) ([]*miekgdns.NAPTR, error)
|
||||
}
|
||||
|
||||
type resolverFactory func(bindIP, server net.IP) queryResolver
|
||||
|
||||
type serverResolver struct {
|
||||
native *net.Resolver
|
||||
client *miekgdns.Client
|
||||
address string
|
||||
}
|
||||
|
||||
func newServerResolver(bindIP, server net.IP) queryResolver {
|
||||
return newServerResolverAt(bindIP, server, defaultDNSPort)
|
||||
}
|
||||
|
||||
func newServerResolverAt(bindIP, server net.IP, port string) queryResolver {
|
||||
address := net.JoinHostPort(server.String(), port)
|
||||
dialer := &net.Dialer{}
|
||||
if bindIP != nil {
|
||||
dialer.LocalAddr = &net.UDPAddr{IP: bindIP}
|
||||
}
|
||||
dialDNS := func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return dialer.DialContext(ctx, "udp", address)
|
||||
}
|
||||
return &serverResolver{
|
||||
native: &net.Resolver{PreferGo: true, Dial: dialDNS},
|
||||
client: &miekgdns.Client{Net: "udp", Dialer: dialer, Timeout: registrarQueryTimeout},
|
||||
address: address,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *serverResolver) LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error) {
|
||||
return r.native.LookupIPAddr(ctx, host)
|
||||
}
|
||||
|
||||
func (r *serverResolver) LookupSRV(
|
||||
ctx context.Context,
|
||||
service, proto, name string,
|
||||
) (string, []*net.SRV, error) {
|
||||
return r.native.LookupSRV(ctx, service, proto, name)
|
||||
}
|
||||
|
||||
func (r *serverResolver) LookupNAPTR(ctx context.Context, name string) ([]*miekgdns.NAPTR, error) {
|
||||
message := new(miekgdns.Msg)
|
||||
message.SetQuestion(miekgdns.Fqdn(name), miekgdns.TypeNAPTR)
|
||||
response, _, err := r.client.ExchangeContext(ctx, message, r.address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response == nil {
|
||||
return nil, fmt.Errorf("dns: empty NAPTR response from %s", r.address)
|
||||
}
|
||||
records := make([]*miekgdns.NAPTR, 0, len(response.Answer))
|
||||
for _, answer := range response.Answer {
|
||||
if record, ok := answer.(*miekgdns.NAPTR); ok {
|
||||
records = append(records, record)
|
||||
}
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// LookupHostIPViaDNSServers resolves both A and AAAA records through explicit servers.
|
||||
func LookupHostIPViaDNSServers(
|
||||
ctx context.Context,
|
||||
host string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
) []net.IP {
|
||||
return lookupHostIPViaDNSServers(ctx, host, preferIPv6, bindIP, servers, newServerResolver)
|
||||
}
|
||||
|
||||
func lookupHostIPViaDNSServers(
|
||||
ctx context.Context,
|
||||
host string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
factory resolverFactory,
|
||||
) []net.IP {
|
||||
host = strings.Trim(strings.TrimSpace(host), "[]")
|
||||
if host == "" || len(servers) == 0 {
|
||||
return nil
|
||||
}
|
||||
orderedServers := OrderDNSServersByPreference(servers, preferIPv6)
|
||||
preferred, fallback := make([]net.IP, 0, 4), make([]net.IP, 0, 4)
|
||||
seen := make(map[string]struct{})
|
||||
for _, server := range orderedServers {
|
||||
if !serverUsableForBind(server, bindIP) {
|
||||
continue
|
||||
}
|
||||
addresses, err := factory(bindIP, server).LookupIPAddr(ctx, host)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
preferred, fallback = collectResolvedIPs(addresses, preferIPv6, seen, preferred, fallback)
|
||||
if len(preferred) > 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return append(preferred, fallback...)
|
||||
}
|
||||
|
||||
func collectResolvedIPs(
|
||||
addresses []net.IPAddr,
|
||||
preferIPv6 bool,
|
||||
seen map[string]struct{},
|
||||
preferred, fallback []net.IP,
|
||||
) ([]net.IP, []net.IP) {
|
||||
for _, address := range addresses {
|
||||
if address.IP == nil {
|
||||
continue
|
||||
}
|
||||
key := address.IP.String()
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
if (address.IP.To4() == nil) == preferIPv6 {
|
||||
preferred = append(preferred, address.IP)
|
||||
} else {
|
||||
fallback = append(fallback, address.IP)
|
||||
}
|
||||
}
|
||||
return preferred, fallback
|
||||
}
|
||||
|
||||
func serverUsableForBind(server, bindIP net.IP) bool {
|
||||
return server != nil && (bindIP == nil || (server.To4() != nil) == (bindIP.To4() != nil))
|
||||
}
|
||||
|
||||
// OrderDNSServersByPreference puts the requested address family first.
|
||||
func OrderDNSServersByPreference(servers []net.IP, preferIPv6 bool) []net.IP {
|
||||
preferred := make([]net.IP, 0, len(servers))
|
||||
fallback := make([]net.IP, 0, len(servers))
|
||||
for _, server := range servers {
|
||||
if server == nil {
|
||||
continue
|
||||
}
|
||||
if (server.To4() == nil) == preferIPv6 {
|
||||
preferred = append(preferred, server)
|
||||
} else {
|
||||
fallback = append(fallback, server)
|
||||
}
|
||||
}
|
||||
return append(preferred, fallback...)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// RegistrarNetwork is the IMS network capability needed for registrar SRV lookup.
|
||||
type RegistrarNetwork interface {
|
||||
LookupSRV(context.Context, string, string, string) (string, uint16, error)
|
||||
}
|
||||
|
||||
// DiscoverRegistrarViaNetwork applies the legacy transport order to an IMS network resolver.
|
||||
func DiscoverRegistrarViaNetwork(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
network RegistrarNetwork,
|
||||
) (string, error) {
|
||||
domain = strings.TrimSpace(domain)
|
||||
if domain == "" {
|
||||
return "", errors.New("dns: empty registrar domain")
|
||||
}
|
||||
if network == nil {
|
||||
return "", errors.New("dns: nil IMS registrar network")
|
||||
}
|
||||
var failures []error
|
||||
for _, candidate := range registrarTransportCandidates(transport) {
|
||||
host, port, err := network.LookupSRV(ctx, "sip", candidate, domain)
|
||||
if err != nil {
|
||||
if contextErr := ctx.Err(); contextErr != nil {
|
||||
return "", fmt.Errorf("dns: registrar SRV lookup canceled: %w", contextErr)
|
||||
}
|
||||
failures = append(failures, fmt.Errorf("_%s: %w", candidate, err))
|
||||
continue
|
||||
}
|
||||
host = strings.TrimSuffix(strings.TrimSpace(host), ".")
|
||||
if host == "" || port == 0 {
|
||||
failures = append(failures, fmt.Errorf("_%s: empty SRV target", candidate))
|
||||
continue
|
||||
}
|
||||
return net.JoinHostPort(host, strconv.Itoa(int(port))), nil
|
||||
}
|
||||
// RFC 3263 falls back to the domain's address records when SRV is absent.
|
||||
if len(failures) > 0 {
|
||||
return net.JoinHostPort(domain, strconv.Itoa(defaultRegistrarSIPPort)), nil
|
||||
}
|
||||
return "", errors.New("dns: registrar discovery produced no candidates")
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// DiscoveryResult is the error-reporting form of the legacy discovery result.
|
||||
type DiscoveryResult struct {
|
||||
Registrar string
|
||||
Source string
|
||||
}
|
||||
|
||||
func registrarTransportCandidates(transport string) []string {
|
||||
switch strings.ToLower(strings.TrimSpace(transport)) {
|
||||
case "udp":
|
||||
return []string{"udp"}
|
||||
default:
|
||||
return []string{"tcp", "udp"}
|
||||
}
|
||||
}
|
||||
|
||||
// DiscoverRegistrarAutoViaDNS restores the legacy registrar discovery API.
|
||||
func DiscoverRegistrarAutoViaDNS(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
) (string, string, bool) {
|
||||
result, err := DiscoverRegistrarAutoViaDNSResult(ctx, domain, transport, preferIPv6, bindIP, servers)
|
||||
return result.Registrar, result.Source, err == nil
|
||||
}
|
||||
|
||||
// DiscoverRegistrarAutoViaDNSResult preserves discovery errors for new callers.
|
||||
func DiscoverRegistrarAutoViaDNSResult(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
) (DiscoveryResult, error) {
|
||||
return discoverRegistrarWithOptions(
|
||||
ctx, domain, transport, preferIPv6, bindIP, servers,
|
||||
true, ReadSystemDNSServers(), true, nil, newServerResolver,
|
||||
)
|
||||
}
|
||||
|
||||
// DiscoverRegistrarAutoViaDNSWithOptions restores the legacy explicit-stage API.
|
||||
func DiscoverRegistrarAutoViaDNSWithOptions(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
includeSystem bool,
|
||||
systemServers []net.IP,
|
||||
includePublic bool,
|
||||
publicServers []net.IP,
|
||||
) (string, string, bool) {
|
||||
result, err := discoverRegistrarWithOptions(
|
||||
ctx, domain, transport, preferIPv6, bindIP, servers,
|
||||
includeSystem, systemServers, includePublic, publicServers, newServerResolver,
|
||||
)
|
||||
return result.Registrar, result.Source, err == nil
|
||||
}
|
||||
|
||||
func discoverRegistrarWithOptions(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
includeSystem bool,
|
||||
systemServers []net.IP,
|
||||
includePublic bool,
|
||||
publicServers []net.IP,
|
||||
factory resolverFactory,
|
||||
) (DiscoveryResult, error) {
|
||||
stages := registrarDiscoveryDNSServerStages(
|
||||
servers, bindIP, includeSystem, systemServers, includePublic, publicServers,
|
||||
)
|
||||
var failures []error
|
||||
for _, stage := range stages {
|
||||
registrar, err := discoverRegistrarViaDNS(
|
||||
ctx, domain, transport, preferIPv6, bindIP, stage.Servers, factory,
|
||||
)
|
||||
if err == nil {
|
||||
return DiscoveryResult{Registrar: registrar, Source: stage.Source}, nil
|
||||
}
|
||||
failures = append(failures, fmt.Errorf("%s: %w", stage.Source, err))
|
||||
}
|
||||
if len(stages) == 0 {
|
||||
return DiscoveryResult{}, errors.New("dns: no DNS servers match the bind address")
|
||||
}
|
||||
return DiscoveryResult{}, fmt.Errorf("dns: discover registrar for %s: %w", domain, errors.Join(failures...))
|
||||
}
|
||||
|
||||
// DiscoverRegistrarViaDNS restores direct SRV, NAPTR and address discovery.
|
||||
func DiscoverRegistrarViaDNS(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
) (string, bool) {
|
||||
registrar, err := discoverRegistrarViaDNS(
|
||||
ctx, domain, transport, preferIPv6, bindIP, servers, newServerResolver,
|
||||
)
|
||||
return registrar, err == nil
|
||||
}
|
||||
|
||||
func discoverRegistrarViaDNS(
|
||||
ctx context.Context,
|
||||
domain, transport string,
|
||||
preferIPv6 bool,
|
||||
bindIP net.IP,
|
||||
servers []net.IP,
|
||||
factory resolverFactory,
|
||||
) (string, error) {
|
||||
domain = strings.TrimSpace(domain)
|
||||
if domain == "" {
|
||||
return "", errors.New("dns: empty registrar domain")
|
||||
}
|
||||
ordered := OrderDNSServersByPreference(servers, preferIPv6)
|
||||
if len(ordered) == 0 {
|
||||
return "", errors.New("dns: no DNS servers")
|
||||
}
|
||||
var failures []error
|
||||
for _, transportCandidate := range registrarTransportCandidates(transport) {
|
||||
for _, server := range ordered {
|
||||
if !serverUsableForBind(server, bindIP) {
|
||||
continue
|
||||
}
|
||||
registrar, err := discoverRegistrarFromServer(
|
||||
ctx, factory(bindIP, server), domain, transportCandidate, preferIPv6,
|
||||
)
|
||||
if err == nil {
|
||||
return registrar, nil
|
||||
}
|
||||
failures = append(failures, fmt.Errorf("%s via %s: %w", transportCandidate, server, err))
|
||||
}
|
||||
}
|
||||
if len(failures) == 0 {
|
||||
return "", errors.New("dns: no DNS servers match the bind address")
|
||||
}
|
||||
return "", errors.Join(failures...)
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
miekgdns "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
func TestDiscoverRegistrarViaDNSQueriesSRVAndBothAddressFamilies(t *testing.T) {
|
||||
ip, port := startTestDNSServer(t, registrarDNSHandler(false))
|
||||
factory := func(bindIP, server net.IP) queryResolver {
|
||||
return newServerResolverAt(bindIP, server, port)
|
||||
}
|
||||
result, err := discoverRegistrarViaDNS(
|
||||
context.Background(), "ims.example", "tcp", false, ip, []net.IP{ip}, factory,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "192.0.2.20:5070,[2001:db8::20]:5070,192.0.2.10:5060,[2001:db8::10]:5060"
|
||||
if result != want {
|
||||
t.Fatalf("registrar = %q, want %q", result, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverRegistrarViaDNSUsesNAPTRReplacement(t *testing.T) {
|
||||
ip, port := startTestDNSServer(t, registrarDNSHandler(true))
|
||||
factory := func(bindIP, server net.IP) queryResolver {
|
||||
return newServerResolverAt(bindIP, server, port)
|
||||
}
|
||||
result, err := discoverRegistrarViaDNS(
|
||||
context.Background(), "naptr.example", "tcp", false, ip, []net.IP{ip}, factory,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result != "192.0.2.30:5090,[2001:db8::30]:5090" {
|
||||
t.Fatalf("registrar = %q", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupHostIPViaDNSServersHonorsContextTimeout(t *testing.T) {
|
||||
handler := miekgdns.HandlerFunc(func(writer miekgdns.ResponseWriter, request *miekgdns.Msg) {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
_ = writer.WriteMsg(new(miekgdns.Msg).SetReply(request))
|
||||
})
|
||||
ip, port := startTestDNSServer(t, handler)
|
||||
factory := func(bindIP, server net.IP) queryResolver {
|
||||
return newServerResolverAt(bindIP, server, port)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Millisecond)
|
||||
defer cancel()
|
||||
started := time.Now()
|
||||
result := lookupHostIPViaDNSServers(ctx, "slow.example", false, ip, []net.IP{ip}, factory)
|
||||
if len(result) != 0 {
|
||||
t.Fatalf("result = %v", result)
|
||||
}
|
||||
if elapsed := time.Since(started); elapsed > 150*time.Millisecond {
|
||||
t.Fatalf("lookup ignored context timeout: %v", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLookupHostIPViaDNSServersAccumulatesUntilPreferredFamily(t *testing.T) {
|
||||
servers := []net.IP{net.ParseIP("192.0.2.53"), net.ParseIP("192.0.2.54")}
|
||||
factory := func(_, server net.IP) queryResolver {
|
||||
if server.Equal(servers[0]) {
|
||||
return staticQueryResolver{addresses: []net.IPAddr{{IP: net.ParseIP("2001:db8::1")}}}
|
||||
}
|
||||
return staticQueryResolver{addresses: []net.IPAddr{{IP: net.ParseIP("192.0.2.1")}}}
|
||||
}
|
||||
got := lookupHostIPViaDNSServers(
|
||||
context.Background(), "pcscf.example", false, nil, servers, factory,
|
||||
)
|
||||
if values := ipStrings(got); len(values) != 2 || values[0] != "192.0.2.1" || values[1] != "2001:db8::1" {
|
||||
t.Fatalf("addresses = %v", values)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiscoverRegistrarWithOptionsReportsStageSource(t *testing.T) {
|
||||
ip, port := startTestDNSServer(t, registrarDNSHandler(false))
|
||||
factory := func(bindIP, server net.IP) queryResolver {
|
||||
return newServerResolverAt(bindIP, server, port)
|
||||
}
|
||||
result, err := discoverRegistrarWithOptions(
|
||||
context.Background(), "ims.example", "tcp", false, ip, []net.IP{ip},
|
||||
false, nil, false, nil, factory,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result.Source != "dns" || !strings.HasPrefix(result.Registrar, "192.0.2.20:5070") {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStructuredDiscoveryFallsBackToAAndAAAA(t *testing.T) {
|
||||
ip, port := startTestDNSServer(t, registrarDNSHandler(false))
|
||||
candidates, err := DiscoverRegistrarCandidatesViaDNS(
|
||||
"fallback.example", []string{net.JoinHostPort(ip.String(), port)}, time.Second,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(candidates) != 2 || candidates[0].Port != 5060 || candidates[1].Port != 5060 {
|
||||
t.Fatalf("candidates = %#v", candidates)
|
||||
}
|
||||
}
|
||||
|
||||
type staticQueryResolver struct {
|
||||
addresses []net.IPAddr
|
||||
}
|
||||
|
||||
func (resolver staticQueryResolver) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) {
|
||||
return resolver.addresses, nil
|
||||
}
|
||||
|
||||
func (staticQueryResolver) LookupSRV(context.Context, string, string, string) (string, []*net.SRV, error) {
|
||||
return "", nil, nil
|
||||
}
|
||||
|
||||
func (staticQueryResolver) LookupNAPTR(context.Context, string) ([]*miekgdns.NAPTR, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func startTestDNSServer(t *testing.T, handler miekgdns.Handler) (net.IP, string) {
|
||||
t.Helper()
|
||||
packet, err := net.ListenPacket("udp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := &miekgdns.Server{PacketConn: packet, Handler: handler}
|
||||
go func() { _ = server.ActivateAndServe() }()
|
||||
t.Cleanup(func() { _ = server.Shutdown() })
|
||||
host, port, err := net.SplitHostPort(packet.LocalAddr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return net.ParseIP(host), port
|
||||
}
|
||||
|
||||
func registrarDNSHandler(useNAPTR bool) miekgdns.Handler {
|
||||
return miekgdns.HandlerFunc(func(writer miekgdns.ResponseWriter, request *miekgdns.Msg) {
|
||||
response := new(miekgdns.Msg)
|
||||
response.SetReply(request)
|
||||
response.Authoritative = true
|
||||
for _, question := range request.Question {
|
||||
appendRegistrarDNSAnswers(response, question, useNAPTR)
|
||||
}
|
||||
_ = writer.WriteMsg(response)
|
||||
})
|
||||
}
|
||||
|
||||
func appendRegistrarDNSAnswers(response *miekgdns.Msg, question miekgdns.Question, useNAPTR bool) {
|
||||
name := strings.ToLower(question.Name)
|
||||
switch {
|
||||
case !useNAPTR && question.Qtype == miekgdns.TypeSRV && name == "_sip._tcp.ims.example.":
|
||||
response.Answer = append(response.Answer,
|
||||
netSRVHeader{target: "a.example.", port: 5060, priority: 10, weight: 10}.record(question.Name),
|
||||
netSRVHeader{target: "b.example.", port: 5070, priority: 10, weight: 20}.record(question.Name),
|
||||
)
|
||||
case useNAPTR && question.Qtype == miekgdns.TypeNAPTR && name == "naptr.example.":
|
||||
response.Answer = append(response.Answer, &miekgdns.NAPTR{
|
||||
Hdr: miekgdns.RR_Header{Name: question.Name, Rrtype: miekgdns.TypeNAPTR, Class: miekgdns.ClassINET, Ttl: 60},
|
||||
Order: 10, Preference: 10, Service: "SIP+D2U", Replacement: "_sip._udp.alt.example.",
|
||||
})
|
||||
case useNAPTR && question.Qtype == miekgdns.TypeSRV && name == "_sip._udp.alt.example.":
|
||||
response.Answer = append(response.Answer,
|
||||
netSRVHeader{target: "c.example.", port: 5090}.record(question.Name),
|
||||
)
|
||||
case question.Qtype == miekgdns.TypeA:
|
||||
if address := testIPv4ForName(name); address != nil {
|
||||
response.Answer = append(response.Answer, &miekgdns.A{
|
||||
Hdr: addressHeader(question.Name, miekgdns.TypeA), A: address,
|
||||
})
|
||||
}
|
||||
case question.Qtype == miekgdns.TypeAAAA:
|
||||
if address := testIPv6ForName(name); address != nil {
|
||||
response.Answer = append(response.Answer, &miekgdns.AAAA{
|
||||
Hdr: addressHeader(question.Name, miekgdns.TypeAAAA), AAAA: address,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type netSRVHeader struct {
|
||||
target string
|
||||
port uint16
|
||||
priority uint16
|
||||
weight uint16
|
||||
}
|
||||
|
||||
func (header netSRVHeader) record(name string) *miekgdns.SRV {
|
||||
return &miekgdns.SRV{
|
||||
Hdr: addressHeader(name, miekgdns.TypeSRV), Target: header.target,
|
||||
Port: header.port, Priority: header.priority, Weight: header.weight,
|
||||
}
|
||||
}
|
||||
|
||||
func addressHeader(name string, recordType uint16) miekgdns.RR_Header {
|
||||
return miekgdns.RR_Header{Name: name, Rrtype: recordType, Class: miekgdns.ClassINET, Ttl: 60}
|
||||
}
|
||||
|
||||
func testIPv4ForName(name string) net.IP {
|
||||
switch name {
|
||||
case "a.example.":
|
||||
return net.ParseIP("192.0.2.10")
|
||||
case "b.example.":
|
||||
return net.ParseIP("192.0.2.20")
|
||||
case "c.example.":
|
||||
return net.ParseIP("192.0.2.30")
|
||||
case "fallback.example.":
|
||||
return net.ParseIP("192.0.2.40")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func testIPv6ForName(name string) net.IP {
|
||||
switch name {
|
||||
case "a.example.":
|
||||
return net.ParseIP("2001:db8::10")
|
||||
case "b.example.":
|
||||
return net.ParseIP("2001:db8::20")
|
||||
case "c.example.":
|
||||
return net.ParseIP("2001:db8::30")
|
||||
case "fallback.example.":
|
||||
return net.ParseIP("2001:db8::40")
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
miekgdns "github.com/miekg/dns"
|
||||
)
|
||||
|
||||
func discoverRegistrarFromServer(
|
||||
ctx context.Context,
|
||||
resolver queryResolver,
|
||||
domain, transport string,
|
||||
preferIPv6 bool,
|
||||
) (string, error) {
|
||||
var failures []error
|
||||
if candidates, err := lookupSRVCandidates(ctx, resolver, "sip", transport, domain, preferIPv6); err == nil {
|
||||
return strings.Join(candidates, ","), nil
|
||||
} else {
|
||||
failures = append(failures, err)
|
||||
}
|
||||
if service, proto, name, ok, err := lookupNAPTRTarget(ctx, resolver, domain, transport); err == nil && ok {
|
||||
if candidates, srvErr := lookupSRVCandidates(ctx, resolver, service, proto, name, preferIPv6); srvErr == nil {
|
||||
return strings.Join(candidates, ","), nil
|
||||
} else {
|
||||
failures = append(failures, srvErr)
|
||||
}
|
||||
} else if err != nil {
|
||||
failures = append(failures, err)
|
||||
}
|
||||
addresses, err := lookupTargetAddresses(ctx, resolver, domain, preferIPv6)
|
||||
if err != nil {
|
||||
failures = append(failures, err)
|
||||
return "", errors.Join(failures...)
|
||||
}
|
||||
return strings.Join(formatEndpoints(addresses, defaultRegistrarSIPPort), ","), nil
|
||||
}
|
||||
|
||||
func lookupSRVCandidates(
|
||||
ctx context.Context,
|
||||
resolver queryResolver,
|
||||
service, proto, domain string,
|
||||
preferIPv6 bool,
|
||||
) ([]string, error) {
|
||||
queryCtx, cancel := context.WithTimeout(ctx, registrarQueryTimeout)
|
||||
defer cancel()
|
||||
_, records, err := resolver.LookupSRV(queryCtx, service, proto, domain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(records) == 0 {
|
||||
return nil, fmt.Errorf("dns: no SRV records for _%s._%s.%s", service, proto, domain)
|
||||
}
|
||||
sort.SliceStable(records, func(i, j int) bool { return lessSRV(records[i], records[j]) })
|
||||
candidates := make([]string, 0, len(records))
|
||||
seen := make(map[string]struct{})
|
||||
for _, record := range records {
|
||||
port := int(record.Port)
|
||||
if port == 0 {
|
||||
port = defaultRegistrarSIPPort
|
||||
}
|
||||
target := strings.TrimSuffix(strings.TrimSpace(record.Target), ".")
|
||||
addresses, resolveErr := lookupTargetAddresses(ctx, resolver, target, preferIPv6)
|
||||
if resolveErr != nil {
|
||||
addresses = []string{target}
|
||||
}
|
||||
appendUniqueEndpoints(&candidates, seen, addresses, port)
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
return nil, errors.New("dns: SRV records contained no registrar targets")
|
||||
}
|
||||
return candidates, nil
|
||||
}
|
||||
|
||||
func lessSRV(left, right *net.SRV) bool {
|
||||
if left.Priority != right.Priority {
|
||||
return left.Priority < right.Priority
|
||||
}
|
||||
if left.Weight != right.Weight {
|
||||
return left.Weight > right.Weight
|
||||
}
|
||||
return left.Target < right.Target
|
||||
}
|
||||
|
||||
func lookupNAPTRTarget(
|
||||
ctx context.Context,
|
||||
resolver queryResolver,
|
||||
domain, transport string,
|
||||
) (string, string, string, bool, error) {
|
||||
queryCtx, cancel := context.WithTimeout(ctx, registrarQueryTimeout)
|
||||
defer cancel()
|
||||
records, err := resolver.LookupNAPTR(queryCtx, domain)
|
||||
if err != nil {
|
||||
return "", "", "", false, err
|
||||
}
|
||||
sort.SliceStable(records, func(i, j int) bool {
|
||||
if records[i].Order != records[j].Order {
|
||||
return records[i].Order < records[j].Order
|
||||
}
|
||||
return records[i].Preference < records[j].Preference
|
||||
})
|
||||
wanted := "SIP+D2U"
|
||||
if transport == "tcp" {
|
||||
wanted = "SIP+D2T"
|
||||
}
|
||||
replacement := selectNAPTRReplacement(records, wanted)
|
||||
service, proto, name, ok := parseSRVReplacement(replacement)
|
||||
return service, proto, name, ok, nil
|
||||
}
|
||||
|
||||
func selectNAPTRReplacement(records []*miekgdns.NAPTR, wanted string) string {
|
||||
for _, record := range records {
|
||||
if strings.EqualFold(strings.TrimSpace(record.Service), wanted) && strings.TrimSpace(record.Replacement) != "" {
|
||||
return record.Replacement
|
||||
}
|
||||
}
|
||||
for _, record := range records {
|
||||
if strings.TrimSpace(record.Replacement) != "" {
|
||||
return record.Replacement
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseSRVReplacement(replacement string) (string, string, string, bool) {
|
||||
parts := strings.Split(strings.TrimSuffix(strings.TrimSpace(replacement), "."), ".")
|
||||
if len(parts) < 3 || !strings.HasPrefix(parts[0], "_") || !strings.HasPrefix(parts[1], "_") {
|
||||
return "", "", "", false
|
||||
}
|
||||
service := strings.TrimPrefix(parts[0], "_")
|
||||
proto := strings.TrimPrefix(parts[1], "_")
|
||||
name := strings.Join(parts[2:], ".")
|
||||
return service, proto, name, service != "" && proto != "" && name != ""
|
||||
}
|
||||
|
||||
func lookupTargetAddresses(
|
||||
ctx context.Context,
|
||||
resolver queryResolver,
|
||||
host string,
|
||||
preferIPv6 bool,
|
||||
) ([]string, error) {
|
||||
host = strings.TrimSuffix(strings.TrimSpace(host), ".")
|
||||
if host == "" {
|
||||
return nil, errors.New("dns: empty lookup target")
|
||||
}
|
||||
queryCtx, cancel := context.WithTimeout(ctx, registrarQueryTimeout)
|
||||
defer cancel()
|
||||
addresses, err := resolver.LookupIPAddr(queryCtx, host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ipv4 := make([]string, 0, len(addresses))
|
||||
globalIPv6 := make([]string, 0, len(addresses))
|
||||
otherIPv6 := make([]string, 0, len(addresses))
|
||||
seen := make(map[string]struct{})
|
||||
for _, address := range addresses {
|
||||
if address.IP == nil {
|
||||
continue
|
||||
}
|
||||
key := address.IP.String()
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
if address.IP.To4() != nil {
|
||||
ipv4 = append(ipv4, key)
|
||||
} else if address.IP.IsGlobalUnicast() {
|
||||
globalIPv6 = append(globalIPv6, key)
|
||||
} else {
|
||||
otherIPv6 = append(otherIPv6, key)
|
||||
}
|
||||
}
|
||||
if len(ipv4)+len(globalIPv6)+len(otherIPv6) == 0 {
|
||||
return nil, fmt.Errorf("dns: no address records for %s", host)
|
||||
}
|
||||
ipv6 := append(globalIPv6, otherIPv6...)
|
||||
if preferIPv6 {
|
||||
return append(ipv6, ipv4...), nil
|
||||
}
|
||||
return append(ipv4, ipv6...), nil
|
||||
}
|
||||
|
||||
func formatEndpoints(hosts []string, port int) []string {
|
||||
result := make([]string, 0, len(hosts))
|
||||
appendUniqueEndpoints(&result, make(map[string]struct{}), hosts, port)
|
||||
return result
|
||||
}
|
||||
|
||||
func appendUniqueEndpoints(result *[]string, seen map[string]struct{}, hosts []string, port int) {
|
||||
if port < 1 {
|
||||
return
|
||||
}
|
||||
for _, host := range hosts {
|
||||
host = strings.Trim(strings.TrimSpace(host), "[]")
|
||||
if host == "" {
|
||||
continue
|
||||
}
|
||||
endpoint := net.JoinHostPort(host, strconv.Itoa(port))
|
||||
if _, exists := seen[endpoint]; exists {
|
||||
continue
|
||||
}
|
||||
seen[endpoint] = struct{}{}
|
||||
*result = append(*result, endpoint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultDNSPort = "53"
|
||||
registrarQueryTimeout = 3 * time.Second
|
||||
defaultRegistrarSIPPort = 5060
|
||||
)
|
||||
|
||||
type registrarDiscoveryDNSServerStage struct {
|
||||
Source string
|
||||
Servers []net.IP
|
||||
}
|
||||
|
||||
// ReadSystemDNSServers reads unique nameserver addresses from resolv.conf.
|
||||
func ReadSystemDNSServers() []net.IP {
|
||||
contents, err := os.ReadFile("/etc/resolv.conf")
|
||||
if err != nil || len(contents) == 0 {
|
||||
return nil
|
||||
}
|
||||
return parseResolvConf(contents)
|
||||
}
|
||||
|
||||
func parseResolvConf(contents []byte) []net.IP {
|
||||
servers := make([]net.IP, 0, 4)
|
||||
seen := make(map[string]struct{})
|
||||
for _, line := range strings.Split(string(contents), "\n") {
|
||||
fields := strings.Fields(strings.TrimSpace(line))
|
||||
if len(fields) < 2 || strings.HasPrefix(strings.TrimSpace(line), "#") || fields[0] != "nameserver" {
|
||||
continue
|
||||
}
|
||||
ip := net.ParseIP(strings.TrimSpace(fields[1]))
|
||||
if ip == nil {
|
||||
continue
|
||||
}
|
||||
key := ip.String()
|
||||
if _, exists := seen[key]; exists {
|
||||
continue
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
servers = append(servers, ip)
|
||||
}
|
||||
return servers
|
||||
}
|
||||
|
||||
// FilterDNSServersForBind separates servers matching bindIP's address family.
|
||||
func FilterDNSServersForBind(servers []net.IP, bindIP net.IP) ([]net.IP, []net.IP) {
|
||||
if len(servers) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
if bindIP == nil {
|
||||
return servers, nil
|
||||
}
|
||||
preferred := make([]net.IP, 0, len(servers))
|
||||
fallback := make([]net.IP, 0, len(servers))
|
||||
wantIPv4 := bindIP.To4() != nil
|
||||
for _, server := range servers {
|
||||
if server == nil {
|
||||
continue
|
||||
}
|
||||
if (server.To4() != nil) == wantIPv4 {
|
||||
preferred = append(preferred, server)
|
||||
} else {
|
||||
fallback = append(fallback, server)
|
||||
}
|
||||
}
|
||||
return preferred, fallback
|
||||
}
|
||||
|
||||
func defaultRegistrarPublicDNSServers() []net.IP {
|
||||
return []net.IP{net.ParseIP("1.1.1.1")}
|
||||
}
|
||||
|
||||
func registrarDiscoveryDNSServerStages(
|
||||
assigned []net.IP,
|
||||
bindIP net.IP,
|
||||
includeSystem bool,
|
||||
system []net.IP,
|
||||
includePublic bool,
|
||||
public []net.IP,
|
||||
) []registrarDiscoveryDNSServerStage {
|
||||
if len(assigned) > 0 {
|
||||
preferred, _ := FilterDNSServersForBind(assigned, bindIP)
|
||||
if len(preferred) == 0 {
|
||||
return nil
|
||||
}
|
||||
return []registrarDiscoveryDNSServerStage{{Source: "dns", Servers: cloneIPs(preferred)}}
|
||||
}
|
||||
stages := make([]registrarDiscoveryDNSServerStage, 0, 2)
|
||||
stages = appendDNSStage(stages, "systemdns", includeSystem, system, bindIP)
|
||||
if includePublic && len(public) == 0 {
|
||||
public = defaultRegistrarPublicDNSServers()
|
||||
}
|
||||
return appendDNSStage(stages, "publicdns", includePublic, public, bindIP)
|
||||
}
|
||||
|
||||
func appendDNSStage(
|
||||
stages []registrarDiscoveryDNSServerStage,
|
||||
source string,
|
||||
include bool,
|
||||
servers []net.IP,
|
||||
bindIP net.IP,
|
||||
) []registrarDiscoveryDNSServerStage {
|
||||
if !include {
|
||||
return stages
|
||||
}
|
||||
preferred, _ := FilterDNSServersForBind(servers, bindIP)
|
||||
if len(preferred) == 0 {
|
||||
return stages
|
||||
}
|
||||
return append(stages, registrarDiscoveryDNSServerStage{Source: source, Servers: cloneIPs(preferred)})
|
||||
}
|
||||
|
||||
func cloneIPs(ips []net.IP) []net.IP {
|
||||
cloned := make([]net.IP, 0, len(ips))
|
||||
for _, ip := range ips {
|
||||
if ip != nil {
|
||||
cloned = append(cloned, append(net.IP(nil), ip...))
|
||||
}
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package dns
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegistrarTransportCandidates(t *testing.T) {
|
||||
tests := map[string][]string{
|
||||
"udp": {"udp"}, " UDP ": {"udp"}, "tcp": {"tcp", "udp"},
|
||||
"auto": {"tcp", "udp"}, "": {"tcp", "udp"}, "tls": {"tcp", "udp"},
|
||||
}
|
||||
for input, want := range tests {
|
||||
if got := registrarTransportCandidates(input); !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("candidates(%q) = %v, want %v", input, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseResolvConf(t *testing.T) {
|
||||
contents := []byte("# comment\nnameserver 1.1.1.1\nnameserver 2001:4860:4860::8888\n" +
|
||||
"nameserver 1.1.1.1\nnameserver invalid\n")
|
||||
servers := parseResolvConf(contents)
|
||||
if len(servers) != 2 || servers[0].String() != "1.1.1.1" || servers[1].To4() != nil {
|
||||
t.Fatalf("servers = %v", servers)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterDNSServersForBind(t *testing.T) {
|
||||
servers := []net.IP{nil, net.ParseIP("2001:db8::53"), net.ParseIP("192.0.2.53")}
|
||||
preferred, fallback := FilterDNSServersForBind(servers, net.ParseIP("192.0.2.10"))
|
||||
if got := ipStrings(preferred); len(got) != 1 || got[0] != "192.0.2.53" {
|
||||
t.Fatalf("preferred = %v", got)
|
||||
}
|
||||
if got := ipStrings(fallback); len(got) != 1 || got[0] != "2001:db8::53" {
|
||||
t.Fatalf("fallback = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOrderDNSServersByPreference(t *testing.T) {
|
||||
servers := []net.IP{net.ParseIP("192.0.2.53"), net.ParseIP("2001:db8::53")}
|
||||
got := ipStrings(OrderDNSServersByPreference(servers, true))
|
||||
if len(got) != 2 || got[0] != "2001:db8::53" || got[1] != "192.0.2.53" {
|
||||
t.Fatalf("ordered = %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrarDiscoveryDNSServerStages(t *testing.T) {
|
||||
assigned := []net.IP{net.ParseIP("192.0.2.53")}
|
||||
stages := registrarDiscoveryDNSServerStages(
|
||||
assigned, net.ParseIP("192.0.2.10"), true,
|
||||
[]net.IP{net.ParseIP("192.0.2.54")}, true, nil,
|
||||
)
|
||||
if len(stages) != 1 || stages[0].Source != "dns" || stages[0].Servers[0].String() != "192.0.2.53" {
|
||||
t.Fatalf("stages = %#v", stages)
|
||||
}
|
||||
assigned[0][0] ^= 0xff
|
||||
if stages[0].Servers[0].String() != "192.0.2.53" {
|
||||
t.Fatal("stage did not clone assigned DNS address")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrarDiscoveryStagesUseRecoveredPublicResolver(t *testing.T) {
|
||||
stages := registrarDiscoveryDNSServerStages(nil, nil, false, nil, true, nil)
|
||||
if len(stages) != 1 || stages[0].Source != "publicdns" {
|
||||
t.Fatalf("stages = %#v", stages)
|
||||
}
|
||||
if got := stages[0].Servers[0].String(); got != "1.1.1.1" {
|
||||
t.Fatalf("public DNS = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParserRegistrarHostPort(t *testing.T) {
|
||||
host, port, ok := parserRegistrarHostPort("sips:[2001:db8::1]:5070;transport=tcp", 5060)
|
||||
if !ok || host != "2001:db8::1" || port != 5070 {
|
||||
t.Fatalf("parsed = %q %d %v", host, port, ok)
|
||||
}
|
||||
host, port, ok = parserRegistrarHostPort("pcscf.example?x=1", 5060)
|
||||
if !ok || host != "pcscf.example" || port != 5060 {
|
||||
t.Fatalf("defaulted = %q %d %v", host, port, ok)
|
||||
}
|
||||
host, port, ok = parserRegistrarHostPort("pcscf.example:invalid", 5060)
|
||||
if !ok || host != "pcscf.example" || port != 0 {
|
||||
t.Fatalf("invalid port = %q %d %v", host, port, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExpandRegistrarCandidatesPreservesUnresolvedHost(t *testing.T) {
|
||||
got := ExpandRegistrarCandidates(
|
||||
context.Background(), "sip:pcscf.invalid,sip:pcscf.invalid,[2001:db8::1]:5070,bad.example:bad",
|
||||
true, nil, nil,
|
||||
)
|
||||
want := "pcscf.invalid:5060,[2001:db8::1]:5070"
|
||||
if got != want {
|
||||
t.Fatalf("expanded = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStructuredDiscoveryWithoutServersReturnsError(t *testing.T) {
|
||||
if _, err := DiscoverRegistrarCandidatesViaDNS("ims.example", nil, 0); err == nil {
|
||||
t.Fatal("expected missing DNS server error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRegistrarCandidatesRetainsAdditiveAPI(t *testing.T) {
|
||||
got := NormalizeRegistrarCandidates([]RegistrarCandidate{
|
||||
{Host: "a.example", Transport: "udp"},
|
||||
{Host: "a.example", Transport: "udp"},
|
||||
{Host: "b.example", Transport: "tls"},
|
||||
})
|
||||
if len(got) != 2 || got[0].Port != 5060 || got[1].Port != 5061 {
|
||||
t.Fatalf("normalized = %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func ipStrings(ips []net.IP) []string {
|
||||
result := make([]string, 0, len(ips))
|
||||
for _, ip := range ips {
|
||||
result = append(result, ip.String())
|
||||
}
|
||||
return result
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package imscore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type registrarDiscoveryNetwork struct {
|
||||
*SystemIMSNetwork
|
||||
calls []string
|
||||
}
|
||||
|
||||
func (network *registrarDiscoveryNetwork) LookupSRV(
|
||||
_ context.Context,
|
||||
service, proto, name string,
|
||||
) (string, uint16, error) {
|
||||
network.calls = append(network.calls, service+":"+proto+":"+name)
|
||||
if proto == "tcp" {
|
||||
return "pcscf.ims.example.", 5070, nil
|
||||
}
|
||||
return "", 0, errors.New("not found")
|
||||
}
|
||||
|
||||
func TestDiscoverRegistrarUsesDNSModuleInProductionPath(t *testing.T) {
|
||||
network := ®istrarDiscoveryNetwork{SystemIMSNetwork: NewSystemIMSNetwork(net.ParseIP("192.0.2.10"))}
|
||||
service := &Service{cfg: &IMSConfig{Domain: "ims.example", IMSNetwork: network}}
|
||||
registrar, err := service.discoverRegistrar(context.Background(), "tcp")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if registrar != "pcscf.ims.example:5070" {
|
||||
t.Fatalf("registrar = %q", registrar)
|
||||
}
|
||||
if len(network.calls) != 1 || network.calls[0] != "sip:tcp:ims.example" {
|
||||
t.Fatalf("calls = %v", network.calls)
|
||||
}
|
||||
}
|
||||
|
||||
type networkWithoutSRV struct {
|
||||
IMSNetwork
|
||||
}
|
||||
|
||||
func TestDiscoverRegistrarRejectsNetworkWithoutSRV(t *testing.T) {
|
||||
network := &networkWithoutSRV{IMSNetwork: NewSystemIMSNetwork(net.ParseIP("192.0.2.10"))}
|
||||
service := &Service{cfg: &IMSConfig{Domain: "ims.example", IMSNetwork: network}}
|
||||
if _, err := service.discoverRegistrar(context.Background(), "udp"); err == nil {
|
||||
t.Fatal("expected missing SRV capability error")
|
||||
}
|
||||
}
|
||||
+12
-12
@@ -7,6 +7,8 @@ import (
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
vowifidns "github.com/iniwex5/vowifi-go/internal/vowifi/dns"
|
||||
)
|
||||
|
||||
type initialRegistrationTransport struct {
|
||||
@@ -152,7 +154,11 @@ func closeRegistrationReservations(serverListener, clientReservation net.Listene
|
||||
func (s *Service) resolveRegistrar(ctx context.Context, transport string) (*net.UDPAddr, error) {
|
||||
target := strings.TrimSpace(s.cfg.Registrar)
|
||||
if target == "" {
|
||||
target = s.discoverRegistrar(ctx, transport)
|
||||
var err error
|
||||
target, err = s.discoverRegistrar(ctx, transport)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
host, portText, err := net.SplitHostPort(target)
|
||||
if err != nil {
|
||||
@@ -169,16 +175,10 @@ func (s *Service) resolveRegistrar(ctx context.Context, transport string) (*net.
|
||||
return &net.UDPAddr{IP: ip, Port: port}, nil
|
||||
}
|
||||
|
||||
func (s *Service) discoverRegistrar(ctx context.Context, transport string) string {
|
||||
domain := strings.TrimSpace(s.cfg.Domain)
|
||||
type srvResolver interface {
|
||||
LookupSRV(context.Context, string, string, string) (string, uint16, error)
|
||||
func (s *Service) discoverRegistrar(ctx context.Context, transport string) (string, error) {
|
||||
resolver, ok := s.cfg.IMSNetwork.(vowifidns.RegistrarNetwork)
|
||||
if !ok {
|
||||
return "", errors.New("imscore: IMS network does not support SRV lookup")
|
||||
}
|
||||
if resolver, ok := s.cfg.IMSNetwork.(srvResolver); ok {
|
||||
host, port, err := resolver.LookupSRV(ctx, "sip", transport, domain)
|
||||
if err == nil && strings.TrimSpace(host) != "" && port != 0 {
|
||||
return net.JoinHostPort(strings.TrimSpace(host), strconv.Itoa(int(port)))
|
||||
}
|
||||
}
|
||||
return net.JoinHostPort(domain, strconv.Itoa(defaultSIPPort))
|
||||
return vowifidns.DiscoverRegistrarViaNetwork(ctx, s.cfg.Domain, transport, resolver)
|
||||
}
|
||||
Reference in new issue
Block a user