aboutsummaryrefslogtreecommitdiff
path: root/index.js
blob: 4453820a49d94bb470477f8bc4bf3be6f789fd67 (plain)
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
const ServerPort = 8888;
const AllowMods = false;

const _version = "0.1";
const Net = require('net');
const clients = {};

class MessageBuffer {
    constructor(delimiter) {
        this.delimiter = delimiter
        this.buffer = ""
    }

    isFinished() {
        if (
            this.buffer.length === 0 ||
            this.buffer.indexOf(this.delimiter) === -1
        ) {
            return true
        }
        return false
    }

    push(data) {
        this.buffer += data
    }

    getMessage() {
        const delimiterIndex = this.buffer.indexOf(this.delimiter)
        if (delimiterIndex !== -1) {
            const message = this.buffer.slice(0, delimiterIndex)
            this.buffer = this.buffer.replace(message + this.delimiter, "")
            return message
        }
        return null
    }

    handleData() {
        /**
         * Try to accumulate the buffer with messages
         *
         * If the server isnt sending delimiters for some reason
         * then nothing will ever come back for these requests
         */
        const message = this.getMessage()
        return message
    }
}

class KartikError extends Error {
    constructor(message, type) {
        super(message);
        this.name = "KartikError";
        this.ktype = type;
    }
}

const server = new Net.Server();

server.on('connection', (socket) => {
    socket.connectionId = (Math.random().toString(36).split(".")[1] + Math.random().toString(36).split(".")[1]).substr(0, 8);
    socket.linkedTo = null;
    clients[socket.connectionId] = socket;
    console.log("New connection " + socket.connectionId)

    socket.write(JSON.stringify(
        {
            _type: "init",
            name: "Kartik Server",
            version: _version,
            id: socket.connectionId,
            modded: null
        }
    ) + "\n")

    setTimeout(() => {
        try {
            if (socket.linkedTo === null) {
                throw new KartikError("Not linked within 3 minutes", "net.minteckprojects.kartik.KartikServer.ClientConnectTimeoutException");
            }
        } catch (e) {
            console.error(e);
            if (e.name !== "KartikError") {
                e.ktype = "nodejs.lang." + e.name.replaceAll("Error", "Exception");
            }
            socket.write(JSON.stringify({
                _type: "error",
                message: e.message,
                type: e.ktype
            }) + "\n")
            socket.end();
        }
    }, 180000)

    /*let received = "";
    socket.on("data", (data) => {
        data = data.toString();

        received = received + data.substr(1);
        console.log("{{" + data + "}}");
        if (data.startsWith(":")) {
            return;
        }
        try {
            raw = chunk.toString().replaceAll("}{", "}|{");

            datas = raw.split("|").filter(i => i.trim() !== "");
            datas.forEach((data) => {
                try {
                    info = JSON.parse(data);
                } catch(e) {
                    console.dir(data);
                    throw e;
                }

                if (data.length > 1200) {
                    console.dir(data);
                    throw new KartikError("Received data is too long", "net.minteckprojects.kartik.KartikServer.DataLengthException");
                }

                if (typeof info['_type'] != "string") {
                    throw new KartikError("Invalid JSON data", "net.minteckprojects.kartik.KartikServer.JsonDataException");
                }
                if (!socket.initialized) {
                    switch (info['_type']) {
                        case "init":
                            if (info['name'] !== "Kartik Core") {
                                throw new KartikError("Invalid client", "net.minteckprojects.kartik.KartikServer.AuthenticationException");
                            }
                            if (!info.modded) {
                                console.log("Connection initialized. Client running " + info.name + " version " + info.version + ", official client");
                            } else {
                                console.log("Connection initialized. Client running " + info.name + " version " + info.version + ", MODDED client");
                                if (!AllowMods) {
                                    console.log("Modded clients are not accepted");
                                    socket.end();
                                }
                            }
                            socket.initialized = true;
                            break;
                        default:
                            throw new KartikError("Trying to receive data but client not initialized", "net.minteckprojects.kartik.KartikServer.AuthenticationException");
                    }
                } else {
                    switch (info['_type']) {
                        case "init":
                            throw new KartikError("Trying to initialize client but client is already initialized", "net.minteckprojects.kartik.KartikServer.AuthenticationException");
                        case "link":
                            if (typeof info['client'] !== "string" || isNaN(parseInt(info['client'], 16))) {
                                throw new KartikError("Invalid client link ID", "net.minteckprojects.kartik.KartikServer.GuestIdentifierException");
                            }
                            if (typeof clients[info['client']] === "undefined") {
                                throw new KartikError("Guest client not found", "net.minteckprojects.kartik.KartikServer.GuestConnectException");
                            }
                            if (clients[info['client']].linkedTo === null) {
                                socket.linkedTo = clients[info['client']];
                                clients[info['client']].linkedTo = socket;
                                socket.linkedTo.role = "host";
                                socket.linkedTo.write(JSON.stringify(
                                    {
                                        _type: "linked",
                                        role: "host",
                                        ids: {
                                            host: socket.linkedTo.connectionId,
                                            guest: socket.connectionId
                                        }
                                    }
                                ))
                                socket.role = "guest";
                                socket.write(JSON.stringify(
                                    {
                                        _type: "linked",
                                        role: "guest",
                                        ids: {
                                            host: socket.linkedTo.connectionId,
                                            guest: socket.connectionId
                                        }
                                    }
                                ))
                                console.log("Link created: (H) " + socket.connectionId + " <-> " + socket.linkedTo.connectionId + " (G)")
                            } else {
                                throw new KartikError("Client already linked to another client", "net.minteckprojects.kartik.KartikServer.GuestAllocationException")
                            }
                            break;
                        default:
                            if (socket.linkedTo === null) {
                                throw new KartikError("Client not linked to another client", "net.minteckprojects.kartik.KartikServer.DataRoutingException");
                            } else {
                                socket.linkedTo.write(JSON.stringify(info));
                            }
                    }
                }
            })
        } catch (e) {
            console.error(e);
            if (e.name !== "KartikError") {
                e.ktype = "nodejs.lang." + e.name.replaceAll("Error", "Exception");
            }
            socket.write(JSON.stringify({
                _type: "error",
                message: e.message,
                type: e.ktype
            }))
            socket.end();
        }
    })*/

    let received = new MessageBuffer("\n")
    socket.on("data", data => {
        received.push(data)
        while (!received.isFinished()) {
            const chunk = received.handleData()
            try {
                raw = chunk.toString().replaceAll("}{", "}|{");

                datas = raw.split("|").filter(i => i.trim() !== "");
                datas.forEach((data) => {
                    try {
                        info = JSON.parse(data);
                    } catch(e) {
                        console.dir(data);
                        throw e;
                    }

                    if (data.length > 1200) {
                        console.dir(data);
                        throw new KartikError("Received data is too long", "net.minteckprojects.kartik.KartikServer.DataLengthException");
                    }

                    if (typeof info['_type'] != "string") {
                        throw new KartikError("Invalid JSON data", "net.minteckprojects.kartik.KartikServer.JsonDataException");
                    }
                    if (!socket.initialized) {
                        switch (info['_type']) {
                            case "init":
                                if (info['name'] !== "Kartik Core") {
                                    throw new KartikError("Invalid client", "net.minteckprojects.kartik.KartikServer.AuthenticationException");
                                }
                                if (!info.modded) {
                                    console.log("Connection initialized. Client running " + info.name + " version " + info.version + ", official client");
                                } else {
                                    console.log("Connection initialized. Client running " + info.name + " version " + info.version + ", MODDED client");
                                    if (!AllowMods) {
                                        console.log("Modded clients are not accepted");
                                        socket.end();
                                    }
                                }
                                socket.initialized = true;
                                break;
                            default:
                                throw new KartikError("Trying to receive data but client not initialized", "net.minteckprojects.kartik.KartikServer.AuthenticationException");
                        }
                    } else {
                        switch (info['_type']) {
                            case "init":
                                throw new KartikError("Trying to initialize client but client is already initialized", "net.minteckprojects.kartik.KartikServer.AuthenticationException");
                            case "ping":
                                socket.write(JSON.stringify(
                                    {
                                        _type: "pong",
                                    }
                                ) + "\n")
                                break;
                            case "link":
                                if (typeof info['client'] !== "string" || isNaN(parseInt(info['client'], 16))) {
                                    throw new KartikError("Invalid client link ID", "net.minteckprojects.kartik.KartikServer.GuestIdentifierException");
                                }
                                if (typeof clients[info['client']] === "undefined") {
                                    throw new KartikError("Guest client not found", "net.minteckprojects.kartik.KartikServer.GuestConnectException");
                                }
                                if (clients[info['client']].linkedTo === null) {
                                    socket.linkedTo = clients[info['client']];
                                    clients[info['client']].linkedTo = socket;
                                    socket.linkedTo.role = "host";
                                    socket.linkedTo.write(JSON.stringify(
                                        {
                                            _type: "linked",
                                            role: "host",
                                            ids: {
                                                host: socket.linkedTo.connectionId,
                                                guest: socket.connectionId
                                            }
                                        }
                                    ) + "\n")
                                    socket.role = "guest";
                                    socket.write(JSON.stringify(
                                        {
                                            _type: "linked",
                                            role: "guest",
                                            ids: {
                                                host: socket.linkedTo.connectionId,
                                                guest: socket.connectionId
                                            }
                                        }
                                    ) + "\n")
                                    console.log("Link created: (H) " + socket.connectionId + " <-> " + socket.linkedTo.connectionId + " (G)")
                                } else {
                                    throw new KartikError("Client already linked to another client", "net.minteckprojects.kartik.KartikServer.GuestAllocationException")
                                }
                                break;
                            default:
                                if (socket.linkedTo === null) {
                                    throw new KartikError("Client not linked to another client", "net.minteckprojects.kartik.KartikServer.DataRoutingException");
                                } else {
                                    socket.linkedTo.write(JSON.stringify(info) + "\n");
                                }
                        }
                    }
                })
            } catch (e) {
                console.error(e);
                if (e.name !== "KartikError") {
                    e.ktype = "nodejs.lang." + e.name.replaceAll("Error", "Exception");
                }
                socket.write(JSON.stringify({
                    _type: "error",
                    message: e.message,
                    type: e.ktype
                }) + "\n")
                socket.end();
            }
        }
    })

    socket.on('error', (err) => {
        console.error(err);
        try {
            if (err.code === "ECONNRESET") {
                try {
                    socket.linkedTo.end();
                } catch (e) {
                    console.log("Cannot end other client's session");
                }
            }
        } catch (e) {
            console.log("Cannot check if connection reset")
        }
    })

    socket.on('end', (chunk) => {
        console.log("Connection from " + socket.connectionId + " closed");
        if (socket.linkedTo !== null) {
            if (socket.role === "guest") {
                console.log("Link broken: (H) " + socket.linkedTo.connectionId + " <-> " + socket.connectionId + " (G)");
            } else {
                console.log("Link broken: (H) " + socket.connectionId + " <-> " + socket.linkedTo.connectionId + " (G)");
            }
            try {
                socket.linkedTo.end();
            } catch (e) {
                console.log("Cannot end other client's session");
            }
        }
        delete clients[socket.connectionId];
    })
})

server.listen(ServerPort, () => {
    console.log("Kartik Server " + _version + " listening for connections on 0.0.0.0:" + ServerPort)
})