1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312 | package main
import (
"encoding/json"
"log"
"net"
"net/http"
"regexp"
"sync"
"time"
"github.com/gorilla/websocket"
)
const (
maxFrameBytes = 64 << 10 // SDP is 2-8 KiB; encrypted blobs stay well under this
writeWait = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = 25 * time.Second
sendQueueDepth = 64
)
var (
roomRe = regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`) // base64url of 32 bytes
peerRe = regexp.MustCompile(`^[a-f0-9]{32}$`) // hex of 16 bytes
)
type Hub struct {
cfg *Config
upgrader websocket.Upgrader
mu sync.Mutex
rooms map[string]map[string]*client
perIP map[string]int
}
type client struct {
hub *Hub
ws *websocket.Conn
send chan []byte
ip string
bucket *bucket
mu sync.Mutex
room string
peer string
}
func newHub(cfg *Config) *Hub {
h := &Hub{
cfg: cfg,
rooms: map[string]map[string]*client{},
perIP: map[string]int{},
}
h.upgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 4096,
CheckOrigin: func(r *http.Request) bool {
return cfg.originAllowed(r.Header.Get("Origin"))
},
}
return h
}
func (h *Hub) stats() (rooms, peers int) {
h.mu.Lock()
defer h.mu.Unlock()
for _, m := range h.rooms {
peers += len(m)
}
return len(h.rooms), peers
}
func (h *Hub) handleWS(w http.ResponseWriter, r *http.Request) {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
h.mu.Lock()
if h.perIP[ip] >= h.cfg.MaxConnsPerIP {
h.mu.Unlock()
http.Error(w, "too many connections", http.StatusTooManyRequests)
return
}
h.perIP[ip]++
h.mu.Unlock()
ws, err := h.upgrader.Upgrade(w, r, nil)
if err != nil {
h.dropIP(ip)
return
}
c := &client{
hub: h,
ws: ws,
send: make(chan []byte, sendQueueDepth),
ip: ip,
bucket: newBucket(30, 60),
}
go c.writePump()
c.readPump()
}
func (h *Hub) dropIP(ip string) {
h.mu.Lock()
if h.perIP[ip]--; h.perIP[ip] <= 0 {
delete(h.perIP, ip)
}
h.mu.Unlock()
}
// wire types
type inMsg struct {
T string `json:"t"`
Room string `json:"room,omitempty"`
Peer string `json:"peer,omitempty"`
To string `json:"to,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
}
type outMsg struct {
T string `json:"t"`
Peer string `json:"peer,omitempty"`
Peers []string `json:"peers,omitzero"`
From string `json:"from,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
Code string `json:"code,omitempty"`
}
func (c *client) sendJSON(m outMsg) {
b, _ := json.Marshal(m)
select {
case c.send <- b:
default:
// Slow consumer: drop the connection rather than block the room.
c.ws.Close()
}
}
func (c *client) readPump() {
defer c.teardown()
c.ws.SetReadLimit(maxFrameBytes)
c.ws.SetReadDeadline(time.Now().Add(pongWait))
c.ws.SetPongHandler(func(string) error {
c.ws.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
for {
_, data, err := c.ws.ReadMessage()
if err != nil {
return
}
if !c.bucket.take() {
c.sendJSON(outMsg{T: "error", Code: "rate-limited"})
continue
}
var m inMsg
if err := json.Unmarshal(data, &m); err != nil {
c.sendJSON(outMsg{T: "error", Code: "bad-message"})
continue
}
switch m.T {
case "join":
c.handleJoin(m)
case "signal":
c.handleSignal(m)
case "leave":
return // teardown broadcasts peer-left
case "ping":
c.sendJSON(outMsg{T: "pong"})
default:
c.sendJSON(outMsg{T: "error", Code: "bad-message"})
}
}
}
func (c *client) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.ws.Close()
}()
for {
select {
case b, ok := <-c.send:
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
c.ws.WriteMessage(websocket.CloseMessage, nil)
return
}
if err := c.ws.WriteMessage(websocket.TextMessage, b); err != nil {
return
}
case <-ticker.C:
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.ws.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
func (c *client) handleJoin(m inMsg) {
if !roomRe.MatchString(m.Room) || !peerRe.MatchString(m.Peer) {
c.sendJSON(outMsg{T: "error", Code: "bad-message"})
return
}
c.mu.Lock()
alreadyJoined := c.room != ""
c.mu.Unlock()
if alreadyJoined {
c.sendJSON(outMsg{T: "error", Code: "bad-message"})
return
}
h := c.hub
h.mu.Lock()
room := h.rooms[m.Room]
if room == nil {
if len(h.rooms) >= h.cfg.MaxRooms {
h.mu.Unlock()
c.sendJSON(outMsg{T: "error", Code: "too-many-rooms"})
return
}
room = map[string]*client{}
h.rooms[m.Room] = room
}
// Same peerId rejoining (e.g. zombie socket after mobile sleep): replace.
if old := room[m.Peer]; old != nil {
delete(room, m.Peer)
defer old.ws.Close()
} else if len(room) >= h.cfg.MaxRoomPeers {
h.mu.Unlock()
c.sendJSON(outMsg{T: "error", Code: "room-full"})
return
}
peers := make([]string, 0, len(room))
others := make([]*client, 0, len(room))
for id, cl := range room {
peers = append(peers, id)
others = append(others, cl)
}
room[m.Peer] = c
h.mu.Unlock()
c.mu.Lock()
c.room, c.peer = m.Room, m.Peer
c.mu.Unlock()
c.sendJSON(outMsg{T: "peers", Peers: peers})
for _, o := range others {
o.sendJSON(outMsg{T: "peer-joined", Peer: m.Peer})
}
log.Printf("join: room peers=%d (total rooms=%d)", len(peers)+1, roomCount(h))
}
func (c *client) handleSignal(m inMsg) {
c.mu.Lock()
room, me := c.room, c.peer
c.mu.Unlock()
if room == "" {
c.sendJSON(outMsg{T: "error", Code: "not-joined"})
return
}
if !peerRe.MatchString(m.To) || len(m.Payload) == 0 {
c.sendJSON(outMsg{T: "error", Code: "bad-message"})
return
}
h := c.hub
h.mu.Lock()
target := h.rooms[room][m.To]
h.mu.Unlock()
if target == nil {
return // peer left; silently drop
}
// `from` is stamped from the joined connection — clients cannot spoof it.
target.sendJSON(outMsg{T: "signal", From: me, Payload: m.Payload})
}
func (c *client) teardown() {
c.ws.Close()
c.mu.Lock()
room, peer := c.room, c.peer
c.room, c.peer = "", ""
c.mu.Unlock()
h := c.hub
h.dropIP(c.ip)
if room == "" {
return
}
h.mu.Lock()
var others []*client
if m := h.rooms[room]; m != nil && m[peer] == c {
delete(m, peer)
for _, cl := range m {
others = append(others, cl)
}
if len(m) == 0 {
delete(h.rooms, room)
}
}
h.mu.Unlock()
for _, o := range others {
o.sendJSON(outMsg{T: "peer-left", Peer: peer})
}
}
func roomCount(h *Hub) int {
h.mu.Lock()
defer h.mu.Unlock()
return len(h.rooms)
}
|