-
Notifications
You must be signed in to change notification settings - Fork 53
/
KMPClientMain.cs
2586 lines (2253 loc) · 107 KB
/
KMPClientMain.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Security.Cryptography;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
using System.Collections;
using KSP.IO;
using UnityEngine;
using System.Xml;
namespace KMP
{
class KMPClientMain
{
public struct InTextMessage
{
public bool fromServer;
public bool isMOTD;
public String message;
}
public struct ServerMessage
{
public KMPCommon.ServerMessageID id;
public byte[] data;
}
//Constants
public const String USERNAME_LABEL = "username";
public const String IP_LABEL = "hostname";
public const String PORT_LABEL = "port";
public const String AUTO_RECONNECT_LABEL = "reconnect";
public const String FAVORITE_LABEL = "pos";
public const String NAME_LABEL = "name";
//public const String INTEROP_CLIENT_FILENAME = "interopclient.txt";
//public const String INTEROP_PLUGIN_FILENAME = "interopplugin.txt";
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 CRAFT_FILE_EXTENSION = ".craft";
public const int MAX_USERNAME_LENGTH = 16;
public const int MAX_TEXT_MESSAGE_QUEUE = 128;
public const long KEEPALIVE_DELAY = 2000;
public const long UDP_PROBE_DELAY = 1000;
public const long UDP_TIMEOUT_DELAY = 8000;
public const int SLEEP_TIME = 5;
public const int CLIENT_DATA_FORCE_WRITE_INTERVAL = 10000;
public const int RECONNECT_DELAY = 1000;
public const int MAX_RECONNECT_ATTEMPTS = 0;
public const int MAX_QUEUED_CHAT_LINES = 8;
public const int DEFAULT_PORT = 2076;
public static UnicodeEncoding encoder = new UnicodeEncoding();
//Settings
private static String mUsername = "";
private static Guid playerGuid;
public static String username
{
set
{
if (value != null && value.Length > MAX_USERNAME_LENGTH)
mUsername = value.Substring(0, MAX_USERNAME_LENGTH);
else
mUsername = value;
}
get
{
return mUsername;
}
}
public static String hostname = "localhost:2076";
public static int updateInterval = 100;
public static int screenshotInterval = 1000;
public static bool autoReconnect = true;
public static byte inactiveShipsPerUpdate = 0;
public static ScreenshotSettings screenshotSettings = new ScreenshotSettings();
public static Dictionary<String, String[]> favorites = new Dictionary<String, String[]>();
//ModChecking
public static bool modFileChecked = false;
public static List<string> partList = new List<string>();
public static Dictionary<string, SHAMod> modFileList = new Dictionary<string, SHAMod>();
public static List<string> resourceList = new List<string>();
public static List<string> requiredModList = new List<string>();
public static string resourceControlMode = "blacklist";
public static string modMismatchError = "Mod Verification Failed - Reason Unknown";
public static string GAMEDATAPATH = new System.IO.DirectoryInfo(getKMPDirectory()).Parent.Parent.FullName;
public static byte[] kmpModControl_bytes;
//Connection
public static int clientID;
public static bool endSession;
public static bool intentionalConnectionEnd;
public static bool handshakeCompleted;
public static TcpClient tcpClient;
public static long lastKeepAliveSendTime;
public static long lastTCPMessageSendTime;
public static bool quitHelperMessageShow;
public static int reconnectAttempts;
public static UdpClient udpClient;
public static bool udpConnected;
public static long lastUDPMessageSendTime;
public static long lastUDPAckReceiveTime;
public static long lastUDPProbeTime;
public static bool receivedSettings;
//Plugin Interop
public static Queue<byte[]> interopInQueue;
public static Queue<byte[]> pluginUpdateInQueue;
public static Queue<InTextMessage> textMessageQueue;
public static long lastScreenshotShareTime;
public static byte[] queuedOutScreenshot;
public static byte[] lastSharedScreenshot;
public static List<String> screenshotsWaiting = new List<String>();
public static String currentGameTitle;
public static String watchPlayerName;
public static long lastClientDataWriteTime;
public static long lastClientDataChangeTime;
public static String message = "Not connected";
//Messages
public static Queue<ServerMessage> receivedMessageQueue;
public static byte[] currentMessage; //Switches between holding header and message data.
public static int currentBytesToReceive; //Switches between the bytes needed for a complete header or message.
public static bool currentMessageHeaderRecieved; //If false, receiving header, if true, reciving message.
public static KMPCommon.ServerMessageID currentMessageID;
public static KMPCommon.ServerMessageID handlingMessageType;
private static Queue<byte[]> queuedOutMessagesHighPriority;
private static Queue<byte[]> queuedOutMessagesSplit;
private static Queue<byte[]> queuedOutMessages;
private static bool isClientSendingData;
private static Queue<byte[]> queuedOutUDPMessages;
private static bool isClientSendingUDPData;
//Split message
private static int splitMessageReceiveIndex = 0;
private static byte[] splitMessageData;
//Threading
public static object sendOutgoingMessagesLock = new object();
public static object sendOutgoingUDPMessagesLock = new object();
public static object serverSettingsLock = new object();
public static object screenshotOutLock = new object();
public static object threadExceptionLock = new object();
public static object clientDataLock = new object();
public static object udpTimestampLock = new object();
public static object interopOutQueueLock = new object();
public static String threadExceptionStackTrace;
public static Exception threadException;
public static Thread serverThread;
public static Thread interopThread;
public static Thread chatThread;
public static Thread connectionThread;
public static Stopwatch stopwatch;
public static KMPManager gameManager;
public static bool debugging = false;
public static void InitMPClient(KMPManager manager)
{
if (Environment.GetCommandLineArgs().Contains("-kmpdebug"))
{
Log.MinLogLevel = Log.LogLevels.Debug;
}
else if (Environment.GetCommandLineArgs().Count(s => s.Contains("-kmpLogLevel:")) == 1)//if a -kmpLogLevel:[loglevel] is in the arguments
{
string logLevel = Environment.GetCommandLineArgs().First(s => s.Contains("-kmpLogLevel:"));
Log.MinLogLevel = (Log.LogLevels)Enum.Parse(typeof(Log.LogLevels), logLevel.Split(':')[1],true);
}
else
{
Log.MinLogLevel = Log.LogLevels.Info;
}
gameManager = manager;
Log.Debug("KMP Client version " + KMPCommon.PROGRAM_VERSION);
Log.Debug(" Created by Shaun Esau and developed by the KMP team http://sesau.ca/ksp/KMP_contribs.html");
Log.Debug(" Based on Kerbal LiveFeed created by Alfred Lam");
Log.Info("KMP started in LogLevel {0}",Log.MinLogLevel);
stopwatch = new Stopwatch();
stopwatch.Start();
favorites.Clear();
}
public static String GetUsername()
{
return username;
}
public static void SetUsername(String newUsername)
{
if (username != newUsername)
{
username = newUsername;
if (username.Length > MAX_USERNAME_LENGTH)
username = username.Substring(0, MAX_USERNAME_LENGTH); //Trim username
writeConfigFile();
}
}
public static void SetServer(String newHostname)
{
if (hostname != newHostname)
{
hostname = newHostname;
writeConfigFile();
}
}
public static void SetAutoReconnect(bool newAutoReconnect)
{
if (autoReconnect != newAutoReconnect)
{
autoReconnect = newAutoReconnect;
writeConfigFile();
}
}
public static Dictionary<String, String[]> GetFavorites()
{
return favorites;
}
public static void SetFavorites(Dictionary<String, String[]> newFavorites)
{
// Verification of change is handled in KMPManager
favorites = newFavorites;
writeConfigFile();
}
private static void parseModFile(string ModFileContent)
{
using (System.IO.StringReader reader = new System.IO.StringReader(ModFileContent))
{
string resourcemode = "whitelist";
List<string> allowedParts = new List<string>();
Dictionary<string, SHAMod> hashes = new Dictionary<string, SHAMod>();
List<string> resources = new List<string>();
List<string> modList = new List<string>();
string line;
string[] splitline = new string[2];
string readmode = "";
while (true)
{
line = reader.ReadLine(); //Trim off any whitespace from the start or end. This would allow indenting of the mod file.
if (line == null)
{
break;
}
line = line.Trim();
try
{
if (!String.IsNullOrEmpty(line) && line[0] != '#') //Skip empty or commented lines.
{
if (line[0] == '!') //changing readmode
{
string trimmedLine = line.Substring(1); //Returns 'partslist' from ' !partslist'
switch (trimmedLine)
{
case "partslist":
case "required-files":
case "optional-files":
readmode = trimmedLine;
break;
case "resource-blacklist": //allow all resources EXCEPT these in file
readmode = "resource";
resourcemode = "blacklist";
break;
case "resource-whitelist": //allow NO resources EXCEPT these in file
readmode = "resource";
resourcemode = "whitelist";
break;
}
}
else
{
if (readmode == "partslist")
{
allowedParts.Add(line);
}
if (readmode == "required-files")
{
string hash = "";
splitline[0] = line;
if (line.Contains('=')) //Let's make the = on the end of the lines optional
{
splitline = line.Split('=');
if (splitline.Length > 1)
{
hash = splitline[1];
}
}
hashes.Add(splitline[0], new SHAMod { sha = hash, required = true });
}
if (readmode == "optional-files")
{
splitline = line.Split('=');
string hash = "";
splitline[0] = line;
if (line.Contains('=')) //Let's make the = on the end of the lines optional
{
splitline = line.Split('=');
if (splitline.Length > 1)
{
hash = splitline[1];
}
}
hashes.Add(splitline[0], new SHAMod { sha = hash, required = false });
}
if (readmode == "resource")
{
resources.Add(line);
}
if (readmode == "required")
{
modList.Add(line);
}
}
}
}
catch (Exception e)
{
Log.Info(e.ToString());
}
}
partList = allowedParts; //make all the vars global once we're done parsing
modFileList = hashes;
resourceControlMode = resourcemode;
resourceList = resources;
requiredModList = modList;
}
}
private static bool FileCheck()
{
try
{
//If required, check exists and same hash
foreach (KeyValuePair<string, SHAMod> entry in modFileList.Where(x => x.Value.required == true))
{
if (entry.Key.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase))
{
//DLL's are checked against the load list
if (KMPManager.LoadedModfiles.Where(x => x.ModPath == entry.Key).Count() == 0)
{
modMismatchError = "Required File Missing: " + entry.Key;
return false;
}
if (KMPManager.LoadedModfiles.Where(x => x.ModPath == entry.Key && x.SHA256 == entry.Value.sha.ToUpperInvariant()).Count() == 0 && entry.Value.sha != "")
{
LoadedFileInfo debugTest = KMPManager.LoadedModfiles.Where(x => x.ModPath == entry.Key).First();
modMismatchError = "SHA Checksum Mismatch: " + entry.Key + " " + debugTest.SHA256 + "/" + entry.Value.sha.ToUpperInvariant();
return false;
}
}
else
{
//All other files are checked against the filesystem
string fileToCheck = System.IO.Path.Combine(GAMEDATAPATH, entry.Key);
if (!System.IO.File.Exists(fileToCheck))
{
modMismatchError = "Required File Missing: " + entry.Key;
return false;
}
if (entry.Value.sha != "")
{
try
{
using (System.IO.Stream hashStream = new System.IO.FileStream(fileToCheck, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
using (SHA256Managed sha = new SHA256Managed())
{
byte[] hash = sha.ComputeHash(hashStream);
if (BitConverter.ToString(hash).Replace("-", String.Empty) != entry.Value.sha.ToUpperInvariant())
{
modMismatchError = "SHA Checksum Mismatch: " + entry.Key;
return false;
}
}
}
}
catch (Exception e)
{
Log.Debug("Failed to hash: " + entry.Key + ", exception" + e.Message.ToString());
modMismatchError = "Failed to hash: " + entry.Key;
return false;
}
}
}
}
//If optional, if exists check hash
foreach (KeyValuePair<string, SHAMod> entry in modFileList.Where(x => x.Value.required == false))
{
if (entry.Key.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase))
{
if (KMPManager.LoadedModfiles.Where(x => x.ModPath == entry.Key) != null)
{
if (KMPManager.LoadedModfiles.Where(x => x.ModPath == entry.Key && x.SHA256 == entry.Value.sha.ToUpperInvariant()) == null && entry.Value.sha != "")
{
modMismatchError = "SHA Checksum Mismatch: " + entry.Key;
return false;
}
}
}
else
{
string fileToCheck = System.IO.Path.Combine(GAMEDATAPATH, entry.Key);
if (System.IO.File.Exists(fileToCheck) && entry.Value.sha != "")
{
using (System.IO.Stream hashStream = new System.IO.FileStream(fileToCheck, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite))
{
using (SHA256Managed sha = new SHA256Managed())
{
byte[] hash = sha.ComputeHash(hashStream);
if (BitConverter.ToString(hash).Replace("-", String.Empty) != entry.Value.sha.ToUpperInvariant())
{
modMismatchError = "SHA Checksum Mismatch: " + entry.Key;
return false;
}
}
}
}
}
}
}
catch (Exception e)
{
Log.Debug("Failed to complete files check: " + e.ToString());
modMismatchError = e.Message;
return false;
}
return true;
}
private static bool resourceCheck()
{
//We should auto-allow KMP resources.
List<string> allowList = new List<string>();
allowList.Add("000_Toolbar/Toolbar.dll");
allowList.Add("KMP/Plugins/KerbalMultiPlayer.dll");
allowList.Add("KMP/Plugins/ICSharpCode.SharpZipLib.dll");
try
{
if (resourceControlMode == "blacklist")
{
foreach (string checkedResource in resourceList)
{
foreach (LoadedFileInfo file in KMPManager.LoadedModfiles)
{
if (file.ModPath.Contains(checkedResource))
{
modMismatchError = "File blacklisted: " + file.LoadedPath;
return false;
}
}
}
}
else if (resourceControlMode == "whitelist")
{
foreach (LoadedFileInfo file in KMPManager.LoadedModfiles)
{
if (!resourceList.Contains(file.ModPath) && !modFileList.ContainsKey(file.ModPath) && !allowList.Contains(file.ModPath)) // check if the resource is a) whitelisted, or b) listed in the optional or required SHA sections. If not, the file is not allowed to be loaded.
{
modMismatchError = "File not allowed on this server: " + file.LoadedPath;
return false;
}
}
}
return true;
}
catch (Exception e)
{
modMismatchError = e.Message;
Log.Debug(e.ToString());
return false;
}
}
private static bool modCheck(byte[] kmpModControl_bytes)
{
if (!modFileChecked)
{
modFileChecked = true;
string modFilePath = System.IO.Path.Combine(GAMEDATAPATH, "KMP/Plugins/PluginData/KerbalMultiPlayer/" + MOD_CONTROL_FILENAME);
System.IO.File.WriteAllBytes(modFilePath, kmpModControl_bytes);
parseModFile(System.Text.Encoding.UTF8.GetString(kmpModControl_bytes));
if (!resourceCheck() || !FileCheck())
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
public static void Connect()
{
gameManager.forceQuit = false;
gameManager.delayForceQuit = true;
gameManager.gameStart = false;
clearConnectionState();
File.Delete<KMPClientMain>("debug");
serverThread = new Thread(beginConnect);
serverThread.Start();
}
private static void beginConnect()
{
SetMessage("Attempting to connect...");
bool allow_reconnect = false;
reconnectAttempts = MAX_RECONNECT_ATTEMPTS;
do
{
allow_reconnect = false;
try
{
//Run the connection loop then determine if a reconnect attempt should be made
if (connectionLoop())
reconnectAttempts = 0;
allow_reconnect = autoReconnect && !intentionalConnectionEnd && reconnectAttempts < MAX_RECONNECT_ATTEMPTS;
}
catch (Exception e)
{
//Write an error log
Log.Debug("Exception thrown in beginConnect(), catch 1, Exception: {0}", e.ToString());
KSP.IO.TextWriter writer = KSP.IO.File.AppendText<KMPClientMain>("KMPClientlog.txt");
writer.WriteLine(e.ToString());
if (threadExceptionStackTrace != null && threadExceptionStackTrace.Length > 0)
{
writer.WriteLine("KMP Stacktrace: ");
writer.WriteLine(threadExceptionStackTrace);
}
writer.Close();
Log.Error(e.ToString());
if (threadExceptionStackTrace != null && threadExceptionStackTrace.Length > 0)
{
Log.Debug(threadExceptionStackTrace);
}
Log.Error("Unexpected exception encountered! Crash report written to KMPClientlog.txt");
}
if (allow_reconnect)
{
//Attempt a reconnect after a delay
SetMessage("Attempting to reconnect...");
Thread.Sleep(RECONNECT_DELAY);
reconnectAttempts++;
}
} while (allow_reconnect);
}
/// <summary>
/// Connect to the server and run a session until the connection ends
/// </summary>
/// <returns>True iff a connection was successfully established with the server</returns>
static bool connectionLoop()
{
//Look for a port-number in the hostname
int port = DEFAULT_PORT;
String trimmed_hostname = hostname;
int port_start_index = hostname.LastIndexOf(':');
if (port_start_index >= 0 && port_start_index < (hostname.Length - 1))
{
String port_substring = hostname.Substring(port_start_index + 1);
if (!int.TryParse(port_substring, out port) || port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
port = DEFAULT_PORT;
trimmed_hostname = hostname.Substring(0, port_start_index);
}
//Look up the actual IP address
bool ipv6_connected = false;
IPAddress address = null;
IPAddress.TryParse(trimmed_hostname, out address);
if (address == null) {
IPHostEntry host_entry = new IPHostEntry();
try
{
host_entry = Dns.GetHostEntry(trimmed_hostname);
}
catch (Exception e)
{
Log.Debug("Exception thrown in connectionLoop(), catch 1, Exception: {0}", e.ToString());
host_entry = null;
}
if (host_entry != null)
{
IPAddress ipv4_address = Array.Find(host_entry.AddressList, a => a.AddressFamily == AddressFamily.InterNetwork);
IPAddress ipv6_address = Array.Find(host_entry.AddressList, a => a.AddressFamily == AddressFamily.InterNetworkV6);
address = ipv4_address;
if ( ipv6_address != null ) {
try {
//Connects IPv6 Hostnames
TcpClient ipv6_tcpClient = new TcpClient(ipv6_address.AddressFamily);
ipv6_tcpClient.NoDelay = true;
IPEndPoint ipv6_endpoint = new IPEndPoint(ipv6_address, port);
SetMessage("Connecting to IPv6: [" + ipv6_address + "]:" + port);
ipv6_tcpClient.Connect(ipv6_endpoint);
if (ipv6_tcpClient.Client.Connected) {
ipv6_connected = true;
address = ipv6_address;
tcpClient = ipv6_tcpClient;
} else {
ipv6_tcpClient = null;
ipv6_endpoint = null;
}
}
catch (Exception e) {
Log.Debug("Exception thrown in connectionLoop(), catch 2, Exception: {0}", e.ToString());
}
}
}
}
if (address == null)
{
SetMessage("Invalid server address.");
return false;
}
try
{
//Connects IPv4 Hostnames, And IPv6/IPv4 IP's.
if (ipv6_connected == false) {
tcpClient = new TcpClient(address.AddressFamily);
tcpClient.NoDelay = true;
IPEndPoint endpoint = new IPEndPoint(address, port);
if (address.AddressFamily == AddressFamily.InterNetworkV6) {
SetMessage("Connecting to IPv6: [" + address + "]:" + port);
} else {
SetMessage("Connecting to IPv4: " + address + ":" + port);
}
tcpClient.Connect(endpoint);
}
//tcpSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true);
if (tcpClient != null ? tcpClient.Connected : false)
{
SetMessage("TCP connection established");
clientID = -1;
endSession = false;
intentionalConnectionEnd = false;
handshakeCompleted = false;
receivedSettings = false;
splitMessageData = null;
splitMessageReceiveIndex = 0;
screenshotsWaiting.Clear();
modFileChecked = false;
isClientSendingData = false;
isClientSendingUDPData = false;
pluginUpdateInQueue = new Queue<byte[]>();
textMessageQueue = new Queue<InTextMessage>();
interopInQueue = new Queue<byte[]>();
receivedMessageQueue = new Queue<ServerMessage>();
queuedOutMessages = new Queue<byte[]>();
queuedOutMessagesSplit = new Queue<byte[]>();
queuedOutMessagesHighPriority = new Queue<byte[]>();
queuedOutUDPMessages = new Queue<byte[]>();
threadException = null;
currentGameTitle = String.Empty;
watchPlayerName = String.Empty;
lastSharedScreenshot = null;
lastScreenshotShareTime = 0;
lastTCPMessageSendTime = 0;
lastClientDataWriteTime = 0;
lastClientDataChangeTime = stopwatch.ElapsedMilliseconds;
quitHelperMessageShow = true;
//Init udp socket
try
{
IPEndPoint endpoint = new IPEndPoint(address, port);
udpClient = new UdpClient(endpoint.AddressFamily);
udpClient.Connect(endpoint);
}
catch (Exception e)
{
Log.Debug("Exception thrown in connectionLoop(), catch 3, Exception: {0}", e.ToString());
if (udpClient != null)
udpClient.Close();
udpClient = null;
}
udpConnected = false;
lastUDPAckReceiveTime = 0;
lastUDPMessageSendTime = stopwatch.ElapsedMilliseconds;
//Create a thread to handle chat
chatThread = new Thread(new ThreadStart(handleChat));
chatThread.Start();
//Create a thread to handle client interop
interopThread = new Thread(new ThreadStart(handlePluginInterop));
interopThread.Start();
//Create a thread to handle disconnection
connectionThread = new Thread(new ThreadStart(handleConnection));
connectionThread.Start();
beginAsyncRead();
SetMessage("Connected to server! Handshaking...");
while (!endSession && !intentionalConnectionEnd && tcpClient != null)
{
//Check for exceptions thrown by threads
lock (threadExceptionLock)
{
if (threadException != null)
{
Exception e = threadException;
threadExceptionStackTrace = e.StackTrace;
throw e;
}
}
Thread.Sleep(SLEEP_TIME);
}
if (intentionalConnectionEnd)
enqueuePluginChatMessage("Closed connection with server", true);
else
enqueuePluginChatMessage("Lost connection with server", true);
ScreenMessages.PostScreenMessage("Lost connection with server. Please return to the Main Menu to reconnect.",300f,ScreenMessageStyle.UPPER_CENTER);
return true;
}
}
catch (Exception e)
{
Log.Debug("Exception thrown in connectionLoop(), catch 4, Exception: {0}", e.ToString());
SetMessage("Disconnected");
if (tcpClient != null)
tcpClient.Close();
tcpClient = null;
}
return false;
}
static void handleMessage(KMPCommon.ServerMessageID id, byte[] data)
{
//LogAndShare("Message ID: " + id.ToString() + " data: " + (data == null ? "0" : System.Text.Encoding.ASCII.GetString(data)));
handlingMessageType = id;
switch (id)
{
case KMPCommon.ServerMessageID.HANDSHAKE:
if (handshakeCompleted) {
return;
}
if (data != null)
{
if (data.Length > 4)
{
//Check protocol version
Int32 protocol_version = KMPCommon.intFromBytes(data);
if (protocol_version != KMPCommon.NET_PROTOCOL_VERSION)
{
//End the session if the protocol version doesn't match
endSession = true;
intentionalConnectionEnd = true;
gameManager.disconnect("Your client is incompatible with this server");
return;
}
Int32 server_version_length = KMPCommon.intFromBytes(data, 4);
String server_version = encoder.GetString(data, 8, server_version_length);
clientID = KMPCommon.intFromBytes(data, 8 + server_version_length);
gameManager.gameMode = KMPCommon.intFromBytes(data, 12 + server_version_length);
gameManager.numberOfShips = KMPCommon.intFromBytes(data, 16 + server_version_length);
int kmpModControl_length = KMPCommon.intFromBytes(data, 20 + server_version_length);
kmpModControl_bytes = new byte[kmpModControl_length];
Array.Copy(data, 24 + server_version_length, kmpModControl_bytes, 0, kmpModControl_length);
SetMessage("Handshake received. Server version: " + server_version);
if (!modCheck(kmpModControl_bytes))
{
endSession = true;
intentionalConnectionEnd = true;
gameManager.disconnect(modMismatchError);
return;
}
sendHandshakeMessage(); //Reply to the handshake
lock (udpTimestampLock)
{
lastUDPMessageSendTime = stopwatch.ElapsedMilliseconds;
}
handshakeCompleted = true;
}
else
{
//End the session if we get a bad handshake. Protects against byte[0].
endSession = true;
intentionalConnectionEnd = true;
gameManager.disconnect("Your client is incompatible with this server");
return;
}
}
else
{
//End the session if we get a bad handshake. Protects against null.
endSession = true;
intentionalConnectionEnd = true;
gameManager.disconnect("Your client is incompatible with this server");
return;
}
break;
case KMPCommon.ServerMessageID.HANDSHAKE_REFUSAL:
String refusal_message = encoder.GetString(data, 0, data.Length);
endSession = true;
intentionalConnectionEnd = true;
enqueuePluginChatMessage("Server refused connection. Reason: " + refusal_message, true);
break;
case KMPCommon.ServerMessageID.SERVER_MESSAGE:
case KMPCommon.ServerMessageID.TEXT_MESSAGE:
if (data != null)
{
InTextMessage in_message = new InTextMessage();
in_message.fromServer = (id == KMPCommon.ServerMessageID.SERVER_MESSAGE);
in_message.isMOTD = (id == KMPCommon.ServerMessageID.MOTD_MESSAGE);
in_message.message = encoder.GetString(data, 0, data.Length);
if (in_message.message.Contains(" has shared a screenshot.")) {
int screenshotSharePlayerNameIndex = in_message.message.IndexOf(" has shared a screenshot.");
string screenshotSharePlayerName = in_message.message.Substring(0, screenshotSharePlayerNameIndex);
if (screenshotSharePlayerName != username) {
bool listPlayerNameInScreenshotsWaiting = false;
foreach (string listPlayer in screenshotsWaiting)
{
if (listPlayer == screenshotSharePlayerName) {
listPlayerNameInScreenshotsWaiting = true;
}
}
if (listPlayerNameInScreenshotsWaiting == false)
{
screenshotsWaiting.Add(screenshotSharePlayerName);
}
}
}
if (in_message.message.Contains(" has disconnected : ")) {
int quitPlayerNameIndex = in_message.message.IndexOf(" has disconnected : ");
string quitPlayerName = in_message.message.Substring(0, quitPlayerNameIndex);
if (quitPlayerName != username) {
bool listPlayerNameInScreenshotsWaiting = false;
foreach (string listPlayer in screenshotsWaiting)
{
if (listPlayer == quitPlayerName) {
listPlayerNameInScreenshotsWaiting = true;
}
}
if (listPlayerNameInScreenshotsWaiting)
{
screenshotsWaiting.Remove(quitPlayerName);
}
}
}
//Queue the message
enqueueTextMessage(in_message);
}
break;
case KMPCommon.ServerMessageID.MOTD_MESSAGE:
if (gameManager.gameRunning == false) {
gameManager.gameStart = true;
}
if (data != null)
{
InTextMessage in_message = new InTextMessage();
in_message.fromServer = (id == KMPCommon.ServerMessageID.SERVER_MESSAGE);
in_message.isMOTD = (id == KMPCommon.ServerMessageID.MOTD_MESSAGE);
in_message.message = encoder.GetString(data, 0, data.Length);
enqueueTextMessage(in_message);
}
break;
case KMPCommon.ServerMessageID.PLUGIN_UPDATE:
if (data != null)
enqueueClientInteropMessage(KMPCommon.ClientInteropMessageID.PLUGIN_UPDATE, data);
break;
case KMPCommon.ServerMessageID.SCENARIO_UPDATE:
if (data != null)
enqueueClientInteropMessage(KMPCommon.ClientInteropMessageID.SCENARIO_UPDATE, data);
break;
case KMPCommon.ServerMessageID.SERVER_SETTINGS:
lock (serverSettingsLock)
{
if (data != null && data.Length >= KMPCommon.SERVER_SETTINGS_LENGTH && handshakeCompleted)
{
updateInterval = KMPCommon.intFromBytes(data, 0);
screenshotInterval = KMPCommon.intFromBytes(data, 4);
lock (clientDataLock)
{
int new_screenshot_height = KMPCommon.intFromBytes(data, 8);
if (screenshotSettings.maxHeight != new_screenshot_height)
{
screenshotSettings.maxHeight = new_screenshot_height;
lastClientDataChangeTime = stopwatch.ElapsedMilliseconds;
enqueueTextMessage("Screenshot Height has been set to " + screenshotSettings.maxHeight);
}
gameManager.safetyBubbleRadius = BitConverter.ToDouble(data, 12);
if (inactiveShipsPerUpdate != data[20])