From b0652c2c83dc24b1db72849d431ca653fc75488b Mon Sep 17 00:00:00 2001 From: Bluzume <39113159+KuromeSan@users.noreply.github.com> Date: Wed, 30 Sep 2020 18:23:19 +1300 Subject: [PATCH] Add files via upload --- .../Horse Isle Server/Authentication.cs | 178 ++-- Horse Isle Server/Horse Isle Server/Client.cs | 271 ++--- .../Horse Isle Server/ConfigReader.cs | 210 ++-- .../Horse Isle Server/Converters.cs | 76 +- .../Horse Isle Server/CrossDomainPolicy.cs | 68 +- .../Horse Isle Server/Database.cs | 994 +++++++++--------- .../Horse Isle Server/Gamedata.cs | 116 +- .../Horse Isle Server.csproj | 218 ++-- Horse Isle Server/Horse Isle Server/Logger.cs | 50 +- .../Horse Isle Server/Mailbox.cs | 40 +- Horse Isle Server/Horse Isle Server/Map.cs | 93 +- .../Horse Isle Server/Messages.cs | 78 +- .../Horse Isle Server/PacketBuilder.cs | 854 +++++++-------- .../Horse Isle Server/Program.cs | 66 +- .../Properties/AssemblyInfo.cs | 72 +- .../Properties/Resources.Designer.cs | 208 ++-- .../Properties/Resources.resx | 252 ++--- .../Resources/default_cross_domain.xml | 4 +- .../Resources/server.properties | 55 +- Horse Isle Server/Horse Isle Server/Server.cs | 340 +++--- Horse Isle Server/Horse Isle Server/User.cs | 326 +++--- Horse Isle Server/Horse Isle Server/World.cs | 158 +-- .../Horse Isle Server/packages.config | 18 +- 23 files changed, 2422 insertions(+), 2323 deletions(-) diff --git a/Horse Isle Server/Horse Isle Server/Authentication.cs b/Horse Isle Server/Horse Isle Server/Authentication.cs index cc8e6dd..1a8bb31 100644 --- a/Horse Isle Server/Horse Isle Server/Authentication.cs +++ b/Horse Isle Server/Horse Isle Server/Authentication.cs @@ -1,89 +1,89 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Security.Cryptography; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Authentication - { - public static string DecryptLogin(string encpass) - { - string decrypt = ""; - string ROTPOOL = "bl7Jgk61IZdnY mfDN5zjM2XLqTCty4WSEoKR3BFVQsaUhHOAx0rPwp9uc8iGve"; - string POSPOOL = "DQc3uxiGsKZatMmOS5qYveN71zoPTk8yU0H2w9VjprBXWn l4FJd6IRbhgACfEL"; - string ROTPOOL2 = "evGi8cu9pwPr0xAOHhUasQVFB3RKoESW4ytCTqLX2Mjz5NDfm YndZI16kgJ7lb"; - - - int i = 0; - int ii = 0; - while (i < encpass.Length) - { - int ROT = ROTPOOL.IndexOf(encpass[i].ToString()); - int POS = POSPOOL.IndexOf(encpass[i + 1].ToString()); - POS -= (ROT + ii); - if (POS < 0) - { - POS = (POS / -1) - 1; - - while (POS >= ROTPOOL.Length) - { - POS -= ROTPOOL.Length; - } - - decrypt += ROTPOOL2[POS]; - } - else - { - while (POS >= ROTPOOL.Length) - { - POS -= ROTPOOL.Length; - } - - decrypt += ROTPOOL[POS]; - } - - i += 2; - ii += 1; - } - return decrypt.Replace(" ", ""); - } - - - - public static byte[] HashAndSalt(string plaintext, byte[] salt) - { - byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); - - SHA512 sha512 = new SHA512Managed(); - byte[] hash = sha512.ComputeHash(plaintextBytes); - - for (int i = 0; i < hash.Length; i++) - { - hash[i] ^= salt[i]; - } - - - byte[] finalHash = sha512.ComputeHash(hash); - - return finalHash; - } - - public static bool CheckPassword(string username, string password) - { - if(Database.CheckUserExist(username)) - { - byte[] expectedPassword = Database.GetPasswordHash(username); - byte[] salt = Database.GetPasswordSalt(username); - byte[] hashedPassword = HashAndSalt(password, salt); - - if (Enumerable.SequenceEqual(expectedPassword, hashedPassword)) - return true; - } - return false; - } - - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Authentication + { + public static string DecryptLogin(string encpass) + { + string decrypt = ""; + string ROTPOOL = "bl7Jgk61IZdnY mfDN5zjM2XLqTCty4WSEoKR3BFVQsaUhHOAx0rPwp9uc8iGve"; + string POSPOOL = "DQc3uxiGsKZatMmOS5qYveN71zoPTk8yU0H2w9VjprBXWn l4FJd6IRbhgACfEL"; + string ROTPOOL2 = "evGi8cu9pwPr0xAOHhUasQVFB3RKoESW4ytCTqLX2Mjz5NDfm YndZI16kgJ7lb"; + + + int i = 0; + int ii = 0; + while (i < encpass.Length) + { + int ROT = ROTPOOL.IndexOf(encpass[i].ToString()); + int POS = POSPOOL.IndexOf(encpass[i + 1].ToString()); + POS -= (ROT + ii); + if (POS < 0) + { + POS = (POS / -1) - 1; + + while (POS >= ROTPOOL.Length) + { + POS -= ROTPOOL.Length; + } + + decrypt += ROTPOOL2[POS]; + } + else + { + while (POS >= ROTPOOL.Length) + { + POS -= ROTPOOL.Length; + } + + decrypt += ROTPOOL[POS]; + } + + i += 2; + ii += 1; + } + return decrypt.Replace(" ", ""); + } + + + + public static byte[] HashAndSalt(string plaintext, byte[] salt) + { + byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext); + + SHA512 sha512 = new SHA512Managed(); + byte[] hash = sha512.ComputeHash(plaintextBytes); + + for (int i = 0; i < hash.Length; i++) + { + hash[i] ^= salt[i]; + } + + + byte[] finalHash = sha512.ComputeHash(hash); + + return finalHash; + } + + public static bool CheckPassword(string username, string password) + { + if(Database.CheckUserExist(username)) + { + byte[] expectedPassword = Database.GetPasswordHash(username); + byte[] salt = Database.GetPasswordSalt(username); + byte[] hashedPassword = HashAndSalt(password, salt); + + if (Enumerable.SequenceEqual(expectedPassword, hashedPassword)) + return true; + } + return false; + } + + } +} diff --git a/Horse Isle Server/Horse Isle Server/Client.cs b/Horse Isle Server/Horse Isle Server/Client.cs index 5c97df7..3d9fbeb 100644 --- a/Horse Isle Server/Horse Isle Server/Client.cs +++ b/Horse Isle Server/Horse Isle Server/Client.cs @@ -1,134 +1,137 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Client - { - public Socket ClientSocket; - public string RemoteIp; - - public bool LoggedIn = false; - public User LoggedinUser; - - private Thread recvPackets; - - - public void Login(int id) - { - LoggedinUser = new User(id); - LoggedIn = true; - } - private void receivePackets() - { - // HI1 Packets are terminates by 0x00 so we have to read until we receive that terminator - MemoryStream ms = new MemoryStream(); - - while(ClientSocket.Connected) - { - try - { - if (ClientSocket.Available >= 1) - { - byte[] buffer = new byte[ClientSocket.Available]; - ClientSocket.Receive(buffer); - - - foreach (Byte b in buffer) - { - ms.WriteByte(b); - if (b == 0x00) - { - ms.Seek(0x00, SeekOrigin.Begin); - byte[] fullPacket = ms.ToArray(); - parsePackets(fullPacket); - ms.Close(); - ms = new MemoryStream(); - } - } - - } - } - catch(SocketException e) - { - Logger.ErrorPrint("Socket exception occured: " + e.Message +" and so it was disconnected."); - Disconnect(); - break; - } - - } - - - } - - private void parsePackets(byte[] Packet) - { - if (Packet.Length < 1) - { - Logger.ErrorPrint("Received an invalid packet (size: "+Packet.Length+")"); - } - - byte identifier = Packet[0]; - if (!LoggedIn) // Must be either login or policy-file-request - { - if (Encoding.UTF8.GetString(Packet).StartsWith("")) // Policy File Request - { - Server.OnCrossdomainPolicyRequest(this); - } - switch (identifier) - { - case PacketBuilder.PACKET_LOGIN: - Server.OnLoginRequest(this, Packet); - break; - } - } - else - { - switch (identifier) - { - case PacketBuilder.PACKET_LOGIN: - Server.OnUserInfoRequest(this, Packet); - break; - case PacketBuilder.PACKET_MOVE: - Server.OnMovementPacket(this, Packet); - break; - default: - Logger.ErrorPrint("Unimplemented Packet: " + BitConverter.ToString(Packet).Replace('-', ' ')); - break; - } - } - } - - public void Disconnect() - { - Server.ConnectedClients.Remove(this); - ClientSocket.Dispose(); - } - - public void SendPacket(byte[] PacketData) - { - ClientSocket.Send(PacketData); - } - - public Client(Socket clientSocket) - { - ClientSocket = clientSocket; - RemoteIp = clientSocket.RemoteEndPoint.ToString(); - - Logger.DebugPrint("Client connected @ " + RemoteIp); - - recvPackets = new Thread(() => - { - receivePackets(); - }); - recvPackets.Start(); - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Client + { + public Socket ClientSocket; + public string RemoteIp; + + public bool LoggedIn = false; + public User LoggedinUser; + + private Thread recvPackets; + + + public void Login(int id) + { + LoggedinUser = new User(id); + LoggedIn = true; + } + private void receivePackets() + { + // HI1 Packets are terminates by 0x00 so we have to read until we receive that terminator + MemoryStream ms = new MemoryStream(); + + while(ClientSocket.Connected) + { + try + { + if (ClientSocket.Available >= 1) + { + byte[] buffer = new byte[ClientSocket.Available]; + ClientSocket.Receive(buffer); + + + foreach (Byte b in buffer) + { + ms.WriteByte(b); + if (b == 0x00) + { + ms.Seek(0x00, SeekOrigin.Begin); + byte[] fullPacket = ms.ToArray(); + parsePackets(fullPacket); + ms.Close(); + ms = new MemoryStream(); + } + } + + } + } + catch(SocketException e) + { + Logger.ErrorPrint("Socket exception occured: " + e.Message +" and so it was disconnected."); + Disconnect(); + break; + } + + } + + + } + + private void parsePackets(byte[] Packet) + { + if (Packet.Length < 1) + { + Logger.ErrorPrint("Received an invalid packet (size: "+Packet.Length+")"); + } + + byte identifier = Packet[0]; + if (!LoggedIn) // Must be either login or policy-file-request + { + if (Encoding.UTF8.GetString(Packet).StartsWith("")) // Policy File Request + { + Server.OnCrossdomainPolicyRequest(this); + } + switch (identifier) + { + case PacketBuilder.PACKET_LOGIN: + Server.OnLoginRequest(this, Packet); + break; + } + } + else + { + switch (identifier) + { + case PacketBuilder.PACKET_LOGIN: + Server.OnUserInfoRequest(this, Packet); + break; + case PacketBuilder.PACKET_MOVE: + Server.OnMovementPacket(this, Packet); + break; + default: + Logger.ErrorPrint("Unimplemented Packet: " + BitConverter.ToString(Packet).Replace('-', ' ')); + break; + } + } + } + + public void Disconnect() + { + Logger.DebugPrint(ClientSocket.RemoteEndPoint + " has Disconnected."); + LoggedIn = false; + LoggedinUser = null; + Server.ConnectedClients.Remove(this); + ClientSocket.Dispose(); + } + + public void SendPacket(byte[] PacketData) + { + ClientSocket.Send(PacketData); + } + + public Client(Socket clientSocket) + { + ClientSocket = clientSocket; + RemoteIp = clientSocket.RemoteEndPoint.ToString(); + + Logger.DebugPrint("Client connected @ " + RemoteIp); + + recvPackets = new Thread(() => + { + receivePackets(); + }); + recvPackets.Start(); + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/ConfigReader.cs b/Horse Isle Server/Horse Isle Server/ConfigReader.cs index 7d6a6b6..1254087 100644 --- a/Horse Isle Server/Horse Isle Server/ConfigReader.cs +++ b/Horse Isle Server/Horse Isle Server/ConfigReader.cs @@ -1,107 +1,103 @@ -using Horse_Isle_Server.Properties; -using System; -using System.IO; - -namespace Horse_Isle_Server -{ - - class ConfigReader - { - public static int Port; - public static string BindIP; - - public static string DatabaseIP; - public static string DatabaseUsername; - public static string DatabaseName; - public static string DatabasePassword; - public static int DatabasePort; - - public static string Motd; - public static string MapFile; - public static string OverlayMapFile; - public static string GameDataFile; - public static string CrossDomainPolicyFile; - public static bool Debug; - - private static string ConfigurationFileName = "server.properties"; - public static void OpenConfig() - { - if (!File.Exists(ConfigurationFileName)) - { - Logger.ErrorPrint(ConfigurationFileName+" not found! writing default."); - File.WriteAllText(ConfigurationFileName,Resources.DefaultServerProperties); - } - - string[] configFile = File.ReadAllLines(ConfigurationFileName); - foreach (string setting in configFile) - { - /* - * Avoid crashing. - */ - if (setting.Length < 1) - continue; - if (setting[0] == '#') - continue; - if (!setting.Contains("=")) - continue; - - string[] dataPair = setting.Split('='); - - string key = dataPair[0]; - string data = dataPair[1]; - /* - * Parse configuration file - */ - - switch (key) - { - case "port": - Port = int.Parse(data); - break; - case "ip": - BindIP = data; - break; - case "db_ip": - DatabaseIP = data; - break; - case "db_username": - DatabaseUsername = data; - break; - case "db_password": - DatabasePassword = data; - break; - case "db_name": - DatabaseName = data; - break; - case "db_port": - DatabasePort = int.Parse(data); - break; - case "map": - MapFile = data; - break; - case "motd": - Motd = data; - break; - case "gamedata": - GameDataFile = data; - break; - case "overlaymap": - OverlayMapFile = data; - break; - case "crossdomain": - CrossDomainPolicyFile = data; - break; - case "debug": - Debug = data == "true"; - break; - } - - - - } - - - } - - } -} +using Horse_Isle_Server.Properties; +using System; +using System.IO; + +namespace Horse_Isle_Server +{ + + class ConfigReader + { + public static int Port; + public static string BindIP; + + public static string DatabaseIP; + public static string DatabaseUsername; + public static string DatabaseName; + public static string DatabasePassword; + public static int DatabasePort; + + public static string Motd; + public static string MapFile; + public static string GameDataFile; + public static string CrossDomainPolicyFile; + public static bool Debug; + + private static string ConfigurationFileName = "server.properties"; + public static void OpenConfig() + { + if (!File.Exists(ConfigurationFileName)) + { + Logger.ErrorPrint(ConfigurationFileName+" not found! writing default."); + File.WriteAllText(ConfigurationFileName,Resources.DefaultServerProperties); + } + + string[] configFile = File.ReadAllLines(ConfigurationFileName); + foreach (string setting in configFile) + { + /* + * Avoid crashing. + */ + if (setting.Length < 1) + continue; + if (setting[0] == '#') + continue; + if (!setting.Contains("=")) + continue; + + string[] dataPair = setting.Split('='); + + string key = dataPair[0]; + string data = dataPair[1]; + /* + * Parse configuration file + */ + + switch (key) + { + case "port": + Port = int.Parse(data); + break; + case "ip": + BindIP = data; + break; + case "db_ip": + DatabaseIP = data; + break; + case "db_username": + DatabaseUsername = data; + break; + case "db_password": + DatabasePassword = data; + break; + case "db_name": + DatabaseName = data; + break; + case "db_port": + DatabasePort = int.Parse(data); + break; + case "map": + MapFile = data; + break; + case "motd": + Motd = data; + break; + case "gamedata": + GameDataFile = data; + break; + case "crossdomain": + CrossDomainPolicyFile = data; + break; + case "debug": + Debug = data == "true"; + break; + } + + + + } + + + } + + } +} diff --git a/Horse Isle Server/Horse Isle Server/Converters.cs b/Horse Isle Server/Horse Isle Server/Converters.cs index 915b7fa..9d4bc23 100644 --- a/Horse Isle Server/Horse Isle Server/Converters.cs +++ b/Horse Isle Server/Horse Isle Server/Converters.cs @@ -1,38 +1,38 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Converters - { - // Thanks Stackoverflow (https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array) - private static int getHexVal(char hex) - { - int val = (int)hex; - //For uppercase A-F letters: - //return val - (val < 58 ? 48 : 55); - //For lowercase a-f letters: - //return val - (val < 58 ? 48 : 87); - //Or the two combined, but a bit slower: - return val - (val < 58 ? 48 : (val < 97 ? 55 : 87)); - } - public static byte[] StringToByteArray(string hex) - { - if (hex.Length % 2 == 1) - throw new ArgumentException("The binary key cannot have an odd number of digits"); - - byte[] arr = new byte[hex.Length >> 1]; - - for (int i = 0; i < hex.Length >> 1; ++i) - { - arr[i] = (byte)((getHexVal(hex[i << 1]) << 4) + (getHexVal(hex[(i << 1) + 1]))); - } - - return arr; - } - - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Converters + { + // Thanks Stackoverflow (https://stackoverflow.com/questions/321370/how-can-i-convert-a-hex-string-to-a-byte-array) + private static int getHexVal(char hex) + { + int val = (int)hex; + //For uppercase A-F letters: + //return val - (val < 58 ? 48 : 55); + //For lowercase a-f letters: + //return val - (val < 58 ? 48 : 87); + //Or the two combined, but a bit slower: + return val - (val < 58 ? 48 : (val < 97 ? 55 : 87)); + } + public static byte[] StringToByteArray(string hex) + { + if (hex.Length % 2 == 1) + throw new ArgumentException("The binary key cannot have an odd number of digits"); + + byte[] arr = new byte[hex.Length >> 1]; + + for (int i = 0; i < hex.Length >> 1; ++i) + { + arr[i] = (byte)((getHexVal(hex[i << 1]) << 4) + (getHexVal(hex[(i << 1) + 1]))); + } + + return arr; + } + + } +} diff --git a/Horse Isle Server/Horse Isle Server/CrossDomainPolicy.cs b/Horse Isle Server/Horse Isle Server/CrossDomainPolicy.cs index e9c9d7c..279171c 100644 --- a/Horse Isle Server/Horse Isle Server/CrossDomainPolicy.cs +++ b/Horse Isle Server/Horse Isle Server/CrossDomainPolicy.cs @@ -1,34 +1,34 @@ -using Horse_Isle_Server.Properties; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class CrossDomainPolicy - { - public static byte[] GetPolicy() - { - if (!File.Exists(ConfigReader.CrossDomainPolicyFile)) { - if (ConfigReader.Debug) - Console.WriteLine("[DEBUG] Cross-Domain-Policy file not found, using default"); - File.WriteAllText(ConfigReader.CrossDomainPolicyFile, Resources.DefaultCrossDomain); - } - - - MemoryStream ms = new MemoryStream(); - byte[] policyFileBytes = File.ReadAllBytes(ConfigReader.CrossDomainPolicyFile); - ms.Write(policyFileBytes, 0x00, policyFileBytes.Length); - ms.WriteByte(0x00); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] policyFileData = ms.ToArray(); - ms.Close(); - - return policyFileData; - } - } -} +using Horse_Isle_Server.Properties; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class CrossDomainPolicy + { + public static byte[] GetPolicy() + { + if (!File.Exists(ConfigReader.CrossDomainPolicyFile)) { + if (ConfigReader.Debug) + Console.WriteLine("[DEBUG] Cross-Domain-Policy file not found, using default"); + File.WriteAllText(ConfigReader.CrossDomainPolicyFile, Resources.DefaultCrossDomain); + } + + + MemoryStream ms = new MemoryStream(); + byte[] policyFileBytes = File.ReadAllBytes(ConfigReader.CrossDomainPolicyFile); + ms.Write(policyFileBytes, 0x00, policyFileBytes.Length); + ms.WriteByte(0x00); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] policyFileData = ms.ToArray(); + ms.Close(); + + return policyFileData; + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/Database.cs b/Horse Isle Server/Horse Isle Server/Database.cs index b8fb96f..2aba0c9 100644 --- a/Horse Isle Server/Horse Isle Server/Database.cs +++ b/Horse Isle Server/Horse Isle Server/Database.cs @@ -1,498 +1,498 @@ -using System; -using System.Collections.Generic; -using MySqlConnector; - -namespace Horse_Isle_Server -{ - class Database - { - - public static MySqlConnection db; - - public static void OpenDatabase() - { - db = new MySqlConnection("server=" + ConfigReader.DatabaseIP + ";user=" + ConfigReader.DatabaseUsername + ";password=" + ConfigReader.DatabasePassword+";database="+ConfigReader.DatabaseName); - db.Open(); - string UserTable = "CREATE TABLE Users(Id INT, Username TEXT(16),Email TEXT(128),Country TEXT(128),SecurityQuestion Text(128),SecurityAnswerHash TEXT(128),Age INT,PassHash TEXT(128), Salt TEXT(128),Gender TEXT(16), Admin TEXT(3), Moderator TEXT(3))"; - string ExtTable = "CREATE TABLE UserExt(Id INT, X INT, Y INT, Money INT, BankBalance BIGINT,ProfilePage Text(1028), CharId INT)"; - string MailTable = "CREATE TABLE Mailbox(IdTo INT, PlayerFrom TEXT(16),Subject TEXT(128), Message Text(1028), TimeSent INT)"; - string WorldTable = "CREATE TABLE World(TimeStarted INT, Weather TEXT(64))"; - string DroppedTable = "CREATE TABLE DroppedItems(X INT, Y INT, ItemID INT)"; - - try - { - - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = UserTable; - sqlCommand.ExecuteNonQuery(); - } - catch (Exception e) { - Logger.WarnPrint(e.Message); - }; - - try - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = ExtTable; - sqlCommand.ExecuteNonQuery(); - } - catch (Exception e) - { - Logger.WarnPrint(e.Message); - }; - - try - { - - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = MailTable; - sqlCommand.ExecuteNonQuery(); - } - catch (Exception e) - { - Logger.WarnPrint(e.Message); - }; - - try - { - - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = DroppedTable; - sqlCommand.ExecuteNonQuery(); - } - catch (Exception e) - { - Logger.WarnPrint(e.Message); - }; - - - try - { - - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = WorldTable; - sqlCommand.ExecuteNonQuery(); - - - int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; - - sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "INSERT INTO World VALUES(@unix,'SUNNY')"; - sqlCommand.Parameters.AddWithValue("@unix", epoch); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - - } - catch (Exception e) - { - Logger.WarnPrint(e.Message); - }; - } - - - public static int GetServerCreationTime() - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT TimeStarted FROM World"; - int creationTime = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return creationTime; - } - - public static string GetWorldWeather() - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Weather FROM World"; - string Weather = sqlCommand.ExecuteScalar().ToString(); - return Weather; - } - - public static void SetWorldWeather(string Weather) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "UPDATE World SET Weather=@weather"; - sqlCommand.Parameters.AddWithValue("@weather", Weather); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - - public static byte[] GetPasswordSalt(string username) - { - if (CheckUserExist(username)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Salt FROM Users WHERE Username=@name"; - sqlCommand.Parameters.AddWithValue("@name", username); - sqlCommand.Prepare(); - string expectedHash = sqlCommand.ExecuteScalar().ToString(); - return Converters.StringToByteArray(expectedHash); - } - else - { - throw new KeyNotFoundException("Username " + username + " not found in database."); - } - } - - public static int CheckMailcount(int id) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT COUNT(1) FROM Mailbox WHERE IdTo=@id"; - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - - Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return count; - } - - public static void AddMail(int toId, string fromName, string subject, string message) - { - MySqlCommand sqlCommand = db.CreateCommand(); - int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; - - sqlCommand.CommandText = "INSERT INTO Mailbox VALUES(@toId,@from,@subject,@message,@time)"; - sqlCommand.Parameters.AddWithValue("@toId", toId); - sqlCommand.Parameters.AddWithValue("@from", fromName); - sqlCommand.Parameters.AddWithValue("@subject", subject); - sqlCommand.Parameters.AddWithValue("@mesasge", message); - sqlCommand.Parameters.AddWithValue("@time", epoch); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - - - } - - public static bool CheckUserExist(int id) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - - Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return count >= 1; - } - public static bool CheckUserExist(string username) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Username=@name"; - sqlCommand.Parameters.AddWithValue("@name", username); - sqlCommand.Prepare(); - - Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return count >= 1; - } - public static bool CheckUserExtExists(int id) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT COUNT(1) FROM UserExt WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - - Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return count >= 1; - } - - - public static bool CheckUserIsModerator(string username) - { - if (CheckUserExist(username)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Moderator FROM Users WHERE Username=@name"; - sqlCommand.Parameters.AddWithValue("@name", username); - sqlCommand.Prepare(); - string modStr = sqlCommand.ExecuteScalar().ToString(); - return modStr == "YES"; - } - else - { - throw new KeyNotFoundException("Username " + username + " not found in database."); - } - } - - - public static bool CheckUserIsAdmin(string username) - { - if (CheckUserExist(username)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Admin FROM Users WHERE Username=@name"; - sqlCommand.Parameters.AddWithValue("@name", username); - sqlCommand.Prepare(); - string adminStr = sqlCommand.ExecuteScalar().ToString(); - return adminStr == "YES"; - } - else - { - throw new KeyNotFoundException("Username " + username + " not found in database."); - } - } - - public static void CreateUserExt(int id) - { - if (CheckUserExtExists(id)) // user allready exists! - throw new Exception("Userid " + id + " Allready in userext."); - - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "INSERT INTO UserExt VALUES(@id,@x,@y,0,0,'',5)"; - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Parameters.AddWithValue("@x", Gamedata.NewUserStartX); - sqlCommand.Parameters.AddWithValue("@y", Gamedata.NewUserStartY); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - - public static int GetUserid(string username) - { - if (CheckUserExist(username)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Id FROM Users WHERE Username=@name"; - sqlCommand.Parameters.AddWithValue("@name", username); - sqlCommand.Prepare(); - int userId = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return userId; - } - else - { - throw new KeyNotFoundException("Username " + username + " not found in database."); - } - } - - public static int GetPlayerCharId(int userId) - { - if (CheckUserExtExists(userId)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT CharId FROM UserExt WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", userId); - sqlCommand.Prepare(); - int CharId = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return CharId; - } - else - { - throw new KeyNotFoundException("Id " + userId + " not found in database."); - } - } - - public static void SetPlayerCharId(int charid, int id) - { - if (CheckUserExist(id)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "UPDATE UserExt SET CharId=@charId WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@charId", charid); - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - else - { - throw new KeyNotFoundException("Id " + id + " not found in database."); - } - } - - public static int GetPlayerX(int userId) - { - if (CheckUserExtExists(userId)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT X FROM UserExt WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", userId); - sqlCommand.Prepare(); - int X = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return X; - } - else - { - throw new KeyNotFoundException("Id " + userId + " not found in database."); - } - } - - public static void SetPlayerX(int x, int id) - { - if (CheckUserExist(id)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "UPDATE UserExt SET X=@x WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@x", x); - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - else - { - throw new KeyNotFoundException("Id " + id + " not found in database."); - } - } - - public static int GetPlayerY(int userId) - { - if (CheckUserExtExists(userId)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Y FROM UserExt WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", userId); - sqlCommand.Prepare(); - int Y = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return Y; - } - else - { - throw new KeyNotFoundException("Id " + userId + " not found in database."); - } - } - public static void SetPlayerY(int y, int id) - { - if (CheckUserExist(id)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "UPDATE UserExt SET Y=@y WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@y", y); - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - else - { - throw new KeyNotFoundException("Id " + id + " not found in database."); - } - } - - public static void SetPlayerMoney(int money, int id) - { - if (CheckUserExist(id)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "UPDATE UserExt SET Money=@money WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@money", money); - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - else - { - throw new KeyNotFoundException("Id " + id + " not found in database."); - } - } - public static int GetPlayerMoney(int userId) - { - if (CheckUserExtExists(userId)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Money FROM UserExt WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", userId); - sqlCommand.Prepare(); - int Money = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return Money; - } - else - { - throw new KeyNotFoundException("Id " + userId + " not found in database."); - } - } - - public static int GetPlayerBankMoney(int userId) - { - if (CheckUserExtExists(userId)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT BankBalance FROM UserExt WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", userId); - sqlCommand.Prepare(); - int BankMoney = Convert.ToInt32(sqlCommand.ExecuteScalar()); - return BankMoney; - } - else - { - throw new KeyNotFoundException("Id " + userId + " not found in database."); - } - } - - public static void SetPlayerBankMoney(int bankMoney, int id) - { - if (CheckUserExist(id)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "UPDATE UserExt SET BankBalance=@bankMoney WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@bankMoney", bankMoney); - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - else - { - throw new KeyNotFoundException("Id " + id + " not found in database."); - } - } - - public static void SetPlayerProfile(string profilePage, int id) - { - if (CheckUserExist(id)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "UPDATE UserExt SET ProfilePage=@profilePage WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@profilePage", profilePage); - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - sqlCommand.ExecuteNonQuery(); - } - else - { - throw new KeyNotFoundException("Id " + id + " not found in database."); - } - } - - public static string GetPlayerProfile(int id) - { - if (CheckUserExist(id)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT ProfilePage FROM UserExt WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", id); - sqlCommand.Prepare(); - string profilePage = sqlCommand.ExecuteScalar().ToString(); - return profilePage; - } - else - { - throw new KeyNotFoundException("Id " + id + " not found in database."); - } - } - - - public static string GetUsername(int userId) - { - if(CheckUserExist(userId)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT Username FROM Users WHERE Id=@id"; - sqlCommand.Parameters.AddWithValue("@id", userId); - sqlCommand.Prepare(); - string username = sqlCommand.ExecuteScalar().ToString(); - return username; - } - else - { - throw new KeyNotFoundException("Id " + userId + " not found in database."); - } - } - public static byte[] GetPasswordHash(string username) - { - if(CheckUserExist(username)) - { - MySqlCommand sqlCommand = db.CreateCommand(); - sqlCommand.CommandText = "SELECT PassHash FROM Users WHERE Username=@name"; - sqlCommand.Parameters.AddWithValue("@name", username); - sqlCommand.Prepare(); - string expectedHash = sqlCommand.ExecuteScalar().ToString(); - return Converters.StringToByteArray(expectedHash); - } - else - { - throw new KeyNotFoundException("Username " + username + " not found in database."); - } - } - } - +using System; +using System.Collections.Generic; +using MySqlConnector; + +namespace Horse_Isle_Server +{ + class Database + { + + public static MySqlConnection db; + + public static void OpenDatabase() + { + db = new MySqlConnection("server=" + ConfigReader.DatabaseIP + ";user=" + ConfigReader.DatabaseUsername + ";password=" + ConfigReader.DatabasePassword+";database="+ConfigReader.DatabaseName); + db.Open(); + string UserTable = "CREATE TABLE Users(Id INT, Username TEXT(16),Email TEXT(128),Country TEXT(128),SecurityQuestion Text(128),SecurityAnswerHash TEXT(128),Age INT,PassHash TEXT(128), Salt TEXT(128),Gender TEXT(16), Admin TEXT(3), Moderator TEXT(3))"; + string ExtTable = "CREATE TABLE UserExt(Id INT, X INT, Y INT, Money INT, BankBalance BIGINT,ProfilePage Text(1028), CharId INT)"; + string MailTable = "CREATE TABLE Mailbox(IdTo INT, PlayerFrom TEXT(16),Subject TEXT(128), Message Text(1028), TimeSent INT)"; + string WorldTable = "CREATE TABLE World(TimeStarted INT, Weather TEXT(64))"; + string DroppedTable = "CREATE TABLE DroppedItems(X INT, Y INT, ItemID INT)"; + + try + { + + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = UserTable; + sqlCommand.ExecuteNonQuery(); + } + catch (Exception e) { + Logger.WarnPrint(e.Message); + }; + + try + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = ExtTable; + sqlCommand.ExecuteNonQuery(); + } + catch (Exception e) + { + Logger.WarnPrint(e.Message); + }; + + try + { + + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = MailTable; + sqlCommand.ExecuteNonQuery(); + } + catch (Exception e) + { + Logger.WarnPrint(e.Message); + }; + + try + { + + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = DroppedTable; + sqlCommand.ExecuteNonQuery(); + } + catch (Exception e) + { + Logger.WarnPrint(e.Message); + }; + + + try + { + + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = WorldTable; + sqlCommand.ExecuteNonQuery(); + + + int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + + sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "INSERT INTO World VALUES(@unix,'SUNNY')"; + sqlCommand.Parameters.AddWithValue("@unix", epoch); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + + } + catch (Exception e) + { + Logger.WarnPrint(e.Message); + }; + } + + + public static int GetServerCreationTime() + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT TimeStarted FROM World"; + int creationTime = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return creationTime; + } + + public static string GetWorldWeather() + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Weather FROM World"; + string Weather = sqlCommand.ExecuteScalar().ToString(); + return Weather; + } + + public static void SetWorldWeather(string Weather) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "UPDATE World SET Weather=@weather"; + sqlCommand.Parameters.AddWithValue("@weather", Weather); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + + public static byte[] GetPasswordSalt(string username) + { + if (CheckUserExist(username)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Salt FROM Users WHERE Username=@name"; + sqlCommand.Parameters.AddWithValue("@name", username); + sqlCommand.Prepare(); + string expectedHash = sqlCommand.ExecuteScalar().ToString(); + return Converters.StringToByteArray(expectedHash); + } + else + { + throw new KeyNotFoundException("Username " + username + " not found in database."); + } + } + + public static int CheckMailcount(int id) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT COUNT(1) FROM Mailbox WHERE IdTo=@id"; + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + + Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return count; + } + + public static void AddMail(int toId, string fromName, string subject, string message) + { + MySqlCommand sqlCommand = db.CreateCommand(); + int epoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; + + sqlCommand.CommandText = "INSERT INTO Mailbox VALUES(@toId,@from,@subject,@message,@time)"; + sqlCommand.Parameters.AddWithValue("@toId", toId); + sqlCommand.Parameters.AddWithValue("@from", fromName); + sqlCommand.Parameters.AddWithValue("@subject", subject); + sqlCommand.Parameters.AddWithValue("@mesasge", message); + sqlCommand.Parameters.AddWithValue("@time", epoch); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + + + } + + public static bool CheckUserExist(int id) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + + Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return count >= 1; + } + public static bool CheckUserExist(string username) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT COUNT(1) FROM Users WHERE Username=@name"; + sqlCommand.Parameters.AddWithValue("@name", username); + sqlCommand.Prepare(); + + Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return count >= 1; + } + public static bool CheckUserExtExists(int id) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT COUNT(1) FROM UserExt WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + + Int32 count = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return count >= 1; + } + + + public static bool CheckUserIsModerator(string username) + { + if (CheckUserExist(username)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Moderator FROM Users WHERE Username=@name"; + sqlCommand.Parameters.AddWithValue("@name", username); + sqlCommand.Prepare(); + string modStr = sqlCommand.ExecuteScalar().ToString(); + return modStr == "YES"; + } + else + { + throw new KeyNotFoundException("Username " + username + " not found in database."); + } + } + + + public static bool CheckUserIsAdmin(string username) + { + if (CheckUserExist(username)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Admin FROM Users WHERE Username=@name"; + sqlCommand.Parameters.AddWithValue("@name", username); + sqlCommand.Prepare(); + string adminStr = sqlCommand.ExecuteScalar().ToString(); + return adminStr == "YES"; + } + else + { + throw new KeyNotFoundException("Username " + username + " not found in database."); + } + } + + public static void CreateUserExt(int id) + { + if (CheckUserExtExists(id)) // user allready exists! + throw new Exception("Userid " + id + " Allready in userext."); + + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "INSERT INTO UserExt VALUES(@id,@x,@y,0,0,'',0)"; + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Parameters.AddWithValue("@x", Map.NewUserStartX); + sqlCommand.Parameters.AddWithValue("@y", Map.NewUserStartY); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + + public static int GetUserid(string username) + { + if (CheckUserExist(username)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Id FROM Users WHERE Username=@name"; + sqlCommand.Parameters.AddWithValue("@name", username); + sqlCommand.Prepare(); + int userId = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return userId; + } + else + { + throw new KeyNotFoundException("Username " + username + " not found in database."); + } + } + + public static int GetPlayerCharId(int userId) + { + if (CheckUserExtExists(userId)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT CharId FROM UserExt WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", userId); + sqlCommand.Prepare(); + int CharId = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return CharId; + } + else + { + throw new KeyNotFoundException("Id " + userId + " not found in database."); + } + } + + public static void SetPlayerCharId(int charid, int id) + { + if (CheckUserExist(id)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "UPDATE UserExt SET CharId=@charId WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@charId", charid); + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + else + { + throw new KeyNotFoundException("Id " + id + " not found in database."); + } + } + + public static int GetPlayerX(int userId) + { + if (CheckUserExtExists(userId)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT X FROM UserExt WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", userId); + sqlCommand.Prepare(); + int X = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return X; + } + else + { + throw new KeyNotFoundException("Id " + userId + " not found in database."); + } + } + + public static void SetPlayerX(int x, int id) + { + if (CheckUserExist(id)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "UPDATE UserExt SET X=@x WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@x", x); + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + else + { + throw new KeyNotFoundException("Id " + id + " not found in database."); + } + } + + public static int GetPlayerY(int userId) + { + if (CheckUserExtExists(userId)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Y FROM UserExt WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", userId); + sqlCommand.Prepare(); + int Y = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return Y; + } + else + { + throw new KeyNotFoundException("Id " + userId + " not found in database."); + } + } + public static void SetPlayerY(int y, int id) + { + if (CheckUserExist(id)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "UPDATE UserExt SET Y=@y WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@y", y); + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + else + { + throw new KeyNotFoundException("Id " + id + " not found in database."); + } + } + + public static void SetPlayerMoney(int money, int id) + { + if (CheckUserExist(id)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "UPDATE UserExt SET Money=@money WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@money", money); + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + else + { + throw new KeyNotFoundException("Id " + id + " not found in database."); + } + } + public static int GetPlayerMoney(int userId) + { + if (CheckUserExtExists(userId)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Money FROM UserExt WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", userId); + sqlCommand.Prepare(); + int Money = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return Money; + } + else + { + throw new KeyNotFoundException("Id " + userId + " not found in database."); + } + } + + public static int GetPlayerBankMoney(int userId) + { + if (CheckUserExtExists(userId)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT BankBalance FROM UserExt WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", userId); + sqlCommand.Prepare(); + int BankMoney = Convert.ToInt32(sqlCommand.ExecuteScalar()); + return BankMoney; + } + else + { + throw new KeyNotFoundException("Id " + userId + " not found in database."); + } + } + + public static void SetPlayerBankMoney(int bankMoney, int id) + { + if (CheckUserExist(id)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "UPDATE UserExt SET BankBalance=@bankMoney WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@bankMoney", bankMoney); + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + else + { + throw new KeyNotFoundException("Id " + id + " not found in database."); + } + } + + public static void SetPlayerProfile(string profilePage, int id) + { + if (CheckUserExist(id)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "UPDATE UserExt SET ProfilePage=@profilePage WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@profilePage", profilePage); + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + sqlCommand.ExecuteNonQuery(); + } + else + { + throw new KeyNotFoundException("Id " + id + " not found in database."); + } + } + + public static string GetPlayerProfile(int id) + { + if (CheckUserExist(id)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT ProfilePage FROM UserExt WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", id); + sqlCommand.Prepare(); + string profilePage = sqlCommand.ExecuteScalar().ToString(); + return profilePage; + } + else + { + throw new KeyNotFoundException("Id " + id + " not found in database."); + } + } + + + public static string GetUsername(int userId) + { + if(CheckUserExist(userId)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT Username FROM Users WHERE Id=@id"; + sqlCommand.Parameters.AddWithValue("@id", userId); + sqlCommand.Prepare(); + string username = sqlCommand.ExecuteScalar().ToString(); + return username; + } + else + { + throw new KeyNotFoundException("Id " + userId + " not found in database."); + } + } + public static byte[] GetPasswordHash(string username) + { + if(CheckUserExist(username)) + { + MySqlCommand sqlCommand = db.CreateCommand(); + sqlCommand.CommandText = "SELECT PassHash FROM Users WHERE Username=@name"; + sqlCommand.Parameters.AddWithValue("@name", username); + sqlCommand.Prepare(); + string expectedHash = sqlCommand.ExecuteScalar().ToString(); + return Converters.StringToByteArray(expectedHash); + } + else + { + throw new KeyNotFoundException("Username " + username + " not found in database."); + } + } + } + } \ No newline at end of file diff --git a/Horse Isle Server/Horse Isle Server/Gamedata.cs b/Horse Isle Server/Horse Isle Server/Gamedata.cs index 6f6ede9..03ddb91 100644 --- a/Horse Isle Server/Horse Isle Server/Gamedata.cs +++ b/Horse Isle Server/Horse Isle Server/Gamedata.cs @@ -1,60 +1,56 @@ -using System.Collections.Generic; -using System.IO; -using Newtonsoft.Json; - -namespace Horse_Isle_Server -{ - - - - class Gamedata - { - public static string TileFlags; - - public static int NewUserStartX; - public static int NewUserStartY; - // Messages - public static string NewUserMessage; - public static string AreaMessage; - public static string NothingMessage; - public static string LoginMessage; - - public static void ReadGamedata() - { - if(!File.Exists(ConfigReader.GameDataFile)) - { - Logger.ErrorPrint("Game Data JSON File: " + ConfigReader.GameDataFile + " Does not exist!"); - return; - } - string jsonData = File.ReadAllText(ConfigReader.GameDataFile); - dynamic gameData = JsonConvert.DeserializeObject(jsonData); - - int totalIsles = gameData.isles.Count; - for(int i = 0; i < totalIsles; i++) - { - - World.Isle isle = new World.Isle(); - isle.StartX = gameData.isles[i].start_x; - isle.StartY = gameData.isles[i].start_y; - isle.EndX = gameData.isles[i].end_x; - isle.EndY = gameData.isles[i].end_y; - isle.Tileset = gameData.isles[i].tileset; - isle.Name = gameData.isles[i].name; - - Logger.DebugPrint("Registered Isle: " + isle.Name + " X " + isle.StartX + "-" + isle.EndX + " Y " + isle.StartY + "-" + isle.EndY + " tileset: " + isle.Tileset); - World.Isles.Add(isle); - } - - NewUserMessage = gameData.new_user.starting_message; - NewUserStartX = gameData.new_user.starting_x; - NewUserStartY = gameData.new_user.starting_y; - - LoginMessage = gameData.messages.login_format; - AreaMessage = gameData.messages.area_format; - NothingMessage = gameData.messages.nothing_message; - - TileFlags = gameData.map_flags; - } - - } -} +using System.Collections.Generic; +using System.IO; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Horse_Isle_Server +{ + + + + class Gamedata + { + + public static void ReadGamedata() + { + if(!File.Exists(ConfigReader.GameDataFile)) + { + Logger.ErrorPrint("Game Data JSON File: " + ConfigReader.GameDataFile + " Does not exist!"); + return; + } + string jsonData = File.ReadAllText(ConfigReader.GameDataFile); + dynamic gameData = JsonConvert.DeserializeObject(jsonData); + + int totalIsles = gameData.isles.Count; + for(int i = 0; i < totalIsles; i++) + { + + World.Isle isle = new World.Isle(); + isle.StartX = gameData.isles[i].start_x; + isle.StartY = gameData.isles[i].start_y; + isle.EndX = gameData.isles[i].end_x; + isle.EndY = gameData.isles[i].end_y; + isle.Tileset = gameData.isles[i].tileset; + isle.Name = gameData.isles[i].name; + + Logger.DebugPrint("Registered Isle: " + isle.Name + " X " + isle.StartX + "-" + isle.EndX + " Y " + isle.StartY + "-" + isle.EndY + " tileset: " + isle.Tileset); + World.Isles.Add(isle); + } + + Messages.NewUserMessage = gameData.new_user.starting_message; + Map.NewUserStartX = gameData.new_user.starting_x; + Map.NewUserStartY = gameData.new_user.starting_y; + + Messages.LoginFormat = gameData.messages.login_format; + Messages.AreaMessage = gameData.messages.area_format; + Messages.NothingMessage = gameData.messages.nothing_message; + Messages.MotdFormat = gameData.messages.motd_format; + + JArray overlayTileDepth = gameData.tile_paramaters.overlay_tiles.tile_depth; + JArray terrainTilePassibility = gameData.tile_paramaters.terrain_tiles.passibility; + Map.OverlayTileDepth = overlayTileDepth.ToObject(); + Map.TerrainTilePassibility = terrainTilePassibility.ToObject(); + } + + } +} diff --git a/Horse Isle Server/Horse Isle Server/Horse Isle Server.csproj b/Horse Isle Server/Horse Isle Server/Horse Isle Server.csproj index c216cd4..a877ecd 100644 --- a/Horse Isle Server/Horse Isle Server/Horse Isle Server.csproj +++ b/Horse Isle Server/Horse Isle Server/Horse Isle Server.csproj @@ -1,110 +1,110 @@ - - - - - Debug - AnyCPU - {C48CBD82-AB30-494A-8FFA-4DE7069B5827} - Exe - Horse_Isle_Server - Horse Isle Server - v4.8 - 512 - true - true - - - - - - AnyCPU - true - full - false - bin\Debug\ - DEBUG;TRACE - prompt - 4 - false - - - AnyCPU - pdbonly - true - bin\Release\ - TRACE - prompt - 4 - false - - - - - ..\packages\MySqlConnector.1.0.1\lib\net471\MySqlConnector.dll - - - ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll - - - - ..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll - - - - - ..\packages\System.Memory.4.5.0\lib\netstandard2.0\System.Memory.dll - - - - - ..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll - - - ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll - - - ..\packages\System.Threading.Tasks.Extensions.4.3.0\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll - - - - - - - - - - - - - - - - - - - - - - True - True - Resources.resx - - - - - - - - - - - - ResXFileCodeGenerator - Resources.Designer.cs - - - - - - + + + + + Debug + AnyCPU + {C48CBD82-AB30-494A-8FFA-4DE7069B5827} + Exe + Horse_Isle_Server + Horse Isle Server + v4.8 + 512 + true + true + + + + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + false + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + false + + + + + ..\packages\MySqlConnector.1.0.1\lib\net471\MySqlConnector.dll + + + ..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll + + + + ..\packages\System.Buffers.4.4.0\lib\netstandard2.0\System.Buffers.dll + + + + + ..\packages\System.Memory.4.5.0\lib\netstandard2.0\System.Memory.dll + + + + + ..\packages\System.Numerics.Vectors.4.4.0\lib\net46\System.Numerics.Vectors.dll + + + ..\packages\System.Runtime.CompilerServices.Unsafe.4.5.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll + + + ..\packages\System.Threading.Tasks.Extensions.4.3.0\lib\portable-net45+win8+wp8+wpa81\System.Threading.Tasks.Extensions.dll + + + + + + + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + \ No newline at end of file diff --git a/Horse Isle Server/Horse Isle Server/Logger.cs b/Horse Isle Server/Horse Isle Server/Logger.cs index 3d6abe9..ef8f0f3 100644 --- a/Horse Isle Server/Horse Isle Server/Logger.cs +++ b/Horse Isle Server/Horse Isle Server/Logger.cs @@ -1,25 +1,25 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Logger - { - public static void DebugPrint(string text) - { - if (ConfigReader.Debug) - Console.WriteLine("[DEBUG] " + text); - } - public static void WarnPrint(string text) - { - Console.WriteLine("[WARN] " + text); - } - public static void ErrorPrint(string text) - { - Console.WriteLine("[ERROR] " + text); - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Logger + { + public static void DebugPrint(string text) + { + if (ConfigReader.Debug) + Console.WriteLine("[DEBUG] " + text); + } + public static void WarnPrint(string text) + { + Console.WriteLine("[WARN] " + text); + } + public static void ErrorPrint(string text) + { + Console.WriteLine("[ERROR] " + text); + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/Mailbox.cs b/Horse Isle Server/Horse Isle Server/Mailbox.cs index d6d851a..67d5b4f 100644 --- a/Horse Isle Server/Horse Isle Server/Mailbox.cs +++ b/Horse Isle Server/Horse Isle Server/Mailbox.cs @@ -1,20 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Mailbox - { - private User baseUser; - public int MailCount; - - public Mailbox(User user) - { - MailCount = Database.CheckMailcount(user.Id); - baseUser = user; - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Mailbox + { + private User baseUser; + public int MailCount; + + public Mailbox(User user) + { + MailCount = Database.CheckMailcount(user.Id); + baseUser = user; + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/Map.cs b/Horse Isle Server/Horse Isle Server/Map.cs index e62dbc5..26de300 100644 --- a/Horse Isle Server/Horse Isle Server/Map.cs +++ b/Horse Isle Server/Horse Isle Server/Map.cs @@ -1,42 +1,51 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Map - { - public static Bitmap MapData; - public static Bitmap oMapData; - public static int GetTileId(int x, int y, bool overlay) - { - if ((x > MapData.Width || x < 0) || (y > MapData.Height || y < 0)) // Outside map? - return 0x01; - - if (overlay) - return oMapData.GetPixel(x, y).B; - else - return MapData.GetPixel(x, y).B; - } - public static bool CheckPassable(int x, int y) - { - return true; // not implemented yet - } - - public static void OpenMap() - { - if(!File.Exists(ConfigReader.MapFile) || !File.Exists(ConfigReader.OverlayMapFile)) - { - Logger.ErrorPrint("Map file not found."); - return; - } - - MapData = new Bitmap(ConfigReader.MapFile); - oMapData = new Bitmap(ConfigReader.OverlayMapFile); - } - } -} +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Map + { + public static int[] OverlayTileDepth; + public static bool[] TerrainTilePassibility; + + public static Bitmap MapData; + + public static int NewUserStartX; + public static int NewUserStartY; + public static int GetTileId(int x, int y, bool overlay) + { + if ((x > MapData.Width || x < 0) || (y > MapData.Height || y < 0)) // Outside map? + return 0x1; + + + if (overlay) + return MapData.GetPixel(x, y).R; + else + return MapData.GetPixel(x, y).B; + } + public static bool CheckPassable(int x, int y) + { + int tileId = GetTileId(x, y, false); + bool passable = TerrainTilePassibility[tileId-1]; + Logger.DebugPrint("Checking tile passibility for tileid: " + tileId + " at " + x + "," + y+" passable: " +passable); + return passable; + } + + public static void OpenMap() + { + if(!File.Exists(ConfigReader.MapFile)) + { + Logger.ErrorPrint("Map file not found."); + return; + } + + MapData = new Bitmap(ConfigReader.MapFile); + } + } +} + \ No newline at end of file diff --git a/Horse Isle Server/Horse Isle Server/Messages.cs b/Horse Isle Server/Horse Isle Server/Messages.cs index a17cbbb..77549f5 100644 --- a/Horse Isle Server/Horse Isle Server/Messages.cs +++ b/Horse Isle Server/Horse Isle Server/Messages.cs @@ -1,34 +1,44 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Messages - { - - public static string LoginMessage(string username) - { - return Gamedata.LoginMessage.Replace("%USERNAME%", username); - } - - public static string LocationData(int x, int y) - { - string message = ""; - try - { - World.Isle isle = World.GetIsle(x, y); - message = Gamedata.AreaMessage.Replace("%AREA%", isle.Name); - } - catch (Exception) { } - - int[] itemIds = World.GetDroppedItems(x, y); - if (itemIds.Length == 0) - message += Gamedata.NothingMessage; - - return message; - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Messages + { + public static string NewUserMessage; + public static string AreaMessage; + public static string NothingMessage; + public static string LoginFormat; + + public static string MotdFormat; + + public static string GetMOTD() + { + return MotdFormat.Replace("%MOTD%", ConfigReader.Motd); + } + public static string GetLoginMessage(string username) + { + return LoginFormat.Replace("%USERNAME%", username); + } + + public static string LocationData(int x, int y) + { + string message = ""; + try + { + World.Isle isle = World.GetIsle(x, y); + message = AreaMessage.Replace("%AREA%", isle.Name); + } + catch (Exception) { } + + int[] itemIds = World.GetDroppedItems(x, y); + if (itemIds.Length == 0) + message += NothingMessage; + + return message; + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/PacketBuilder.cs b/Horse Isle Server/Horse Isle Server/PacketBuilder.cs index 03e6897..6e10f91 100644 --- a/Horse Isle Server/Horse Isle Server/PacketBuilder.cs +++ b/Horse Isle Server/Horse Isle Server/PacketBuilder.cs @@ -1,412 +1,442 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class PacketBuilder - { - - public const byte PACKET_TERMINATOR = 0x00; - public const byte PACKET_A_TERMINATOR = 0x0A; - - - public const byte PACKET_LOGIN = 0x7F; - public const byte PACKET_CHAT = 0x14; - public const byte PACKET_MOVE = 0x15; - public const byte PACKET_USERINFO = 0x81; - public const byte PACKET_WORLD = 0x7A; - public const byte PACKET_BASE_STATS = 0x7B; - public const byte PACKET_PLACE_INFO = 0x1E; - public const byte PACKET_AREA_DEFS = 0x79; - public const byte PACKET_TILE_FLAGS = 0x75; - - public const byte AREA_SEPERATOR = 0x5E; - - public const byte MOVE_UP = 0x14; - public const byte MOVE_DOWN = 0x15; - public const byte MOVE_RIGHT = 0x16; - public const byte MOVE_LEFT = 0x17; - public const byte MOVE_EXIT = 0x10; - - public const byte CHAT_BOTTOM_LEFT = 0x14; - public const byte CHAT_BOTTOM_RIGHT = 0x15; - - public const byte LOGIN_INVALID_USER_PASS = 0x15; - public const byte LOGIN_SUCCESS = 0x14; - - public const byte DIRECTION_UP = 0; - public const byte DIRECTION_RIGHT = 1; - public const byte DIRECTION_DOWN = 2; - public const byte DIRECTION_LEFT = 3; - public const byte DIRECTION_LOGIN = 4; - - - - public static byte[] CreateLoginPacket(bool Success) - { - MemoryStream ms = new MemoryStream(); - ms.WriteByte(PACKET_LOGIN); - if (Success) - ms.WriteByte(LOGIN_SUCCESS); - else - ms.WriteByte(LOGIN_INVALID_USER_PASS); - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - - public static byte[] CreateMovementPacket(int x, int y,int charId,int facing, int direction, bool walk) - { - // Header information - MemoryStream ms = new MemoryStream(); - ms.WriteByte(PACKET_MOVE); - - ms.WriteByte((byte)((x / 64) + 20)); //1 - ms.WriteByte((byte)((x % 64) + 20)); //2 - - ms.WriteByte((byte)((y / 64) + 20)); //3 - ms.WriteByte((byte)((y % 64) + 20)); //4 - - ms.WriteByte((byte)(facing + 20)); //5 - - ms.WriteByte((byte)((charId / 64) + 20)); //6 - ms.WriteByte((byte)((charId % 64) + 20)); //7 - - ms.WriteByte((byte)(direction + 20)); //8 - - ms.WriteByte((byte)(Convert.ToInt32(walk) + 20)); //9 - - // Map Data - - if (direction >= 20) - { - direction -= 20; - } - - int ystart = y - 3; - int xstart = x - 2; - - - if (direction == DIRECTION_UP) - { - for (int relx = 0; relx <= 12; relx++) - { - int tileId = Map.GetTileId(xstart + relx, ystart, false); - int otileId = Map.GetTileId(xstart + relx, ystart, true); - - if (tileId == 290) - tileId -= 100; - if (otileId == 290) - otileId -= 100; - - ms.WriteByte((byte)tileId); - ms.WriteByte((byte)otileId); - } - } - - if (direction == DIRECTION_LEFT) - { - for (int rely = 0; rely <= 9; rely++) - { - int tileId = Map.GetTileId(xstart, ystart + rely, false); - int otileId = Map.GetTileId(xstart, ystart + rely, true); - - if (tileId == 290) - tileId -= 100; - if (otileId == 290) - otileId -= 100; - - ms.WriteByte((byte)tileId); - ms.WriteByte((byte)otileId); - } - } - - - if (direction == DIRECTION_RIGHT) - { - for (int rely = 0; rely <= 9; rely++) - { - int tileId = Map.GetTileId(xstart + 12, ystart + rely, false); - int otileId = Map.GetTileId(xstart + 12, ystart + rely, true); - - if (tileId == 290) - tileId -= 100; - if (otileId == 290) - otileId -= 100; - - ms.WriteByte((byte)tileId); - ms.WriteByte((byte)otileId); - } - } - - if (direction == DIRECTION_DOWN) - { - for (int relx = 0; relx <= 12; relx++) - { - int tileId = Map.GetTileId(xstart + relx, ystart + 9, false); - int otileId = Map.GetTileId(xstart + relx, ystart + 9, true); - - if (tileId == 290) - tileId -= 100; - if (otileId == 290) - otileId -= 100; - - ms.WriteByte((byte)tileId); - ms.WriteByte((byte)otileId); - } - } - if (direction == DIRECTION_LOGIN) - { - for(int rely = 0; rely <= 9; rely++) - { - for (int relx = 0; relx <= 12; relx++) - { - int tileId = Map.GetTileId(xstart + relx, ystart + rely, false); - int otileId = Map.GetTileId(xstart + relx, ystart + rely, true); - - if (tileId == 290) - tileId -= 100; - if(otileId == 290) - otileId -= 100; - - ms.WriteByte((byte)tileId); - ms.WriteByte((byte)otileId); - } - } - - } - - - ms.WriteByte(PACKET_TERMINATOR); - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - return Packet; - } - - public static byte[] CreatePlaceInfo(string formattedText) - { - byte[] strBytes = Encoding.UTF8.GetBytes(formattedText); - - MemoryStream ms = new MemoryStream(); - - ms.WriteByte(PACKET_PLACE_INFO); - - ms.Write(strBytes, 0x00, strBytes.Length); - - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - public static byte[] CreateChat(string formattedText, byte chatWindow) - { - byte[] strBytes = Encoding.UTF8.GetBytes(formattedText); - - MemoryStream ms = new MemoryStream(); - - ms.WriteByte(PACKET_CHAT); - ms.WriteByte(chatWindow); - - ms.Write(strBytes, 0x00, strBytes.Length); - - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - - public static byte[] CreateAreaMessage(int x, int y) - { - string locationStr = Messages.LocationData(x, y); - return CreatePlaceInfo(locationStr); - } - public static byte[] CreateLoginMessage(string username) - { - string formattedStr = Messages.LoginMessage(username); - return CreateChat(formattedStr,CHAT_BOTTOM_RIGHT); - } - - public static byte[] CreateWorldData(int gameTime, int gameDay, int gameYear, string weather) - { - byte[] strBytes = Encoding.UTF8.GetBytes(weather); - - MemoryStream ms = new MemoryStream(); - ms.WriteByte(PACKET_WORLD); - - ms.WriteByte((byte)((gameTime / 64) + 20)); - ms.WriteByte((byte)((gameTime % 64) + 20)); - - ms.WriteByte((byte)((gameDay / 64) + 20)); - ms.WriteByte((byte)((gameDay % 64) + 20)); - - ms.WriteByte((byte)((gameYear / 64) + 20)); - ms.WriteByte((byte)((gameYear % 64) + 20)); - - ms.Write(strBytes,0x00, strBytes.Length); - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - - public static byte[] CreateIsleData(World.Isle[] isles) - { - MemoryStream ms = new MemoryStream(); - ms.WriteByte(PACKET_AREA_DEFS); - foreach(World.Isle isle in isles) - { - byte[] strBytes = Encoding.UTF8.GetBytes(isle.Name); - - ms.WriteByte(AREA_SEPERATOR); - - ms.WriteByte((byte)((isle.StartX / 64) + 20)); - ms.WriteByte((byte)((isle.StartX % 64) + 20)); - - ms.WriteByte((byte)((isle.EndX / 64) + 20)); - ms.WriteByte((byte)((isle.EndX % 64) + 20)); - - ms.WriteByte((byte)((isle.StartY / 64) + 20)); - ms.WriteByte((byte)((isle.StartY % 64) + 20)); - - ms.WriteByte((byte)((isle.EndY / 64) + 20)); - ms.WriteByte((byte)((isle.EndY % 64) + 20)); - - ms.WriteByte((byte)isle.Tileset.ToString()[0]); - - ms.Write(strBytes, 0x00, strBytes.Length); - } - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - - public static byte[] CreateBaseStats(int money, int playerCount, int mail) - { - byte[] moneyStrBytes = Encoding.UTF8.GetBytes(money.ToString()); - byte[] playerStrBytes = Encoding.UTF8.GetBytes(playerCount.ToString()); - byte[] mailStrBytes = Encoding.UTF8.GetBytes(mail.ToString()); - - MemoryStream ms = new MemoryStream(); - ms.WriteByte(PACKET_BASE_STATS); - ms.Write(moneyStrBytes, 0x00, moneyStrBytes.Length); - ms.WriteByte((byte)'|'); - ms.Write(playerStrBytes, 0x00, playerStrBytes.Length); - ms.WriteByte((byte)'|'); - ms.Write(mailStrBytes, 0x00, mailStrBytes.Length); - ms.WriteByte((byte)'|'); - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - - public static byte[] CreateTileFlags(string tileFlags) - { - MemoryStream ms = new MemoryStream(); - ms.WriteByte(PACKET_TILE_FLAGS); - - byte[] strBytes = Encoding.UTF8.GetBytes(tileFlags); - ms.Write(strBytes, 0x00, strBytes.Length); - - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - public static byte[] CreateSecCode(byte[] SecCodeSeed, int SecCodeInc, bool Admin, bool Moderator) - { - MemoryStream ms = new MemoryStream(); - ms.WriteByte(PACKET_USERINFO); - - ms.WriteByte((byte)(SecCodeSeed[0] + 33)); - ms.WriteByte((byte)(SecCodeSeed[1] + 33)); - ms.WriteByte((byte)(SecCodeSeed[2] + 33)); - ms.WriteByte((byte)(SecCodeInc + 33)); - - char userType = 'N'; // Normal? - if (Moderator) - userType = 'M'; - if (Admin) - userType = 'A'; - - ms.WriteByte((byte)userType); - ms.WriteByte(PACKET_TERMINATOR); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - - public static byte[] CreateUserInfo(Client client) - { - MemoryStream ms = new MemoryStream(); - if(!client.LoggedIn) - throw new Exception("Client is not logged in."); - User user = client.LoggedinUser; - - byte[] MovementPacket = CreateMovementPacket(user.X, user.Y, user.CharacterId, DIRECTION_DOWN, DIRECTION_LOGIN, false); - ms.Write(MovementPacket, 0x00, MovementPacket.Length); - - byte[] LoginMessage = CreateLoginMessage(user.Username); - ms.Write(LoginMessage, 0x00, LoginMessage.Length); - - World.Time time = World.GetGameTime(); - int timestamp = time.hours * 60; - timestamp += time.minutes; - - byte[] WorldData = CreateWorldData(timestamp, time.days, time.year, World.GetWeather()); - ms.Write(WorldData, 0x00, WorldData.Length); - - byte[] SecCodePacket = CreateSecCode(user.SecCodeSeeds, user.SecCodeInc, user.Administrator, user.Moderator); - ms.Write(SecCodePacket, 0x00, SecCodePacket.Length); - - byte[] BaseStatsPacketData = CreateBaseStats(user.Money, Server.GetNumberOfPlayers(), user.MailBox.MailCount); - ms.Write(BaseStatsPacketData, 0x00, BaseStatsPacketData.Length); - - byte[] AreaMessage = CreateAreaMessage(user.X,user.Y); - ms.Write(AreaMessage, 0x00, AreaMessage.Length); - - byte[] IsleData = CreateIsleData(World.Isles.ToArray()); - ms.Write(IsleData, 0x00, IsleData.Length); - - byte[] TileFlags = CreateTileFlags(Gamedata.TileFlags); - ms.Write(TileFlags, 0x00, TileFlags.Length); - - ms.Seek(0x00, SeekOrigin.Begin); - byte[] Packet = ms.ToArray(); - ms.Dispose(); - - return Packet; - } - } -} +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class PacketBuilder + { + + public const byte PACKET_TERMINATOR = 0x00; + public const byte PACKET_A_TERMINATOR = 0x0A; + + + public const byte PACKET_LOGIN = 0x7F; + public const byte PACKET_CHAT = 0x14; + public const byte PACKET_MOVE = 0x15; + public const byte PACKET_USERINFO = 0x81; + public const byte PACKET_WORLD = 0x7A; + public const byte PACKET_BASE_STATS = 0x7B; + public const byte PACKET_PLACE_INFO = 0x1E; + public const byte PACKET_AREA_DEFS = 0x79; + public const byte PACKET_ANNOUNCEMENT = 0x7E; + public const byte PACKET_TILE_FLAGS = 0x75; + + public const byte AREA_SEPERATOR = 0x5E; + + public const byte MOVE_UP = 0x14; + public const byte MOVE_DOWN = 0x15; + public const byte MOVE_RIGHT = 0x16; + public const byte MOVE_LEFT = 0x17; + public const byte MOVE_EXIT = 0x10; + + public const byte CHAT_BOTTOM_LEFT = 0x14; + public const byte CHAT_BOTTOM_RIGHT = 0x15; + + public const byte LOGIN_INVALID_USER_PASS = 0x15; + public const byte LOGIN_SUCCESS = 0x14; + + public const byte DIRECTION_UP = 0; + public const byte DIRECTION_RIGHT = 1; + public const byte DIRECTION_DOWN = 2; + public const byte DIRECTION_LEFT = 3; + public const byte DIRECTION_LOGIN = 4; + public const byte DIRECTION_NONE = 10; + + + + public static byte[] CreateLoginPacket(bool Success) + { + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_LOGIN); + if (Success) + ms.WriteByte(LOGIN_SUCCESS); + else + ms.WriteByte(LOGIN_INVALID_USER_PASS); + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + + public static byte[] CreateMovementPacket(int x, int y,int charId,int facing, int direction, bool walk) + { + // Header information + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_MOVE); + + ms.WriteByte((byte)(((x-4) / 64) + 20)); //1 + ms.WriteByte((byte)(((x-4) % 64) + 20)); //2 + + ms.WriteByte((byte)(((y-1) / 64) + 20)); //3 + ms.WriteByte((byte)(((y-1) % 64) + 20)); //4 + + ms.WriteByte((byte)(facing + 20)); //5 + + ms.WriteByte((byte)((charId / 64) + 20)); //6 + ms.WriteByte((byte)((charId % 64) + 20)); //7 + + ms.WriteByte((byte)(direction + 20)); //8 + + ms.WriteByte((byte)(Convert.ToInt32(walk) + 20)); //9 + + // Map Data + + if (direction >= 20) + { + direction -= 20; + } + + int ystart = y - 4; + int xstart = x - 6; + + + if (direction == DIRECTION_UP) + { + for (int relx = 0; relx <= 12; relx++) + { + int tileId = Map.GetTileId(xstart + relx, ystart, false); + int otileId = Map.GetTileId(xstart + relx, ystart, true); + + + ms.WriteByte((byte)tileId); + if (tileId == 190) + ms.WriteByte((byte)0x5B); + ms.WriteByte((byte)otileId); + if (otileId == 190) + ms.WriteByte((byte)0x5A); + } + } + + if (direction == DIRECTION_LEFT) + { + for (int rely = 0; rely <= 9; rely++) + { + int tileId = Map.GetTileId(xstart, ystart + rely, false); + int otileId = Map.GetTileId(xstart, ystart + rely, true); + + + ms.WriteByte((byte)tileId); + if (tileId == 190) + ms.WriteByte((byte)0x5B); + ms.WriteByte((byte)otileId); + if (otileId == 190) + ms.WriteByte((byte)0x5A); + } + } + + + if (direction == DIRECTION_RIGHT) + { + for (int rely = 0; rely <= 9; rely++) + { + int tileId = Map.GetTileId(xstart + 12, ystart + rely, false); + int otileId = Map.GetTileId(xstart + 12, ystart + rely, true); + + + ms.WriteByte((byte)tileId); + if (tileId == 190) + ms.WriteByte((byte)0x5B); + ms.WriteByte((byte)otileId); + if (otileId == 190) + ms.WriteByte((byte)0x5A); + } + } + + if (direction == DIRECTION_DOWN) + { + for (int relx = 0; relx <= 12; relx++) + { + int tileId = Map.GetTileId(xstart + relx, ystart + 9, false); + int otileId = Map.GetTileId(xstart + relx, ystart + 9, true); + + + ms.WriteByte((byte)tileId); + if (tileId == 190) + ms.WriteByte((byte)0x5B); + ms.WriteByte((byte)otileId); + if (otileId == 190) + ms.WriteByte((byte)0x5A); + } + } + if (direction == DIRECTION_LOGIN) + { + for(int rely = 0; rely <= 9; rely++) + { + for (int relx = 0; relx <= 12; relx++) + { + int tileId = Map.GetTileId(xstart + relx, ystart + rely, false); + int otileId = Map.GetTileId(xstart + relx, ystart + rely, true); + + + ms.WriteByte((byte)tileId); + if (tileId == 190) + ms.WriteByte((byte)0x5B); + + ms.WriteByte((byte)otileId); + if (otileId == 190) + ms.WriteByte((byte)0x5A); + } + } + + } + + + ms.WriteByte(PACKET_TERMINATOR); + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + Logger.DebugPrint(BitConverter.ToString(Packet).Replace('-', ' ')); + + return Packet; + } + + public static byte[] CreatePlaceInfo(string formattedText) + { + byte[] strBytes = Encoding.UTF8.GetBytes(formattedText); + + MemoryStream ms = new MemoryStream(); + + ms.WriteByte(PACKET_PLACE_INFO); + + ms.Write(strBytes, 0x00, strBytes.Length); + + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + public static byte[] CreateChat(string formattedText, byte chatWindow) + { + byte[] strBytes = Encoding.UTF8.GetBytes(formattedText); + + MemoryStream ms = new MemoryStream(); + + ms.WriteByte(PACKET_CHAT); + ms.WriteByte(chatWindow); + + ms.Write(strBytes, 0x00, strBytes.Length); + + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + + public static byte[] CreateWorldData(int gameTime, int gameDay, int gameYear, string weather) + { + byte[] strBytes = Encoding.UTF8.GetBytes(weather); + + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_WORLD); + + ms.WriteByte((byte)((gameTime / 64) + 20)); + ms.WriteByte((byte)((gameTime % 64) + 20)); + + ms.WriteByte((byte)((gameDay / 64) + 20)); + ms.WriteByte((byte)((gameDay % 64) + 20)); + + ms.WriteByte((byte)((gameYear / 64) + 20)); + ms.WriteByte((byte)((gameYear % 64) + 20)); + + ms.Write(strBytes,0x00, strBytes.Length); + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + + public static byte[] CreateIsleData(World.Isle[] isles) + { + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_AREA_DEFS); + foreach(World.Isle isle in isles) + { + byte[] strBytes = Encoding.UTF8.GetBytes(isle.Name); + + ms.WriteByte(AREA_SEPERATOR); + + ms.WriteByte((byte)(((isle.StartX - 4) / 64) + 20)); + ms.WriteByte((byte)(((isle.StartX - 4) % 64) + 20)); + + ms.WriteByte((byte)(((isle.EndX - 4) / 64) + 20)); + ms.WriteByte((byte)(((isle.EndX - 4) % 64) + 20)); + + ms.WriteByte((byte)(((isle.StartY - 1) / 64) + 20)); + ms.WriteByte((byte)(((isle.StartY - 1) % 64) + 20)); + + ms.WriteByte((byte)(((isle.EndY - 1) / 64) + 20)); + ms.WriteByte((byte)(((isle.EndY - 1) % 64) + 20)); + + ms.WriteByte((byte)isle.Tileset.ToString()[0]); + + ms.Write(strBytes, 0x00, strBytes.Length); + } + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + + public static byte[] CreateBaseStats(int money, int playerCount, int mail) + { + byte[] moneyStrBytes = Encoding.UTF8.GetBytes(money.ToString()); + byte[] playerStrBytes = Encoding.UTF8.GetBytes(playerCount.ToString()); + byte[] mailStrBytes = Encoding.UTF8.GetBytes(mail.ToString()); + + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_BASE_STATS); + ms.Write(moneyStrBytes, 0x00, moneyStrBytes.Length); + ms.WriteByte((byte)'|'); + ms.Write(playerStrBytes, 0x00, playerStrBytes.Length); + ms.WriteByte((byte)'|'); + ms.Write(mailStrBytes, 0x00, mailStrBytes.Length); + ms.WriteByte((byte)'|'); + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + + public static byte[] CreateTileOverlayFlags(int[] tileDepthFlags) + { + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_TILE_FLAGS); + + foreach(int tileDepthFlag in tileDepthFlags) + { + ms.WriteByte((byte)tileDepthFlag.ToString()[0]); + } + + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + public static byte[] CreateSecCode(byte[] SecCodeSeed, int SecCodeInc, bool Admin, bool Moderator) + { + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_USERINFO); + + ms.WriteByte((byte)(SecCodeSeed[0] + 33)); + ms.WriteByte((byte)(SecCodeSeed[1] + 33)); + ms.WriteByte((byte)(SecCodeSeed[2] + 33)); + ms.WriteByte((byte)(SecCodeInc + 33)); + + char userType = 'N'; // Normal? + if (Moderator) + userType = 'M'; + if (Admin) + userType = 'A'; + + ms.WriteByte((byte)userType); + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + public static byte[] CreateAnnouncement(string announcement) + { + MemoryStream ms = new MemoryStream(); + ms.WriteByte(PACKET_ANNOUNCEMENT); + byte[] strBytes = Encoding.UTF8.GetBytes(announcement); + ms.Write(strBytes, 0x00, strBytes.Length); + ms.WriteByte(PACKET_TERMINATOR); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + + public static byte[] CreateAreaMessage(int x, int y) + { + string locationStr = Messages.LocationData(x, y); + return CreatePlaceInfo(locationStr); + } + public static byte[] CreateMotd() + { + string formattedMotd = Messages.GetMOTD(); + return CreateAnnouncement(formattedMotd); + } + public static byte[] CreateLoginMessage(string username) + { + string formattedStr = Messages.GetLoginMessage(username); + return CreateChat(formattedStr, CHAT_BOTTOM_RIGHT); + } + + public static byte[] CreateUserInfo(Client client) + { + MemoryStream ms = new MemoryStream(); + if(!client.LoggedIn) + throw new Exception("Client is not logged in."); + User user = client.LoggedinUser; + + byte[] MovementPacket = CreateMovementPacket(user.X, user.Y, user.CharacterId, DIRECTION_DOWN, DIRECTION_LOGIN, true); + ms.Write(MovementPacket, 0x00, MovementPacket.Length); + + byte[] LoginMessage = CreateLoginMessage(user.Username); + ms.Write(LoginMessage, 0x00, LoginMessage.Length); + + World.Time time = World.GetGameTime(); + int timestamp = time.hours * 60; + timestamp += time.minutes; + + byte[] WorldData = CreateWorldData(timestamp, time.days, time.year, World.GetWeather()); + ms.Write(WorldData, 0x00, WorldData.Length); + + byte[] SecCodePacket = CreateSecCode(user.SecCodeSeeds, user.SecCodeInc, user.Administrator, user.Moderator); + ms.Write(SecCodePacket, 0x00, SecCodePacket.Length); + + byte[] BaseStatsPacketData = CreateBaseStats(user.Money, Server.GetNumberOfPlayers(), user.MailBox.MailCount); + ms.Write(BaseStatsPacketData, 0x00, BaseStatsPacketData.Length); + + byte[] AreaMessage = CreateAreaMessage(user.X,user.Y); + ms.Write(AreaMessage, 0x00, AreaMessage.Length); + + byte[] IsleData = CreateIsleData(World.Isles.ToArray()); + ms.Write(IsleData, 0x00, IsleData.Length); + + byte[] TileFlags = CreateTileOverlayFlags(Map.OverlayTileDepth); + ms.Write(TileFlags, 0x00, TileFlags.Length); + + byte[] MotdData = CreateMotd(); + ms.Write(MotdData, 0x00, MotdData.Length); + + ms.Seek(0x00, SeekOrigin.Begin); + byte[] Packet = ms.ToArray(); + ms.Dispose(); + + return Packet; + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/Program.cs b/Horse Isle Server/Horse Isle Server/Program.cs index 1d9db89..923515f 100644 --- a/Horse Isle Server/Horse Isle Server/Program.cs +++ b/Horse Isle Server/Horse Isle Server/Program.cs @@ -1,21 +1,45 @@ -using System; -using System.IO; -using System.Reflection; - -namespace Horse_Isle_Server -{ - class Program - { - static void Main(string[] args) - { - Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); - ConfigReader.OpenConfig(); - CrossDomainPolicy.GetPolicy(); - Database.OpenDatabase(); - Map.OpenMap(); - Gamedata.ReadGamedata(); - Server.StartServer(); - - } - } -} +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Reflection; + +namespace Horse_Isle_Server +{ + class Program + { + static void Main(string[] args) + { + /* + Bitmap mbmp = new Bitmap("MapData.bmp"); + Bitmap bmp = new Bitmap("oMapData.bmp"); + Console.WriteLine(bmp.PixelFormat); + Bitmap bbmp = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format24bppRgb); + for(int x = 0; x < bmp.Width; x++) + { + for(int y = 0; y < bmp.Height; y++) + { + Color col = mbmp.GetPixel(x, y); + Color col2 = bmp.GetPixel(x, y); + + bbmp.SetPixel(x,y,Color.FromArgb(col2.B, 0, col.B)); + + } + } + bbmp.Save("MapData2.bmp", ImageFormat.Bmp); + Console.WriteLine("image checked"); + */ + + + + Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)); + ConfigReader.OpenConfig(); + CrossDomainPolicy.GetPolicy(); + Database.OpenDatabase(); + Map.OpenMap(); + Gamedata.ReadGamedata(); + Server.StartServer(); + + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/Properties/AssemblyInfo.cs b/Horse Isle Server/Horse Isle Server/Properties/AssemblyInfo.cs index b0554c3..d604330 100644 --- a/Horse Isle Server/Horse Isle Server/Properties/AssemblyInfo.cs +++ b/Horse Isle Server/Horse Isle Server/Properties/AssemblyInfo.cs @@ -1,36 +1,36 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: AssemblyTitle("Horse Isle Server")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Horse Isle Server")] -[assembly: AssemblyCopyright("Copyright © 2020")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("c48cbd82-ab30-494a-8ffa-4de7069b5827")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Build and Revision Numbers -// by using the '*' as shown below: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Horse Isle Server")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Horse Isle Server")] +[assembly: AssemblyCopyright("Copyright © 2020")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("c48cbd82-ab30-494a-8ffa-4de7069b5827")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Horse Isle Server/Horse Isle Server/Properties/Resources.Designer.cs b/Horse Isle Server/Horse Isle Server/Properties/Resources.Designer.cs index c9c8041..1633fc7 100644 --- a/Horse Isle Server/Horse Isle Server/Properties/Resources.Designer.cs +++ b/Horse Isle Server/Horse Isle Server/Properties/Resources.Designer.cs @@ -1,104 +1,104 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Horse_Isle_Server.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Horse_Isle_Server.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to <cross-domain-policy> - /// <allow-access-from domain="*" to-ports="1080" secure="false"/> - ///</cross-domain-policy>. - /// - internal static string DefaultCrossDomain { - get { - return ResourceManager.GetString("DefaultCrossDomain", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to # Horse Isle Server Default Configuration File - /// - ///# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES) - ///ip=0.0.0.0 - ///# Port the server will bind to (default: 1080) - ///port=1080 - /// - ///# MariaDB Database - ///db_ip=127.0.0.1 - ///db_username=root - ///db_password=test123 - ///db_port=3306 - /// - ///# Map Data - ///map=MapData.bmp - ///overlaymap=oMapData.bmp - /// - ///# Cross-Domain Policy File - ///crossdomain="CrossDomainPolicy.xml - /// - ///# Should print debug logs - ///debug=false. - /// - internal static string DefaultServerProperties { - get { - return ResourceManager.GetString("DefaultServerProperties", resourceCulture); - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Horse_Isle_Server.Properties { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Horse_Isle_Server.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to <cross-domain-policy> + /// <allow-access-from domain="*" to-ports="1080" secure="false"/> + ///</cross-domain-policy>. + /// + internal static string DefaultCrossDomain { + get { + return ResourceManager.GetString("DefaultCrossDomain", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to # Horse Isle Server Default Configuration File + /// + ///# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES) + ///ip=0.0.0.0 + ///# Port the server will bind to (default: 1080) + ///port=1080 + /// + ///# MariaDB Database + ///db_ip=127.0.0.1 + ///db_username=root + ///db_password=test123 + ///db_port=3306 + /// + ///# Map Data + ///map=MapData.bmp + ///overlaymap=oMapData.bmp + /// + ///# Cross-Domain Policy File + ///crossdomain="CrossDomainPolicy.xml + /// + ///# Should print debug logs + ///debug=false. + /// + internal static string DefaultServerProperties { + get { + return ResourceManager.GetString("DefaultServerProperties", resourceCulture); + } + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/Properties/Resources.resx b/Horse Isle Server/Horse Isle Server/Properties/Resources.resx index 8473728..594555e 100644 --- a/Horse Isle Server/Horse Isle Server/Properties/Resources.resx +++ b/Horse Isle Server/Horse Isle Server/Properties/Resources.resx @@ -1,127 +1,127 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - ..\Resources\default_cross_domain.xml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - - - ..\Resources\server.properties;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + ..\Resources\default_cross_domain.xml;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + + + ..\Resources\server.properties;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252 + \ No newline at end of file diff --git a/Horse Isle Server/Horse Isle Server/Resources/default_cross_domain.xml b/Horse Isle Server/Horse Isle Server/Resources/default_cross_domain.xml index b9c7e79..f1dfb38 100644 --- a/Horse Isle Server/Horse Isle Server/Resources/default_cross_domain.xml +++ b/Horse Isle Server/Horse Isle Server/Resources/default_cross_domain.xml @@ -1,3 +1,3 @@ - - + + \ No newline at end of file diff --git a/Horse Isle Server/Horse Isle Server/Resources/server.properties b/Horse Isle Server/Horse Isle Server/Resources/server.properties index afa5908..4a0083f 100644 --- a/Horse Isle Server/Horse Isle Server/Resources/server.properties +++ b/Horse Isle Server/Horse Isle Server/Resources/server.properties @@ -1,29 +1,28 @@ -# Horse Isle Server Default Configuration File - -# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES) -ip=0.0.0.0 -# Port the server will bind to (default: 12321) -port=12321 - -# MariaDB Database -db_ip=127.0.0.1 -db_name=beta -db_username=root -db_password=test123 -db_port=3306 - -# Map Data -map=MapData.bmp -overlaymap=oMapData.bmp - -# Game Data JSON -gamedata=gamedata.json - -# Cross-Domain Policy File -crossdomain=CrossDomainPolicy.xml - -# Red Text Stating "Todays Note:" -motd=April 11, 2020. New breed, Camarillo White Horse. Two new quests. - -# Should print debug logs +# Horse Isle Server Default Configuration File + +# Ip address the server will bind to (default: 0.0.0.0 ALL INTERFACES) +ip=0.0.0.0 +# Port the server will bind to (default: 12321) +port=12321 + +# MariaDB Database +db_ip=127.0.0.1 +db_name=beta +db_username=root +db_password=test123 +db_port=3306 + +# Map Data +map=MapDataCombined.bmp + +# Game Data JSON +gamedata=gamedata.json + +# Cross-Domain Policy File +crossdomain=CrossDomainPolicy.xml + +# Red Text Stating "Todays Note:" +motd=April 11, 2020. New breed, Camarillo White Horse. Two new quests. + +# Should print debug logs debug=false \ No newline at end of file diff --git a/Horse Isle Server/Horse Isle Server/Server.cs b/Horse Isle Server/Horse Isle Server/Server.cs index 726594d..154474c 100644 --- a/Horse Isle Server/Horse Isle Server/Server.cs +++ b/Horse Isle Server/Horse Isle Server/Server.cs @@ -1,154 +1,186 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class Server - { - - public static Socket ServerSocket; - public static List ConnectedClients = new List(); - - public static void OnCrossdomainPolicyRequest(Client sender) // When a cross-domain-policy request is received. - { - Logger.DebugPrint("Cross-Domain-Policy request received from: " + sender.RemoteIp); - - byte[] crossDomainPolicyResponse = CrossDomainPolicy.GetPolicy(); // Generate response packet - - sender.SendPacket(crossDomainPolicyResponse); // Send to client. - } - - public static void OnUserInfoRequest(Client sender, byte[] packet) - { - if (!sender.LoggedIn) - { - Logger.ErrorPrint(sender.RemoteIp + " Requested user information when not logged in."); - return; - } - Logger.DebugPrint(sender.LoggedinUser.Username + " Requesting user information."); - byte[] userInfoPackets = PacketBuilder.CreateUserInfo(sender); - sender.SendPacket(userInfoPackets); - } - - public static void OnMovementPacket(Client sender, byte[] packet) - { - if (!sender.LoggedIn) - { - Logger.ErrorPrint(sender.RemoteIp + " Sent movement packet when not logged in."); - return; - } - - User loggedInUser = sender.LoggedinUser; - byte movementDirection = packet[1]; - switch(movementDirection) - { - case PacketBuilder.MOVE_UP: - if(Map.CheckPassable(loggedInUser.X, loggedInUser.Y+1)) - loggedInUser.Y -= 1; - byte[] moveUpResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_UP, PacketBuilder.DIRECTION_UP, true); - sender.SendPacket(moveUpResponse); - break; - case PacketBuilder.MOVE_LEFT: - if (Map.CheckPassable(loggedInUser.X - 1, loggedInUser.Y)) - loggedInUser.X -= 1; - byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_LEFT, PacketBuilder.DIRECTION_LEFT, true); - sender.SendPacket(moveLeftResponse); - break; - case PacketBuilder.MOVE_RIGHT: - if (Map.CheckPassable(loggedInUser.X +1 , loggedInUser.Y)) - loggedInUser.X += 1; - byte[] moveRightResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_RIGHT, PacketBuilder.DIRECTION_RIGHT, true); - sender.SendPacket(moveRightResponse); - break; - case PacketBuilder.MOVE_DOWN: - if (Map.CheckPassable(loggedInUser.X, loggedInUser.Y + 1)) - loggedInUser.Y += 1; - byte[] moveDownResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_DOWN, PacketBuilder.DIRECTION_DOWN, true); - sender.SendPacket(moveDownResponse); - break; - } - - byte[] tileData = PacketBuilder.CreateAreaMessage(loggedInUser.X, loggedInUser.Y); - sender.SendPacket(tileData); - } - public static void OnLoginRequest(Client sender, byte[] packet) - { - Logger.DebugPrint("Login request received from: " + sender.RemoteIp); - - string loginRequestString = Encoding.UTF8.GetString(packet).Substring(1); - - if (!loginRequestString.Contains('|') || packet.Length < 3) - { - Logger.ErrorPrint(sender.RemoteIp + " Sent an invalid login request"); - return; - } - - if(packet[1] != PacketBuilder.PACKET_A_TERMINATOR) - { - string[] loginParts = loginRequestString.Split('|'); - if (loginParts.Length < 3) - { - Logger.ErrorPrint(sender.RemoteIp + " Sent a login request of invalid length. " + loginRequestString); - return; - } - - int version = int.Parse(loginParts[0]); - string encryptedUsername = loginParts[1]; - string encryptedPassword = loginParts[2]; - string username = Authentication.DecryptLogin(encryptedUsername); - string password = Authentication.DecryptLogin(encryptedPassword); - - if (Authentication.CheckPassword(username, password)) - { - // Obtain user information - int userId = Database.GetUserid(username); - sender.Login(userId); - - byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(true); - sender.SendPacket(ResponsePacket); - } - else - { - Logger.WarnPrint(sender.RemoteIp + " Attempted to login to: " + username + " with incorrect password " + password); - byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(false); - sender.SendPacket(ResponsePacket); - } - } - - } - - public static int GetNumberOfPlayers() - { - int count = 0; - foreach(Client client in ConnectedClients) - { - if (client.LoggedIn) - count++; - } - return count; - } - public static void StartServer() - { - ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - IPAddress hostIP = IPAddress.Parse(ConfigReader.BindIP); - IPEndPoint ep = new IPEndPoint(hostIP, ConfigReader.Port); - ServerSocket.Bind(ep); - Logger.DebugPrint("Binding to ip: " + ConfigReader.BindIP + " On port: " + ConfigReader.Port.ToString()); - ServerSocket.Listen(10000); - - while(true) - { - Logger.DebugPrint("Waiting for new connections..."); - - Socket cientSocket = ServerSocket.Accept(); - Client client = new Client(cientSocket); - ConnectedClients.Add(client); - } - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class Server + { + + public static Socket ServerSocket; + public static List ConnectedClients = new List(); + + public static void OnCrossdomainPolicyRequest(Client sender) // When a cross-domain-policy request is received. + { + Logger.DebugPrint("Cross-Domain-Policy request received from: " + sender.RemoteIp); + + byte[] crossDomainPolicyResponse = CrossDomainPolicy.GetPolicy(); // Generate response packet + + sender.SendPacket(crossDomainPolicyResponse); // Send to client. + } + + public static void OnUserInfoRequest(Client sender, byte[] packet) + { + if (!sender.LoggedIn) + { + Logger.ErrorPrint(sender.RemoteIp + " Requested user information when not logged in."); + return; + } + Logger.DebugPrint(sender.LoggedinUser.Username + " Requesting user information."); + byte[] userInfoPackets = PacketBuilder.CreateUserInfo(sender); + sender.SendPacket(userInfoPackets); + } + + public static void OnMovementPacket(Client sender, byte[] packet) + { + if (!sender.LoggedIn) + { + Logger.ErrorPrint(sender.RemoteIp + " Sent movement packet when not logged in."); + return; + } + + User loggedInUser = sender.LoggedinUser; + byte movementDirection = packet[1]; + + if(movementDirection == PacketBuilder.MOVE_UP) + { + if (Map.CheckPassable(loggedInUser.X, loggedInUser.Y - 1)) + { + loggedInUser.Y -= 1; + byte[] moveUpResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_UP, PacketBuilder.DIRECTION_UP, true); + sender.SendPacket(moveUpResponse); + } + else + { + byte[] moveUpResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_UP, PacketBuilder.DIRECTION_NONE, false); + sender.SendPacket(moveUpResponse); + } + } + else if(movementDirection == PacketBuilder.MOVE_LEFT) + { + if (Map.CheckPassable(loggedInUser.X - 1, loggedInUser.Y)) + { + loggedInUser.X -= 1; + byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_LEFT, PacketBuilder.DIRECTION_LEFT, true); + sender.SendPacket(moveLeftResponse); + } + else + { + byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_LEFT, PacketBuilder.DIRECTION_NONE, false); + sender.SendPacket(moveLeftResponse); + } + } + else if(movementDirection == PacketBuilder.MOVE_RIGHT) + { + if (Map.CheckPassable(loggedInUser.X + 1, loggedInUser.Y)) + { + loggedInUser.X += 1; + byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_RIGHT, PacketBuilder.DIRECTION_RIGHT, true); + sender.SendPacket(moveLeftResponse); + } + else + { + byte[] moveLeftResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_RIGHT, PacketBuilder.DIRECTION_NONE, false); + sender.SendPacket(moveLeftResponse); + } + } + else if(movementDirection == PacketBuilder.MOVE_DOWN) + { + if (Map.CheckPassable(loggedInUser.X, loggedInUser.Y + 1)) + { + loggedInUser.Y += 1; + byte[] moveDownResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_DOWN, PacketBuilder.DIRECTION_DOWN, true); + sender.SendPacket(moveDownResponse); + } + else + { + byte[] moveDownResponse = PacketBuilder.CreateMovementPacket(loggedInUser.X, loggedInUser.Y, loggedInUser.CharacterId, PacketBuilder.DIRECTION_DOWN, PacketBuilder.DIRECTION_NONE, false); + sender.SendPacket(moveDownResponse); + } + + } + + + byte[] tileData = PacketBuilder.CreateAreaMessage(loggedInUser.X, loggedInUser.Y); + sender.SendPacket(tileData); + } + public static void OnLoginRequest(Client sender, byte[] packet) + { + Logger.DebugPrint("Login request received from: " + sender.RemoteIp); + + string loginRequestString = Encoding.UTF8.GetString(packet).Substring(1); + + if (!loginRequestString.Contains('|') || packet.Length < 3) + { + Logger.ErrorPrint(sender.RemoteIp + " Sent an invalid login request"); + return; + } + + if(packet[1] != PacketBuilder.PACKET_A_TERMINATOR) + { + string[] loginParts = loginRequestString.Split('|'); + if (loginParts.Length < 3) + { + Logger.ErrorPrint(sender.RemoteIp + " Sent a login request of invalid length. " + loginRequestString); + return; + } + + int version = int.Parse(loginParts[0]); + string encryptedUsername = loginParts[1]; + string encryptedPassword = loginParts[2]; + string username = Authentication.DecryptLogin(encryptedUsername); + string password = Authentication.DecryptLogin(encryptedPassword); + + if (Authentication.CheckPassword(username, password)) + { + // Obtain user information + int userId = Database.GetUserid(username); + sender.Login(userId); + + byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(true); + sender.SendPacket(ResponsePacket); + } + else + { + Logger.WarnPrint(sender.RemoteIp + " Attempted to login to: " + username + " with incorrect password " + password); + byte[] ResponsePacket = PacketBuilder.CreateLoginPacket(false); + sender.SendPacket(ResponsePacket); + } + } + + } + + public static int GetNumberOfPlayers() + { + int count = 0; + foreach(Client client in ConnectedClients) + { + if (client.LoggedIn) + count++; + } + return count; + } + public static void StartServer() + { + ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + IPAddress hostIP = IPAddress.Parse(ConfigReader.BindIP); + IPEndPoint ep = new IPEndPoint(hostIP, ConfigReader.Port); + ServerSocket.Bind(ep); + Logger.DebugPrint("Binding to ip: " + ConfigReader.BindIP + " On port: " + ConfigReader.Port.ToString()); + ServerSocket.Listen(10000); + + while(true) + { + Logger.DebugPrint("Waiting for new connections..."); + + Socket cientSocket = ServerSocket.Accept(); + Client client = new Client(cientSocket); + ConnectedClients.Add(client); + } + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/User.cs b/Horse Isle Server/Horse Isle Server/User.cs index 80b1f06..f8d4d9a 100644 --- a/Horse Isle Server/Horse Isle Server/User.cs +++ b/Horse Isle Server/Horse Isle Server/User.cs @@ -1,163 +1,163 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - class User - { - public int Id; - public string Username; - public bool Administrator; - public bool Moderator; - public bool NewPlayer = false; - public Mailbox MailBox; - - public string ProfilePage { - get - { - return profilePage; - } - set - { - Database.SetPlayerProfile(value, Id); - profilePage = value; - } - } - - public int Money - { - get - { - return money; - } - set - { - Database.SetPlayerBankMoney(value, Id); - money = value; - } - } - - public int BankMoney - { - get - { - return bankMoney; - } - set - { - Database.SetPlayerBankMoney(value, Id); - bankMoney = value; - } - } - - public int X - { - get - { - return x; - } - set - { - Database.SetPlayerX(value, Id); - x = value; - } - } - - public int Y - { - get - { - return y; - } - set - { - Database.SetPlayerY(value, Id); - y = value; - } - } - - public int CharacterId - { - get - { - return charId; - } - set - { - Database.SetPlayerCharId(value, Id); - charId = value; - } - } - - private int charId; - private string profilePage; - private int x; - private int y; - private int money; - private int bankMoney; - - public byte[] SecCodeSeeds = new byte[3]; - public int SecCodeInc = 0; - public int SecCodeCount = 0; - - - public byte[] GenerateSecCode() - { - var i = 0; - SecCodeCount++; - SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] + SecCodeInc); - SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] % 92); - i = SecCodeSeeds[0] + SecCodeSeeds[1] * SecCodeSeeds[2] - SecCodeSeeds[1]; - i = Math.Abs(i); - i = i % 92; - - byte[] SecCode = new byte[4]; - SecCode[0] = (byte)(SecCodeSeeds[0] + 33); - SecCode[1] = (byte)(SecCodeSeeds[1] + 33); - SecCode[2] = (byte)(SecCodeSeeds[2] + 33); - SecCode[3] = (byte)(i + 33); - return SecCode; - } - - public User(int UserId) - { - if (!Database.CheckUserExist(UserId)) - throw new KeyNotFoundException("User " + UserId + " not found in database!"); - - if (!Database.CheckUserExtExists(UserId)) - { - Database.CreateUserExt(UserId); - NewPlayer = true; - } - - Id = UserId; - Username = Database.GetUsername(UserId); - - Administrator = Database.CheckUserIsAdmin(Username); - Moderator = Database.CheckUserIsModerator(Username); - - x = Database.GetPlayerX(UserId); - y = Database.GetPlayerY(UserId); - charId = Database.GetPlayerCharId(UserId); - - money = Database.GetPlayerMoney(UserId); - bankMoney = Database.GetPlayerBankMoney(UserId); - - profilePage = Database.GetPlayerProfile(UserId); - - MailBox = new Mailbox(this); - - // Generate SecCodes - - Random rng = new Random(); - SecCodeSeeds[0] = (byte)rng.Next(0, 255 - 33); - SecCodeSeeds[1] = (byte)rng.Next(0, 255 - 33); - SecCodeSeeds[2] = (byte)rng.Next(0, 255 - 33); - SecCodeInc = (byte)rng.Next(0, 255 - 33); - - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + class User + { + public int Id; + public string Username; + public bool Administrator; + public bool Moderator; + public bool NewPlayer = false; + public Mailbox MailBox; + + public string ProfilePage { + get + { + return profilePage; + } + set + { + Database.SetPlayerProfile(value, Id); + profilePage = value; + } + } + + public int Money + { + get + { + return money; + } + set + { + Database.SetPlayerBankMoney(value, Id); + money = value; + } + } + + public int BankMoney + { + get + { + return bankMoney; + } + set + { + Database.SetPlayerBankMoney(value, Id); + bankMoney = value; + } + } + + public int X + { + get + { + return x; + } + set + { + Database.SetPlayerX(value, Id); + x = value; + } + } + + public int Y + { + get + { + return y; + } + set + { + Database.SetPlayerY(value, Id); + y = value; + } + } + + public int CharacterId + { + get + { + return charId; + } + set + { + Database.SetPlayerCharId(value, Id); + charId = value; + } + } + + private int charId; + private string profilePage; + private int x; + private int y; + private int money; + private int bankMoney; + + public byte[] SecCodeSeeds = new byte[3]; + public int SecCodeInc = 0; + public int SecCodeCount = 0; + + + public byte[] GenerateSecCode() + { + var i = 0; + SecCodeCount++; + SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] + SecCodeInc); + SecCodeSeeds[SecCodeCount % 3] = (byte)(SecCodeSeeds[SecCodeCount % 3] % 92); + i = SecCodeSeeds[0] + SecCodeSeeds[1] * SecCodeSeeds[2] - SecCodeSeeds[1]; + i = Math.Abs(i); + i = i % 92; + + byte[] SecCode = new byte[4]; + SecCode[0] = (byte)(SecCodeSeeds[0] + 33); + SecCode[1] = (byte)(SecCodeSeeds[1] + 33); + SecCode[2] = (byte)(SecCodeSeeds[2] + 33); + SecCode[3] = (byte)(i + 33); + return SecCode; + } + + public User(int UserId) + { + if (!Database.CheckUserExist(UserId)) + throw new KeyNotFoundException("User " + UserId + " not found in database!"); + + if (!Database.CheckUserExtExists(UserId)) + { + Database.CreateUserExt(UserId); + NewPlayer = true; + } + + Id = UserId; + Username = Database.GetUsername(UserId); + + Administrator = Database.CheckUserIsAdmin(Username); + Moderator = Database.CheckUserIsModerator(Username); + + x = Database.GetPlayerX(UserId); + y = Database.GetPlayerY(UserId); + charId = Database.GetPlayerCharId(UserId); + + money = Database.GetPlayerMoney(UserId); + bankMoney = Database.GetPlayerBankMoney(UserId); + + profilePage = Database.GetPlayerProfile(UserId); + + MailBox = new Mailbox(this); + + // Generate SecCodes + + Random rng = new Random(); + SecCodeSeeds[0] = (byte)rng.Next(0, 255 - 33); + SecCodeSeeds[1] = (byte)rng.Next(0, 255 - 33); + SecCodeSeeds[2] = (byte)rng.Next(0, 255 - 33); + SecCodeInc = (byte)rng.Next(0, 255 - 33); + + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/World.cs b/Horse Isle Server/Horse Isle Server/World.cs index 526ca5f..8f57039 100644 --- a/Horse Isle Server/Horse Isle Server/World.cs +++ b/Horse Isle Server/Horse Isle Server/World.cs @@ -1,79 +1,79 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Horse_Isle_Server -{ - - class World - { - public struct Isle - { - public int StartX; - public int EndX; - public int StartY; - public int EndY; - public int Tileset; - public string Name; - } - - public struct Time - { - public int minutes; - public int hours; - public int days; - public int year; - } - public const int MINUTE = 4320; - - public static List Isles = new List(); - public static Time GetGameTime() - { - int epoch = Database.GetServerCreationTime(); - DateTime serverCreationTime = DateTimeOffset.FromUnixTimeSeconds(epoch).DateTime; - DateTime currentTime = DateTime.Now; - - TimeSpan difference = (currentTime.Date - currentTime.Date); - - int totalMilis = Convert.ToInt32(difference.TotalMilliseconds); - - - int gameMinutes = totalMilis / MINUTE; - int gameHours = (totalMilis / MINUTE * 600); - int gameDays = (totalMilis / (MINUTE * 60) * 24); - int gameYears = ((totalMilis / (MINUTE * 60) * 24)*365); - - Time time = new Time(); - time.days = gameDays; - time.year = gameYears; - time.minutes = gameMinutes; - time.hours = gameHours; - - return time; - } - - - public static Isle GetIsle(int x, int y) - { - foreach(Isle isle in Isles) - { - - if (isle.StartX <= x && isle.EndX >= x && isle.StartY <= y && isle.EndY >= y) - { - return isle; - } - } - throw new KeyNotFoundException("x,y not in an isle!"); - } - public static int[] GetDroppedItems(int x, int y) - { - return new int[] { }; // Not implemented yet. - } - public static string GetWeather() - { - return Database.GetWorldWeather(); - } - } -} +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Horse_Isle_Server +{ + + class World + { + public struct Isle + { + public int StartX; + public int EndX; + public int StartY; + public int EndY; + public int Tileset; + public string Name; + } + + public struct Time + { + public int minutes; + public int hours; + public int days; + public int year; + } + public const int MINUTE = 4320; + + public static List Isles = new List(); + public static Time GetGameTime() + { + int epoch = Database.GetServerCreationTime(); + DateTime serverCreationTime = DateTimeOffset.FromUnixTimeSeconds(epoch).DateTime; + DateTime currentTime = DateTime.Now; + + TimeSpan difference = (currentTime.Date - currentTime.Date); + + int totalMilis = Convert.ToInt32(difference.TotalMilliseconds); + + + int gameMinutes = totalMilis / MINUTE; + int gameHours = (totalMilis / MINUTE * 600); + int gameDays = (totalMilis / (MINUTE * 60) * 24); + int gameYears = ((totalMilis / (MINUTE * 60) * 24)*365); + + Time time = new Time(); + time.days = gameDays; + time.year = gameYears; + time.minutes = gameMinutes; + time.hours = gameHours; + + return time; + } + + + public static Isle GetIsle(int x, int y) + { + foreach(Isle isle in Isles) + { + + if (isle.StartX <= x && isle.EndX >= x && isle.StartY <= y && isle.EndY >= y) + { + return isle; + } + } + throw new KeyNotFoundException("x,y not in an isle!"); + } + public static int[] GetDroppedItems(int x, int y) + { + return new int[] { }; // Not implemented yet. + } + public static string GetWeather() + { + return Database.GetWorldWeather(); + } + } +} diff --git a/Horse Isle Server/Horse Isle Server/packages.config b/Horse Isle Server/Horse Isle Server/packages.config index fadcd48..550ff67 100644 --- a/Horse Isle Server/Horse Isle Server/packages.config +++ b/Horse Isle Server/Horse Isle Server/packages.config @@ -1,10 +1,10 @@ - - - - - - - - - + + + + + + + + + \ No newline at end of file