Skip to content

Commit 7321303

Browse files
committed
Move lock to handshake so no race can occur
1 parent fbe847c commit 7321303

File tree

1 file changed

+7
-2
lines changed

1 file changed

+7
-2
lines changed

peer/conn.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -280,8 +280,11 @@ func (c *Conn) negotiate() {
280280
case remoteDescription = <-c.remoteSessionDescriptionChannel:
281281
}
282282

283+
// Must lock new candidates from being sent while the description is being flushed.
284+
c.pendingCandidatesMutex.Lock()
283285
err := c.rtc.SetRemoteDescription(remoteDescription)
284286
if err != nil {
287+
c.pendingCandidatesMutex.Unlock()
285288
_ = c.CloseWithError(xerrors.Errorf("set remote description (closed %v): %w", c.isClosed(), err))
286289
return
287290
}
@@ -291,8 +294,11 @@ func (c *Conn) negotiate() {
291294
// time. If candidates flush before this point, a connection could fail.
292295
c.flushPendingCandidates()
293296
}
297+
c.pendingCandidatesMutex.Unlock()
294298

295299
if !c.offerrer {
300+
c.pendingCandidatesMutex.Lock()
301+
296302
answer, err := c.rtc.CreateAnswer(&webrtc.AnswerOptions{})
297303
if err != nil {
298304
_ = c.CloseWithError(xerrors.Errorf("create answer: %w", err))
@@ -314,13 +320,13 @@ func (c *Conn) negotiate() {
314320

315321
// Wait until the local description is set to flush candidates.
316322
c.flushPendingCandidates()
323+
c.pendingCandidatesMutex.Unlock()
317324
}
318325
}
319326

320327
// flushPendingCandidates writes all local candidates to the candidate send channel.
321328
// The localCandidateChannel is expected to be serviced, otherwise this could block.
322329
func (c *Conn) flushPendingCandidates() {
323-
c.pendingCandidatesMutex.Lock()
324330
for _, localCandidate := range c.pendingCandidates {
325331
c.opts.Logger.Debug(context.Background(), "flushing local candidate")
326332
select {
@@ -331,7 +337,6 @@ func (c *Conn) flushPendingCandidates() {
331337
}
332338
c.pendingCandidates = make([]webrtc.ICECandidateInit, 0)
333339
c.opts.Logger.Debug(context.Background(), "flushed candidates")
334-
c.pendingCandidatesMutex.Unlock()
335340
}
336341

337342
// LocalCandidate returns a channel that emits when a local candidate

0 commit comments

Comments
 (0)