Skip to content

Commit

Permalink
Fixed merge conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
milutinke committed Dec 2, 2023
2 parents a41b671 + f2e1c57 commit 480f0d8
Show file tree
Hide file tree
Showing 15 changed files with 474 additions and 230 deletions.
16 changes: 12 additions & 4 deletions MinecraftClient/ChatBots/WebSocketBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -287,13 +287,21 @@ public class Configs

[TomlInlineComment("$ChatBot.WebSocketBot.DebugMode$")]
public bool DebugMode = false;

[TomlInlineComment("$ChatBot.WebSocketBot.AllowIpAlias$")]
public bool AllowIpAlias = false;
}

public WebSocketBot()
{
_password = Config.Password;
_authenticatedSessions = new();
_waitingEvents = new();

var match = Regex.Match(Config.Ip!, @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}");

if (!match.Success)
// If AllowIpAlias is set to true in the config, then always ignore this check
if (!match.Success & !Config.AllowIpAlias!)
{
LogToConsole(Translations.bot_WebSocketBot_failed_to_start_ip);
return;
Expand All @@ -307,9 +315,6 @@ public WebSocketBot()

_ip = Config.Ip;
_port = Config.Port;
_password = Config.Password;
_authenticatedSessions = new();
_waitingEvents = new();
}

public override void Initialize()
Expand Down Expand Up @@ -420,6 +425,9 @@ private bool ProcessWebsocketCommand(string sessionId, string password, string m
_authenticatedSessions.Add(newId);
}

// Update the responder to the new session id
responder = new WsCommandResponder(this, newId, cmd.Command, cmd.RequestId);

responder.SendSuccessResponse(
responder.Quote("The session ID was successfully changed to: '" + newId + "'"), true);
LogToConsole(string.Format(Translations.bot_WebSocketBot_session_id_changed, sessionId, newId));
Expand Down
10 changes: 10 additions & 0 deletions MinecraftClient/McClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3438,6 +3438,16 @@ public void OnUpdateScore(string entityname, int action, string objectivename, i
{
DispatchBotEvent(bot => bot.OnUpdateScore(entityname, action, objectivename, value));
}

/// <summary>
/// Called when the client received the Tab Header and Footer
/// </summary>
/// <param name="header">Header</param>
/// <param name="footer">Footer</param>
public void OnTabListHeaderAndFooter(string header, string footer)
{
DispatchBotEvent(bot => bot.OnTabListHeaderAndFooter(header, footer));
}

/// <summary>
/// Called when the health of an entity changed
Expand Down
7 changes: 4 additions & 3 deletions MinecraftClient/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ private static void InitializeClient()
else
{
// Validate cached session or login new session.
if (Config.Main.Advanced.SessionCache != CacheType.none && SessionCache.Contains(loginLower))
if (Config.Main.Advanced.SessionCache != CacheType.none && SessionCache.Contains(loginLower) && Config.Main.General.AccountType != LoginType.yggdrasil)
{
session = SessionCache.Get(loginLower);
result = ProtocolHandler.GetTokenValidation(session);
Expand Down Expand Up @@ -447,15 +447,15 @@ private static void InitializeClient()

if (result != ProtocolHandler.LoginResult.Success)
{
ConsoleIO.WriteLine(string.Format(Translations.mcc_connecting, Config.Main.General.AccountType == LoginType.mojang ? "Minecraft.net" : "Microsoft"));
ConsoleIO.WriteLine(string.Format(Translations.mcc_connecting, Config.Main.General.AccountType == LoginType.mojang ? "Minecraft.net" : (Config.Main.General.AccountType == LoginType.microsoft ? "Microsoft" : Config.Main.General.AuthServer.Host)));
result = ProtocolHandler.GetLogin(InternalConfig.Account.Login, InternalConfig.Account.Password, Config.Main.General.AccountType, out session);
}

if (result == ProtocolHandler.LoginResult.Success && Config.Main.Advanced.SessionCache != CacheType.none)
SessionCache.Store(loginLower, session);

if (result == ProtocolHandler.LoginResult.Success)
session.SessionPreCheckTask = Task.Factory.StartNew(() => session.SessionPreCheck());
session.SessionPreCheckTask = Task.Factory.StartNew(() => session.SessionPreCheck(Config.Main.General.AccountType));
}

if (result == ProtocolHandler.LoginResult.Success)
Expand Down Expand Up @@ -649,6 +649,7 @@ private static void InitializeClient()
ProtocolHandler.LoginResult.OtherError => Translations.error_login_network,
ProtocolHandler.LoginResult.SSLError => Translations.error_login_ssl,
ProtocolHandler.LoginResult.UserCancel => Translations.error_login_cancel,
ProtocolHandler.LoginResult.WrongSelection => Translations.error_login_blocked,
_ => Translations.error_login_unknown,
#pragma warning restore format // @formatter:on
};
Expand Down
7 changes: 4 additions & 3 deletions MinecraftClient/Protocol/Handlers/Protocol16.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
using MinecraftClient.Proxy;
using MinecraftClient.Scripting;
using static MinecraftClient.Settings;
using static MinecraftClient.Settings.MainConfigHealper.MainConfig.GeneralConfig;

namespace MinecraftClient.Protocol.Handlers
{
Expand Down Expand Up @@ -504,7 +505,7 @@ private bool Handshake(string uuid, string username, string sessionID, string ho
else if (Settings.Config.Logging.DebugMessages)
ConsoleIO.WriteLineFormatted("§8" + string.Format(Translations.mcc_handshake, serverID));

return StartEncryption(uuid, username, sessionID, token, serverID, PublicServerkey, session);
return StartEncryption(uuid, username, sessionID, Config.Main.General.AccountType, token, serverID, PublicServerkey, session);
}
else
{
Expand All @@ -513,7 +514,7 @@ private bool Handshake(string uuid, string username, string sessionID, string ho
}
}

private bool StartEncryption(string uuid, string username, string sessionID, byte[] token, string serverIDhash, byte[] serverPublicKey, SessionToken session)
private bool StartEncryption(string uuid, string username, string sessionID, LoginType type, byte[] token, string serverIDhash, byte[] serverPublicKey, SessionToken session)
{
RSACryptoServiceProvider RSAService = CryptoHandler.DecodeRSAPublicKey(serverPublicKey)!;
byte[] secretKey = CryptoHandler.ClientAESPrivateKey ?? CryptoHandler.GenerateAESPrivateKey();
Expand All @@ -537,7 +538,7 @@ private bool StartEncryption(string uuid, string username, string sessionID, byt

if (needCheckSession)
{
if (ProtocolHandler.SessionCheck(uuid, sessionID, serverHash))
if (ProtocolHandler.SessionCheck(uuid, sessionID, serverHash, type))
{
session.ServerIDhash = serverIDhash;
session.ServerPublicKey = serverPublicKey;
Expand Down
148 changes: 67 additions & 81 deletions MinecraftClient/Protocol/Handlers/Protocol18.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
using MinecraftClient.Proxy;
using MinecraftClient.Scripting;
using static MinecraftClient.Settings;
using static MinecraftClient.Settings.MainConfigHealper.MainConfig.GeneralConfig;

namespace MinecraftClient.Protocol.Handlers
{
Expand Down Expand Up @@ -337,7 +338,7 @@ internal Tuple<int, Queue<byte>> ReadNextPacket()
{
var toDecompress = packetData.ToArray();
var uncompressed = ZlibUtils.Decompress(toDecompress, sizeUncompressed);
packetData = new(uncompressed);
packetData = new Queue<byte>(uncompressed);
}
}

Expand Down Expand Up @@ -912,8 +913,7 @@ private bool HandlePlayPackets(int packetId, Queue<byte> packetData)
.StringValue;
string? senderTeamName = null;
if (targetName != null &&
(messageTypeEnum == ChatParser.MessageType.TEAM_MSG_COMMAND_INCOMING ||
messageTypeEnum == ChatParser.MessageType.TEAM_MSG_COMMAND_OUTGOING))
messageTypeEnum is ChatParser.MessageType.TEAM_MSG_COMMAND_INCOMING or ChatParser.MessageType.TEAM_MSG_COMMAND_OUTGOING)
senderTeamName = Json.ParseJson(targetName).Properties["with"].DataArray[0]
.Properties["text"].StringValue;

Expand Down Expand Up @@ -1311,7 +1311,7 @@ private bool HandlePlayPackets(int packetId, Queue<byte> packetData)
else
{
var chunksContinuous = dataTypes.ReadNextBool(packetData);
if (protocolVersion >= MC_1_16_Version && protocolVersion <= MC_1_16_1_Version)
if (protocolVersion is >= MC_1_16_Version and <= MC_1_16_1_Version)
dataTypes.ReadNextBool(packetData); // Ignore old data - 1.16 to 1.16.1 only
var chunkMask = protocolVersion >= MC_1_9_Version
? (ushort)dataTypes.ReadNextVarInt(packetData)
Expand Down Expand Up @@ -2758,7 +2758,8 @@ public bool Login(PlayerKeyPair? playerKeyPair, SessionToken session)
var serverId = dataTypes.ReadNextString(packetData);
var serverPublicKey = dataTypes.ReadNextByteArray(packetData);
var token = dataTypes.ReadNextByteArray(packetData);
return StartEncryption(handler.GetUserUuidStr(), handler.GetSessionID(), token, serverId,
return StartEncryption(handler.GetUserUuidStr(), handler.GetSessionID(),
Config.Main.General.AccountType, token, serverId,
serverPublicKey, playerKeyPair, session);
}

Expand Down Expand Up @@ -2793,7 +2794,7 @@ public bool Login(PlayerKeyPair? playerKeyPair, SessionToken session)
/// Start network encryption. Automatically called by Login() if the server requests encryption.
/// </summary>
/// <returns>True if encryption was successful</returns>
private bool StartEncryption(string uuid, string sessionID, byte[] token, string serverIDhash,
private bool StartEncryption(string uuid, string sessionID, LoginType type, byte[] token, string serverIDhash,
byte[] serverPublicKey, PlayerKeyPair? playerKeyPair, SessionToken session)
{
var RSAService = CryptoHandler.DecodeRSAPublicKey(serverPublicKey)!;
Expand All @@ -2818,8 +2819,7 @@ private bool StartEncryption(string uuid, string sessionID, byte[] token, string
if (needCheckSession)
{
var serverHash = CryptoHandler.GetServerHash(serverIDhash, serverPublicKey, secretKey);

if (ProtocolHandler.SessionCheck(uuid, sessionID, serverHash))
if (ProtocolHandler.SessionCheck(uuid, sessionID, serverHash, type))
{
session.ServerIDhash = serverIDhash;
session.ServerPublicKey = serverPublicKey;
Expand Down Expand Up @@ -4142,9 +4142,11 @@ public bool ClickContainerButton(int windowId, int buttonId)
{
try
{
List<byte> packet = new();
packet.Add((byte)windowId);
packet.Add((byte)buttonId);
var packet = new List<byte>
{
(byte)windowId,
(byte)buttonId
};
SendPacket(PacketTypesOut.ClickWindowButton, packet);
return true;
}
Expand Down Expand Up @@ -4271,32 +4273,27 @@ public bool SendUpdateSign(Location sign, string line1, string line2, string lin
public bool UpdateCommandBlock(Location location, string command, CommandBlockMode mode,
CommandBlockFlags flags)
{
if (protocolVersion <= MC_1_13_Version)
if (protocolVersion > MC_1_13_Version) return false;

try
{
try
{
List<byte> packet = new();
packet.AddRange(dataTypes.GetLocation(location));
packet.AddRange(dataTypes.GetString(command));
packet.AddRange(DataTypes.GetVarInt((int)mode));
packet.Add((byte)flags);
SendPacket(PacketTypesOut.UpdateSign, packet);
return true;
}
catch (SocketException)
{
return false;
}
catch (System.IO.IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
List<byte> packet = new();
packet.AddRange(dataTypes.GetLocation(location));
packet.AddRange(dataTypes.GetString(command));
packet.AddRange(DataTypes.GetVarInt((int)mode));
packet.Add((byte)flags);
SendPacket(PacketTypesOut.UpdateSign, packet);
return true;
}
else
catch (SocketException)
{
return false;
}
catch (System.IO.IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
Expand All @@ -4306,8 +4303,7 @@ public bool SendWindowConfirmation(byte windowID, short actionID, bool accepted)
{
try
{
List<byte> packet = new();
packet.Add(windowID);
var packet = new List<byte>() { windowID };
packet.AddRange(dataTypes.GetShort(actionID));
packet.Add(accepted ? (byte)1 : (byte)0);
SendPacket(PacketTypesOut.WindowConfirmation, packet);
Expand All @@ -4330,60 +4326,50 @@ public bool SendWindowConfirmation(byte windowID, short actionID, bool accepted)
public bool SelectTrade(int selectedSlot)
{
// MC 1.13 or greater
if (protocolVersion >= MC_1_13_Version)
if (protocolVersion < MC_1_13_Version) return false;

try
{
try
{
List<byte> packet = new();
packet.AddRange(DataTypes.GetVarInt(selectedSlot));
SendPacket(PacketTypesOut.SelectTrade, packet);
return true;
}
catch (SocketException)
{
return false;
}
catch (System.IO.IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
List<byte> packet = new();
packet.AddRange(DataTypes.GetVarInt(selectedSlot));
SendPacket(PacketTypesOut.SelectTrade, packet);
return true;
}
else
catch (SocketException)
{
return false;
}
catch (System.IO.IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
}

public bool SendSpectate(Guid UUID)
public bool SendSpectate(Guid uuid)
{
// MC 1.8 or greater
if (protocolVersion >= MC_1_8_Version)
if (protocolVersion < MC_1_8_Version) return false;

try
{
try
{
List<byte> packet = new();
packet.AddRange(DataTypes.GetUUID(UUID));
SendPacket(PacketTypesOut.Spectate, packet);
return true;
}
catch (SocketException)
{
return false;
}
catch (System.IO.IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
List<byte> packet = new();
packet.AddRange(DataTypes.GetUUID(uuid));
SendPacket(PacketTypesOut.Spectate, packet);
return true;
}
else
catch (SocketException)
{
return false;
}
catch (System.IO.IOException)
{
return false;
}
catch (ObjectDisposedException)
{
return false;
}
Expand Down Expand Up @@ -4462,7 +4448,7 @@ private byte[] GenerateSalt()
return salt;
}

public static long GetNanos()
private static long GetNanos()
{
var nano = 10000L * Stopwatch.GetTimestamp();
nano /= TimeSpan.TicksPerMillisecond;
Expand Down
7 changes: 7 additions & 0 deletions MinecraftClient/Protocol/IMinecraftComHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,13 @@ public interface IMinecraftComHandler
/// <param name="value">he score to be displayed next to the entry. Only sent when Action does not equal 1.</param>
void OnUpdateScore(string entityname, int action, string objectivename, int value);

/// <summary>
/// Called when the client received the Tab Header and Footer
/// </summary>
/// <param name="header">Header</param>
/// <param name="footer">Footer</param>
void OnTabListHeaderAndFooter(string header, string footer);

/// <summary>
/// Called when tradeList is received from server
/// </summary>
Expand Down
Loading

0 comments on commit 480f0d8

Please sign in to comment.