forked from levrik/node-modern-rcon
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrcon.ts
264 lines (215 loc) · 6.67 KB
/
rcon.ts
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
import * as net from 'net';
import {Buffer} from 'buffer';
export class ExtendableError extends Error {
constructor(message: string = '', public readonly innerException?: Error) {
super(message);
this.message = message;
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
export class RconError extends ExtendableError {
constructor(message: string, innerException?: Error) {
super(message, innerException);
Object.freeze(this);
}
}
export const enum State {
Disconnected = 0,
Connecting = 0.5,
Connected = 1,
Authorized = 2,
Refused = -1,
Unauthorized = -2
}
const enum PacketType {
AUTH = 0x03, // outgoing
COMMAND = 0x02, // outgoing
RESPONSE_AUTH = 0x02 // incoming
}
type Callback = (data: string | null, error?: Error) => void;
export interface RconConfig {
host: string;
port?: number;
password: string;
timeout?: number;
}
export namespace Defaults
{
export const PORT:number = 25575;
export const Timeout:number = 5000;
}
Object.freeze(Defaults);
export class Rcon implements RconConfig {
readonly host: string;
readonly port: number;
readonly password: string;
readonly timeout: number;
enableConsoleLogging: boolean = false;
private _authPacketId: number = NaN;
private _state: State = State.Disconnected;
private _socket: net.Socket | undefined;
private _lastRequestId: number = 0xF4240;
private _callbacks: Map<number, Callback> = new Map();
private _errors: Error[] = [];
private _connector: Promise<Rcon> | undefined;
private _sessionCount:number = 0;
get errors(): Error[] {
return this._errors.slice();
}
get state(): State {
return this._state;
}
constructor(config: RconConfig) {
let host = config.host;
this.host = host = host && host.trim();
if (!host)
throw new TypeError('"host" argument cannot be empty');
this.port = config.port || Defaults.PORT;
const password = config.password;
if (!password || !password.trim())
throw new TypeError('"password" argument cannot be empty');
this.password = password;
this.timeout = config.timeout || Defaults.Timeout;
}
connect(): Promise<Rcon> {
const _ = this;
let p = _._connector;
if (!p) _._connector = p = new Promise<Rcon>((resolve, reject) => {
_._state = State.Connecting;
if (_.enableConsoleLogging) console.log(this.toString(), "Connecting...");
const s = _._socket = net.createConnection(_.port, _.host);
function cleanup(message?: string, error?: Error): RconError | void {
if (error) _._errors.push(error);
s.removeAllListeners();
if (_._socket == s) _._socket = undefined;
if (_._connector == p) _._connector = undefined;
if (message) {
if (_.enableConsoleLogging) console.error(_.toString(), message);
if (message) return new RconError(message, error);
}
}
// Look for connection failure...
s.once('error', error => {
_._state = State.Refused;
reject(cleanup("Connection refused.", error)); // ** First point of failure.
});
// Look for successful connection...
s.once('connect', () => {
s.removeAllListeners('error');
_._state = State.Connected;
if (_.enableConsoleLogging) console.log(_.toString(), "Connected. Authorizing ...");
s.on('data', data => _._handleResponse(data));
s.on('error', error => {
_._errors.push(error);
if (_.enableConsoleLogging) console.error(_.toString(), error);
});
_._send(_.password, PacketType.AUTH).then(() => {
_._state = State.Authorized;
if (_.enableConsoleLogging) console.log(_.toString(), "Authorized.");
resolve(_);
}).catch(error => {
_._state = State.Unauthorized;
reject(cleanup("Authorization failed.", error)); // ** Second point of failure.
});
});
s.once('end', () => {
if (_.enableConsoleLogging) console.warn(this.toString(), "Disconnected.");
_._state = State.Disconnected;
cleanup();
});
});
return p;
}
async session<T>(context:(rcon?:Rcon,sessionId?:number)=>Promise<T>)
{
const sessionId = ++this._sessionCount;
let rcon:Rcon|undefined;
try {
rcon = await this.connect();
return await context(rcon, sessionId);
}
finally {
this._sessionCount--;
if(!this._sessionCount && rcon)
rcon.disconnect();
}
}
toString(): string {
return `RCON: ${this.host}:${this.port}`;
}
disconnect(): void {
const s = this._socket;
this._callbacks.clear();
if (s) s.end();
this._socket = undefined;
this._connector = undefined;
}
_handleResponse(data: Buffer): void {
const len = data.readInt32LE(0);
if (!len) throw new RconError('Received empty response package');
let id = data.readInt32LE(4);
const type = data.readInt32LE(8);
const callbacks = this._callbacks;
const authId = this._authPacketId;
if (id === -1 && !isNaN(authId) && type === PacketType.RESPONSE_AUTH) {
if (callbacks.has(authId)) {
id = authId;
this._authPacketId = NaN;
callbacks.get(authId)!(null, new RconError('Authentication failed.'));
}
}
else if (callbacks.has(id)) {
let str = data.toString('utf8', 12, len + 2);
if (str.charAt(str.length - 1) === '\n')
str = str.substring(0, str.length - 1);
callbacks.get(id)!(str);
}
callbacks.delete(id); // Possibly superfluous but best to be sure.
}
async send(data: string): Promise<string> {
if (!this._connector || this._state <= 0)
throw new RconError('Instance is not connected.');
await this._connector;
return await this._send(data, PacketType.COMMAND);
}
private async _send(data: string, cmd: number): Promise<string> {
const s = this._socket;
if (!s || this._state <= 0)
throw new RconError('Instance was disconnected.');
const length = Buffer.byteLength(data);
const id = ++this._lastRequestId;
if (cmd === PacketType.AUTH) this._authPacketId = id;
const buf = Buffer.allocUnsafe(length + 14);
buf.writeInt32LE(length + 10, 0);
buf.writeInt32LE(id, 4); // Not sure how this is used or needed.
buf.writeInt32LE(cmd, 8);
buf.write(data, 12);
buf.fill(0x00, length + 12);
await s.write(buf, 'binary');
return await new Promise<string>((resolve, reject) => {
const cleanup = () => {
clearTimeout(timeout);
s.removeListener('end', onEnded);
this._callbacks.delete(id);
if (cmd === PacketType.AUTH) this._authPacketId = NaN;
};
const timeout = setTimeout(() => {
cleanup();
reject(new RconError('Request timed out'));
}, this.timeout);
const onEnded = () => {
cleanup();
reject(new RconError('Disconnected before response.'));
};
s.once('end', onEnded);
this._callbacks.set(id, (data, err) => {
cleanup();
if (err) reject(err);
if (data == null) reject(new RconError("No data returned."));
else resolve(data);
});
});
}
}
export default Rcon;