Skip to content

Commit 9ba60d1

Browse files
committed
Update dependencies and various improvements
Listen on port 7171, instead of 80, by default. More control over what parts of the proxy are in use. Fix race condition of resetting the proxy connection.
1 parent 9e81e3b commit 9ba60d1

10 files changed

Lines changed: 79 additions & 50 deletions

File tree

Apps/Record/Program.cs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class Program
4040
static string _loginWebService = string.Empty;
4141
static string _tibiaDirectory = string.Empty;
4242

43-
static int _httpPort = 80;
43+
static int _httpPort = 7171;
4444

4545
static bool _isWritingToFile = false;
4646

@@ -126,7 +126,9 @@ static void Main(string[] args)
126126
client.Connection.OnReceivedServerMessage += Proxy_OnReceivedServerMessage;
127127

128128
// Disable packet parsing as we only care about the raw, decrypted packets and speed.
129-
client.StartConnection(enablePacketParsing: false, httpPort: _httpPort, loginWebService: _loginWebService);
129+
client.Connection.IsClientPacketParsingEnabled = false;
130+
client.Connection.IsServerPacketParsingEnabled = false;
131+
client.StartConnection(httpPort: _httpPort, loginWebService: _loginWebService);
130132

131133
while (Console.ReadLine() != "quit")
132134
{

TibiaAPI/Client.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,9 @@ public Client(string tibiaDirectory = "")
4242
Connection = new Network.Connection(this);
4343
}
4444

45-
public bool StartConnection(bool enablePacketParsing = true, int httpPort = 80, string loginWebService = "")
45+
public bool StartConnection(int httpPort = 7171, string loginWebService = "")
4646
{
47-
return Connection.Start(enablePacketParsing, httpPort, loginWebService);
47+
return Connection.Start(httpPort, loginWebService);
4848
}
4949

5050
public void StopConnection()

TibiaAPI/Constants/Enums.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -511,7 +511,7 @@ public enum ServerPacketType
511511
SpellGroupDelay = 0xA5,
512512
MultiUseDelay = 0xA6,
513513
SetTactics = 0xA7,
514-
SetStoreDeepLink = 0xA8,
514+
SetStoreButtonDeeplink = 0xA8,
515515
RestingAreaState = 0xA9,
516516
Talk = 0xAA,
517517
Channels = 0xAB,

TibiaAPI/GlobalSuppressions.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,6 @@
1515
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1724:Type names should not match namespaces", Justification = "<Pending>", Scope = "type", Target = "~T:OXGaming.TibiaAPI.Network.ServerPackets.Channels")]
1616
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1724:Type names should not match namespaces", Justification = "<Pending>", Scope = "type", Target = "~T:OXGaming.TibiaAPI.WorldMap.Field")]
1717
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1305:Specify IFormatProvider", Justification = "<Pending>", Scope = "member", Target = "~M:OXGaming.TibiaAPI.Network.Communication.ParseServerMessage(OXGaming.TibiaAPI.Client,OXGaming.TibiaAPI.Network.NetworkMessage,OXGaming.TibiaAPI.Network.NetworkMessage)")]
18-
18+
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1062:Validate arguments of public methods", Justification = "<Pending>")]
19+
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "<Pending>")]
20+
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "<Pending>")]

TibiaAPI/Network/Communication.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -761,7 +761,7 @@ public void ParseClientMessage(Client client, NetworkMessage inMessage, NetworkM
761761
return;
762762
}
763763

764-
if (packet.Forward && client.Connection.AllowPacketModification)
764+
if (packet.Forward && client.Connection.IsClientPacketModificationEnabled)
765765
{
766766
packet.AppendToNetworkMessage(outMessage);
767767
}
@@ -1052,7 +1052,7 @@ public void ParseServerMessage(Client client, NetworkMessage inMessage, NetworkM
10521052
case ServerPacketType.SetTactics:
10531053
packet.Forward = OnReceivedServerSetTacticsPacket?.Invoke(packet) ?? true;
10541054
break;
1055-
case ServerPacketType.SetStoreDeepLink:
1055+
case ServerPacketType.SetStoreButtonDeeplink:
10561056
packet.Forward = OnReceivedServerSetStoreDeepLinkPacket?.Invoke(packet) ?? true;
10571057
break;
10581058
case ServerPacketType.RestingAreaState:
@@ -1302,7 +1302,7 @@ public void ParseServerMessage(Client client, NetworkMessage inMessage, NetworkM
13021302
return;
13031303
}
13041304

1305-
if (packet.Forward && client.Connection.AllowPacketModification)
1305+
if (packet.Forward && client.Connection.IsServerPacketModificationEnabled)
13061306
{
13071307
packet.AppendToNetworkMessage(outMessage);
13081308
}

TibiaAPI/Network/Connection.cs

Lines changed: 55 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
using Newtonsoft.Json;
1414

1515
using OXGaming.TibiaAPI.Constants;
16+
using OXGaming.TibiaAPI.Utilities;
1617

1718
namespace OXGaming.TibiaAPI.Network
1819
{
@@ -32,7 +33,6 @@ public class Connection : Communication, IDisposable
3233

3334
private readonly Client _client;
3435

35-
private readonly HttpClient _httpClient = new HttpClient();
3636
private readonly HttpListener _httpListener = new HttpListener();
3737

3838
private readonly NetworkMessage _clientInMessage;
@@ -64,11 +64,10 @@ public class Connection : Communication, IDisposable
6464
private uint _clientSequenceNumber = 1;
6565
private uint _serverSequenceNumber = 1;
6666

67-
private bool _isPacketParsingEnabled;
67+
private bool _isResettingConnection = false;
6868
private bool _isSendingToClient = false;
6969
private bool _isSendingToServer = false;
7070
private bool _isStarted;
71-
private bool _recompressPackets;
7271

7372
public delegate void ReceivedMessageEventHandler(byte[] data);
7473

@@ -77,7 +76,13 @@ public class Connection : Communication, IDisposable
7776

7877
public ConnectionState ConnectionState { get; set; } = ConnectionState.Disconnected;
7978

80-
public bool AllowPacketModification { get; set; } = false;
79+
public bool IsClientPacketDecryptionEnabled { get; set; } = true;
80+
public bool IsClientPacketModificationEnabled { get; set; } = false;
81+
public bool IsClientPacketParsingEnabled { get; set; } = true;
82+
public bool IsServerPacketDecryptionEnabled { get; set; } = true;
83+
public bool IsServerPacketCompressionEnabled { get; set; } = false;
84+
public bool IsServerPacketModificationEnabled { get; set; } = false;
85+
public bool IsServerPacketParsingEnabled { get; set; } = true;
8186

8287
/// <summary>
8388
/// Initializes a new instance of the <see cref="Connection"/> class that acts as a proxy
@@ -90,16 +95,14 @@ public Connection(Client client)
9095
_clientOutMessage = new NetworkMessage(_client);
9196
_serverInMessage = new NetworkMessage(_client);
9297
_serverOutMessage = new NetworkMessage(_client);
93-
94-
_httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0");
9598
}
9699

97100
/// <summary>
98101
/// Starts the <see cref="HttpListener"/> and <see cref="TcpListener"/> objects that listen for incoming
99102
/// connection requests from the Tibia client.
100103
/// </summary>
101104
/// <returns>Returns true on success, or if already started. Returns false if an exception is thrown.</returns>
102-
internal bool Start(bool enablePacketParsing = true, int httpPort = 80, string loginWebService = "", bool recompressPackets = false)
105+
internal bool Start(int httpPort = 7171, string loginWebService = "")
103106
{
104107
if (_isStarted)
105108
{
@@ -130,8 +133,6 @@ internal bool Start(bool enablePacketParsing = true, int httpPort = 80, string l
130133

131134
_isStarted = true;
132135
_loginWebService = loginWebService;
133-
_isPacketParsingEnabled = enablePacketParsing;
134-
_recompressPackets = recompressPackets;
135136
ConnectionState = ConnectionState.ConnectingStage1;
136137
}
137138
catch (Exception ex)
@@ -187,7 +188,7 @@ public void SendToClient(NetworkMessage message)
187188
}
188189
}
189190

190-
message.PrepareToSend(_xteaKey, (_recompressPackets ? _zStream : null));
191+
message.PrepareToSend(_xteaKey, (IsServerPacketCompressionEnabled ? _zStream : null));
191192
SendToClient(message.GetData());
192193
}
193194

@@ -379,6 +380,13 @@ internal void Stop()
379380
/// </summary>
380381
private void ResetConnection()
381382
{
383+
if (_isResettingConnection)
384+
{
385+
return;
386+
}
387+
388+
_isResettingConnection = true;
389+
382390
lock (_clientSendLock)
383391
{
384392
_isSendingToClient = false;
@@ -408,6 +416,7 @@ private void ResetConnection()
408416
_clientSequenceNumber = 1;
409417
_serverSequenceNumber = 1;
410418
_xteaKey = null;
419+
_isResettingConnection = false;
411420
ConnectionState = ConnectionState.ConnectingStage1;
412421
}
413422

@@ -772,7 +781,7 @@ private void BeginReceiveClientCallback(IAsyncResult ar)
772781

773782
OnReceivedClientMessage?.Invoke(_clientInMessage.GetData());
774783

775-
if (_isPacketParsingEnabled)
784+
if (IsClientPacketParsingEnabled)
776785
{
777786
_clientOutMessage.Reset();
778787
ParseClientMessage(_client, _clientInMessage, _clientOutMessage);
@@ -801,27 +810,33 @@ private void BeginReceiveClientCallback(IAsyncResult ar)
801810
}
802811
else
803812
{
804-
_clientInMessage.PrepareToParse(_xteaKey);
805-
OnReceivedClientMessage?.Invoke(_clientInMessage.GetData());
813+
if (IsClientPacketDecryptionEnabled)
814+
{
815+
_clientInMessage.PrepareToParse(_xteaKey);
816+
OnReceivedClientMessage?.Invoke(_clientInMessage.GetData());
817+
}
806818

807-
if (_isPacketParsingEnabled)
819+
if (IsClientPacketParsingEnabled)
808820
{
809821
_clientOutMessage.Reset();
810822
_clientOutMessage.SequenceNumber = _clientInMessage.SequenceNumber;
811823

812824
ParseClientMessage(_client, _clientInMessage, _clientOutMessage);
813825

814-
if (AllowPacketModification)
826+
if (IsClientPacketModificationEnabled && _client.Logger.Level == Logger.LogLevel.Debug)
815827
{
816828
_client.Logger.Debug($"In Size: {_clientInMessage.Size}, Out Size: {_clientOutMessage.Size}");
817829
_client.Logger.Debug($"In Data: {BitConverter.ToString(_clientInMessage.GetData()).Replace('-', ' ')}");
818830
_client.Logger.Debug($"Out Data: {BitConverter.ToString(_clientOutMessage.GetData()).Replace('-', ' ')}");
819831
}
820-
SendToServer(AllowPacketModification ? _clientOutMessage : _clientInMessage);
832+
SendToServer(IsClientPacketModificationEnabled ? _clientOutMessage : _clientInMessage);
821833
}
822834
else
823835
{
824-
_clientInMessage.PrepareToSend(_xteaKey);
836+
if (IsClientPacketDecryptionEnabled)
837+
{
838+
_clientInMessage.PrepareToSend(_xteaKey);
839+
}
825840
SendToServer(_clientInMessage.GetData());
826841
}
827842
}
@@ -879,28 +894,34 @@ private void BeginReceiveServerCallback(IAsyncResult ar)
879894
count += read;
880895
}
881896

882-
_serverInMessage.PrepareToParse(_xteaKey, _zStream);
883-
OnReceivedServerMessage?.Invoke(_serverInMessage.GetData());
897+
if (IsServerPacketDecryptionEnabled)
898+
{
899+
_serverInMessage.PrepareToParse(_xteaKey, _zStream);
900+
OnReceivedServerMessage?.Invoke(_serverInMessage.GetData());
901+
}
884902

885-
if (_isPacketParsingEnabled)
903+
if (IsServerPacketParsingEnabled)
886904
{
887905
_serverOutMessage.Reset();
888906
_serverOutMessage.SequenceNumber = _serverInMessage.SequenceNumber;
889907

890908
ParseServerMessage(_client, _serverInMessage, _serverOutMessage);
891909

892-
if (AllowPacketModification)
910+
if (IsServerPacketModificationEnabled && _client.Logger.Level == Logger.LogLevel.Debug)
893911
{
894912
_client.Logger.Debug($"In Size: {_serverInMessage.Size}, Out Size: {_serverOutMessage.Size}");
895913
_client.Logger.Debug($"In Data: {BitConverter.ToString(_serverInMessage.GetData()).Replace('-', ' ')}");
896914
_client.Logger.Debug($"Out Data: {BitConverter.ToString(_serverOutMessage.GetData()).Replace('-', ' ')}");
897915
}
898916

899-
SendToClient(AllowPacketModification ? _serverOutMessage : _serverInMessage);
917+
SendToClient(IsServerPacketModificationEnabled ? _serverOutMessage : _serverInMessage);
900918
}
901919
else
902920
{
903-
_serverInMessage.PrepareToSend(_xteaKey, (_recompressPackets ? _zStream : null));
921+
if (IsServerPacketDecryptionEnabled)
922+
{
923+
_serverInMessage.PrepareToSend(_xteaKey, IsServerPacketCompressionEnabled ? _zStream : null);
924+
}
904925
SendToClient(_serverInMessage.GetData());
905926
}
906927

@@ -935,12 +956,16 @@ private async Task<string> PostAsync(string content)
935956
{
936957
try
937958
{
938-
var postContent = new StringContent(content, Encoding.UTF8, "application/json");
939-
var response = await _httpClient
940-
.PostAsync(new Uri(GetLoginWebService()), postContent)
941-
.ConfigureAwait(false);
942-
response.EnsureSuccessStatusCode();
943-
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
959+
using (var httpClient = new HttpClient())
960+
{
961+
httpClient.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0");
962+
var postContent = new StringContent(content, Encoding.UTF8, "application/json");
963+
using (var response = await httpClient.PostAsync(new Uri(GetLoginWebService()), postContent).ConfigureAwait(false))
964+
{
965+
postContent.Dispose();
966+
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
967+
}
968+
}
944969
}
945970
catch (Exception ex)
946971
{
@@ -978,7 +1003,7 @@ protected virtual void Dispose(bool disposing)
9781003
{
9791004
if (disposing)
9801005
{
981-
_httpClient.Dispose();
1006+
_httpListener.Close();
9821007

9831008
if (_clientSocket != null)
9841009
{

TibiaAPI/Network/NetworkMessage.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,12 +112,12 @@ public byte[] GetBuffer()
112112
/// Gets the actual data from the underlying buffer.
113113
/// </value>
114114
/// <remarks>
115-
/// Get this only when necessary as it creates a new byte array.
115+
/// Call this only when necessary as it creates a new byte array.
116116
/// </remarks>
117117
public byte[] GetData()
118118
{
119119
var data = new byte[Size];
120-
Array.Copy(_buffer, data, Size);
120+
Buffer.BlockCopy(_buffer, 0, data, 0, (int)Size);
121121
return data;
122122
}
123123

TibiaAPI/Network/ServerPacket.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -168,8 +168,8 @@ public static ServerPacket CreateInstance(Client client, ServerPacketType type)
168168
return new ServerPackets.MultiUseDelay(client);
169169
case ServerPacketType.SetTactics:
170170
return new ServerPackets.SetTactics(client);
171-
case ServerPacketType.SetStoreDeepLink:
172-
return new ServerPackets.SetStoreDeepLink(client);
171+
case ServerPacketType.SetStoreButtonDeeplink:
172+
return new ServerPackets.SetStoreButtonDeeplink(client);
173173
case ServerPacketType.RestingAreaState:
174174
return new ServerPackets.RestingAreaState(client);
175175
case ServerPacketType.Talk:

TibiaAPI/Network/ServerPackets/SetStoreDeepLink.cs renamed to TibiaAPI/Network/ServerPackets/SetStoreButtonDeeplink.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,16 @@
22

33
namespace OXGaming.TibiaAPI.Network.ServerPackets
44
{
5-
public class SetStoreDeepLink : ServerPacket
5+
public class SetStoreButtonDeeplink : ServerPacket
66
{
77
public ushort Unknown { get; set; }
88

99
public byte StoreServiceType { get; set; }
1010

11-
public SetStoreDeepLink(Client client)
11+
public SetStoreButtonDeeplink(Client client)
1212
{
1313
Client = client;
14-
PacketType = ServerPacketType.SetStoreDeepLink;
14+
PacketType = ServerPacketType.SetStoreButtonDeeplink;
1515
}
1616

1717
public override void ParseFromNetworkMessage(NetworkMessage message)
@@ -26,7 +26,7 @@ public override void ParseFromNetworkMessage(NetworkMessage message)
2626

2727
public override void AppendToNetworkMessage(NetworkMessage message)
2828
{
29-
message.Write((byte)ServerPacketType.SetStoreDeepLink);
29+
message.Write((byte)ServerPacketType.SetStoreButtonDeeplink);
3030
if (Client.VersionNumber >= 11887288)
3131
{
3232
message.Write(Unknown);

TibiaAPI/TibiaAPI.csproj

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616
</PropertyGroup>
1717

1818
<ItemGroup>
19-
<PackageReference Include="Google.Protobuf" Version="3.6.1" />
20-
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.6.3">
19+
<PackageReference Include="Google.Protobuf" Version="3.9.1" />
20+
<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.4">
2121
<PrivateAssets>all</PrivateAssets>
2222
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
2323
</PackageReference>
24-
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
24+
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
2525
<PackageReference Include="Portable.BouncyCastle" Version="1.8.5" />
2626
<PackageReference Include="Microsoft.CSharp" Version="4.5.0" />
2727
</ItemGroup>

0 commit comments

Comments
 (0)