forked from knadh/niltalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconn.go
416 lines (333 loc) · 8.31 KB
/
conn.go
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Niltalk, April 2015
// https://niltalk.com
// https://github.com/goniltalk/niltalk
// License AGPL3
package main
import (
"encoding/json"
"errors"
"fmt"
"time"
"github.com/gorilla/websocket"
)
// Known message/action codes in and out of Websockets.
const (
TypeMessage = 1
TypePeers = 2
TypeNotice = 3
TypeHandle = 4
)
// A room.
type Room struct {
Id string
password []byte
timestamp time.Time
// List of connected peers.
peers map[*Peer]bool
// Broadcast channel for messages.
broadcastQueue chan []byte
// Peer registration requests.
register chan *Peer
// Peer removal requests.
unregister chan *Peer
// Stop signal.
stop chan int
// Counter for auto generated peer handles.
counter int
}
// An individual peer / connection.
type Peer struct {
// The Websocket.
ws *websocket.Conn
// Channel for outbound messages.
sendQueue chan []byte
// Peer's unique id.
id string
// Peer's chat handle.
handle string
// Peer's room id.
room_id string
// Rate limiting.
numMessages int
lastMessage time.Time
suspended bool
}
// Pool of active rooms.
var rooms = make(map[string]*Room)
// Create a new room.
func newRoom(id string, password []byte) error {
// Register the room.
db := dbPool.Get()
defer db.Close()
if err := db.PutMap(config.CachePrefixRoom+id, "password", password, "timestamp", time.Now()); err != nil {
return errors.New("Unable to create room")
}
db.Expire(config.CachePrefixRoom+id, config.RoomAge)
return nil
}
// Fetch a room record from the DB and initialize it in memory.
func initializeRoom(id string) (*Room, error) {
data := struct {
Password []byte `redis:"password"`
}{}
db := dbPool.Get()
defer db.Close()
exists, err := db.GetMap(config.CachePrefixRoom+id, &data)
if err != nil {
return nil, errors.New("Error loading room")
} else if !exists {
return nil, nil
}
rooms[id] = &Room{
Id: id,
password: data.Password,
timestamp: time.Now(),
broadcastQueue: make(chan []byte),
register: make(chan *Peer),
unregister: make(chan *Peer),
stop: make(chan int),
peers: make(map[*Peer]bool),
counter: 1,
}
// Room is loaded, start it.
go rooms[id].run()
return rooms[id], nil
}
// Get an initialized room by id.
func getRoom(id string) *Room {
room, exists := rooms[id]
if exists {
return room
} else {
return nil
}
}
// The runner loop for a room. Handles registration, deregistration, and broadcast signals.
func (room *Room) run() {
Logger.Println("Starting room", room.Id)
defer func() {
Logger.Println("Stopped room", room.Id)
room.dispose(0)
}()
loop:
for {
select {
// A new peer has connected.
case peer, ok := <-room.register:
if ok {
room.peers[peer] = true
// Notify all peers of the new addition.
go room.broadcast(preparePeersList(room, peer, true))
Logger.Println(fmt.Sprintf("%s@%s connected", peer.handle, peer.id))
} else {
break loop
}
// A peer has disconnected.
case peer, ok := <-room.unregister:
if ok {
if _, ok := room.peers[peer]; ok {
delete(room.peers, peer)
close(peer.sendQueue)
// Notify all peers of the new one.
go room.broadcast(preparePeersList(room, peer, false))
Logger.Println(fmt.Sprintf("%s@%s disconnected", peer.handle, peer.id))
}
}
// Fanout broadcast to all peers.
case m, ok := <-room.broadcastQueue:
if ok {
for peer := range room.peers {
select {
// Write outgoing message to the peer's send channel.
case peer.sendQueue <- m:
default:
close(peer.sendQueue)
delete(room.peers, peer)
}
}
} else {
break loop
}
// Stop signal.
case _ = <-room.stop:
break loop
// Inactivity timeout.
case <-time.After(time.Second * time.Duration(config.RoomTimeout)):
break loop
}
}
}
// Add a message to the send queue of all peers.
func (room *Room) broadcast(data []byte) {
if len(room.peers) > 0 {
room.broadcastQueue <- data
// Extend the room's age.
if time.Since(room.timestamp) > time.Duration(30)*time.Second {
room.timestamp = time.Now()
room.setExpiry(config.RoomTimeout)
}
}
}
// All peers connected to a room.
func (room *Room) peerList() map[string]string {
list := make(map[string]string)
for peer := range room.peers {
list[peer.id] = peer.handle
}
return list
}
// Count of peers in the room.
func (room *Room) peerCount() int {
return len(room.peers)
}
// Sends dispose signals to all peers and deletes the room record.
func (room *Room) dispose(status int) {
if status == 0 {
status = websocket.CloseNormalClosure
}
// Close all Websocket connections.
for peer := range room.peers {
peer.ws.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(status, "Room disposed"),
time.Time{})
delete(room.peers, peer)
}
// Close all the room channels.
close(room.broadcastQueue)
close(room.register)
close(room.unregister)
delete(rooms, room.Id)
// Delete the room record from the DB.
db := dbPool.Get()
defer db.Close()
db.Delete(config.CachePrefixRoom + room.Id)
}
// Set the room's expiry.
func (room *Room) setExpiry(seconds int) {
db := dbPool.Get()
defer db.Close()
db.Expire(config.CachePrefixRoom+room.Id, seconds)
db.Expire(config.CachePrefixSessions+room.Id, seconds)
}
// Listen to all incoming Websocket messages.
func (peer *Peer) listen() {
defer func() {
if _, exists := rooms[peer.room_id]; exists {
select {
case rooms[peer.room_id].unregister <- peer:
default:
}
}
peer.ws.Close()
}()
// Maximum acceptable message length.
peer.ws.SetReadLimit(int64(config.MaxMessageLength))
// If there is no ping from the peer, timeout.
pongTimeout := time.Duration(config.PongTimeout) * time.Second
peer.ws.SetReadDeadline(time.Now().Add(pongTimeout))
peer.ws.SetPongHandler(func(string) error {
peer.ws.SetReadDeadline(time.Now().Add(pongTimeout))
return nil
})
// This loop runs until the Websocket dies listening for incoming messages.
for {
_, message, err := peer.ws.ReadMessage()
if err != nil {
break
}
peer.processMessage(message)
}
}
// Write a message to the peer's Websocket.
func (peer *Peer) write(mt int, payload []byte) error {
writeTimeout := time.Duration(config.WriteTimeout) * time.Second
peer.ws.SetWriteDeadline(time.Now().Add(writeTimeout))
return peer.ws.WriteMessage(mt, payload)
}
// Process incoming messages from the room and write them to Websockets.
func (peer *Peer) talk() {
ticker := time.NewTicker(time.Duration(config.PingTimeout) * time.Second)
defer func() {
ticker.Stop()
peer.ws.Close()
}()
for {
select {
// Wait for outgoing message to appear in the channel.
case message, ok := <-peer.sendQueue:
if !ok {
peer.write(websocket.CloseMessage, []byte{})
return
}
// Send the message.
if err := peer.write(websocket.TextMessage, message); err != nil {
return
}
case <-ticker.C:
if err := peer.write(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
// Disconnect a peer.
func (peer *Peer) close() {
rooms[peer.room_id].unregister <- peer
}
// Process incoming messages.
func (peer *Peer) processMessage(message []byte) {
data := struct {
Action int `json:"a"`
Message string `json:"m"`
}{}
err := json.Unmarshal(message, &data)
// Invalid JSON.
if err != nil || data.Action == 0 {
return
}
// What action?
switch int(data.Action) {
// Incoming chat message.
case TypeMessage:
if len(data.Message) == 0 {
return
}
now := time.Now()
// Rate limiting.
if (peer.numMessages+1)%config.RateLimitMessages == 0 &&
time.Since(peer.lastMessage).Seconds() < config.RateLimitInterval {
peer.close()
return
}
// Rate limit counters.
peer.lastMessage = now
peer.numMessages += 1
room, exists := rooms[peer.room_id]
// Broadcast to the room.
if exists {
content := struct {
Action int `json:"a"`
Peer string `json:"p"`
Handle string `json:"h"`
Message interface{} `json:"m"`
Time int64 `json:"t"`
}{
TypeMessage,
peer.id,
peer.handle,
data.Message,
now.UTC().Unix(),
}
room.broadcast(prepareMessage(content))
}
// Request for peers list
case TypePeers:
room, exists := rooms[peer.room_id]
if exists {
peer.sendQueue <- preparePeersList(room, nil, false)
}
default:
return
}
}