diff --git a/internal/phone/media.go b/internal/phone/media.go index 0cea2a75..8397bf1a 100644 --- a/internal/phone/media.go +++ b/internal/phone/media.go @@ -8,15 +8,20 @@ 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 { @@ -26,6 +31,8 @@ type MediaOptions struct { RealtimeCodecs []string NewRealtimeCodec RealtimeCodecFactory OnState func(mediaID string, state webrtc.PeerConnectionState) + + lookupPublicIP publicIPLookup // tests only; nil uses the system resolver } type MediaAnswer struct { @@ -43,6 +50,7 @@ type MediaStats struct { type MediaManager struct { api *webrtc.API mux ice.UDPMux + publicHost *webRTCPublicHost iceServers []webrtc.ICEServer realtimeCodecs []string newRealtimeCodec RealtimeCodecFactory @@ -65,20 +73,34 @@ func NewMediaManager(options MediaOptions) (*MediaManager, error) { return nil, fmt.Errorf("phone: listen WebRTC UDP mux on %s: %w", address, err) } mux := webrtc.NewICEUDPMux(nil, connection) - api, err := newWebRTCAPI(mux, options.PublicHost) + publicHost := newWebRTCPublicHost(options.PublicHost, options.lookupPublicIP) + var publicIPs []string + 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 { + _ = 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 + } + } + api, err := newWebRTCAPI(mux, publicIPs) if err != nil { _ = mux.Close() return nil, err } return &MediaManager{ - api: api, mux: mux, iceServers: options.ICEServers, + api: api, mux: mux, publicHost: publicHost, iceServers: options.ICEServers, realtimeCodecs: append([]string(nil), options.RealtimeCodecs...), newRealtimeCodec: options.NewRealtimeCodec, onState: options.OnState, sessions: make(map[string]*MediaSession), }, nil } -func newWebRTCAPI(mux ice.UDPMux, publicHost string) (*webrtc.API, error) { +func newWebRTCAPI(mux ice.UDPMux, publicIPs []string) (*webrtc.API, error) { mediaEngine := &webrtc.MediaEngine{} err := mediaEngine.RegisterCodec(webrtc.RTPCodecParameters{ RTPCodecCapability: webrtc.RTPCodecCapability{ @@ -91,38 +113,95 @@ func newWebRTCAPI(mux ice.UDPMux, publicHost string) (*webrtc.API, error) { } settings := webrtc.SettingEngine{} settings.SetICEUDPMux(mux) - if err := setWebRTCPublicHost(&settings, publicHost, net.DefaultResolver.LookupIPAddr); err != nil { - return nil, err + if len(publicIPs) > 0 { + if err := settings.SetICEAddressRewriteRules(webrtc.ICEAddressRewriteRule{ + External: publicIPs, + AsCandidateType: webrtc.ICECandidateTypeHost, + Mode: webrtc.ICEAddressRewriteAppend, + }); err != nil { + return nil, fmt.Errorf("phone: configure WebRTC public host: %w", err) + } } return webrtc.NewAPI(webrtc.WithMediaEngine(mediaEngine), webrtc.WithSettingEngine(settings)), nil } -type publicIPLookup func(context.Context, string) ([]net.IPAddr, error) - -func setWebRTCPublicHost(settings *webrtc.SettingEngine, value string, lookup publicIPLookup) error { - publicHost := strings.TrimSpace(value) - if publicHost == "" { - return nil +// callAPI returns the API for one call. With webrtc_public_host set it is built +// from a fresh lookup, so a dynamic-DNS name follows the WAN address after a +// redial instead of keeping the address resolved at startup (hideck#93). +func (m *MediaManager) callAPI(ctx context.Context) (*webrtc.API, error) { + if m.publicHost == nil { + return m.api, nil } - publicIPs, err := resolveWebRTCPublicIPs(publicHost, lookup) + publicIPs, err := m.publicHost.resolve(ctx, webRTCPublicHostLookupTimeout) if err != nil { - return err + return nil, err } - if err := settings.SetICEAddressRewriteRules(webrtc.ICEAddressRewriteRule{ - External: publicIPs, - AsCandidateType: webrtc.ICECandidateTypeHost, - Mode: webrtc.ICEAddressRewriteAppend, - }); err != nil { - return fmt.Errorf("phone: configure WebRTC public host: %w", err) - } - return nil + return newWebRTCAPI(m.mux, publicIPs) } -func resolveWebRTCPublicIPs(host string, lookup publicIPLookup) ([]string, error) { +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(context.Background(), host) + addresses, err := lookup(ctx, host) if err != nil { return nil, fmt.Errorf("phone: resolve WebRTC public host %q: %w", host, err) } @@ -157,9 +236,13 @@ func (m *MediaManager) Create(ctx context.Context, owner, offer, accessHost stri if err != nil { return MediaAnswer{}, err } + api, err := m.callAPI(ctx) + if err != nil { + return MediaAnswer{}, err + } session, answer, err := newMediaSession(ctx, mediaSessionOptions{ ID: mediaID, Lease: lease, Owner: owner, Offer: offer, AccessHost: accessHost, - API: m.api, ICEServers: m.iceServers, RealtimeCodecs: m.realtimeCodecs, + API: api, ICEServers: m.iceServers, RealtimeCodecs: m.realtimeCodecs, NewRealtimeCodec: m.newRealtimeCodec, OnState: m.onState, }) if err != nil { diff --git a/internal/phone/media_public_host_test.go b/internal/phone/media_public_host_test.go index 36a426af..bd35011e 100644 --- a/internal/phone/media_public_host_test.go +++ b/internal/phone/media_public_host_test.go @@ -5,19 +5,105 @@ import ( "errors" "net" "reflect" + "strings" + "sync" "testing" - - "github.com/pion/webrtc/v4" + "time" ) -func TestSetWebRTCPublicHostReportsResolutionFailure(t *testing.T) { - settings := &webrtc.SettingEngine{} +func TestNewMediaManagerReportsPublicHostResolutionFailure(t *testing.T) { wantErr := errors.New("lookup failed") - err := setWebRTCPublicHost(settings, "hideck.example.com", func(context.Context, string) ([]net.IPAddr, error) { - return nil, wantErr + _, err := NewMediaManager(MediaOptions{ + UDPAddress: ":0", PublicHost: "hideck.example.com", + lookupPublicIP: func(context.Context, string) ([]net.IPAddr, error) { return nil, wantErr }, }) if !errors.Is(err, wantErr) { - t.Fatalf("setWebRTCPublicHost() error = %v", err) + 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", + lookupPublicIP: 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") } } @@ -35,7 +121,7 @@ func TestResolveWebRTCPublicIPs(t *testing.T) { }, nil } - got, err := resolveWebRTCPublicIPs("hideck.example.com", lookup) + got, err := resolveWebRTCPublicIPs(context.Background(), "hideck.example.com", lookup) if err != nil { t.Fatal(err) } @@ -44,7 +130,7 @@ func TestResolveWebRTCPublicIPs(t *testing.T) { t.Fatalf("resolveWebRTCPublicIPs() = %v, calls = %d", got, lookupCalls) } - got, err = resolveWebRTCPublicIPs("203.0.113.20", lookup) + got, err = resolveWebRTCPublicIPs(context.Background(), "203.0.113.20", lookup) if err != nil { t.Fatal(err) }