forked from jo3bingham/TibiaAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.cs
More file actions
1049 lines (912 loc) · 37.8 KB
/
Connection.cs
File metadata and controls
1049 lines (912 loc) · 37.8 KB
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.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ComponentAce.Compression.Libs.zlib;
using Newtonsoft.Json;
using OXGaming.TibiaAPI.Constants;
using OXGaming.TibiaAPI.Utilities;
namespace OXGaming.TibiaAPI.Network
{
/// <summary>
/// The <see cref="Connection"/> class is used to create a proxy between the Tibia client and the game server.
/// </summary>
public class Connection : Communication, IDisposable
{
private const string LOGIN_WEB_SERVICE = "https://www.tibia.com/clientservices/loginservice.php";
private readonly object _clientSendLock = new object();
private readonly object _serverSendLock = new object();
private readonly object _clientSequenceNumberLock = new object();
private readonly object _ServerSequenceNumberLock = new object();
private readonly Client _client;
private readonly HttpListener _httpListener = new HttpListener();
private readonly NetworkMessage _clientInMessage;
private readonly NetworkMessage _clientOutMessage;
private readonly NetworkMessage _serverInMessage;
private readonly NetworkMessage _serverOutMessage;
private readonly Queue<byte[]> _clientSendQueue = new Queue<byte[]>();
private readonly Queue<byte[]> _serverSendQueue = new Queue<byte[]>();
private readonly Rsa _rsa = new Rsa();
private uint[] _xteaKey;
private ZStream _zStream = new ZStream();
private Socket _clientSocket;
private Socket _serverSocket;
private Thread _clientSendThread;
private Thread _serverSendThread;
private TcpListener _tcpListener;
private dynamic _loginData;
private string _loginWebService;
private uint _clientSequenceNumber = 1;
private uint _serverSequenceNumber = 1;
private bool _isResettingConnection = false;
private bool _isSendingToClient = false;
private bool _isSendingToServer = false;
private bool _isStarted;
public delegate void ReceivedMessageEventHandler(byte[] data);
public event ReceivedMessageEventHandler OnReceivedClientMessage;
public event ReceivedMessageEventHandler OnReceivedServerMessage;
public ConnectionState ConnectionState { get; set; } = ConnectionState.Disconnected;
public bool IsClientPacketDecryptionEnabled { get; set; } = true;
public bool IsClientPacketModificationEnabled { get; set; } = false;
public bool IsClientPacketParsingEnabled { get; set; } = true;
public bool IsServerPacketDecryptionEnabled { get; set; } = true;
public bool IsServerPacketCompressionEnabled { get; set; } = false;
public bool IsServerPacketModificationEnabled { get; set; } = false;
public bool IsServerPacketParsingEnabled { get; set; } = true;
/// <summary>
/// Initializes a new instance of the <see cref="Connection"/> class that acts as a proxy
/// between the Tibia client and the game server.
/// </summary>
public Connection(Client client)
{
_client = client ?? throw new ArgumentNullException(nameof(client));
_clientInMessage = new NetworkMessage(_client);
_clientOutMessage = new NetworkMessage(_client);
_serverInMessage = new NetworkMessage(_client);
_serverOutMessage = new NetworkMessage(_client);
}
/// <summary>
/// Starts the <see cref="HttpListener"/> and <see cref="TcpListener"/> objects that listen for incoming
/// connection requests from the Tibia client.
/// </summary>
/// <returns>Returns true on success, or if already started. Returns false if an exception is thrown.</returns>
internal bool Start(int httpPort = 7171, string loginWebService = "")
{
if (_isStarted)
{
return true;
}
try
{
if (_tcpListener == null)
{
_tcpListener = new TcpListener(IPAddress.Loopback, 0);
}
var uriPrefix = $"http://127.0.0.1:{httpPort}/";
if (!_httpListener.Prefixes.Contains(uriPrefix))
{
_httpListener.Prefixes.Add(uriPrefix);
}
_zStream.deflateInit(zlibConst.Z_DEFAULT_COMPRESSION, -15);
_zStream.inflateInit(-15);
_httpListener.Start();
_httpListener.BeginGetContext(new AsyncCallback(BeginGetContextCallback), _httpListener);
_tcpListener.Start();
_tcpListener.BeginAcceptSocket(new AsyncCallback(BeginAcceptTcpClientCallback), _tcpListener);
_isStarted = true;
_loginWebService = loginWebService;
ConnectionState = ConnectionState.ConnectingStage1;
}
catch (Exception ex)
{
_isStarted = false;
_client.Logger.Error(ex.ToString());
}
return _isStarted;
}
/// <summary>
/// Sends a packet to the Tibia client.
/// </summary>
/// <param name="message">
/// The <see cref="ServerPacket"/> object to be sent.
/// </param>
public void SendToClient(ServerPacket packet)
{
if (packet == null)
{
throw new ArgumentNullException(nameof(packet));
}
var message = new NetworkMessage(_client);
packet.AppendToNetworkMessage(message);
SendToClient(message);
}
/// <summary>
/// Sends a packet to the Tibia client.
/// </summary>
/// <param name="message">
/// The <see cref="NetworkMessage"/> object containing the data to be sent.
/// </param>
public void SendToClient(NetworkMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (message.Size <= 8)
{
return;
}
if (message.SequenceNumber != 0)
{
lock (_clientSequenceNumberLock)
{
message.SequenceNumber = _clientSequenceNumber++;
}
}
message.PrepareToSend(_xteaKey, (IsServerPacketCompressionEnabled ? _zStream : null));
SendToClient(message.GetData());
}
/// <summary>
/// Sends a packet to the Tibia client.
/// </summary>
/// <param name="data">
/// The raw byte-array containing the data to be sent.
/// </param>
public void SendToClient(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Length <= 8)
{
return;
}
lock (_clientSendLock)
{
_clientSendQueue.Enqueue(data);
if (!_isSendingToClient)
{
try
{
_isSendingToClient = true;
_clientSendThread = new Thread(new ThreadStart(ClientSend));
_clientSendThread.Start();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
}
}
}
/// <summary>
/// Sends a packet to the game server.
/// </summary>
/// <param name="packet">
/// The <see cref="ClientPacket"/> to be sent.
/// </param>
public void SendToServer(ClientPacket packet)
{
if (packet == null)
{
throw new ArgumentNullException(nameof(packet));
}
var message = new NetworkMessage(_client);
packet.AppendToNetworkMessage(message);
SendToServer(message);
}
/// <summary>
/// Sends a packet to the game server.
/// </summary>
/// <param name="message">
/// The <see cref="NetworkMessage"/> object containing the data to be sent.
/// </param>
public void SendToServer(NetworkMessage message)
{
if (message == null)
{
throw new ArgumentNullException(nameof(message));
}
if (message.Size <= 8)
{
return;
}
if (message.SequenceNumber != 0)
{
lock (_ServerSequenceNumberLock)
{
message.SequenceNumber = _serverSequenceNumber++;
}
}
message.PrepareToSend(_xteaKey);
SendToServer(message.GetData());
}
/// <summary>
/// Sends a packet to the game server.
/// </summary>
/// <param name="data">
/// Raw byte-array containing the data to be sent.
/// </param>
public void SendToServer(byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data));
}
if (data.Length <= 8)
{
return;
}
lock (_serverSendLock)
{
_serverSendQueue.Enqueue(data);
if (!_isSendingToServer)
{
try
{
_isSendingToServer = true;
_serverSendThread = new Thread(new ThreadStart(ServerSend));
_serverSendThread.Start();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
}
}
}
/// <summary>
/// Sets the XTEA key used for encrypting/decrypting both server and client packets.
/// </summary>
/// <param name="key">List of unsigned integers to be used as the XTEA key.</param>
/// <returns>Returns false if the length of the list is anything other than 4.</returns>
internal bool SetXteaKey(List<uint> key)
{
if (key.Count != 4)
{
return false;
}
_xteaKey = key.ToArray();
return true;
}
/// <summary>
/// Closes any open connections between the Tibia client and game server, and stops listening for any
/// new incoming HTTP or TCP connection requests.
/// </summary>
internal void Stop()
{
if (!_isStarted)
{
return;
}
try
{
_zStream.deflateEnd();
_zStream.inflateEnd();
_httpListener.Close();
if (_tcpListener != null)
{
_tcpListener.Stop();
}
if (_clientSocket != null)
{
_clientSocket.Close();
}
if (_serverSocket != null)
{
_serverSocket.Close();
}
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
_isStarted = false;
_xteaKey = null;
ConnectionState = ConnectionState.Disconnected;
}
/// <summary>
/// Closes any open connections between the Tibia client and game server, and clears
/// any pending packets to be sent.
/// </summary>
private void ResetConnection()
{
if (_isResettingConnection)
{
return;
}
_isResettingConnection = true;
lock (_clientSendLock)
{
_isSendingToClient = false;
_clientSendQueue.Clear();
}
if (_clientSocket != null)
{
_clientSocket.Close();
}
lock (_serverSendLock)
{
_isSendingToServer = false;
_serverSendQueue.Clear();
}
if (_serverSocket != null)
{
_serverSocket.Close();
}
_zStream.deflateEnd();
_zStream.inflateEnd();
_zStream = new ZStream();
_zStream.deflateInit(zlibConst.Z_DEFAULT_COMPRESSION, -15);
_zStream.inflateInit(-15);
_clientSequenceNumber = 1;
_serverSequenceNumber = 1;
_xteaKey = null;
_isResettingConnection = false;
ConnectionState = ConnectionState.ConnectingStage1;
}
/// <summary>
/// Grabs the next packet in the queue and sends it ansychronously to the Tibia client.
/// </summary>
private void ClientSend()
{
if (_clientSocket == null)
{
return;
}
try
{
byte[] data = null;
lock (_clientSendLock)
{
if (_clientSendQueue.Count > 0)
{
data = _clientSendQueue.Dequeue();
}
if (data == null)
{
_isSendingToClient = false;
return;
}
}
_clientSocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(BeginSendClientCallback), _clientSocket);
}
catch (SocketException)
{
// This exception can happen if the client, forcefully, closes the connection (e.g., killing the client process).
ResetConnection();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
}
/// <summary>
/// Grabs the next packet in the queue and sends it ansychronously to the game server.
/// </summary>
private void ServerSend()
{
if (_serverSocket == null)
{
return;
}
try
{
byte[] data = null;
lock (_serverSendLock)
{
if (_serverSendQueue.Count > 0)
{
data = _serverSendQueue.Dequeue();
}
if (data == null)
{
_isSendingToServer = false;
return;
}
}
_serverSocket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(BeginSendServerCallback), _serverSocket);
}
catch (SocketException)
{
// This exception can happen if the server, forcefully, closes the connection.
ResetConnection();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
}
/// <summary>
/// Handles a pending ansynchronous packet send to the Tibia client, and calls <see cref="ClientSend"/> to send the next one.
/// </summary>
/// <param name="ar">
/// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
/// </param>
private void BeginSendClientCallback(IAsyncResult ar)
{
var socket = (Socket)ar.AsyncState;
if (socket == null)
{
throw new Exception("[Connection.BeginSendClientCallback] Client socket is null.");
}
try
{
socket.EndSend(ar);
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
ClientSend();
}
/// <summary>
/// Handles a pending ansynchronous packet send to the game server, and calls <see cref="ServerSend"/> to send the next one.
/// </summary>
/// <param name="ar">
/// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
/// </param>
private void BeginSendServerCallback(IAsyncResult ar)
{
var socket = (Socket)ar.AsyncState;
if (socket == null)
{
throw new Exception("[Connection.BeginSendServerCallback] Server socket is null.");
}
try
{
socket.EndSend(ar);
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
ServerSend();
}
/// <summary>
/// Handles an incoming HTTP request, forwards it to CipSoft's web service, waits for a response,
/// modifies the response if it's the character list, then forwards it to the Tibia client.
/// </summary>
/// <param name="ar">
/// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
/// </param>
private void BeginGetContextCallback(IAsyncResult ar)
{
try
{
var httpListener = (HttpListener)ar.AsyncState;
if (httpListener == null)
{
throw new Exception("[Connection.BeginGetContextCallback] HTTP listener is null.");
}
var context = httpListener.EndGetContext(ar);
var request = context.Request;
var clientRequest = string.Empty;
using (var reader = new StreamReader(request.InputStream, request.ContentEncoding))
{
clientRequest = reader.ReadToEnd();
}
if (string.IsNullOrEmpty(clientRequest))
{
throw new Exception($"[Connection.BeginGetContextCallback] Invalid HTTP request data: {clientRequest ?? "null"}");
}
_client.Logger.Debug($"Client POST: {clientRequest}");
var data = PostAsync(clientRequest).Result;
var response = string.Empty;
using (var compressedStream = new MemoryStream(data))
using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
using (var resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
response = Encoding.UTF8.GetString(resultStream.ToArray());
}
if (string.IsNullOrEmpty(response))
{
// This can happen with Open-Tibia servers where their login service doesn't handle all
// types of requests from the client. Best to keep listening for a proper response.
_httpListener.BeginGetContext(new AsyncCallback(BeginGetContextCallback), _httpListener);
return;
}
_client.Logger.Debug($"Server response: {response}");
try
{
// Login data is the only thing we have to modify, everything else can be piped through.
dynamic loginData = JsonConvert.DeserializeObject(response);
if (loginData != null && loginData.session != null)
{
// Change the address and port of each game world to that of the TCP listener so that
// the Tibia client connects to the TCP listener instead of a game world.
var address = ((IPEndPoint)_tcpListener.LocalEndpoint).Address.ToString();
var port = ((IPEndPoint)_tcpListener.LocalEndpoint).Port;
foreach (var world in loginData.playdata.worlds)
{
world.externaladdressprotected = address;
world.externaladdressunprotected = address;
world.externalportprotected = port;
world.externalportunprotected = port;
}
// Store the original login data so when the Tibia client tries to connect to a game world
// the server socket can recall the address and port to connect to.
_loginData = JsonConvert.DeserializeObject(response);
response = JsonConvert.SerializeObject(loginData);
}
}
catch (JsonReaderException)
{
// This exception can occur if the login server responds with something other than JSON.
// This is usually HTML when Tibia is down for maintenance. Ignore the exception and continue on.
}
catch
{
throw;
}
data = Encoding.UTF8.GetBytes(response);
context.Response.ContentLength64 = data.Length;
context.Response.OutputStream.Write(data, 0, data.Length);
context.Response.Close();
_httpListener.BeginGetContext(new AsyncCallback(BeginGetContextCallback), _httpListener);
}
catch (ObjectDisposedException)
{
// This exception can occur if Stop() is called.
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
}
/// <summary>
/// Handles an incoming TCP connection and begins receiving incoming data.
/// </summary>
/// <param name="ar">
/// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
/// </param>
private void BeginAcceptTcpClientCallback(IAsyncResult ar)
{
try
{
var tcpListener = (TcpListener)ar.AsyncState;
if (tcpListener == null)
{
throw new Exception("[Connection.BeginAcceptTcpClientCallback] TCP client is null.");
}
_clientSocket = tcpListener.EndAcceptSocket(ar);
_clientSocket.LingerState = new LingerOption(true, 2);
_clientSocket.BeginReceive(_clientInMessage.GetBuffer(), 0, 1, SocketFlags.None, new AsyncCallback(BeginReceiveWorldNameCallback), null);
_tcpListener.BeginAcceptSocket(new AsyncCallback(BeginAcceptTcpClientCallback), _tcpListener);
}
catch (ObjectDisposedException)
{
// This exception can occur if Stop() is called.
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
}
}
/// <summary>
/// Handles the first packet the Tibia client sends to the game server; which is just the world name.
/// This is the only packet that doesn't conform to the normal packet structure that Tibia uses.
/// </summary>
/// <param name="ar">
/// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
/// </param>
private void BeginReceiveWorldNameCallback(IAsyncResult ar)
{
try
{
if (_clientSocket == null)
{
return;
}
var count = _clientSocket.EndReceive(ar);
if (count <= 0)
{
ResetConnection();
return;
}
// The first message the client sends to the game server is the world name without a length.
// Read from the socket one byte at a time until the end of the string (\n) is read.
while (_clientInMessage.GetBuffer()[count - 1] != Convert.ToByte('\n'))
{
var read = _clientSocket.Receive(_clientInMessage.GetBuffer(), count, 1, SocketFlags.None);
if (read <= 0)
{
throw new Exception("[Connection.BeginReceiveWorldNameCallback] Client connection broken.");
}
count += read;
}
var worldName = Encoding.UTF8.GetString(_clientInMessage.GetBuffer(), 0, count - 1);
foreach (var world in _loginData.playdata.worlds)
{
var name = (string)world.name;
if (name.Equals(worldName, StringComparison.CurrentCultureIgnoreCase))
{
_clientSocket.BeginReceive(_clientInMessage.GetBuffer(), 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveClientCallback), 0);
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Connect((string)world.externaladdressprotected, (int)world.externalportprotected);
_serverSocket.Send(_clientInMessage.GetBuffer(), 0, count, SocketFlags.None);
_serverSocket.BeginReceive(_serverInMessage.GetBuffer(), 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveServerCallback), 0);
return;
}
}
throw new Exception($"[Connection.BeginReceiveWorldNameCallback] Login data not found for world: {worldName}.");
}
catch (SocketException)
{
// This exception can happen if the client, forcefully, closes the connection (e.g., killing the client process).
ResetConnection();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
_client.Logger.Error($"Data: {BitConverter.ToString(_clientInMessage.GetData()).Replace('-', ' ')}");
}
}
/// <summary>
/// Handles all incoming data from the Tibia client (except the first packet).
/// </summary>
/// <param name="ar">
/// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
/// </param>
private void BeginReceiveClientCallback(IAsyncResult ar)
{
try
{
if (_clientSocket == null)
{
return;
}
var count = _clientSocket.EndReceive(ar);
if (count <= 0)
{
ResetConnection();
return;
}
_clientInMessage.Size = (uint)BitConverter.ToUInt16(_clientInMessage.GetBuffer(), 0) + 2;
while (count < _clientInMessage.Size)
{
var read = _clientSocket.Receive(_clientInMessage.GetBuffer(), count, (int)(_clientInMessage.Size - count), SocketFlags.None);
if (read <= 0)
{
throw new Exception("[Connection.BeginReceiveClientCallback] Client connection broken.");
}
count += read;
}
var protocol = (int)ar.AsyncState;
if (protocol == 0)
{
var rsaStartIndex = _client.VersionNumber >= 124010030 ? 31 : 18;
_rsa.OpenTibiaDecrypt(_clientInMessage, rsaStartIndex);
_clientInMessage.Seek(rsaStartIndex, SeekOrigin.Begin);
if (_clientInMessage.ReadByte() != 0)
{
throw new Exception("[Connection.BeginReceiveClientCallback] RSA decryption failed.");
}
OnReceivedClientMessage?.Invoke(_clientInMessage.GetData());
if (IsClientPacketParsingEnabled)
{
_clientOutMessage.Reset();
ParseClientMessage(_client, _clientInMessage, _clientOutMessage);
}
else
{
_xteaKey = new uint[4];
for (var i = 0; i < 4; ++i)
{
_xteaKey[i] = _clientInMessage.ReadUInt32();
}
}
if (string.IsNullOrEmpty(_loginWebService))
{
_rsa.TibiaEncrypt(_clientInMessage, rsaStartIndex);
}
else
{
// If the user supplied a login web service address,
// it's safe to assume it's an Open-Tibia server.
_rsa.OpenTibiaEncrypt(_clientInMessage, rsaStartIndex);
}
SendToServer(_clientInMessage.GetData());
}
else
{
if (IsClientPacketDecryptionEnabled)
{
_clientInMessage.PrepareToParse(_xteaKey);
OnReceivedClientMessage?.Invoke(_clientInMessage.GetData());
}
if (IsClientPacketParsingEnabled)
{
_clientOutMessage.Reset();
_clientOutMessage.SequenceNumber = _clientInMessage.SequenceNumber;
ParseClientMessage(_client, _clientInMessage, _clientOutMessage);
if (IsClientPacketModificationEnabled && _client.Logger.Level == Logger.LogLevel.Debug)
{
_client.Logger.Debug($"In Size: {_clientInMessage.Size}, Out Size: {_clientOutMessage.Size}");
_client.Logger.Debug($"In Data: {BitConverter.ToString(_clientInMessage.GetData()).Replace('-', ' ')}");
_client.Logger.Debug($"Out Data: {BitConverter.ToString(_clientOutMessage.GetData()).Replace('-', ' ')}");
}
SendToServer(IsClientPacketModificationEnabled ? _clientOutMessage : _clientInMessage);
}
else
{
if (IsClientPacketDecryptionEnabled)
{
_clientInMessage.PrepareToSend(_xteaKey);
}
SendToServer(_clientInMessage.GetData());
}
}
_clientSocket.BeginReceive(_clientInMessage.GetBuffer(), 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveClientCallback), 1);
}
catch (ObjectDisposedException)
{
// This exception can occur when the player logs out of their character (e.g., Ctrl+L).
ResetConnection();
}
catch (SocketException)
{
// This exception can happen if the client, forcefully, closes the connection (e.g., killing the client process).
ResetConnection();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
_client.Logger.Error($"Data: {BitConverter.ToString(_clientInMessage.GetData()).Replace('-', ' ')}");
}
}
/// <summary>
/// Handles all incoming data from the game server.
/// </summary>
/// <param name="ar">
/// An <see cref="IAsyncResult"/> object that indicates the status of the asynchronous operation.
/// </param>
private void BeginReceiveServerCallback(IAsyncResult ar)
{
try
{
if (_serverSocket == null)
{
return;
}
var count = _serverSocket.EndReceive(ar);
if (count <= 0)
{
ResetConnection();
return;
}
_serverInMessage.Size = (uint)BitConverter.ToUInt16(_serverInMessage.GetBuffer(), 0) + 2;
while (count < _serverInMessage.Size)
{
var read = _serverSocket.Receive(_serverInMessage.GetBuffer(), count, (int)(_serverInMessage.Size - count), SocketFlags.None);
if (read <= 0)
{
throw new Exception("[Connection.BeginReceiveServerCallback] Server connection broken.");
}
count += read;
}
if (IsServerPacketDecryptionEnabled)
{
_serverInMessage.PrepareToParse(_xteaKey, _zStream);
OnReceivedServerMessage?.Invoke(_serverInMessage.GetData());
}
if (IsServerPacketParsingEnabled)
{
_serverOutMessage.Reset();
_serverOutMessage.SequenceNumber = _serverInMessage.SequenceNumber;
ParseServerMessage(_client, _serverInMessage, _serverOutMessage);
if (IsServerPacketModificationEnabled && _client.Logger.Level == Logger.LogLevel.Debug)
{
_client.Logger.Debug($"In Size: {_serverInMessage.Size}, Out Size: {_serverOutMessage.Size}");
_client.Logger.Debug($"In Data: {BitConverter.ToString(_serverInMessage.GetData()).Replace('-', ' ')}");
_client.Logger.Debug($"Out Data: {BitConverter.ToString(_serverOutMessage.GetData()).Replace('-', ' ')}");
}
SendToClient(IsServerPacketModificationEnabled ? _serverOutMessage : _serverInMessage);
}
else
{
if (IsServerPacketDecryptionEnabled)
{
_serverInMessage.PrepareToSend(_xteaKey, IsServerPacketCompressionEnabled ? _zStream : null);
}
SendToClient(_serverInMessage.GetData());
}
_serverSocket.BeginReceive(_serverInMessage.GetBuffer(), 0, 2, SocketFlags.None, new AsyncCallback(BeginReceiveServerCallback), 1);
}
catch (ObjectDisposedException)
{
// This exception can occur if Stop() is called.
}
catch (SocketException)
{
// This exception can happen if the server, forcefully, closes the connection.
ResetConnection();
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
_client.Logger.Error($"Data: {BitConverter.ToString(_serverInMessage.GetData()).Replace('-', ' ')}");
}
}
/// <summary>
/// Asynchronously sends an HTTP POST to CipSoft's web service.
/// </summary>
/// <param name="content">
/// The JSON data to POST.
/// </param>
/// <returns>
/// The response from CipSoft's web service.
/// </returns>
private async Task<byte[]> PostAsync(string content)
{
try
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");
httpClient.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
httpClient.DefaultRequestHeaders.Add("Accept-Language", "en-US,*");
httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate");
var postContent = new StringContent(content, Encoding.UTF8, "application/json");
postContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
using (var response = await httpClient.PostAsync(new Uri(GetLoginWebService()), postContent).ConfigureAwait(false))
{
postContent.Dispose();
return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
}
}
}
catch (Exception ex)
{
_client.Logger.Error(ex.ToString());
return Array.Empty<byte>();
}