Skip to content

Commit 4308f16

Browse files
authored
fix: Lock when obtaining a peer connection answer<->offer (#24)
* fix: Lock when obtaining a peer connection answer<->offer This fixes a race in the peerbroker package where ICE candidates could be added before the connection was negotiated. This would result in the connection failing. * Remove unnecessary log
1 parent 550c4fb commit 4308f16

File tree

3 files changed

+13
-1
lines changed

3 files changed

+13
-1
lines changed

peer/conn.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ type Conn struct {
116116
localCandidateChannel chan webrtc.ICECandidateInit
117117
localSessionDescriptionChannel chan webrtc.SessionDescription
118118
remoteSessionDescriptionChannel chan webrtc.SessionDescription
119+
remoteSessionDescriptionMutex sync.Mutex
119120

120121
pingChannelID uint16
121122
pingEchoChannelID uint16
@@ -228,6 +229,11 @@ func (c *Conn) negotiate() {
228229
c.opts.Logger.Debug(context.Background(), "negotiating")
229230
flushCandidates := c.proxyICECandidates()
230231

232+
// Locks while the negotiation for a remote session
233+
// description is taking place.
234+
c.remoteSessionDescriptionMutex.Lock()
235+
defer c.remoteSessionDescriptionMutex.Unlock()
236+
231237
if c.offerrer {
232238
offer, err := c.rtc.CreateOffer(&webrtc.OfferOptions{})
233239
if err != nil {
@@ -328,6 +334,9 @@ func (c *Conn) LocalCandidate() <-chan webrtc.ICECandidateInit {
328334

329335
// AddRemoteCandidate adds a remote candidate to the RTC connection.
330336
func (c *Conn) AddRemoteCandidate(i webrtc.ICECandidateInit) error {
337+
// Prevents candidates from being added before an offer<->answer has occurred.
338+
c.remoteSessionDescriptionMutex.Lock()
339+
defer c.remoteSessionDescriptionMutex.Unlock()
331340
return c.rtc.AddICECandidate(i)
332341
}
333342

peerbroker/dial.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ func Dial(stream proto.DRPCPeerBroker_NegotiateConnectionClient, iceServers []we
8484
for {
8585
serverToClientMessage, err := stream.Recv()
8686
if err != nil {
87-
_ = peerConn.CloseWithError(err)
87+
_ = peerConn.CloseWithError(xerrors.Errorf("recv: %w", err))
8888
return
8989
}
9090

peerbroker/dial_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ func TestMain(m *testing.M) {
1818
}
1919

2020
func TestDial(t *testing.T) {
21+
t.Parallel()
22+
2123
t.Run("Connect", func(t *testing.T) {
24+
t.Parallel()
2225
ctx := context.Background()
2326
client, server := provisionersdk.TransportPipe()
2427
defer client.Close()

0 commit comments

Comments
 (0)