diff --git a/pkg/rtc/participant.go b/pkg/rtc/participant.go index a884a4bd2..4f169654c 100644 --- a/pkg/rtc/participant.go +++ b/pkg/rtc/participant.go @@ -1733,20 +1733,17 @@ func (p *ParticipantImpl) clearMigrationTimer() { } func (p *ParticipantImpl) setupMigrationTimerLocked() { - if p.params.UseSinglePeerConnection { - return - } - // - // On subscriber peer connection, remote side will try ICE on both - // pre- and post-migration ICE candidates as the migrating out - // peer connection leaves itself open to enable transition of - // media with as less disruption as possible. + // The remote side will try ICE on both pre- and post-migration ICE + // candidates as the migrating out peer connections leave themselves + // open to enable transition of media with as less disruption as possible. // // But, sometimes clients could delay the migration because of - // pinging the incorrect ICE candidates. Give the remote some time - // to try and succeed. If not, close the subscriber peer connection - // and help the remote side to narrow down its ICE candidate pool. + // pinging the incorrect ICE candidates, or keep using a pair to this + // node as it keeps answering. Give the remote some time to try and + // succeed. If not, stop ICE on the publisher peer connection and close + // the subscriber peer connection to help the remote side to narrow + // down its ICE candidate pool. // p.migrationTimer = time.AfterFunc(max(p.params.MigrationWaitDuration, migrationWaitDuration), func() { p.clearMigrationTimer() @@ -1754,6 +1751,14 @@ func (p *ParticipantImpl) setupMigrationTimerLocked() { if p.IsClosed() || p.IsDisconnected() { return } + + p.pubLogger.Debugw("shutting down publisher ICE to aid migration") + p.TransportManager.PublisherShutdownICE() + + if p.params.UseSinglePeerConnection { + return + } + p.subLogger.Debugw("closing subscriber peer connection to aid migration") // diff --git a/pkg/rtc/participant_internal_test.go b/pkg/rtc/participant_internal_test.go index bb6827e6e..b651affe8 100644 --- a/pkg/rtc/participant_internal_test.go +++ b/pkg/rtc/participant_internal_test.go @@ -2413,3 +2413,17 @@ func disconnectExpiry(p *ParticipantImpl) func() { _ = p.Close(true, types.ParticipantCloseReasonPeerConnectionDisconnected, false) } } + +func TestMigrationTimerShutsDownPublisherICE(t *testing.T) { + p := newParticipantForTestWithOpts("test", &participantOpts{publisher: true}) + defer p.Close(false, types.ParticipantCloseReasonClientRequestLeave, false) + + p.NotifyMigration() + + publisher, subscriber := p.TransportManager.publisher, p.TransportManager.subscriber + require.False(t, publisher.iceShutdown.Load()) + require.Eventually(t, func() bool { + return publisher.iceShutdown.Load() && subscriber.isClosed.Load() + }, migrationWaitDuration+2*time.Second, 50*time.Millisecond) + require.False(t, publisher.isClosed.Load()) +} diff --git a/pkg/rtc/transport.go b/pkg/rtc/transport.go index e0aeacc0c..ffbd53be5 100644 --- a/pkg/rtc/transport.go +++ b/pkg/rtc/transport.go @@ -100,6 +100,7 @@ var ( ErrNoICETransport = errors.New("no ICE transport") ErrIceRestartWithoutLocalSDP = errors.New("ICE restart without local SDP settled") ErrIceRestartOnClosedPeerConnection = errors.New("ICE restart on closed peer connection") + ErrIceRestartAfterShutdown = errors.New("ICE restart after ICE shutdown") ErrNoTransceiver = errors.New("no transceiver") ErrNoSender = errors.New("no sender") ErrMidNotFound = errors.New("mid not found") @@ -123,6 +124,7 @@ const ( signalSendOffer signalRemoteDescriptionReceived signalICERestart + signalShutdownICE ) func (s signal) String() string { @@ -139,6 +141,8 @@ func (s signal) String() string { return "REMOTE_DESCRIPTION_RECEIVED" case signalICERestart: return "ICE_RESTART" + case signalShutdownICE: + return "SHUTDOWN_ICE" default: return fmt.Sprintf("%d", int(s)) } @@ -231,6 +235,7 @@ type PCTransport struct { tcpICETimer *time.Timer connectAfterICETimer *time.Timer // timer to wait for pc to connect after ice connected resetShortConnOnICERestart atomic.Bool + iceShutdown atomic.Bool signalingRTT atomic.Uint32 // milliseconds hasFullyEstablishedRecorded bool @@ -874,6 +879,10 @@ func (t *PCTransport) onICECandidateTrickle(c *webrtc.ICECandidate) { } func (t *PCTransport) handleConnectionFailed(forceShortConn bool) { + if t.iceShutdown.Load() { + return + } + isShort := forceShortConn if !isShort { var duration time.Duration @@ -2078,6 +2087,17 @@ func (t *PCTransport) ICERestart() error { return nil } +func (t *PCTransport) ShutdownICE() { + t.iceShutdown.Store(true) + t.postEvent(event{ + signal: signalShutdownICE, + }) +} + +func (t *PCTransport) IsICEShutdown() bool { + return t.iceShutdown.Load() +} + func (t *PCTransport) ResetShortConnOnICERestart() { t.resetShortConnOnICERestart.Store(true) } @@ -2369,6 +2389,10 @@ func (t *PCTransport) parseTrackMid(sd webrtc.SessionDescription, senders map[st func (t *PCTransport) postEvent(e event) { e.PCTransport = t t.eventsQueue.Enqueue(func(e event) { + if e.iceShutdown.Load() && e.signal != signalShutdownICE { + return + } + var err error switch e.signal { case signalICEGatheringComplete: @@ -2383,6 +2407,8 @@ func (t *PCTransport) postEvent(e event) { err = e.handleRemoteDescriptionReceived(e) case signalICERestart: err = e.handleICERestart(e) + case signalShutdownICE: + e.handleShutdownICE() } if err != nil { if !e.isClosed.Load() { @@ -3100,6 +3126,14 @@ func (t *PCTransport) doICERestart() error { } } +func (t *PCTransport) handleShutdownICE() { + if _, err := t.pc.CreateOffer(&webrtc.OfferOptions{ICERestart: true}); err != nil { + t.params.Logger.Warnw("failed to shut down ICE", err) + return + } + t.params.Logger.Debugw("ICE shut down") +} + func (t *PCTransport) handleICERestart(_ event) error { return t.doICERestart() } diff --git a/pkg/rtc/transport_test.go b/pkg/rtc/transport_test.go index c4bbefea8..7196e81f2 100644 --- a/pkg/rtc/transport_test.go +++ b/pkg/rtc/transport_test.go @@ -24,6 +24,7 @@ import ( "github.com/pion/dtls/v4/pkg/protocol/handshake" "github.com/pion/sdp/v3" + "github.com/pion/stun/v4" "github.com/pion/webrtc/v4" "github.com/stretchr/testify/require" "go.uber.org/atomic" @@ -1461,3 +1462,89 @@ func TestICELitePlacement(t *testing.T) { }) } } + +func TestShutdownICE(t *testing.T) { + params := TransportParams{ + Config: &WebRTCConfig{}, + IsOfferer: true, + } + + handlerA := &transportfakes.FakeHandler{} + paramsA := params + paramsA.Handler = handlerA + transportA, err := NewPCTransport(paramsA) + require.NoError(t, err) + defer transportA.Close() + _, err = transportA.pc.CreateDataChannel(ReliableDataChannel, nil) + require.NoError(t, err) + + handlerB := &transportfakes.FakeHandler{} + paramsB := params + paramsB.Handler = handlerB + paramsB.IsOfferer = false + transportB, err := NewPCTransport(paramsB) + require.NoError(t, err) + defer transportB.Close() + + handleICEExchange(t, transportA, transportB, handlerA, handlerB) + connectTransports(t, transportA, transportB, handlerA, handlerB, false, 1, 1) + + pair, err := transportB.iceTransport.GetSelectedCandidatePair() + require.NoError(t, err) + require.NotNil(t, pair) + bAddr := &net.UDPAddr{IP: net.ParseIP(pair.Local.Address), Port: int(pair.Local.Port)} + blocalSDPParsed, err := transportB.pc.LocalDescription().Unmarshal() + require.NoError(t, err) + bUfrag, bPwd, err := lksdp.ExtractICECredential(blocalSDPParsed) + require.NoError(t, err) + alocalSDPParsed, err := transportA.pc.LocalDescription().Unmarshal() + require.NoError(t, err) + aUfrag, _, err := lksdp.ExtractICECredential(alocalSDPParsed) + require.NoError(t, err) + + // a check from A's ufrag at a new address, as a remote would send on a new pair to this node + conn, err := net.ListenUDP("udp", nil) + require.NoError(t, err) + defer conn.Close() + probe := func() bool { + req, err := stun.Build( + stun.BindingRequest, + stun.TransactionID, + stun.NewUsername(bUfrag+":"+aUfrag), + stun.RawAttribute{Type: stun.AttrPriority, Value: []byte{0x6e, 0x00, 0x00, 0xff}}, + stun.NewShortTermIntegrity(bPwd), + stun.Fingerprint, + ) + require.NoError(t, err) + if _, err := conn.WriteToUDP(req.Raw, bAddr); err != nil { + return false + } + + buf := make([]byte, 1500) + _ = conn.SetReadDeadline(time.Now().Add(300 * time.Millisecond)) + for { + n, _, err := conn.ReadFromUDP(buf) + if err != nil { + return false + } + res := &stun.Message{Raw: append([]byte{}, buf[:n]...)} + if res.Decode() == nil && res.Type == stun.BindingSuccess && res.TransactionID == req.TransactionID { + return true + } + } + } + require.Eventually(t, probe, 5*time.Second, 10*time.Millisecond, "check not answered before shutdown") + + candidateCount := handlerB.OnICECandidateCallCount() + answerCount := handlerB.OnAnswerCallCount() + + transportB.ShutdownICE() + require.Eventually(t, func() bool { return !probe() }, 5*time.Second, 10*time.Millisecond, "check still answered after shutdown") + require.Never(t, probe, 2*time.Second, 100*time.Millisecond, "check answered after shutdown") + + // the restart's offer and candidates are dropped, and the stalled ICE is not reported + require.Equal(t, candidateCount, handlerB.OnICECandidateCallCount()) + require.Equal(t, answerCount, handlerB.OnAnswerCallCount()) + require.Zero(t, handlerB.OnOfferCallCount()) + require.Zero(t, handlerB.OnFailedCallCount()) +} diff --git a/pkg/rtc/transportmanager.go b/pkg/rtc/transportmanager.go index c5b6b73a0..c8a672a0d 100644 --- a/pkg/rtc/transportmanager.go +++ b/pkg/rtc/transportmanager.go @@ -238,6 +238,10 @@ func (t *TransportManager) SubscriberClose() { t.subscriber.Close() } +func (t *TransportManager) PublisherShutdownICE() { + t.publisher.ShutdownICE() +} + func (t *TransportManager) HasPublisherICEEverConnected() bool { return t.publisher.ICEHasEverConnected() } @@ -697,6 +701,11 @@ func (t *TransportManager) HandleClientReconnect(reason livekit.ReconnectReason) func (t *TransportManager) ICERestart(iceConfig *livekit.ICEConfig) error { t.SetICEConfig(iceConfig) + // A resume back onto this node after ICE shutdown can't recover, the client needs a full reconnect. + if t.publisher.IsICEShutdown() { + return ErrIceRestartAfterShutdown + } + if t.subscriber != nil { return t.subscriber.ICERestart() } diff --git a/pkg/rtc/transportmanager_test.go b/pkg/rtc/transportmanager_test.go index d5623b07e..6b4de00bd 100644 --- a/pkg/rtc/transportmanager_test.go +++ b/pkg/rtc/transportmanager_test.go @@ -193,3 +193,14 @@ func TestMigratedReliableDataChannelIsOrdered(t *testing.T) { server.lock.RUnlock() require.True(t, dc.Ordered()) } + +func TestICERestartAfterShutdownICE(t *testing.T) { + p := newParticipantForTestWithOpts("test", nil) + defer p.Close(false, types.ParticipantCloseReasonNone, false) + + tm := p.TransportManager + require.NoError(t, tm.ICERestart(nil)) + + tm.PublisherShutdownICE() + require.ErrorIs(t, tm.ICERestart(nil), ErrIceRestartAfterShutdown) +}