-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
70 lines (56 loc) · 2.02 KB
/
index.js
File metadata and controls
70 lines (56 loc) · 2.02 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
import Rcon from './rcon.js';
import express from 'express';
import { webOptions, rconOptions, rconPoolSize, logger } from './config.js';
const app = express();
// Create pool connection
const rconPool = [];
let currentRconIndex = 0;
const createRconInstance = async () => {
for (let i = 0; i < rconPoolSize; i++) {
const rconInstance = new Rcon(rconOptions, i);
rconInstance.connect().then(() => {
logger('RCON', 0, `Connected to RCON instance ${i}`);
}).catch((error) => {
logger('RCON', 0, `Error connecting to RCON instance ${i}: ${error}`);
});
rconPool.push(rconInstance);
}
}
createRconInstance();
const authenticateMiddleware = (req, res, next) => {
const token = req.header('Authorization');
if (token === webOptions.secretToken) {
next();
} else {
res.status(401).send('Unauthorized');
logger('HTTP', 1, `Unauthorized request from ${req.ip}`);
}
};
app.use(express.text({ defaultCharset: 'utf-8' }));
app.post('/rcon', authenticateMiddleware, async (req, res) => {
const command = req.body;
logger('HTTP', 1, `[${currentRconIndex}] ${req.method} request to ${req.path} from ${req.ip}`);
// Get the next RCON instance from the pool
const rconInstance = rconPool[currentRconIndex];
currentRconIndex = (currentRconIndex + 1) % rconPool.length;
try {
const response = await rconInstance.execute(command);
res.status(200).send({ response });
} catch (error) {
res.status(500).send(`Error: ${error.message}`);
}
});
const server = app.listen(webOptions.port_web, webOptions.ip_web, () => {
logger('HTTP', 1, `Server listening on ${webOptions.ip_web}:${webOptions.port_web}`);
});
// Add an event listener to close the RCON connections when the HTTP server is stopped
server.on('close', async () => {
for (let i = 0; i < rconPool.length; i++) {
try {
await rconPool[i].disconnect();
logger('RCON', 0, `RCON instance ${i} disconnected`);
} catch (error) {
logger('RCON', 0, `Error disconnecting RCON instance ${i}: ${error}`);
}
}
});