Skip to content

Commit

Permalink
fix: Lock when obtaining a peer connection answer<->offer (#24)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
kylecarbs committed Jan 13, 2022
1 parent 550c4fb commit 4308f16
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
9 changes: 9 additions & 0 deletions peer/conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ type Conn struct {
localCandidateChannel chan webrtc.ICECandidateInit
localSessionDescriptionChannel chan webrtc.SessionDescription
remoteSessionDescriptionChannel chan webrtc.SessionDescription
remoteSessionDescriptionMutex sync.Mutex

pingChannelID uint16
pingEchoChannelID uint16
Expand Down Expand Up @@ -228,6 +229,11 @@ func (c *Conn) negotiate() {
c.opts.Logger.Debug(context.Background(), "negotiating")
flushCandidates := c.proxyICECandidates()

// Locks while the negotiation for a remote session
// description is taking place.
c.remoteSessionDescriptionMutex.Lock()
defer c.remoteSessionDescriptionMutex.Unlock()

if c.offerrer {
offer, err := c.rtc.CreateOffer(&webrtc.OfferOptions{})
if err != nil {
Expand Down Expand Up @@ -328,6 +334,9 @@ func (c *Conn) LocalCandidate() <-chan webrtc.ICECandidateInit {

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

Expand Down
2 changes: 1 addition & 1 deletion peerbroker/dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ func Dial(stream proto.DRPCPeerBroker_NegotiateConnectionClient, iceServers []we
for {
serverToClientMessage, err := stream.Recv()
if err != nil {
_ = peerConn.CloseWithError(err)
_ = peerConn.CloseWithError(xerrors.Errorf("recv: %w", err))
return
}

Expand Down
3 changes: 3 additions & 0 deletions peerbroker/dial_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ func TestMain(m *testing.M) {
}

func TestDial(t *testing.T) {
t.Parallel()

t.Run("Connect", func(t *testing.T) {
t.Parallel()
ctx := context.Background()
client, server := provisionersdk.TransportPipe()
defer client.Close()
Expand Down

0 comments on commit 4308f16

Please sign in to comment.