Files
sing-box-extended-mirror/transport/call/common/ice.go
T
2026-12-01 01:27:01 +03:00

78 lines
1.9 KiB
Go

package common
import (
"context"
"fmt"
"net"
"net/netip"
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing-box/common/dialer"
N "github.com/sagernet/sing/common/network"
)
func NormalizeICEURLs(urls []string) []string {
normalized := make([]string, len(urls))
for i, url := range urls {
normalized[i] = fixICEURL(url)
}
return normalized
}
func ResolveHost(ctx context.Context, dnsRouter adapter.DNSRouter, outboundDialer N.Dialer, host string) ([]netip.Addr, error) {
if address, err := netip.ParseAddr(host); err == nil {
return []netip.Addr{address}, nil
}
if dnsRouter == nil {
return nil, fmt.Errorf("call: missing sing-box DNS router for %s", host)
}
var queryOptions adapter.DNSQueryOptions
if resolveDialer, loaded := outboundDialer.(dialer.ResolveDialer); loaded {
queryOptions = resolveDialer.QueryOptions()
}
addresses, err := dnsRouter.Lookup(ctx, host, queryOptions)
if err != nil {
return nil, err
}
if len(addresses) == 0 {
return nil, fmt.Errorf("call: no addresses for %s", host)
}
return addresses, nil
}
func fixICEURL(iceURL string) string {
before, after, ok := strings.Cut(iceURL, ":")
if !ok {
return iceURL
}
scheme := before
if scheme != "turn" && scheme != "stun" && scheme != "turns" && scheme != "stuns" {
return iceURL
}
rest := after
if strings.HasPrefix(rest, "[") {
return iceURL
}
if strings.Count(rest, ":") <= 1 {
return iceURL
}
params := ""
if queryIndex := strings.Index(rest, "?"); queryIndex >= 0 {
params = rest[queryIndex:]
rest = rest[:queryIndex]
}
lastColon := strings.LastIndex(rest, ":")
if lastColon > 0 {
host := rest[:lastColon]
port := rest[lastColon+1:]
if net.ParseIP(host) != nil {
return scheme + ":[" + host + "]:" + port + params
}
}
if net.ParseIP(rest) != nil {
return scheme + ":[" + rest + "]" + params
}
return iceURL
}