-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
375 lines (299 loc) · 9.08 KB
/
index.js
File metadata and controls
375 lines (299 loc) · 9.08 KB
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
const udp = require('dgram');
const EventEmitter = require('events');
const signature = Buffer.from("[udplus]")
var timeout = 3000
const reserved = ["connection", "disconnected", "keep-alive", "|"]
var logging = true
module.exports = {
createServer: () => {
return createServer()
},
createClient: () => {
return createClient()
},
logging: option => {
logging = option
}
}
function log(message) {
if (logging) {
console.log(`[udplus]`, message);
}
}
function decode(buffer) {
const head = buffer.slice(0, signature.length)
const isUdplus = Buffer.compare(head, signature) === 0
if (!isUdplus) {
return {
channel: "raw",
datatype: "buffer",
data: buffer
}
}
const headerLength = Number(buffer.slice(signature.length, signature.length + 4))
const metadataRaw = String(buffer.slice((4 + signature.length), headerLength))
const dataBuffer = buffer.slice(headerLength, buffer.length)
const metadata = []
for (const entry of metadataRaw.split("|")) {
metadata.push(entry)
}
const packet = {channel: metadata[0], datatype: metadata[1], data: undefined}
//bufer
if (packet.datatype == "buffer") {
packet.data = dataBuffer
return packet
}
//string
if (packet.datatype == "string") {
packet.data = String(dataBuffer)
return packet
}
//number
if (packet.datatype == "number") {
packet.data = Number(dataBuffer)
return packet
}
//object/json
if (packet.datatype == "object") {
packet.data = JSON.parse(String(dataBuffer))
return packet
}
}
function encode(channel, data) {
let datatype = false
let buffer
//encode data
if (Buffer.isBuffer(data)) {
datatype = "buffer"
}
if (!datatype) {
datatype = typeof(data)
}
if (datatype != "buffer") {
if (datatype == "object") {
buffer = Buffer.from(JSON.stringify(data))
}
else {
//maybe problematisch
buffer = Buffer.from(String(data))
}
}
else {
buffer = data
}
//check buffer length
if (buffer.length > 65000) {
throw new Error("Message too large: Max Buffer size is 65000 bytes")
}
//create header
const header = encodeHeader(channel, datatype)
const packet = Buffer.concat([header, buffer])
return packet
}
function encodeHeader(channel, datatype, custom) {
let metadata = ""
addMetadata(channel)
addMetadata(datatype)
if (custom != undefined) {
for (const str of custom) {
if (checkString(str)) {
addMetadata(str)
}
else {
throw new Error(`Invalid channel name ${channel} Illegal channel names/chars: ${reserved}`)
}
}
}
function addMetadata(str) {
if (metadata.length > 0) {
metadata += "|"
}
metadata += str
}
function fixNrLength(nr) {
let str = String(nr)
while (str.length < 4) {
str = "0" + str
}
return str
}
const metaBuffer = Buffer.from(metadata)
const headerLengthString = fixNrLength(metaBuffer.length + signature.length + 4)
const header = Buffer.concat([signature, Buffer.from(headerLengthString), metaBuffer])
return header
}
function checkString(str) {
if (typeof(str) != "string") {
return false
}
if (str.includes("|")) {
return false
}
for (const internal of reserved) {
if (str.includes(internal)) {
return false
}
}
return true
}
function createClient() {
const client = udp.createSocket("udp4")
const events = new EventEmitter();
const connection = {}
//scuffed naming fix
events.dispatch = events.emit
function internalAction(data, info) {
if (data.channel == "connection") {
log(`connection established with ${info.address}:${info.port}`)
timeout = data.data
}
}
events.connect = (address, port, callback) => {
connection.address = address
connection.port = port
keepAlive()
callback(`${address}:${port}`)
}
client.on("message", (buffer, info) => {
const data = decode(buffer)
if (data != undefined) {
if (reserved.includes(data.channel)) {
internalAction(data, info)
}
else {
log(`Message recieved from ${info.address}:${info.port}`)
events.dispatch(data.channel, data.data)
}
}
})
events.emit = (channel, data) => {
if (checkString(channel)) {
dispatch(channel, data)
}
else {
throw new Error(`Invalid channel name ${channel} Illegal channel names/chars: ${reserved}`)
}
}
function dispatch(channel, data) {
const packet = encode(channel, data)
client.send(packet, connection.port, connection.address, err => {
if (err) {
console.log(err);
}
})
}
function keepAlive() {
setInterval(() => {
dispatch("keep-alive", Date.now())
}, Math.round(timeout / 2));
}
return events
}
function createServer() {
const server = udp.createSocket("udp4")
const events = new EventEmitter();
const clients = []
//scuffed naming fix
events.dispatch = events.emit
function registerClient(data, client) {
let registered = false
for (const knownClient of clients) {
if (client.address == knownClient.address) {
registered = true
const knownPort = knownClient.port
knownClient.address = client.address
knownClient.port = client.port
knownClient.lastSignal = Date.now()
if (knownPort != client.port) {
dispatch("connection", timeout, knownClient)
}
}
}
if (!registered) {
//create event emitter for client
const newClient = new EventEmitter()
//scuffed naming fix
newClient.dispatch = newClient.emit
newClient.emit = (channel, data) => {
if (clients.includes(newClient)) {
if (checkString(channel)) {
dispatch(channel, data, newClient)
}
else {
throw new Error(`Invalid channel name ${channel} Illegal channel names/chars: ${reserved}`)
}
}
}
newClient.address = client.address
newClient.port = client.port
newClient.lastSignal = Date.now()
clients.push(newClient)
events.dispatch("connection", newClient)
dispatch("connection", timeout, newClient)
}
}
function dispatch(channel, data, client) {
const packet = encode(channel, data)
server.send(packet, client.port, client.address, err => {
if (err) {
console.log(err);
}
else {
log(`Data Sent to ${client.address}:${client.port}`)
}
})
}
function getClient(info) {
for (const client of clients) {
if (client.address == info.address && client.port == info.port) {
return client;
}
}
return false;
}
server.on("error", err => {
console.log(`UDP Server has errored: ${err}`);
})
server.on("message", (buffer, info) => {
const data = decode(buffer)
//log(`Data received from: ${info.address}`)
if (typeof data === "object") {
if (data.channel != "raw") {
registerClient(data, info)
}
//emit on main emitter
events.dispatch(data.channel, data.data)
//emit on client object
const client = getClient(info)
if (client) {
client.dispatch(data.channel, data.data)
}
}
})
//broadcast message to all clients
events.emit = (channel, data) => {
if (checkString(channel)) {
for (const c of clients) {
dispatch(channel, data, c)
}
}
else {
throw new Error(`Invalid channel name ${channel} Illegal channel names/chars: ${reserved}`)
}
}
events.listen = (port, callback) => {
server.bind(port, "0.0.0.0", () => {
var address = server.address();
callback(`${address.address}:${address.port}`);
});
}
setInterval(() => {
for (const client of clients) {
if (client.lastSignal + timeout < Date.now()) {
log("client disconnected: " + client.address)
clients.splice(clients.indexOf(client), 1)
}
}
}, 2000);
return events
}