mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-06 00:01:20 +00:00
fix(phone): propagate public host DNS refresh failures
Remove the cached-address fallback and fixed lookup timeout introduced by PR #96. Use the caller context and return DNS failures without advertising stale public addresses. Preserve startup and address-change logging, extract public-host resolution into its own module, and cover address changes, DNS errors, cancellation, and caller deadlines.
This commit is contained in:
1 parent
71dd380474
commit
cbb71f33cb
3 files changed
+208
-183
No files matched your search
+3
-95
@@ -8,31 +8,25 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pion/ice/v4"
|
||||
"github.com/pion/webrtc/v4"
|
||||
"github.com/yibaiba/hideck/pkg/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
pcmPayloadType = 0
|
||||
|
||||
webRTCPublicHostLookupTimeout = 3 * time.Second
|
||||
)
|
||||
|
||||
type MediaOptions struct {
|
||||
UDPAddress string
|
||||
PublicHost string
|
||||
LookupIPAddr func(context.Context, string) ([]net.IPAddr, error)
|
||||
ICEServers []webrtc.ICEServer
|
||||
RealtimeCodecs []string
|
||||
NewRealtimeCodec RealtimeCodecFactory
|
||||
OnState func(mediaID string, state webrtc.PeerConnectionState)
|
||||
|
||||
LookupIPAddr func(context.Context, string) ([]net.IPAddr, error)
|
||||
}
|
||||
|
||||
type MediaAnswer struct {
|
||||
@@ -78,11 +72,10 @@ func NewMediaManager(options MediaOptions) (*MediaManager, error) {
|
||||
if publicHost != nil {
|
||||
// A host that does not resolve at startup is still a configuration
|
||||
// error; startup keeps the resolver's own timeout, as before.
|
||||
if publicIPs, err = publicHost.resolve(context.Background(), 0); err != nil {
|
||||
if publicIPs, err = publicHost.resolve(context.Background()); err != nil {
|
||||
_ = mux.Close()
|
||||
return nil, err
|
||||
}
|
||||
logger.Info("WebRTC 公网地址", "host", publicHost.host, "ips", publicIPs)
|
||||
if net.ParseIP(publicHost.host) != nil {
|
||||
publicHost = nil // a literal never changes; the startup API serves every call
|
||||
}
|
||||
@@ -132,98 +125,13 @@ func (m *MediaManager) callAPI(ctx context.Context) (*webrtc.API, error) {
|
||||
if m.publicHost == nil {
|
||||
return m.api, nil
|
||||
}
|
||||
publicIPs, err := m.publicHost.resolve(ctx, webRTCPublicHostLookupTimeout)
|
||||
publicIPs, err := m.publicHost.resolve(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newWebRTCAPI(m.mux, publicIPs)
|
||||
}
|
||||
|
||||
type publicIPLookup func(context.Context, string) ([]net.IPAddr, error)
|
||||
|
||||
// webRTCPublicHost resolves server.webrtc_public_host and keeps the last good
|
||||
// answer for a lookup that fails mid-call-setup.
|
||||
type webRTCPublicHost struct {
|
||||
host string
|
||||
lookup publicIPLookup
|
||||
mu sync.Mutex
|
||||
last []string
|
||||
}
|
||||
|
||||
func newWebRTCPublicHost(value string, lookup publicIPLookup) *webRTCPublicHost {
|
||||
host := strings.TrimSpace(value)
|
||||
if host == "" {
|
||||
return nil
|
||||
}
|
||||
if lookup == nil {
|
||||
lookup = net.DefaultResolver.LookupIPAddr
|
||||
}
|
||||
return &webRTCPublicHost{host: host, lookup: lookup}
|
||||
}
|
||||
|
||||
// resolve bounds the lookup by timeout when it is positive.
|
||||
func (h *webRTCPublicHost) resolve(ctx context.Context, timeout time.Duration) ([]string, error) {
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
lookupCtx, cancel := ctx, context.CancelFunc(func() {})
|
||||
if timeout > 0 {
|
||||
lookupCtx, cancel = context.WithTimeout(ctx, timeout)
|
||||
}
|
||||
defer cancel()
|
||||
publicIPs, err := resolveWebRTCPublicIPs(lookupCtx, h.host, h.lookup)
|
||||
if err != nil && ctx.Err() != nil {
|
||||
// The call setup itself was cancelled; that is not a DNS failure.
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if err != nil {
|
||||
if h.last == nil {
|
||||
return nil, err
|
||||
}
|
||||
logger.Warn("WebRTC 公网地址解析失败,沿用上次结果", "host", h.host, "ips", h.last, "err", err)
|
||||
return h.last, nil
|
||||
}
|
||||
if h.last != nil && !sameIPSet(h.last, publicIPs) {
|
||||
logger.Info("WebRTC 公网地址已变化", "host", h.host, "old", h.last, "new", publicIPs)
|
||||
}
|
||||
h.last = publicIPs
|
||||
return publicIPs, nil
|
||||
}
|
||||
|
||||
// sameIPSet ignores order, which round-robin DNS changes between lookups.
|
||||
func sameIPSet(a, b []string) bool {
|
||||
return slices.Equal(slices.Sorted(slices.Values(a)), slices.Sorted(slices.Values(b)))
|
||||
}
|
||||
|
||||
func resolveWebRTCPublicIPs(ctx context.Context, host string, lookup publicIPLookup) ([]string, error) {
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return []string{ip.String()}, nil
|
||||
}
|
||||
addresses, err := lookup(ctx, host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("phone: resolve WebRTC public host %q: %w", host, err)
|
||||
}
|
||||
unique := make(map[string]struct{}, len(addresses))
|
||||
result := make([]string, 0, len(addresses))
|
||||
for _, address := range addresses {
|
||||
if address.IP == nil {
|
||||
continue
|
||||
}
|
||||
ip := address.IP.String()
|
||||
if _, exists := unique[ip]; exists {
|
||||
continue
|
||||
}
|
||||
unique[ip] = struct{}{}
|
||||
result = append(result, ip)
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil, fmt.Errorf("phone: WebRTC public host %q resolved without IP addresses", host)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (m *MediaManager) Create(ctx context.Context, owner, offer, accessHost string) (MediaAnswer, error) {
|
||||
if m == nil || m.api == nil {
|
||||
return MediaAnswer{}, errors.New("phone: media manager is unavailable")
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
package phone
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/yibaiba/hideck/pkg/logger"
|
||||
)
|
||||
|
||||
type publicIPLookup func(context.Context, string) ([]net.IPAddr, error)
|
||||
|
||||
type webRTCPublicHost struct {
|
||||
host string
|
||||
lookup publicIPLookup
|
||||
mu sync.Mutex
|
||||
last []string // Only used to log address changes, never as a DNS fallback.
|
||||
}
|
||||
|
||||
func newWebRTCPublicHost(value string, lookup publicIPLookup) *webRTCPublicHost {
|
||||
host := strings.TrimSpace(value)
|
||||
if host == "" {
|
||||
return nil
|
||||
}
|
||||
if lookup == nil {
|
||||
lookup = net.DefaultResolver.LookupIPAddr
|
||||
}
|
||||
return &webRTCPublicHost{host: host, lookup: lookup}
|
||||
}
|
||||
|
||||
func (h *webRTCPublicHost) resolve(ctx context.Context) ([]string, error) {
|
||||
publicIPs, err := resolveWebRTCPublicIPs(ctx, h.host, h.lookup)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
if h.last == nil {
|
||||
logger.Info("WebRTC 公网地址", "host", h.host, "ips", publicIPs)
|
||||
} else if !sameIPSet(h.last, publicIPs) {
|
||||
logger.Info("WebRTC 公网地址已变化", "host", h.host, "old", h.last, "new", publicIPs)
|
||||
}
|
||||
h.last = publicIPs
|
||||
return publicIPs, nil
|
||||
}
|
||||
|
||||
// sameIPSet ignores order, which round-robin DNS changes between lookups.
|
||||
func sameIPSet(a, b []string) bool {
|
||||
return slices.Equal(slices.Sorted(slices.Values(a)), slices.Sorted(slices.Values(b)))
|
||||
}
|
||||
|
||||
func resolveWebRTCPublicIPs(ctx context.Context, host string, lookup publicIPLookup) ([]string, error) {
|
||||
if host == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
return []string{ip.String()}, nil
|
||||
}
|
||||
addresses, err := lookup(ctx, host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("phone: resolve WebRTC public host %q: %w", host, err)
|
||||
}
|
||||
unique := make(map[string]struct{}, len(addresses))
|
||||
result := make([]string, 0, len(addresses))
|
||||
for _, address := range addresses {
|
||||
if address.IP == nil {
|
||||
continue
|
||||
}
|
||||
ip := address.IP.String()
|
||||
if _, exists := unique[ip]; exists {
|
||||
continue
|
||||
}
|
||||
unique[ip] = struct{}{}
|
||||
result = append(result, ip)
|
||||
}
|
||||
if len(result) == 0 {
|
||||
return nil, fmt.Errorf("phone: WebRTC public host %q resolved without IP addresses", host)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -6,107 +6,23 @@ import (
|
||||
"net"
|
||||
"reflect"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNewMediaManagerReportsPublicHostResolutionFailure(t *testing.T) {
|
||||
func TestMediaManagerReportsInitialPublicHostResolutionFailure(t *testing.T) {
|
||||
wantErr := errors.New("lookup failed")
|
||||
_, err := NewMediaManager(MediaOptions{
|
||||
UDPAddress: ":0", PublicHost: "hideck.example.com",
|
||||
LookupIPAddr: func(context.Context, string) ([]net.IPAddr, error) { return nil, wantErr },
|
||||
LookupIPAddr: func(context.Context, string) ([]net.IPAddr, error) {
|
||||
return nil, wantErr
|
||||
},
|
||||
})
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("NewMediaManager() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// hideck#93: the public host is looked up again for every call, and a failed
|
||||
// lookup keeps the last good address.
|
||||
func TestMediaManagerFollowsPublicHostAddressChanges(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
current, lookupErr := "203.0.113.10", error(nil)
|
||||
setAnswer := func(ip string, err error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
current, lookupErr = ip, err
|
||||
}
|
||||
manager, err := NewMediaManager(MediaOptions{
|
||||
UDPAddress: ":0", PublicHost: "hideck.example.com",
|
||||
LookupIPAddr: func(context.Context, string) ([]net.IPAddr, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if lookupErr != nil {
|
||||
return nil, lookupErr
|
||||
}
|
||||
return []net.IPAddr{{IP: net.ParseIP(current)}}, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer manager.Close()
|
||||
|
||||
answerFor := func() string {
|
||||
t.Helper()
|
||||
browser, _, _ := newPCMUBrowserPeer(t)
|
||||
defer browser.Close()
|
||||
answer, err := manager.Create(context.Background(), "admin", completeLocalOffer(t, browser), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
manager.Remove(answer.MediaID)
|
||||
return answer.SDP
|
||||
}
|
||||
|
||||
if sdp := answerFor(); !strings.Contains(sdp, " 203.0.113.10 ") {
|
||||
t.Fatalf("first call does not offer the startup address:\n%s", sdp)
|
||||
}
|
||||
setAnswer("198.51.100.20", nil)
|
||||
if sdp := answerFor(); !strings.Contains(sdp, " 198.51.100.20 ") || strings.Contains(sdp, " 203.0.113.10 ") {
|
||||
t.Fatalf("call after the address changed:\n%s", sdp)
|
||||
}
|
||||
setAnswer("", errors.New("temporary DNS failure"))
|
||||
if sdp := answerFor(); !strings.Contains(sdp, " 198.51.100.20 ") {
|
||||
t.Fatalf("call during a failed lookup does not keep the last address:\n%s", sdp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRTCPublicHostDoesNotFallBackWhenCallSetupIsCancelled(t *testing.T) {
|
||||
hang := false
|
||||
host := newWebRTCPublicHost("hideck.example.com", func(ctx context.Context, _ string) ([]net.IPAddr, error) {
|
||||
if hang {
|
||||
// A resolver that never answers: only the context ends the lookup.
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return []net.IPAddr{{IP: net.ParseIP("203.0.113.10")}}, nil
|
||||
})
|
||||
if _, err := host.resolve(context.Background(), time.Second); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hang = true
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
if ips, err := host.resolve(ctx, time.Second); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("resolve(cancelled) = %v, %v; want context.Canceled", ips, err)
|
||||
}
|
||||
// The per-call lookup timeout expiring is a DNS failure: keep the last address.
|
||||
if ips, err := host.resolve(context.Background(), 10*time.Millisecond); err != nil || len(ips) != 1 || ips[0] != "203.0.113.10" {
|
||||
t.Fatalf("resolve(after timeout) = %v, %v", ips, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameIPSetIgnoresOrder(t *testing.T) {
|
||||
if !sameIPSet([]string{"203.0.113.10", "2001:db8::10"}, []string{"2001:db8::10", "203.0.113.10"}) {
|
||||
t.Fatal("reordered round-robin answer counted as a change")
|
||||
}
|
||||
if sameIPSet([]string{"203.0.113.10"}, []string{"198.51.100.20"}) {
|
||||
t.Fatal("a new address was not counted as a change")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveWebRTCPublicIPs(t *testing.T) {
|
||||
lookupCalls := 0
|
||||
lookup := func(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
@@ -137,4 +53,122 @@ func TestResolveWebRTCPublicIPs(t *testing.T) {
|
||||
if !reflect.DeepEqual(got, []string{"203.0.113.20"}) || lookupCalls != 1 {
|
||||
t.Fatalf("IP literal result = %v, calls = %d", got, lookupCalls)
|
||||
}
|
||||
got, err = resolveWebRTCPublicIPs(context.Background(), "", lookup)
|
||||
if err != nil || len(got) != 0 || lookupCalls != 1 {
|
||||
t.Fatalf("empty host result = %v, err = %v, calls = %d", got, err, lookupCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaManagerRefreshesPublicHostForEachSession(t *testing.T) {
|
||||
publicIP := "203.0.113.10"
|
||||
manager, err := NewMediaManager(MediaOptions{
|
||||
UDPAddress: ":0", PublicHost: " hideck.example.com ",
|
||||
LookupIPAddr: func(_ context.Context, host string) ([]net.IPAddr, error) {
|
||||
if host != "hideck.example.com" {
|
||||
t.Fatalf("lookup host = %q", host)
|
||||
}
|
||||
return []net.IPAddr{{IP: net.ParseIP(publicIP)}}, nil
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = manager.Close() })
|
||||
browser, _, _ := newPCMUBrowserPeer(t)
|
||||
t.Cleanup(func() { _ = browser.Close() })
|
||||
offer := completeLocalOffer(t, browser)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), mediaIntegrationTimeout)
|
||||
defer cancel()
|
||||
var firstSession *MediaSession
|
||||
for index, ip := range []string{"203.0.113.10", "203.0.113.20", "203.0.113.30"} {
|
||||
previousIP := publicIP
|
||||
publicIP = ip
|
||||
answer, err := manager.Create(ctx, "admin", offer, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(answer.SDP, " "+ip+" ") {
|
||||
t.Fatalf("session %d SDP is missing current IP %s:\n%s", index, ip, answer.SDP)
|
||||
}
|
||||
if index == 0 {
|
||||
firstSession = manager.Get(answer.MediaID)
|
||||
continue
|
||||
}
|
||||
if strings.Contains(answer.SDP, " "+previousIP+" ") {
|
||||
t.Fatalf("session %d SDP retains previous IP %s:\n%s", index, previousIP, answer.SDP)
|
||||
}
|
||||
}
|
||||
if sdp := firstSession.peer.LocalDescription().SDP; !strings.Contains(sdp, " 203.0.113.10 ") {
|
||||
t.Fatalf("existing session lost its original public IP:\n%s", sdp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaManagerReportsPublicHostRefreshFailures(t *testing.T) {
|
||||
for _, wantErr := range []error{errors.New("DNS unavailable"), context.Canceled} {
|
||||
t.Run(wantErr.Error(), func(t *testing.T) {
|
||||
testMediaManagerPublicHostRefreshFailure(t, wantErr)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testMediaManagerPublicHostRefreshFailure(t *testing.T, wantErr error) {
|
||||
t.Helper()
|
||||
var lookupErr error
|
||||
manager, err := NewMediaManager(MediaOptions{
|
||||
UDPAddress: ":0", PublicHost: "hideck.example.com",
|
||||
LookupIPAddr: func(ctx context.Context, _ string) ([]net.IPAddr, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []net.IPAddr{{IP: net.ParseIP("203.0.113.10")}}, lookupErr
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = manager.Close() })
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
if errors.Is(wantErr, context.Canceled) {
|
||||
cancel()
|
||||
} else {
|
||||
lookupErr = wantErr
|
||||
}
|
||||
answer, err := manager.Create(ctx, "admin", "unused offer", "")
|
||||
if !errors.Is(err, wantErr) {
|
||||
t.Fatalf("Create() error = %v, want %v", err, wantErr)
|
||||
}
|
||||
if answer != (MediaAnswer{}) || len(manager.sessions) != 0 {
|
||||
t.Fatalf("failed DNS refresh created media: %+v", answer)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSameIPSetIgnoresOrder(t *testing.T) {
|
||||
if !sameIPSet([]string{"203.0.113.10", "2001:db8::10"}, []string{"2001:db8::10", "203.0.113.10"}) {
|
||||
t.Fatal("reordered round-robin answer counted as a change")
|
||||
}
|
||||
if sameIPSet([]string{"203.0.113.10"}, []string{"198.51.100.20"}) {
|
||||
t.Fatal("a new address was not counted as a change")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebRTCPublicHostHonorsCallerDeadline(t *testing.T) {
|
||||
blockLookup := false
|
||||
host := newWebRTCPublicHost("hideck.example.com", func(ctx context.Context, _ string) ([]net.IPAddr, error) {
|
||||
if blockLookup {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return []net.IPAddr{{IP: net.ParseIP("203.0.113.10")}}, nil
|
||||
})
|
||||
if _, err := host.resolve(context.Background()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blockLookup = true
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
|
||||
defer cancel()
|
||||
ips, err := host.resolve(ctx)
|
||||
if !errors.Is(err, context.DeadlineExceeded) || len(ips) != 0 {
|
||||
t.Fatalf("resolve() = %v, %v; want no addresses and context.DeadlineExceeded", ips, err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user