This repository has been archived by the owner on Feb 15, 2021. It is now read-only.
forked from KinectTheUnknown/JSRakNet
-
Notifications
You must be signed in to change notification settings - Fork 2
/
listener.js
247 lines (205 loc) · 7.28 KB
/
listener.js
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
const Dgram = require('dgram')
const Crypto = require('crypto')
const EventEmitter = require('events')
const Connection = require('./connection')
const ServerName = require('./utils/server_name')
const InetAddress = require('./utils/inet_address')
const Identifiers = require('./protocol/identifiers')
const UnconnectedPing = require('./protocol/unconnected_ping')
const UnconnectedPong = require('./protocol/unconnected_pong')
const OpenConnectionRequest1 = require('./protocol/open_connection_request_1')
const OpenConnectionReply1 = require('./protocol/open_connection_reply_1')
const OpenConnectionRequest2 = require('./protocol/open_connection_request_2')
const OpenConnectionReply2 = require('./protocol/open_connection_reply_2')
const IncompatibleProtocolVersion = require('./protocol/incompatible_protoco_version')
'use strict'
// Minecraft related protocol
const PROTOCOL = 10
// Raknet ticks
const RAKNET_TPS = 100
const RAKNET_TICK_LENGTH = 1 / RAKNET_TPS
// Listen to packets and then process them
class Listener extends EventEmitter {
/** @type {number} */
#id = Crypto.randomBytes(8).readBigInt64BE() // Generate a signed random 64 bit GUID
/** @type {ServerName} */
#name = new ServerName()
/** @type {Dgram.Socket} */
#socket
/** @type {Map<string, Connection>} */
#connections = new Map()
/** @type {boolean} */
#shutdown = false
/**
* Creates a packet listener on given address and port.
*
* @param {string} address
* @param {number} port
*/
async listen(address, port) {
this.#socket = Dgram.createSocket({ type: 'udp4' })
this.#name.setServerId(this.#id)
this.#socket.on('message', (buffer, rinfo) => {
this.handle(buffer, rinfo)
})
await new Promise((resolve, reject) => {
const failFn = e => reject(e)
this.#socket.once('error', failFn)
this.#socket.bind(port, address, () => {
this.#socket.removeListener('error', failFn)
resolve()
})
})
this.tick() // tick sessions
return this
}
handle(buffer, rinfo) {
let header = buffer.readUInt8() // Read packet header to recognize packet type
let token = `${rinfo.address}:${rinfo.port}`
if (this.#connections.has(token)) {
let connection = this.#connections.get(token)
connection.receive(buffer)
} else {
switch(header) {
case Identifiers.UnconnectedPing:
this.handleUnconnectedPing(buffer).then(buffer => {
this.#socket.send(buffer, 0, buffer.length, rinfo.port, rinfo.address)
})
break
case Identifiers.OpenConnectionRequest1:
this.handleOpenConnectionRequest1(buffer).then(buffer => {
this.#socket.send(buffer, 0, buffer.length, rinfo.port, rinfo.address)
})
break
case Identifiers.OpenConnectionRequest2:
let address = new InetAddress(rinfo.address, rinfo.port)
this.handleOpenConnectionRequest2(buffer, address).then(buffer => {
this.#socket.send(buffer, 0, buffer.length, rinfo.port, rinfo.address)
})
break
}
}
}
// async handlers
async handleUnconnectedPing(buffer) {
let decodedPacket, packet
// Decode server packet
decodedPacket = new UnconnectedPing()
decodedPacket.buffer = buffer
decodedPacket.read()
// Check packet validity
// To refactor
if (!decodedPacket.valid) {
throw new Error('Received an invalid offline message')
}
// Encode response
packet = new UnconnectedPong()
packet.sendTimestamp = decodedPacket.sendTimeStamp
packet.serverGUID = this.#id
let serverQuery = this.#name
/**
* @param {ServerName} serverQuery
*/
this.emit('unconnectedPong', serverQuery)
packet.serverName = serverQuery.toString()
packet.write()
return packet.buffer
}
async handleOpenConnectionRequest1(buffer) {
let decodedPacket, packet
// Decode server packet
decodedPacket = new OpenConnectionRequest1()
decodedPacket.buffer = buffer
decodedPacket.read()
// Check packet validity
// To refactor
if (!decodedPacket.valid) {
throw new Error('Received an invalid offline message')
}
if (decodedPacket.protocol !== PROTOCOL) {
packet = new IncompatibleProtocolVersion()
packet.protocol = PROTOCOL
packet.serverGUID = this.#id
packet.write()
return packet.buffer
}
// Encode response
packet = new OpenConnectionReply1()
packet.serverGUID = this.#id
packet.mtuSize = decodedPacket.mtuSize
packet.write()
return packet.buffer
}
async handleOpenConnectionRequest2(buffer, address) {
let decodedPacket, packet
// Decode server packet
decodedPacket = new OpenConnectionRequest2()
decodedPacket.buffer = buffer
decodedPacket.read()
// Check packet validity
// To refactor
if (!decodedPacket.valid) {
throw new Error('Received an invalid offline message')
}
// Encode response
packet = new OpenConnectionReply2()
packet.serverGUID = this.#id
packet.mtuSize = decodedPacket.mtuSize
packet.clientAddress = address
packet.write()
// Create a session
let token = `${address.address}:${address.port}`
let conn = new Connection(this, decodedPacket.mtuSize, address)
this.#connections.set(token, conn)
return packet.buffer
}
tick() {
let int = setInterval(() => {
if (!this.#shutdown) {
for (let [_, connection]of this.#connections) {
connection.update(Date.now())
}
} else {
clearInterval(int)
}
}, RAKNET_TICK_LENGTH * 1000)
}
/**
* Remove a connection from all connections.
*
* @param {Connection} connection
* @param {string} reason
*/
removeConnection(connection, reason) {
let inetAddr = connection.address
let token = `${inetAddr.address}:${inetAddr.port}`
if (this.#connections.has(token)) {
(this.#connections.get(token)).close()
this.#connections.delete(token)
}
this.emit('closeConnection', connection.address, reason)
}
/**
* Send packet buffer to the client.
*
* @param {Buffer} buffer
* @param {string} address
* @param {number} port
*/
sendBuffer(buffer, address, port) {
this.#socket.send(buffer, 0, buffer.length, port, address)
}
get socket() {
return this.#socket
}
get connections() {
return this.#connections
}
get name () {
return this.#name
}
set name(name) {
this.#name = name
}
}
module.exports = Listener