-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathStarryboundServer.cs
572 lines (486 loc) · 21.3 KB
/
StarryboundServer.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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/*
* Starrybound Server
* Copyright 2013, Avilance Ltd
* Created by Zidonuke (zidonuke@gmail.com) and Crashdoom (crashdoom@avilance.com)
*
* This file is a part of Starrybound Server.
* Starrybound Server 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.
* Starrybound Server 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 Starrybound Server. If not, see http://www.gnu.org/licenses/.
*/
using com.avilance.Starrybound.Packets;
using com.avilance.Starrybound.Util;
using com.avilance.Starrybound.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using com.avilance.Starrybound.Permissions;
using MaxMind;
using System.Net;
namespace com.avilance.Starrybound
{
class StarryboundServer
{
public static string SavePath;
public static BootstrapFile bootstrapConfig = new BootstrapFile();
public static ConfigFile config = new ConfigFile();
public static ServerFile serverConfig = new ServerFile();
public static readonly Version VersionNum = Assembly.GetExecutingAssembly().GetName().Version;
public static readonly int ProtocolVersion = 639;
public static readonly string unmoddedClientDigest = "515E04DF26D1E9777FCFB32D7789DDAF6EF733EFC3BEB798454DAB3BE6668719";
public static StarboundVersion starboundVersion = new StarboundVersion();
public static GeoIPCountry Geo;
public static int parentProcessId;
public static string authCode;
// Dictionary<string, ClientThread>
// string Username Unique username for client, MUST be exactcase
// ClientThread ClientThread Invidivual thread for client, used to access client specific functions
private static Dictionary<string, Client> clients = new Dictionary<string, Client>();
private static Dictionary<uint, Client> clientsById = new Dictionary<uint, Client>();
public static int clientCount { get { return clients.Count; } set { return; } }
public static Dictionary<string, Group> groups = new Dictionary<string, Group>();
public static ServerThread sbServer;
public static ListenerThread listener;
static Thread sbServerThread;
static Thread listenerThread;
static Thread udpThread;
static Thread monitorThread;
public static string privatePassword;
public static int failedConnections;
private static ServerState aServerState;
public static ServerState serverState { get { return aServerState; } set { return; } }
public static int startTime;
public static int restartTime = 0;
private static bool shuttingDown = false;
public static string defaultGroup = null;
public static string motdData = "";
public static string rulesData = "";
public static List<byte[]> sectors = new List<byte[]>();
public static WorldCoordinate spawnPlanet;
public static List<string> logWriteBuffer = new List<string>();
public static bool IsMono
{
get { return (Type.GetType("Mono.Runtime") != null); }
}
static void ProcessExit(object sender, EventArgs e)
{
logDebug("ProcessExit", "Hello");
doShutdown(true);
logDebug("ProcessExit", "Goodbye");
}
static void UnhandledException(object sender, UnhandledExceptionEventArgs args)
{
logDebug("UnhandledException", "Hello");
Exception e = (Exception)args.ExceptionObject;
try
{
logFatal("Unhandled Exception Occurred: " + e.ToString());
doShutdown(true);
Environment.Exit(1);
}
catch (Exception ex)
{
Console.WriteLine("[FATAL ERROR] Unhandled Exception Occurred: " + e.ToString());
Console.WriteLine("[EXCEPTION] Unhandled Exception Handler Failed: " + ex.ToString());
}
logDebug("UnhandledException", "Goodbye");
}
internal static bool ConsoleCtrlCheck()
{
logDebug("ConsoleCtrlCheck", "Hello");
doShutdown(true);
logDebug("ConsoleCtrlCheck", "Goodbye");
Environment.Exit(0);
return true;
}
static void Main(string[] args)
{
#if DEBUG
config.logLevel = LogType.Debug;
#endif
startTime = Utils.getTimestamp();
changeState(ServerState.Starting, "StarryboundServer::Main");
Console.Title = "Loading... Starrybound Server (" + VersionNum + ") (" + ProtocolVersion + ")";
try
{
int processId = Convert.ToInt32(File.ReadAllText("starbound_server.pid"));
Process proc = Process.GetProcessById(processId);
proc.Kill();
File.Delete("starbound_server.pid");
}
catch (Exception) { }
monitorThread = new Thread(new ThreadStart(crashMonitor));
monitorThread.Start();
if (IsMono)
Environment.CurrentDirectory = Path.GetDirectoryName(typeof(StarryboundServer).Assembly.Location);
AppDomain.CurrentDomain.ProcessExit += new EventHandler(ProcessExit);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException);
if (!IsMono)
NativeMethods.SetConsoleCtrlHandler(new NativeMethods.HandlerRoutine(ConsoleCtrlCheck), true);
BootstrapConfig.SetupConfig();
writeLog("", LogType.FileOnly);
writeLog("-- Log Start: " + DateTime.Now + " --", LogType.FileOnly);
logInfo("##############################################");
logInfo("#### Avilance Ltd. Starrybound Server ####");
logInfo("#### Copyright (c) Avilance Ltd. 2013 ####");
logInfo("#### Licensed under the GPLv3 ####");
logInfo("##############################################");
logInfo("Version: " + VersionNum + " (" + ProtocolVersion + ")");
logInfo("Loading Starrybound Server...");
Config.SetupConfig();
ServerConfig.SetupConfig();
Groups.SetupGroups();
Users.SetupUsers();
#if !DEBUG
if (config.logLevel == LogType.Debug)
{
logWarn("The logLevel in your config is currently set to DEBUG. This **WILL** flood your console and log file, if you do not want this please edit your config logLevel to INFO");
logWarn("Launch will proceed in 5 seconds.");
System.Threading.Thread.Sleep(5000);
}
#endif
#if !NOSERVER
if(config.proxyPort == config.serverPort)
{
logFatal("You cannot have the serverPort and proxyPort on the same port!");
Thread.Sleep(5000);
Environment.Exit(3);
}
#endif
var geoippath = Path.Combine(SavePath, "GeoIP.dat");
if (config.enableGeoIP && File.Exists(geoippath))
Geo = new GeoIPCountry(geoippath);
foreach(string sector in config.sectors)
{
byte[] sectorBytes = Encoding.UTF8.GetBytes(sector);
byte[] buffer = new byte[sectorBytes.Length + 1];
buffer[0] = (byte)sectorBytes.Length;
Buffer.BlockCopy(sectorBytes, 0, buffer, 1, sectorBytes.Length);
sectors.Add(sectorBytes);
}
Bans.ProcessBans();
logInfo("Starrybound Server initialization complete.");
listener = new ListenerThread();
listenerThread = new Thread(new ThreadStart(listener.runTcp));
listenerThread.Start();
udpThread = new Thread(new ThreadStart(listener.runUdp));
udpThread.Start();
while (serverState != ServerState.ListenerReady) { }
if ((int)serverState > 3) return;
Console.Title = "Starting... Starrybound Server (" + VersionNum + ") (" + ProtocolVersion + ")";
#if !NOSERVER
logInfo("Starting parent Starbound server - This may take a few moments...");
sbServer = new ServerThread();
sbServerThread = new Thread(new ThreadStart(sbServer.run));
sbServerThread.Start();
while (serverState != ServerState.StarboundReady) { }
if ((int)serverState > 3) return;
#endif
logInfo("Parent Starbound server is ready. Starrybound Server now accepting connections.");
changeState(ServerState.Running, "StarryboundServer::Main");
}
private static void crashMonitor()
{
int lastCount = -1;
while (true)
{
if (lastCount != clientCount && serverState == ServerState.Running)
Console.Title = serverConfig.serverName + " (" + clientCount + "/" + config.maxClients + ") - Starrybound Server (" + VersionNum + ") (" + ProtocolVersion + ")";
if (logWriteBuffer.Count > 0)
{
try
{
using (StreamWriter w = File.AppendText(Path.Combine(SavePath, "log.txt")))
{
for (int i = 0; i < logWriteBuffer.Count; i++)
{
w.WriteLine(logWriteBuffer[i]);
logWriteBuffer.RemoveAt(i);
}
}
}
catch (Exception e)
{
if (config.logLevel == LogType.Debug) Console.WriteLine("[DEBUG] Logger Exception: " + e.ToString());
}
}
if (restartTime != 0)
{
int remaining = restartTime - Utils.getTimestamp();
if (remaining < 0)
doRestart();
else if ((remaining % 5 == 0 || remaining < 5) && remaining != 0)
{
logWarn("The server will restart in " + remaining + " seconds.");
sendGlobalMessage("^#f75d5d;The server will restart in " + remaining + " seconds.");
}
}
if (serverState == ServerState.Crashed)
{
logFatal("The server has encountered a fatal error and cannot continue. Restarting in 5 seconds.");
Thread.Sleep(5000);
doRestart();
return;
}
else if(serverState == ServerState.Shutdown)
{
logFatal("OS, or Unhandled Exception requested immediate shutdown.");
doShutdown(true);
Environment.Exit(0);
}
else if(serverState == ServerState.GracefulShutdown)
{
logWarn("User or Console requested graceful shutdown.");
doShutdown(false);
Environment.Exit(0);
}
if (restartTime != 0)
Thread.Sleep(1000);
else
Thread.Sleep(2000);
}
}
public static void changeState(ServerState aState, string caller, string reason = "Not Specified")
{
string format = "StateChange requested by {0} to {1}: {2}";
switch (aState)
{
case ServerState.Crashed:
logWarn(string.Format(format, caller, aState, reason));
break;
case ServerState.GracefulShutdown:
logWarn(string.Format(format, caller, aState, reason));
break;
default:
logDebug("StarryboundServer::changeState", string.Format(format, caller, aState, reason));
break;
}
aServerState = aState;
}
private static void doRestart()
{
doShutdown(false);
if (!config.attemptAutoRestart) Environment.Exit(0);
logInfo("Now restarting...");
Thread.Sleep(2500);
if (serverState == ServerState.Shutdown || serverState == ServerState.GracefulShutdown)
{
logWarn("Something requested shutdown while restarting. Exiting.");
Environment.Exit(1);
}
try
{
Process.Start(Assembly.GetEntryAssembly().Location);
}
catch (Exception e)
{
if (IsMono) logWarn("Auto Restarter was unable to complete successfully via this version of Mono. Exception: " + e.ToString());
else logWarn("Auto Restarter encountered an error while attempting to restart. Exception: " + e.ToString());
}
Environment.Exit(0);
}
private static void doShutdown(bool quick)
{
if (shuttingDown) return;
shuttingDown = true;
Console.Title = "Shutting Down... Starrybound Server (" + VersionNum + ") (" + ProtocolVersion + ")";
logInfo("Starting graceful shutdown...");
try
{
try { Geo.Dispose(); }
catch (Exception) { }
try
{
if (!quick)
{
logDebug("Shutdown", "Disconnect all clients.");
foreach (Client client in clients.Values.ToList())
{
client.delayDisconnect("You have been disconnected. The server is being shut down.");
}
logInfo("Waiting 10 seconds for all clients to leave.");
int startWait = Utils.getTimestamp();
while (clientCount > 0)
{
if (Utils.getTimestamp() > startWait + 10)
{
logDebug("Shutdown", "Forcefully disconnecting all clients. Timeout exceeded.");
foreach (Client client in clients.Values.ToList())
{
client.closeConnection();
}
break;
}
Thread.Sleep(500);
}
}
else
{
logDebug("Shutdown", "Quick, Disconnect all clients.");
foreach (Client client in clients.Values.ToList())
{
client.closeConnection();
}
}
}
catch (Exception) { }
logDebug("Shutdown", "Requesting starbound_server close.");
try { sbServer.process.CloseMainWindow(); }
catch (Exception) { }
logDebug("Shutdown", "Waiting for starbound_server to close.");
Thread.Sleep(2000);
logDebug("Shutdown", "Aborting server thread.");
try { sbServerThread.Abort(); }
catch (Exception) { }
logDebug("Shutdown", "Killing starbound_server process.");
try
{
Process proc = Process.GetProcessById(parentProcessId);
proc.Kill();
File.Delete("starbound_server.pid");
}
catch (Exception) { }
logDebug("Shutdown", "Aborting TCP listener.");
try
{
lock (listener.tcpSocket)
{
listener.tcpSocket.Stop();
}
lock (listener.udpSocket)
{
listener.udpSocket.Close();
listenerThread.Abort();
}
}
catch (Exception) { }
logInfo("Graceful shutdown complete.");
logDebug("Shutdown", "Flushing all pending log data to file (If any)");
using (StreamWriter w = File.AppendText(Path.Combine(SavePath, "log.txt")))
{
for (int i = 0; i < logWriteBuffer.Count; i++)
{
w.WriteLine(logWriteBuffer[i]);
logWriteBuffer.RemoveAt(i);
}
}
}
catch(Exception e)
{
try
{
logException("Graceful shutdown failed: " + e.ToString());
Process proc = Process.GetProcessById(parentProcessId);
proc.Kill();
File.Delete("starbound_server.pid");
}
catch (Exception) { }
}
logDebug("Shutdown", "Goodbye.");
}
public static void logDebug(string source, string message) { writeLog("[" + source + "]:" + message, LogType.Debug); }
public static void logInfo(string message) { writeLog(message, LogType.Info); }
public static void logWarn(string message) { writeLog(message, LogType.Warn); }
public static void logError(string message) { writeLog(message, LogType.Error); }
public static void logException(string message) { writeLog(message, LogType.Exception); }
public static void logFatal(string message) { writeLog(message, LogType.Fatal); }
public static void writeLog(string message, LogType logType)
{
if ((int)config.logLevel > (int)logType && logType != LogType.FileOnly) return;
switch (logType)
{
case LogType.Debug:
message = "[DEBUG] " + message;
break;
case LogType.Info:
message = "[INFO] " + message;
break;
case LogType.Warn:
message = "[WARN] " + message;
break;
case LogType.Error:
message = "[ERROR] " + message;
break;
case LogType.Exception:
message = "[EXCEPTION] " + message;
break;
case LogType.Fatal:
message = "[FATAL ERROR] " + message;
break;
}
logWriteBuffer.Add(message);
if ((int)logType >= (int)config.logLevel) Console.WriteLine(message);
}
public struct StarboundVersion
{
public int Protocol;
public int Minor;
public string Name;
}
public static void sendGlobalMessage(string message)
{
sendGlobalMessage(message, "#5dc4f4");
}
public static void sendGlobalMessage(string message, string color)
{
Task sendMessages = Task.Factory.StartNew(() =>
{
var buffer = clients.Values.ToList();
foreach (Client client in buffer)
{
client.sendChatMessage("^" + color + ";" + message);
}
});
}
public static List<Client> getClients()
{
List<Client> result = new List<Client>();
foreach(Client client in clients.Values.ToList())
{
result.Add(client);
}
return result;
}
public static List<Client> getClients(string groupName)
{
List<Client> result = new List<Client>();
foreach (Client client in clients.Values.ToList())
{
if (client.playerData.group.name.Equals(groupName)) result.Add(client);
}
return result;
}
public static Client getClient(string name)
{
Client result;
if (clients.TryGetValue(name, out result))
return result;
else
return null;
}
public static Client getClient(uint id)
{
Client result;
if (clientsById.TryGetValue(id, out result))
return result;
else
return null;
}
public static void addClient(Client client)
{
clients.Add(client.playerData.name, client);
clientsById.Add(client.playerData.id, client);
}
public static void removeClient(Client client)
{
clients.Remove(client.playerData.name);
clientsById.Remove(client.playerData.id);
}
}
}