forked from PretendoNetwork/nex-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
464 lines (362 loc) · 11.7 KB
/
server.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
package nex
import (
"fmt"
"math/rand"
"net"
"runtime"
)
// Server represents a PRUDP server
type Server struct {
socket *net.UDPConn
compressPacket func([]byte) []byte
decompressPacket func([]byte) []byte
clients map[string]*Client
genericEventHandles map[string][]func(PacketInterface)
prudpV0EventHandles map[string][]func(*PacketV0)
prudpV1EventHandles map[string][]func(*PacketV1)
accessKey string
prudpVersion int
nexVersion int
fragmentSize int16
resendTimeout float32
usePacketCompression bool
pingTimeout int
signatureVersion int
flagsVersion int
checksumVersion int
kerberosKeySize int
kerberosKeyDerivation int
serverVersion int
}
// Listen starts a NEX server on a given address
func (server *Server) Listen(address string) {
protocol := "udp"
udpAddress, err := net.ResolveUDPAddr(protocol, address)
if err != nil {
panic(err)
}
socket, err := net.ListenUDP(protocol, udpAddress)
if err != nil {
panic(err)
}
server.SetSocket(socket)
quit := make(chan struct{})
for i := 0; i < runtime.NumCPU(); i++ {
go server.listenDatagram(quit)
}
fmt.Println("NEX server listening on address", udpAddress)
server.Emit("Listening", nil)
<-quit
}
func (server *Server) listenDatagram(quit chan struct{}) {
err := error(nil)
for err == nil {
err = server.handleSocketMessage()
}
quit <- struct{}{}
panic(err)
}
func (server *Server) handleSocketMessage() error {
var buffer [64000]byte
socket := server.Socket()
length, addr, err := socket.ReadFromUDP(buffer[0:])
if err != nil {
return err
}
discriminator := addr.String()
if _, ok := server.clients[discriminator]; !ok {
newClient := NewClient(addr, server)
server.clients[discriminator] = newClient
}
client := server.clients[discriminator]
data := buffer[0:length]
var packet PacketInterface
if server.PrudpVersion() == 0 {
packet, err = NewPacketV0(client, data)
} else {
packet, err = NewPacketV1(client, data)
}
if err != nil {
fmt.Println(err)
return nil
}
if packet.HasFlag(FlagAck) || packet.HasFlag(FlagMultiAck) {
return nil
}
if packet.HasFlag(FlagNeedsAck) {
if packet.Type() != ConnectPacket || (packet.Type() == ConnectPacket && len(packet.Payload()) <= 0) {
go server.AcknowledgePacket(packet, nil)
}
}
switch packet.Type() {
case SynPacket:
client.Reset()
server.Emit("Syn", packet)
case ConnectPacket:
packet.Sender().SetClientConnectionSignature(packet.ConnectionSignature())
server.Emit("Connect", packet)
case DataPacket:
server.Emit("Data", packet)
case DisconnectPacket:
server.Kick(client)
server.Emit("Disconnect", packet)
case PingPacket:
server.SendPing(client)
server.Emit("Ping", packet)
}
server.Emit("Packet", packet)
return nil
}
// On sets the data event handler
func (server *Server) On(event string, handler interface{}) {
// Check if the handler type matches one of the allowed types, and store the handler in it's allowed property
// Need to cast the handler to the correct function type before storing
switch handler.(type) {
case func(PacketInterface):
server.genericEventHandles[event] = append(server.genericEventHandles[event], handler.(func(PacketInterface)))
case func(*PacketV0):
server.prudpV0EventHandles[event] = append(server.prudpV0EventHandles[event], handler.(func(*PacketV0)))
case func(*PacketV1):
server.prudpV1EventHandles[event] = append(server.prudpV1EventHandles[event], handler.(func(*PacketV1)))
}
}
// Emit runs the given event handle
func (server *Server) Emit(event string, packet interface{}) {
eventName := server.genericEventHandles[event]
for i := 0; i < len(eventName); i++ {
handler := eventName[i]
packet := packet.(PacketInterface)
go handler(packet)
}
// Check if the packet type matches one of the allowed types and run the given handler
switch packet.(type) {
case *PacketV0:
eventName := server.prudpV0EventHandles[event]
for i := 0; i < len(eventName); i++ {
handler := eventName[i]
go handler(packet.(*PacketV0))
}
case *PacketV1:
eventName := server.prudpV1EventHandles[event]
for i := 0; i < len(eventName); i++ {
handler := eventName[i]
go handler(packet.(*PacketV1))
}
}
}
// ClientConnected checks if a given client is stored on the server
func (server *Server) ClientConnected(client *Client) bool {
discriminator := client.Address().String()
_, connected := server.clients[discriminator]
return connected
}
// Kick removes a client from the server
func (server *Server) Kick(client *Client) {
discriminator := client.Address().String()
if _, ok := server.clients[discriminator]; ok {
delete(server.clients, discriminator)
fmt.Println("Kicked user", discriminator)
}
}
// SendPing sends a ping packet to the given client
func (server *Server) SendPing(client *Client) {
var pingPacket PacketInterface
if server.PrudpVersion() == 0 {
pingPacket, _ = NewPacketV0(client, nil)
} else {
pingPacket, _ = NewPacketV1(client, nil)
}
pingPacket.SetSource(0xA1)
pingPacket.SetDestination(0xAF)
pingPacket.SetType(PingPacket)
pingPacket.AddFlag(FlagNeedsAck)
pingPacket.AddFlag(FlagReliable)
server.Send(pingPacket)
}
// AcknowledgePacket acknowledges that the given packet was recieved
func (server *Server) AcknowledgePacket(packet PacketInterface, payload []byte) {
sender := packet.Sender()
var ackPacket PacketInterface
if server.PrudpVersion() == 0 {
ackPacket, _ = NewPacketV0(sender, nil)
} else {
ackPacket, _ = NewPacketV1(sender, nil)
}
ackPacket.SetSource(packet.Destination())
ackPacket.SetDestination(packet.Source())
ackPacket.SetType(packet.Type())
ackPacket.SetSequenceID(packet.SequenceID())
ackPacket.SetFragmentID(packet.FragmentID())
ackPacket.AddFlag(FlagAck)
if payload != nil {
ackPacket.SetPayload(payload)
}
if server.PrudpVersion() == 1 {
packet := packet.(*PacketV1)
ackPacket := ackPacket.(*PacketV1)
ackPacket.SetVersion(1)
ackPacket.SetSubstreamID(0)
ackPacket.AddFlag(FlagHasSize)
if packet.Type() == SynPacket {
serverConnectionSignature := make([]byte, 16)
rand.Read(serverConnectionSignature)
ackPacket.Sender().SetServerConnectionSignature(serverConnectionSignature)
ackPacket.SetSupportedFunctions(packet.SupportedFunctions())
ackPacket.SetMaximumSubstreamID(0)
ackPacket.SetConnectionSignature(serverConnectionSignature)
}
if packet.Type() == ConnectPacket {
ackPacket.SetConnectionSignature(make([]byte, 16))
ackPacket.SetSupportedFunctions(packet.SupportedFunctions())
ackPacket.SetInitialSequenceID(10000)
ackPacket.SetMaximumSubstreamID(0)
}
if packet.Type() == DataPacket {
// Aggregate acknowledgement
ackPacket.ClearFlag(FlagAck)
ackPacket.AddFlag(FlagMultiAck)
payloadStream := NewStreamOut(server)
// New version
if server.NexVersion() >= 2 {
ackPacket.SetSequenceID(0)
ackPacket.SetSubstreamID(1)
// I'm lazy so just ack one packet
payloadStream.WriteUInt8(0) // substream ID
payloadStream.WriteUInt8(0) // length of additional sequence ids
payloadStream.WriteUInt16LE(packet.SequenceID()) // Sequence id
}
ackPacket.SetPayload(payloadStream.Bytes())
}
}
data := ackPacket.Bytes()
server.SendRaw(sender.Address(), data)
}
// Socket returns the underlying server UDP socket
func (server *Server) Socket() *net.UDPConn {
return server.socket
}
// SetSocket sets the underlying UDP socket
func (server *Server) SetSocket(socket *net.UDPConn) {
server.socket = socket
}
// PrudpVersion returns the server PRUDP version
func (server *Server) PrudpVersion() int {
return server.prudpVersion
}
// SetPrudpVersion sets the server PRUDP version
func (server *Server) SetPrudpVersion(prudpVersion int) {
server.prudpVersion = prudpVersion
}
// NexVersion returns the server NEX version
func (server *Server) NexVersion() int {
return server.nexVersion
}
// SetNexVersion sets the server NEX version
func (server *Server) SetNexVersion(nexVersion int) {
server.nexVersion = nexVersion
}
// ChecksumVersion returns the server packet checksum version
func (server *Server) ChecksumVersion() int {
return server.checksumVersion
}
// SetChecksumVersion sets the server packet checksum version
func (server *Server) SetChecksumVersion(checksumVersion int) {
server.checksumVersion = checksumVersion
}
// FlagsVersion returns the server packet flags version
func (server *Server) FlagsVersion() int {
return server.flagsVersion
}
// SetFlagsVersion sets the server packet flags version
func (server *Server) SetFlagsVersion(flagsVersion int) {
server.flagsVersion = flagsVersion
}
// AccessKey returns the server access key
func (server *Server) AccessKey() string {
return server.accessKey
}
// SetAccessKey sets the server access key
func (server *Server) SetAccessKey(accessKey string) {
server.accessKey = accessKey
}
// SignatureVersion returns the server packet signature version
func (server *Server) SignatureVersion() int {
return server.signatureVersion
}
// SetSignatureVersion sets the server packet signature version
func (server *Server) SetSignatureVersion(signatureVersion int) {
server.signatureVersion = signatureVersion
}
// KerberosKeySize returns the server kerberos key size
func (server *Server) KerberosKeySize() int {
return server.kerberosKeySize
}
// SetKerberosKeySize sets the server kerberos key size
func (server *Server) SetKerberosKeySize(kerberosKeySize int) {
server.kerberosKeySize = kerberosKeySize
}
// UsePacketCompression enables or disables packet compression
func (server *Server) UsePacketCompression(usePacketCompression bool) {
if usePacketCompression {
compression := ZLibCompression{}
server.SetPacketCompression(compression.Compress)
} else {
compression := DummyCompression{}
server.SetPacketCompression(compression.Compress)
}
server.usePacketCompression = usePacketCompression
}
// SetPacketCompression sets the packet compression function
func (server *Server) SetPacketCompression(compression func([]byte) []byte) {
server.compressPacket = compression
}
// Send writes data to client
func (server *Server) Send(packet PacketInterface) {
data := packet.Payload()
fragments := int(int16(len(data)) / server.fragmentSize)
fragmentID := 1
for i := 0; i <= fragments; i++ {
if int16(len(data)) < server.fragmentSize {
packet.SetPayload(data)
server.SendFragment(packet, 0)
} else {
packet.SetPayload(data[:server.fragmentSize])
server.SendFragment(packet, fragmentID)
data = data[server.fragmentSize:]
fragmentID++
}
}
}
// SendFragment sends a packet fragment to the client
func (server *Server) SendFragment(packet PacketInterface, fragmentID int) {
data := packet.Payload()
client := packet.Sender()
packet.SetPayload(server.compressPacket(data))
packet.SetSequenceID(uint16(client.SequenceIDCounterOut().Increment()))
encodedPacket := packet.Bytes()
server.SendRaw(client.Address(), encodedPacket)
}
// SendRaw writes raw packet data to the client socket
func (server *Server) SendRaw(conn *net.UDPAddr, data []byte) {
server.Socket().WriteToUDP(data, conn)
}
// NewServer returns a new NEX server
func NewServer() *Server {
server := &Server{
genericEventHandles: make(map[string][]func(PacketInterface)),
prudpV0EventHandles: make(map[string][]func(*PacketV0)),
prudpV1EventHandles: make(map[string][]func(*PacketV1)),
clients: make(map[string]*Client),
prudpVersion: 1,
fragmentSize: 1300,
resendTimeout: 1.5,
pingTimeout: 5,
signatureVersion: 0,
flagsVersion: 1,
checksumVersion: 1,
kerberosKeySize: 32,
kerberosKeyDerivation: 0,
}
server.UsePacketCompression(false)
return server
}