Skip to content
This repository was archived by the owner on Aug 30, 2024. It is now read-only.

Commit 00318a0

Browse files
committed
Fix race conditions
1 parent 56ddb93 commit 00318a0

File tree

2 files changed

+26
-12
lines changed

2 files changed

+26
-12
lines changed

wsnet/rtc.go

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"io"
1010
"net"
1111
"strings"
12+
"sync"
1213
"time"
1314

1415
"github.com/pion/dtls/v2"
@@ -168,27 +169,34 @@ func newPeerConnection(servers []webrtc.ICEServer) (*webrtc.PeerConnection, erro
168169

169170
// Proxies ICE candidates using the protocol to a writer.
170171
func proxyICECandidates(conn *webrtc.PeerConnection, w io.Writer) func() {
171-
queue := make([]*webrtc.ICECandidate, 0)
172-
flushed := false
173-
write := func(i *webrtc.ICECandidate) {
174-
b, _ := json.Marshal(&protoMessage{
175-
Candidate: i.ToJSON().Candidate,
176-
})
177-
_, _ = w.Write(b)
178-
}
172+
var (
173+
mut sync.Mutex
174+
queue = []*webrtc.ICECandidate{}
175+
flushed = false
176+
write = func(i *webrtc.ICECandidate) {
177+
b, _ := json.Marshal(&protoMessage{
178+
Candidate: i.ToJSON().Candidate,
179+
})
180+
_, _ = w.Write(b)
181+
}
182+
)
179183

180184
conn.OnICECandidate(func(i *webrtc.ICECandidate) {
181185
if i == nil {
182186
return
183187
}
184188
if !flushed {
189+
mut.Lock()
190+
defer mut.Unlock()
185191
queue = append(queue, i)
186192
return
187193
}
188194

189195
write(i)
190196
})
191197
return func() {
198+
mut.Lock()
199+
defer mut.Unlock()
192200
for _, i := range queue {
193201
write(i)
194202
}

wsnet/wsnet_test.go

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
// +build !race
2-
31
package wsnet
42

53
import (
@@ -15,6 +13,7 @@ import (
1513
"math/big"
1614
"net"
1715
"net/http"
16+
"sync"
1817
"testing"
1918
"time"
2019

@@ -35,14 +34,19 @@ func createDumbBroker(t *testing.T) (connectAddr string, listenAddr string) {
3534
t.Cleanup(func() {
3635
listener.Close()
3736
})
38-
mux := http.NewServeMux()
39-
var sess *yamux.Session
37+
var (
38+
mux = http.NewServeMux()
39+
sess *yamux.Session
40+
mut sync.Mutex
41+
)
4042
mux.HandleFunc("/listen", func(w http.ResponseWriter, r *http.Request) {
4143
c, err := websocket.Accept(w, r, nil)
4244
if err != nil {
4345
t.Error(err)
4446
}
4547
nc := websocket.NetConn(context.Background(), c, websocket.MessageBinary)
48+
mut.Lock()
49+
defer mut.Unlock()
4650
sess, err = yamux.Client(nc, nil)
4751
if err != nil {
4852
t.Error(err)
@@ -54,6 +58,8 @@ func createDumbBroker(t *testing.T) (connectAddr string, listenAddr string) {
5458
t.Error(err)
5559
}
5660
nc := websocket.NetConn(context.Background(), c, websocket.MessageBinary)
61+
mut.Lock()
62+
defer mut.Unlock()
5763
oc, err := sess.Open()
5864
if err != nil {
5965
t.Error(err)

0 commit comments

Comments
 (0)