forked from TehGimp/KerbalMultiPlayer
/
Server.cs
3883 lines (3420 loc) · 171 KB
/
Server.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
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//#define DEBUG_OUT
//#define SEND_UPDATES_TO_SENDER
using KMP;
using MySql.Data.MySqlClient;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace KMPServer
{
internal class Server
{
public struct ClientMessage
{
public Client client;
public KMPCommon.ClientMessageID id;
public byte[] data;
}
#region Singletons
private DatabaseHelper _helperSingleton = null;
#endregion
public const long CLIENT_TIMEOUT_DELAY = 16000;
public const long CLIENT_HANDSHAKE_TIMEOUT_DELAY = 6000;
public const int GHOST_CHECK_DELAY = 30000;
public const int SLEEP_TIME = 10;
public const int MAX_SCREENSHOT_COUNT = 10000;
public const int UDP_ACK_THROTTLE = 1000;
public const int MESSAGE_HANDLE_TIMEOUT = 500; //Allow a maximum of 0.5 seconds of server lag, then lets try to handle server lag.
public const float NOT_IN_FLIGHT_UPDATE_WEIGHT = 1.0f / 4.0f;
public const int ACTIVITY_RESET_DELAY = 10000;
public const String SCREENSHOT_DIR = "KMPScreenshots";
// No longer valid as Database Helper takes care of this -NC
// public const string DB_FILE_CONN = "Data Source=KMP_universe.db";
public const string DB_FILE = "KMP_universe.db";
public const string MOD_CONTROL_FILE = "KMPModControl.txt";
public const string MODS_PATH = "Mods";
public const string PLUGIN_DATA_DIRECTORY = "KMP/Plugins/PluginData/KerbalMultiPlayer/";
public const string CLIENT_CONFIG_FILENAME = "KMPClientConfig.xml";
public const string CLIENT_TOKEN_FILENAME = "KMPPlayerToken.txt";
public const string MOD_CONTROL_FILENAME = "KMPModControl.txt";
public const String GLOBAL_SETTINGS_FILENAME = "globalsettings.txt";
public static byte[] kmpModControl;
public const int UNIVERSE_VERSION = 6;
public bool quit = false;
public bool stop = false;
public String threadExceptionStackTrace;
public Exception threadException;
public object threadExceptionLock = new object();
public static object consoleWriteLock = new object();
public static object databaseVacuumLock = new object();
public Thread listenThread;
public Thread commandThread;
public Thread connectionThread;
public Thread outgoingMessageThread;
public Thread ghostCheckThread;
public Timer autoDekesslerTimer;
public TcpListener tcpListener;
public UdpClient udpClient;
public HttpListener httpListener;
public SynchronizedCollection<Client> clients;
public SynchronizedCollection<Client> flight_clients;
public SynchronizedCollection<Client> cleanupClients;
public ConcurrentQueue<ClientMessage> clientMessageQueue;
public int clientIndex = 0;
public ServerSettings.ConfigStore settings;
public Stopwatch stopwatch = new Stopwatch();
// BOOM! TODO: Remove all this commented code. Just leaving here for first commit to show when it was removed
// public static DatabaseHelper universeDB;
private bool backedUpSinceEmpty = false;
private Dictionary<Guid, long> recentlyDestroyed = new Dictionary<Guid, long>();
private Dictionary<int, double> subSpaceMasterTick = new Dictionary<int, double>();
private Dictionary<int, long> subSpaceMasterTime = new Dictionary<int, long>();
private Dictionary<int, float> subSpaceMasterSpeed = new Dictionary<int, float>();
private Dictionary<int, long> subSpaceLastRateCheck = new Dictionary<int, long>();
private Boolean bHandleCommandsRunning = true;
private int uncleanedBackups = 0;
/// <summary>
/// Database Helper Instance
/// </summary>
private DatabaseHelper Database
{
get
{
return _helperSingleton = _helperSingleton ?? (settings.useMySQL ?
DatabaseHelper.CreateForMySQL(settings.mySQLConnString) :
DatabaseHelper.CreateForSQLite(DB_FILE));
}
}
public long currentMillisecond
{
get
{
return stopwatch.ElapsedMilliseconds;
}
}
public int updateInterval
{
get
{
float relevant_player_count = 0;
//Create a weighted count of clients in-flight and not in-flight to estimate the amount of update traffic
relevant_player_count = flight_clients.Count + (activeClientCount() - flight_clients.Count) * NOT_IN_FLIGHT_UPDATE_WEIGHT;
if (relevant_player_count <= 0)
return ServerSettings.MIN_UPDATE_INTERVAL;
//Calculate the value that satisfies updates per second
int val = (int)Math.Round(1.0f / (settings.updatesPerSecond / relevant_player_count) * 1000);
//Bound the values by the minimum and maximum
if (val < ServerSettings.MIN_UPDATE_INTERVAL)
return ServerSettings.MIN_UPDATE_INTERVAL;
if (val > ServerSettings.MAX_UPDATE_INTERVAL)
return ServerSettings.MAX_UPDATE_INTERVAL;
return val;
}
}
public byte inactiveShipsPerClient
{
get
{
int relevant_player_count = 0;
relevant_player_count = flight_clients.Count;
if (relevant_player_count <= 0)
return settings.totalInactiveShips;
if (relevant_player_count > settings.totalInactiveShips)
return 0;
return (byte)(settings.totalInactiveShips / relevant_player_count);
}
}
//Methods
public Server(ServerSettings.ConfigStore settings)
{
this.settings = settings;
}
public void clearState()
{
safeAbort(listenThread);
safeAbort(commandThread);
safeAbort(connectionThread);
safeAbort(outgoingMessageThread);
safeAbort(ghostCheckThread);
if (clients != null)
{
foreach (Client client in clients.ToList())
{
client.endReceivingMessages();
if (client.tcpClient != null)
client.tcpClient.Close();
}
}
if (tcpListener != null)
{
try
{
tcpListener.Stop();
}
catch (System.Net.Sockets.SocketException)
{
}
}
if (httpListener != null)
{
try
{
httpListener.Stop();
httpListener.Close();
}
catch (ObjectDisposedException)
{
}
}
if (udpClient != null)
{
try
{
udpClient.Close();
}
catch { }
}
udpClient = null;
BackupDatabase();
}
private static List<string> generatePartsList()
{
List<string> partList = new List<string>();
//0.21 (& below) parts
partList.Add("StandardCtrlSrf"); partList.Add("CanardController"); partList.Add("noseCone"); partList.Add("AdvancedCanard"); partList.Add("airplaneTail");
partList.Add("deltaWing"); partList.Add("noseConeAdapter"); partList.Add("rocketNoseCone"); partList.Add("smallCtrlSrf"); partList.Add("standardNoseCone");
partList.Add("sweptWing"); partList.Add("tailfin"); partList.Add("wingConnector"); partList.Add("winglet"); partList.Add("R8winglet");
partList.Add("winglet3"); partList.Add("Mark1Cockpit"); partList.Add("Mark2Cockpit"); partList.Add("Mark1-2Pod"); partList.Add("advSasModule");
partList.Add("asasmodule1-2"); partList.Add("avionicsNoseCone"); partList.Add("crewCabin"); partList.Add("cupola"); partList.Add("landerCabinSmall");
partList.Add("mark3Cockpit"); partList.Add("mk1pod"); partList.Add("mk2LanderCabin"); partList.Add("probeCoreCube"); partList.Add("probeCoreHex");
partList.Add("probeCoreOcto"); partList.Add("probeCoreOcto2"); partList.Add("probeCoreSphere"); partList.Add("probeStackLarge"); partList.Add("probeStackSmall");
partList.Add("sasModule"); partList.Add("seatExternalCmd"); partList.Add("rtg"); partList.Add("batteryBank"); partList.Add("batteryBankLarge");
partList.Add("batteryBankMini"); partList.Add("batteryPack"); partList.Add("ksp.r.largeBatteryPack"); partList.Add("largeSolarPanel"); partList.Add("solarPanels1");
partList.Add("solarPanels2"); partList.Add("solarPanels3"); partList.Add("solarPanels4"); partList.Add("solarPanels5"); partList.Add("JetEngine");
partList.Add("engineLargeSkipper"); partList.Add("ionEngine"); partList.Add("liquidEngine"); partList.Add("liquidEngine1-2"); partList.Add("liquidEngine2");
partList.Add("liquidEngine2-2"); partList.Add("liquidEngine3"); partList.Add("liquidEngineMini"); partList.Add("microEngine"); partList.Add("nuclearEngine");
partList.Add("radialEngineMini"); partList.Add("radialLiquidEngine1-2"); partList.Add("sepMotor1"); partList.Add("smallRadialEngine"); partList.Add("solidBooster");
partList.Add("solidBooster1-1"); partList.Add("toroidalAerospike"); partList.Add("turboFanEngine"); partList.Add("MK1Fuselage"); partList.Add("Mk1FuselageStructural");
partList.Add("RCSFuelTank"); partList.Add("RCSTank1-2"); partList.Add("rcsTankMini"); partList.Add("rcsTankRadialLong"); partList.Add("fuelTank");
partList.Add("fuelTank1-2"); partList.Add("fuelTank2-2"); partList.Add("fuelTank3-2"); partList.Add("fuelTank4-2"); partList.Add("fuelTankSmall");
partList.Add("fuelTankSmallFlat"); partList.Add("fuelTank.long"); partList.Add("miniFuelTank"); partList.Add("mk2Fuselage"); partList.Add("mk2SpacePlaneAdapter");
partList.Add("mk3Fuselage"); partList.Add("mk3spacePlaneAdapter"); partList.Add("radialRCSTank"); partList.Add("toroidalFuelTank"); partList.Add("xenonTank");
partList.Add("xenonTankRadial"); partList.Add("adapterLargeSmallBi"); partList.Add("adapterLargeSmallQuad"); partList.Add("adapterLargeSmallTri"); partList.Add("adapterSmallMiniShort");
partList.Add("adapterSmallMiniTall"); partList.Add("nacelleBody"); partList.Add("radialEngineBody"); partList.Add("smallHardpoint"); partList.Add("stationHub");
partList.Add("structuralIBeam1"); partList.Add("structuralIBeam2"); partList.Add("structuralIBeam3"); partList.Add("structuralMiniNode"); partList.Add("structuralPanel1");
partList.Add("structuralPanel2"); partList.Add("structuralPylon"); partList.Add("structuralWing"); partList.Add("strutConnector"); partList.Add("strutCube");
partList.Add("strutOcto"); partList.Add("trussAdapter"); partList.Add("trussPiece1x"); partList.Add("trussPiece3x"); partList.Add("CircularIntake");
partList.Add("landingLeg1"); partList.Add("landingLeg1-2"); partList.Add("RCSBlock"); partList.Add("stackDecoupler"); partList.Add("airScoop");
partList.Add("commDish"); partList.Add("decoupler1-2"); partList.Add("dockingPort1"); partList.Add("dockingPort2"); partList.Add("dockingPort3");
partList.Add("dockingPortLarge"); partList.Add("dockingPortLateral"); partList.Add("fuelLine"); partList.Add("ladder1"); partList.Add("largeAdapter");
partList.Add("largeAdapter2"); partList.Add("launchClamp1"); partList.Add("linearRcs"); partList.Add("longAntenna"); partList.Add("miniLandingLeg");
partList.Add("parachuteDrogue"); partList.Add("parachuteLarge"); partList.Add("parachuteRadial"); partList.Add("parachuteSingle"); partList.Add("radialDecoupler");
partList.Add("radialDecoupler1-2"); partList.Add("radialDecoupler2"); partList.Add("ramAirIntake"); partList.Add("roverBody"); partList.Add("sensorAccelerometer");
partList.Add("sensorBarometer"); partList.Add("sensorGravimeter"); partList.Add("sensorThermometer"); partList.Add("spotLight1"); partList.Add("spotLight2");
partList.Add("stackBiCoupler"); partList.Add("stackDecouplerMini"); partList.Add("stackPoint1"); partList.Add("stackQuadCoupler"); partList.Add("stackSeparator");
partList.Add("stackSeparatorBig"); partList.Add("stackSeparatorMini"); partList.Add("stackTriCoupler"); partList.Add("telescopicLadder"); partList.Add("telescopicLadderBay");
partList.Add("SmallGearBay"); partList.Add("roverWheel1"); partList.Add("roverWheel2"); partList.Add("roverWheel3"); partList.Add("wheelMed"); partList.Add("flag");
partList.Add("kerbalEVA");
//0.22 parts
partList.Add("mediumDishAntenna"); partList.Add("GooExperiment"); partList.Add("science.module");
//0.23 parts
partList.Add("RAPIER"); partList.Add("Large.Crewed.Lab");
//0.23.5 parts
partList.Add("GrapplingDevice"); partList.Add("LaunchEscapeSystem"); partList.Add("MassiveBooster"); partList.Add("PotatoRoid"); partList.Add("Size2LFB");
partList.Add("Size3AdvancedEngine"); partList.Add("size3Decoupler"); partList.Add("Size3EngineCluster"); partList.Add("Size3LargeTank"); partList.Add("Size3MediumTank");
partList.Add("Size3SmallTank"); partList.Add("Size3to2Adapter");
return partList;
//foreach(string part in partList) writer.WriteLine(part);
}
private static void readModControl()
{
try
{
Log.Info("Reading {0}", MOD_CONTROL_FILE);
kmpModControl = File.ReadAllBytes(MOD_CONTROL_FILE);
Log.Info("Mod control reloaded.");
}
catch
{
Log.Info(MOD_CONTROL_FILE + " not found, generating...");
//Generate a default blacklist no-sha file.
writeModControl(true, false);
}
}
public static string ModFilesToListing(string mode, bool sha)
{
string result = "";
if (mode == "required" || mode == "optional")
{
string[] lsDirectory = Directory.GetDirectories(MODS_PATH);
foreach (string modDirectory in lsDirectory)
{
string modType = "optional";
string[] lsFiles = Directory.GetFiles(modDirectory, "*", SearchOption.AllDirectories);
List<string> dllFiles = new List<string>();
foreach (string modFile in lsFiles)
{
//Remove the Mods/ part, Change path seperators to the unix ones.
string trimmedModFile = modFile.Remove(0, MODS_PATH.Length + 1);
if (!trimmedModFile.ToLowerInvariant().StartsWith("squad") && !trimmedModFile.ToLowerInvariant().StartsWith("nasamission") && !trimmedModFile.ToLowerInvariant().StartsWith("kmp") && !trimmedModFile.ToLowerInvariant().StartsWith("000_toolbar"))
if (trimmedModFile.ToLowerInvariant().EndsWith(".cfg"))
{
using (StreamReader sr = new StreamReader(modFile))
{
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("PART"))
{
modType = "required";
}
}
}
}
if (trimmedModFile.ToLowerInvariant().EndsWith(".dll"))
{
dllFiles.Add(modFile);
}
}
if (modType == mode)
{
foreach (string dllFile in dllFiles)
{
//Remove the Mods/ part, Change path seperators to the unix ones.
string trimmedDllFile = dllFile.Remove(0, MODS_PATH.Length + 1).Replace("\\", "/");
Log.Info("Adding " + trimmedDllFile + " into the " + modType + " section.");
result += trimmedDllFile;
//We shouldn't ever care what version of non-part-adding mods the client has.
if (sha && modType == "required")
{
using (SHA256Managed shaManager = new SHA256Managed())
{
using (FileStream stream = File.OpenRead(dllFile))
{
byte[] hash = shaManager.ComputeHash(stream);
result += "=" + BitConverter.ToString(hash).Replace("-", String.Empty);
}
}
}
result += "\n";
}
}
}
}
if (mode == "resource-whitelist")
{
string[] lsFiles = Directory.GetFiles(MODS_PATH, "*", SearchOption.AllDirectories);
foreach (string modFile in lsFiles)
{
string trimmedModFile = modFile.Remove(0, MODS_PATH.Length + 1).Replace("\\", "/");
if (!trimmedModFile.ToLowerInvariant().StartsWith("squad") && !trimmedModFile.ToLowerInvariant().StartsWith("nasamission") && !trimmedModFile.ToLowerInvariant().StartsWith("kmp") && !trimmedModFile.ToLowerInvariant().StartsWith("000_toolbar") && trimmedModFile.ToLowerInvariant().EndsWith(".dll"))
{
result += modFile.Remove(0, MODS_PATH.Length + 1).Replace("\\", "/") + "\n"; //Remove the starting parth and add it to the list.
}
}
}
return result;
}
public static void writeModControlCommand(string[] input)
{
string[] commandParts = new string[0];
if (input.Length == 2)
{
commandParts = input[1].Split(new char[] { ' ' });
}
bool blacklist = true;
bool sha = false;
//This allows a user to type the modgen parameters in any order.
foreach (string part in commandParts)
{
if (part.ToLowerInvariant() == "whitelist")
{
blacklist = false;
}
if (part.ToLowerInvariant() == "sha")
{
sha = true;
}
}
writeModControl(blacklist, sha);
}
public static void writeModControl(bool blacklist, bool sha)
{
bool autoAdd = Directory.GetDirectories(MODS_PATH).Count() > 0;
if (!autoAdd)
{
Log.Info("To generate an automatic KMPModControl.txt file, Copy mods from the GameData directory to the '" + MODS_PATH + "' folder.");
}
string filestring = "\n" +
"#You can comment by starting a line with a #, these are ignored by the server.\n" +
"#Commenting will NOT work unless the line STARTS with a '#'.\n" +
"#You can also indent the file with tabs or spaces.\n" +
"#Sections supported are required-files, optional-files, partslist, resource-blacklist and resource-whitelist.\n" +
"#The client will be required to have the files found in required-files, and they must match the SHA hash if specified (this is where part mod files and play-altering files should go, like KWRocketry or Ferram Aerospace Research" +
"#The client may have the files found in optional-files, but IF they do then they must match the SHA hash (this is where mods that do not affect other players should go, like EditorExtensions or part catalogue managers\n" +
"#You cannot use both resource-blacklist AND resource-whitelist in the same file.\n" +
"#resource-blacklist bans ONLY the files you specify\n" +
"#resource-whitelist bans ALL resources except those specified in the resource-whitelist section OR in the SHA sections. A file listed in resource-whitelist will NOT be checked for SHA hash. This is useful if you want a mod that modifies files in its own directory as you play.\n" +
"#Each section has its own type of formatting. Examples have been given.\n" +
"#Sections are defined as follows:\n" +
"\n" +
"\n" +
"!required-files" +
"\n" +
"#To generate the SHA256 of a file you can use a utility such as this one: http://hash.online-convert.com/sha256-generator (use the 'hex' string), or use sha256sum on linux.\n" +
"#File paths are read from inside GameData.\n" +
"#If there is no SHA256 hash listed here (i.e. blank after the equals sign or no equals sign), SHA matching will not be enforced.\n" +
"#You may not specify multiple SHAs for the same file. Do not put spaces around equals sign. Follow the example carefully.\n" +
"#Syntax:\n" +
"#[File Path]=[SHA] or [File Path]\n" +
"#Example: MechJeb2/Plugins/MechJeb2.dll=B84BB63AE740F0A25DA047E5EDA35B26F6FD5DF019696AC9D6AF8FC3E031F0B9\n" +
"#Example: MechJeb2/Plugins/MechJeb2.dll\n\n";
if (autoAdd)
{
Log.Info("Beginning SHA256 hash of required mod files...");
// add mods that user must have, but don't have to match SHA hash
filestring += ModFilesToListing("required", sha);
}
filestring += "\n\n!optional-files\n" +
"#Formatting for this section is the same as the 'required-files' section\n\n";
if (autoAdd)
{
Log.Info("Beginning SHA256 hash of optional mod files...");
filestring += ModFilesToListing("optional", sha);
}
if (blacklist)
{
filestring += "\n\n!resource-blacklist\n#!resource-whitelist\n\n";
filestring += "#Alternatively, change 'blacklist' to 'whitelist' and clients will only be allowed to use dll's listed here or in the 'required-files' and 'optional-files' sections.\n";
}
else
{
filestring += "\n\n!resource-whitelist\n#!resource-blacklist\n\n";
filestring += "#Alternatively, change 'whitelist' to 'blacklist' and clients will not be allowed to use dll's listed here.\n";
}
filestring += "#You can ban specific files in resource-blacklist mode, or only allow specific files in resource-whitelist mode.\n" +
"#Syntax:\n" +
"#[File Path]\n" +
"#Example: MechJeb2/Plugins/MechJeb2.dll\n\n";
//We don't need to write any files here in blacklist mode.
if (autoAdd && !blacklist)
{
filestring += ModFilesToListing("resource-whitelist", sha);
}
filestring += "\n\n" +
"!partslist\n" +
"#This is a list of parts to allow users to put on their ships.\n" +
"#If a part the client has doesn't appear on this list, they can still join the server but not use the part.\n" +
"#The default stock parts have been added already for you.\n" +
"#To add a mod part, add the name from the part's .cfg file. The name is the name from the PART{} section, where underscores are replaced with periods.\n" +
"#[partname]\n" +
"#Example: mumech.MJ2.Pod (NOTE: In the part.cfg this MechJeb2 pod is named mumech_MJ2_Pod. The _ have been replaced with .)\n" +
"#You can use this application to generate partlists from a KSP installation if you want to add mod parts: http://forum.kerbalspaceprogram.com/threads/57284 \n" +
"\n";
List<string> parts = new List<string>();
parts = generatePartsList();
if (autoAdd) // add a part list for all part in the Required and Optional folders
{
string[] ls = Directory.GetFiles(MODS_PATH, "*", SearchOption.AllDirectories);
ls = ls.Distinct().ToArray();
char[] toperiod = { '_' };
foreach (string file in ls)
{
//We add Squad files manually in generatePartsList above.
if (!file.ToLowerInvariant().StartsWith("squad") && !file.ToLowerInvariant().StartsWith("nasamission") && file.Substring(file.Length - 4).Equals(".cfg", StringComparison.InvariantCultureIgnoreCase)) // check if config file (only place where parts are located)
{
using (StreamReader sr = new StreamReader(file))
{
bool newPart = false;
while (!sr.EndOfStream)
{
string word = str_nextword(sr);
if (word == "PART")
{
newPart = true;
}
else if (word.Equals("name", StringComparison.InvariantCultureIgnoreCase) && str_nextword(sr).Equals("=", StringComparison.InvariantCultureIgnoreCase) && newPart)
{
string line = sr.ReadLine();
line.Trim(); // remove whitespace from part name
string[] temp = line.Split(toperiod, StringSplitOptions.RemoveEmptyEntries); // convert spaces and underscores to periods
line = String.Join(".", temp);
parts.Add(line);
newPart = false;
}
}
}
}
}
parts = parts.Distinct().ToList();
}
foreach (string part in parts)
{
filestring += part + "\n";
}
File.WriteAllText(MOD_CONTROL_FILE, filestring);
Log.Info("New {0} file written.", MOD_CONTROL_FILE);
readModControl();
}
private static string str_nextword(StreamReader file)
{
char[] wordBoundaries = { '\n', ' ', '\t', '\r' };
string output = "";
bool started = false;
while (!file.EndOfStream)
{
char c = (char)file.Read();
if (wordBoundaries.Contains(c))
{
if (!started)
{
continue;
}
else
{
break;
}
}
else
{
started = true;
output += c;
}
}
return output;
}
public void saveScreenshot(byte[] bytes, String player)
{
if (!Directory.Exists(SCREENSHOT_DIR))
{
//Create the screenshot directory
try
{
if (!Directory.CreateDirectory(SCREENSHOT_DIR).Exists)
return;
}
catch (Exception)
{
return;
}
}
//Write the screenshot to file
String filename = string.Format("{0}/{1} {2}.png", SCREENSHOT_DIR, KMPCommon.filteredFileName(player), System.DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"));
if (!File.Exists(filename))
{
try
{
//Read description length
int description_length = KMPCommon.intFromBytes(bytes, 0);
//Trim the description bytes from the image
byte[] trimmed_bytes = new byte[bytes.Length - 4 - description_length];
Array.Copy(bytes, 4 + description_length, trimmed_bytes, 0, trimmed_bytes.Length);
File.WriteAllBytes(filename, trimmed_bytes);
}
catch (Exception)
{
}
}
}
private void safeAbort(Thread thread, bool join = false)
{
if (thread != null)
{
try
{
thread.Abort();
if (join)
thread.Join();
}
catch (ThreadStateException) { }
catch (ThreadInterruptedException) { }
}
}
public void passExceptionToMain(Exception e)
{
lock (threadExceptionLock)
{
if (threadException == null)
threadException = e; //Pass exception to main thread
}
}
//Threads
public void hostingLoop()
{
clearState();
try
{
startDatabase();
//Start hosting server
stopwatch.Start();
//read info for server sided mod support
readModControl();
Log.Info("Hosting server on port {0} ...", settings.port);
clients = new SynchronizedCollection<Client>(settings.maxClients);
flight_clients = new SynchronizedCollection<Client>(settings.maxClients);
cleanupClients = new SynchronizedCollection<Client>(settings.maxClients);
clientMessageQueue = new ConcurrentQueue<ClientMessage>();
listenThread = new Thread(new ThreadStart(listenForClients));
commandThread = new Thread(new ThreadStart(handleCommands));
connectionThread = new Thread(new ThreadStart(handleConnections));
outgoingMessageThread = new Thread(new ThreadStart(sendOutgoingMessages));
ghostCheckThread = new Thread(new ThreadStart(checkGhosts));
threadException = null;
if (settings.ipBinding == "0.0.0.0" && settings.hostIPv6 == true)
{
settings.ipBinding = "::";
}
tcpListener = new TcpListener(IPAddress.Parse(settings.ipBinding), settings.port);
if (settings.hostIPv6 == true)
{
try
{
//Windows defaults to v6 only, but this option does not exist in mono so it has to be in a try/catch block along with the casted int.
tcpListener.Server.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
}
catch
{
Log.Debug("Failed to unset IPv6Only. Linux and Mac have this option off by default.");
}
}
listenThread.Start();
try
{
udpClient = new UdpClient((IPEndPoint)tcpListener.LocalEndpoint);
udpClient.BeginReceive(asyncUDPReceive, null);
//udpClient.Client.AllowNatTraversal(1);
}
catch
{
udpClient = null;
}
displayCommands();
commandThread.Start();
connectionThread.Start();
outgoingMessageThread.Start();
ghostCheckThread.Start();
if (settings.autoDekessler)
{
autoDekesslerTimer = new Timer(_ => dekesslerServerCommand(new string[0]), null, settings.autoDekesslerTime * 60000, settings.autoDekesslerTime * 60000);
Log.Debug("Starting AutoDekessler: Timer Set to " + settings.autoDekesslerTime + " Minutes");
}
if (settings.httpBroadcast)
startHttpServer();
long last_backup_time = 0;
while (!stop)
{
//Check for exceptions that occur in threads
lock (threadExceptionLock)
{
if (threadException != null)
{
Exception e = threadException;
threadExceptionStackTrace = e.StackTrace;
throw e;
}
}
if (currentMillisecond - last_backup_time > (settings.backupInterval * 60000) && (activeClientCount() > 0 || !backedUpSinceEmpty))
{
if (activeClientCount() <= 0)
{
backedUpSinceEmpty = true;
if (settings.freezeTimeWhenServerIsEmpty)
{
subSpaceMasterTick.Clear();
subSpaceMasterTime.Clear();
subSpaceMasterSpeed.Clear();
}
CleanDatabase();
}
last_backup_time = currentMillisecond;
BackupDatabase();
}
Thread.Sleep(SLEEP_TIME);
}
clearState();
stopwatch.Stop();
Log.Info("Server session ended.");
if (quit) { Log.Info("Quitting"); Thread.Sleep(1000); Environment.Exit(0); }
}
catch (MySqlException e)
{
Log.Error("Fatal error accessing MySQL database, server session ended!");
Log.Error(e.Message);
Log.Debug(e.StackTrace);
}
catch (Exception e)
{
Log.Error("Fatal error, server session ended! Exception: {0}", e.Message);
Log.Debug(e.StackTrace);
}
}
private void startHttpServer()
{
//Begin listening for HTTP requests
httpListener = new HttpListener(); //Might need a replacement as HttpListener needs admin rights
try
{
httpListener.Prefixes.Add("http://*:" + settings.httpPort + '/');
httpListener.Start();
httpListener.BeginGetContext(asyncHTTPCallback, httpListener);
}
catch (Exception e)
{
Log.Error("Error starting http server: {0}", e);
Log.Error("Please try running the server as an administrator");
}
}
private void killHttpServer()
{
httpListener.Stop();
}
private void processCommand(String input)
{
Log.Info("Command Input: {0}", input);
try
{
String cleanInput = input.ToLower().Trim();
var rawParts = input.Split(new char[] { ' ' }, 2);
var parts = cleanInput.Split(new char[] { ' ' }, 2);
//if (!parts[0].StartsWith("/")) { return; } //Allow server to send chat messages
switch (parts[0])
{
case "/ban": banServerCommand(parts); break;
case "/clearclients": clearClientsServerCommand(); break;
case "/countclients": countServerCommand(); break;
case "/help": displayCommands(); break;
case "/kick": kickServerCommand(parts); break;
case "/listclients": listServerCommand(); break;
case "/quit":
case "/stop": quitServerCommand(parts); bHandleCommandsRunning = false; break;
case "/save": saveServerCommand(); break;
case "/register": registerServerCommand(parts); break;
case "/update": updateServerCommand(parts); break;
case "/unregister": unregisterServerCommand(parts); break;
case "/dekessler": dekesslerServerCommand(parts); break;
case "/countships": countShipsServerCommand(); break;
case "/listships": listShipsServerCommand(); break;
case "/lockship": lockShipServerCommand(parts); break;
case "/deleteship": deleteShipServerCommand(parts); break;
case "/reloadmodfile": reloadModFileServerCommand(); break;
case "/say": sayServerCommand(rawParts); break;
case "/motd": motdServerCommand(rawParts); break;
case "/rules": rulesServerCommand(rawParts); break;
case "/setinfo": serverInfoServerCommand(rawParts); break;
case "/modgen": writeModControlCommand(parts); break;
case "/dbdiag": Log.Info("[DBDIAG] {0}", Database); break;
default: Log.Info("Unknown Command: " + cleanInput); break;
}
}
catch (FormatException e)
{
Log.Error("Error handling server command. Maybe a typo? {0} {1}", e.Message, e.StackTrace);
}
catch (IndexOutOfRangeException)
{
Log.Error("Command found but missing elements.");
}
}
private void handleCommands()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
try
{
while (bHandleCommandsRunning)
{
String input = Console.ReadLine();
processCommand(input);
}
}
catch (ArgumentOutOfRangeException)
{
}
catch (ThreadAbortException)
{
}
catch (Exception e)
{
passExceptionToMain(e);
}
}
//Sends messages from Server
private void sayServerCommand(string[] parts)
{
if (parts.Length > 1)
{
if (parts[1].IndexOf("-u") == 0)
{
parts = parts[1].Split(new char[] { ' ' }, 3);
if (parts.Length > 2)
{
String sName = parts[1];
var clientToMessage = clients.Where(cl => cl.username.ToLower() == sName && cl.isReady).FirstOrDefault();
if (clientToMessage != null)
{
string message = parts[2];
sendServerMessage(clientToMessage, message);
}
else
Log.Info("Username " + sName + " not found.");
}
else
Log.Info("Error: -u flag found but missing message.");
}
else if (parts[1].IndexOf("-u") != -1)
{
Log.Info("Error: -u flag found but in wrong location.");
}
else
sendServerMessageToAll(parts[1]);
}
else
Log.Info("Error: /say command improperly formatted. Missing message. /say <-u username> [message]");
}
private void countShipsServerCommand(bool bList = false)
{
int count = 0;
Database.ExecuteReader("SELECT vu.UpdateMessage, v.ProtoVessel, v.Guid" +
" FROM kmpVesselUpdate vu" +
" INNER JOIN kmpVessel v ON v.Guid = vu.Guid AND v.Destroyed IS NULL" +
" INNER JOIN kmpSubspace s ON s.ID = vu.Subspace" +
" INNER JOIN" +
" (SELECT vu.Guid, MAX(s.LastTick) AS LastTick" +
" FROM kmpVesselUpdate vu" +
" INNER JOIN kmpSubspace s ON s.ID = vu.Subspace" +
" GROUP BY vu.Guid) t ON t.Guid = vu.Guid AND t.LastTick = s.LastTick;",
record =>
{
KMPVesselUpdate vessel_update = (KMPVesselUpdate)ByteArrayToObject(GetDataReaderBytes(record, 0));
if (bList)
Log.Info("Name: {0}\tID: {1}", vessel_update.name, vessel_update.kmpID);
count++;
});
if (count == 0)
Log.Info("No ships.");
else if (!bList)
Log.Info("Number of ships: {0}", count);
}
private int countShipsInDatabase()
{
int count = Convert.ToInt32(Database.ExecuteScalar("SELECT COUNT(*)" +
" FROM kmpVesselUpdate vu" +
" INNER JOIN kmpVessel v ON v.Guid = vu.Guid AND v.Destroyed IS NULL" +
" INNER JOIN kmpSubspace s ON s.ID = vu.Subspace" +
" INNER JOIN" +
" (SELECT vu.Guid, MAX(s.LastTick) AS LastTick" +
" FROM kmpVesselUpdate vu" +
" INNER JOIN kmpSubspace s ON s.ID = vu.Subspace" +
" GROUP BY vu.Guid) t ON t.Guid = vu.Guid AND t.LastTick = s.LastTick"));
return count; // TODO: @NeverCast, Give ExecuteScalar a generic overload
}
private void listShipsServerCommand()
{
countShipsServerCommand(true);
}
private void lockShipServerCommand(string[] parts)
{
String[] args = parts[1].Split(' ');
if (args.Length == 2)
{
try
{
Guid vesselGuid = new Guid(args[0]);
bool lockShip = Boolean.Parse(args[1].ToLower());
int rows = Database.ExecuteNonQuery("UPDATE kmpVessel" +
" SET Private = @private" +
" WHERE Guid = @guid",
"private", lockShip,
"guid", vesselGuid.ToByteArray());
if (rows != -1 && rows <= 1)
{
if (lockShip)
Log.Info("Vessel {0} is now private.", args[0]);
else
Log.Info("Vessel {0} is now public.", args[0]);
}
else
Log.Info("Vessel {0} not found.", args[0]);
}
catch (FormatException)
{
Log.Error("Supplied tokens are invalid. Use /listships to double check your ID.");
}
}
else
{
Log.Info("Could not parse lock ship command. Format is \"/lockship <vesselID> <true/false>\"");
}
}
private void deleteShipServerCommand(string[] parts)
{
try
{
Guid tokill = new Guid(parts[1]);
int rows = Database.ExecuteNonQuery("UPDATE kmpVessel SET Destroyed = 1 WHERE Guid = @guid;",
"guid", tokill.ToByteArray());
if (rows != -1 && rows != 0)
{
Log.Info("Vessel {0} marked for deletion.", parts[1]);
}
else
{
Log.Info("Vessel {0} not found.", parts[1]);
}
}
catch (FormatException)
{
Log.Info("Vessel ID invalid.");
}