forked from Pryaxis/TShock
/
RconHandler.cs
455 lines (433 loc) · 12.1 KB
/
RconHandler.cs
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
/*
TShock, a server mod for Terraria
Copyright (C) 2011 The TShock Team
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Streams;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Terraria;
namespace TShockAPI
{
internal class RconHandler
{
public static string Password = "";
private static DateTime LastRequest;
private static DateTime LastHeartbeat;
public static int ListenPort;
public static bool ContinueServer = true;
public static string Response = "";
private static bool Started;
private static UdpClient listener;
private static Thread startThread;
private static Thread heartbeat;
private static Thread listen;
public static void ShutdownAllThreads()
{
if (Started)
{
startThread.Abort();
heartbeat.Abort();
listen.Abort();
Started = false;
}
}
public static void StartThread()
{
if (!Started)
{
startThread = new Thread(Start);
startThread.Start();
heartbeat = new Thread(SendHeartbeat);
heartbeat.Start();
}
Started = true;
}
public static void Start()
{
Log.Info("Starting RconHandler.");
try
{
Console.WriteLine(string.Format("RconHandler is running at UDP port {0} and password is {1}",
ListenPort,
Password));
listen = new Thread(Listener);
listen.Start();
while (true)
{
if (listen.ThreadState != ThreadState.Running)
{
listen.Abort();
while (listen.ThreadState != ThreadState.Stopped)
continue;
listen.Start();
}
Thread.Sleep(3000);
}
}
catch (Exception e)
{
Log.Error(e.ToString());
}
}
private static void Listener()
{
if (listener == null)
try
{
listener = new UdpClient(ListenPort);
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.AddressAlreadyInUse)
Log.ConsoleError("Could not bind to " + ListenPort + ". Are you sure you don't have another instance running?");
}
catch (Exception e)
{
Log.Error(e.ToString());
}
while (ContinueServer)
{
try
{
var listenEP = new IPEndPoint(IPAddress.Any, ListenPort);
LastRequest = DateTime.Now;
byte[] bytes = listener.Receive(ref listenEP);
var packet = ParsePacket(bytes, listenEP);
listener.Send(packet, packet.Length, listenEP);
}
catch (Exception e)
{
Log.Error(e.ToString());
}
}
}
private static string SendPacket(byte[] bytes, string hostname, int port)
{
var response = Encoding.UTF8.GetString(new byte[] {0xFF, 0xFF, 0xFF, 0xFF}) + "disconnect";
try
{
var EP = new IPEndPoint(IPAddress.Any, port);
using (var client = new UdpClient())
{
client.Connect(hostname, port);
client.Client.ReceiveTimeout = 500;
client.Send(bytes, bytes.Length);
response = Encoding.UTF8.GetString(client.Receive(ref EP));
}
}
catch (Exception e)
{
Log.Error(e.ToString());
}
return response;
}
private static byte[] ParsePacket(byte[] bytes, IPEndPoint EP)
{
string response = "";
var packetstring = Encoding.UTF8.GetString(PadPacket(bytes));
var redirect = false;
var print = true;
if ((DateTime.Now - LastRequest).Milliseconds >= 100)
{
if (packetstring.StartsWith("rcon") || packetstring.Substring(4).StartsWith("rcon") ||
packetstring.Substring(5).StartsWith("rcon"))
{
if (!string.IsNullOrEmpty(Password))
{
var args = ParseParameters(packetstring);
if (args.Count >= 3)
{
if (args[1] == Password)
{
args[1] = args[0] = "";
string command = string.Join(" ", args.ToArray());
command = command.TrimEnd(' ').TrimEnd('\0').TrimStart(' ');
Log.ConsoleInfo("Rcon from " + EP + ":" + command);
Response = "";
response = ExecuteCommand(command);
response += "\n" + Response;
Response = "";
response = response.TrimStart('\n');
}
else
{
response = "Bad rcon password.\n";
Log.ConsoleInfo("Bad rcon password from " + EP);
}
}
else
response = "";
}
else
{
response = "No rcon password set on the server.\n";
Log.Info("No password for rcon set");
}
}
else
redirect = true;
}
if (packetstring.StartsWith("getinfo")
|| packetstring.Substring(4).StartsWith("getinfo")
|| packetstring.Substring(5).StartsWith("getinfo"))
{
var challenge = "";
if (packetstring.Split(' ').Length == 2)
challenge = packetstring.Split(' ')[1];
response = "infoResponse\n";
var infostring =
string.Format(
@"\_TShock_ver\{6}\mapname\{1}\sv_maxclients\{2}\clients\{3}\sv_privateClients\{4}\hconly\{5}\gamename\TERRARIA\protocol\100\sv_hostname\{0}\g_needPass\{7}",
TShock.Config.ServerName, Main.worldName, Main.maxNetPlayers,
TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots,
TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum,
Netplay.password != "" ? 1 : 0);
if (challenge != "")
infostring += @"\challenge\" + challenge;
response += infostring;
print = false;
redirect = false;
}
else if (packetstring.StartsWith("getstatus")
|| packetstring.Substring(4).StartsWith("getstatus")
|| packetstring.Substring(5).StartsWith("getstatus"))
{
var challenge = "";
if (packetstring.Split(' ').Length == 2)
challenge = packetstring.Split(' ')[1];
response = "statusResponse\n";
var statusstring = string.Format(
@"\_TShock_ver\{6}\mapname\{1}\sv_maxclients\{2}\clients\{3}\sv_privateClients\{4}\hconly\{5}\gamename\TERRARIA\protocol\100\sv_hostname\{0}\g_needPass\{7}",
TShock.Config.ServerName, Main.worldName, Main.maxNetPlayers,
TShock.Utils.ActivePlayers(), Main.maxNetPlayers - TShock.Config.MaxSlots,
TShock.Config.HardcoreOnly ? 1 : 0, TShock.VersionNum,
Netplay.password != "" ? 1 : 0) + "\n";
if (challenge != "")
statusstring += @"\challenge\" + challenge;
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.Active)
statusstring += (string.Format("0 0 {0}\n", player.Name));
}
response += statusstring;
print = false;
redirect = false;
}
if (!redirect)
return (ConstructPacket(response, print));
else
return (ConstructPacket("disconnect", false));
}
private static string ExecuteCommand(string text)
{
if (Main.rand == null)
Main.rand = new Random();
if (WorldGen.genRand == null)
WorldGen.genRand = new Random();
if (text.StartsWith("exit"))
{
TShock.Utils.ForceKickAll("Server shutting down!");
WorldGen.saveWorld(false);
Netplay.disconnect = true;
return "Server shutting down.";
}
else if (text.StartsWith("playing") || text.StartsWith("/playing"))
{
int count = 0;
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.Active)
{
count++;
TSPlayer.Server.SendMessage(string.Format("{0} ({1}) [{2}] <{3}>", player.Name, player.IP, player.Group.Name,
player.UserAccountName));
}
}
TSPlayer.Server.SendMessage(string.Format("{0} players connected.", count));
}
else if (text.StartsWith("status"))
{
Response += "map: " + Main.worldName + "\n";
Response += "num score ping name lastmsg address qport rate\n";
int count = 0;
foreach (TSPlayer player in TShock.Players)
{
if (player != null && player.Active)
{
count++;
Response +=
(string.Format("{0} 0 0 {1}({2}) {3} {4} 0 0", count, player.Name, player.Group.Name,
Netplay.serverSock[player.Index].tcpClient.Client.RemoteEndPoint, "")) + "\n";
}
}
}
else if (text.StartsWith("say "))
{
Log.Info(string.Format("Server said: {0}", text.Remove(0, 4)));
return string.Format("Server said: {0}", text.Remove(0, 4));
}
else if (text == "autosave")
{
Main.autoSave = TShock.Config.AutoSave = !TShock.Config.AutoSave;
Log.ConsoleInfo("AutoSave " + (TShock.Config.AutoSave ? "Enabled" : "Disabled"));
return "AutoSave " + (TShock.Config.AutoSave ? "Enabled" : "Disabled");
}
else if (text.StartsWith("/"))
{
if (!Commands.HandleCommand(TSPlayer.Server, text))
return "Invalid command.";
}
else if (!Commands.HandleCommand(TSPlayer.Server, "/" + text))
return "Invalid command.";
return "";
}
private static byte[] ConstructPacket(string response, bool print)
{
var oob = new byte[] {0xFF, 0xFF, 0xFF, 0xFF};
using (var stream = new MemoryStream())
{
stream.WriteBytes(oob);
if (print)
stream.WriteBytes(Encoding.UTF8.GetBytes(string.Format("print\n{0}", response)));
else
stream.WriteBytes(Encoding.UTF8.GetBytes(response));
var trimmedpacket = new byte[(int) stream.Length];
var packet = stream.GetBuffer();
Array.Copy(packet, trimmedpacket, (int) stream.Length);
return trimmedpacket;
}
}
private static byte[] PadPacket(byte[] packet)
{
var returnpacket = new byte[(4 + packet.Length)];
int h = 0;
if (packet[0] != 0xFF)
{
for (int i = 0; i < 4; i++)
returnpacket[i] = 0xFF;
for (int i = 4; i < returnpacket.Length; i++)
returnpacket[i] = packet[h++];
}
else
returnpacket = packet;
return returnpacket;
}
private static void SendHeartbeat()
{
LastHeartbeat = DateTime.UtcNow.Subtract(new TimeSpan(0, 0, 30));
while (true)
{
if ((DateTime.UtcNow - LastHeartbeat).Seconds >= 30)
{
var packet = ConstructPacket("heartbeat TerrariaShock", false);
if (listener == null)
try
{
listener = new UdpClient(ListenPort);
}
catch (SocketException e)
{
if (e.SocketErrorCode == SocketError.AddressAlreadyInUse)
Log.ConsoleError("Could not bind to " + ListenPort + ". Are you sure you don't have another instance running?");
}
catch (Exception e)
{
Log.Error(e.ToString());
}
listener.Send(packet, packet.Length, TShock.Config.MasterServer, 27950);
LastHeartbeat = DateTime.UtcNow;
}
Thread.Sleep(10000);
}
}
#region ParseParams
private static List<String> ParseParameters(string str)
{
var ret = new List<string>();
var sb = new StringBuilder();
bool instr = false;
for (int i = 0; i < str.Length; i++)
{
char c = str[i];
if (instr)
{
if (c == '\\')
{
if (i + 1 >= str.Length)
break;
c = GetEscape(str[++i]);
}
else if (c == '"')
{
ret.Add(sb.ToString());
sb.Clear();
instr = false;
continue;
}
sb.Append(c);
}
else
{
if (IsWhiteSpace(c))
{
if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
}
else if (c == '"')
{
if (sb.Length > 0)
{
ret.Add(sb.ToString());
sb.Clear();
}
instr = true;
}
else
{
sb.Append(c);
}
}
}
if (sb.Length > 0)
ret.Add(sb.ToString());
return ret;
}
private static char GetEscape(char c)
{
switch (c)
{
case '\\':
return '\\';
case '"':
return '"';
case 't':
return '\t';
default:
return c;
}
}
private static bool IsWhiteSpace(char c)
{
return c == ' ' || c == '\t' || c == '\n';
}
#endregion
}
}