Advertisement
Guest User

Untitled

a guest
Mar 7th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.57 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading;
  7. using System.Windows.Forms;
  8. using MySql.Data.MySqlClient;
  9. using Emulator.Core;
  10. using Emulator.HabboHotel;
  11. using Emulator.HabboHotel.GameClients;
  12. using Emulator.HabboHotel.Users;
  13. using Emulator.Utilities;
  14. using log4net;
  15. using Emulator.HabboHotel.Cache.Type;
  16. using Emulator.HabboHotel.Users.UserData;
  17. using Emulator.Messages.Net;
  18. using System.Collections.Concurrent;
  19. using Emulator.Communication.Packets.Outgoing.Moderation;
  20. using Emulator.Communication.Encryption.Keys;
  21. using Emulator.Communication.Encryption;
  22. using Emulator.Database.Interfaces;
  23. using Emulator.Database;
  24. using Emulator.Communication.RCON;
  25. using Emulator.Core.FigureData;
  26. using Emulator.Core.Language;
  27. using System.Net;
  28. using Emulator.HabboHotel.Security;
  29.  
  30. namespace Emulator
  31. {
  32. public static class HabboEnvironment
  33. {
  34. private static readonly ILog log = LogManager.GetLogger("Emulator.HabboEnvironment");
  35. // internal static bool IsLive;
  36. public const string PrettyVersion = "Habbo Emulator";
  37. public const string PrettyBuild = "3.4.3.0";
  38. private static bool DoubleCurrency = false;
  39. private static ConfigurationData _configuration;
  40. private static Encoding _defaultEncoding;
  41. private static ConnectionHandling _connectionManager;
  42. private static Game _game;
  43. private static Staff _staff;
  44. private static LanguageManager _languageManager;
  45. public static string UpdateBuild = "v1.1";
  46. private static DatabaseManager _manager;
  47. public static ConfigData ConfigData;
  48. public static RCONSocket _rcon;
  49. private static FigureDataManager _figureManager;
  50.  
  51. public static CultureInfo CultureInfo;
  52.  
  53. public static bool Event = false;
  54. public static DateTime lastEvent;
  55. public static DateTime ServerStarted;
  56.  
  57. private static readonly List<char> Allowedchars = new List<char>(new[]
  58. {
  59. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
  60. 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
  61. 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '.'
  62. });
  63.  
  64.  
  65.  
  66. private static ConcurrentDictionary<int, Habbo> _usersCached = new ConcurrentDictionary<int, Habbo>();
  67.  
  68. public static string SWFRevision = "PRODUCTION-201709052204-426856518";
  69.  
  70. public static void Initialize()
  71. {
  72. ServerStarted = DateTime.Now;
  73. Console.ForegroundColor = ConsoleColor.White;
  74. Console.Title = "Loading Habbo Emulator";
  75. _defaultEncoding = Encoding.Default;
  76. CultureInfo = CultureInfo.CreateSpecificCulture("en-GB");
  77. try
  78. {
  79.  
  80. _configuration = new ConfigurationData(Path.Combine(Application.StartupPath, @"config.ini"));
  81.  
  82. var connectionString = new MySqlConnectionStringBuilder
  83. {
  84. ConnectionTimeout = 10,
  85. Database = GetConfig().data["db.name"],
  86. DefaultCommandTimeout = 30,
  87. Logging = false,
  88. MaximumPoolSize = uint.Parse(GetConfig().data["db.pool.maxsize"]),
  89. MinimumPoolSize = uint.Parse(GetConfig().data["db.pool.minsize"]),
  90. Password = GetConfig().data["db.password"],
  91. Pooling = true,
  92. Port = uint.Parse(GetConfig().data["db.port"]),
  93. Server = GetConfig().data["db.hostname"],
  94. UserID = GetConfig().data["db.username"],
  95. AllowZeroDateTime = true,
  96. ConvertZeroDateTime = true,
  97. };
  98.  
  99. _manager = new DatabaseManager(connectionString.ToString());
  100.  
  101. if (!_manager.IsConnected())
  102. {
  103. log.Error("Failed to connect to the specified MySQL server.");
  104. Console.ReadKey(true);
  105. Environment.Exit(1);
  106. return;
  107. }
  108.  
  109. log.Info("Connected to Database!");
  110.  
  111. //Reset our statistics first.
  112. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  113. {
  114. dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`");
  115. dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0';");
  116. dbClient.RunQuery("UPDATE `users` SET `online` = '0' WHERE `online` = '1'");
  117. dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
  118. }
  119.  
  120. //Get the configuration & Game set.
  121. ConfigData = new ConfigData();
  122. _game = new Game();
  123. _languageManager = new LanguageManager();
  124.  
  125. _staff = new Staff();
  126. _staff.Initilize();
  127.  
  128. // _figureManager = new FigureDataManager();
  129. //_figureManager.Init();
  130.  
  131. //Have our encryption ready.
  132. HabboEncryptionV2.Initialize(new RSAKeys());
  133.  
  134. //Make sure RCON is connected before we allow clients to connect.
  135. _rcon = new RCONSocket(GetConfig().data["rcon.tcp.bindip"], int.Parse(GetConfig().data["rcon.tcp.port"]), GetConfig().data["rcon.tcp.allowedaddr"].Split(Convert.ToChar(";")));
  136.  
  137. //Accept connections.
  138. _connectionManager = new ConnectionHandling(int.Parse(GetConfig().data["game.tcp.port"]), int.Parse(GetConfig().data["game.tcp.conlimit"]), int.Parse(GetConfig().data["game.tcp.conperip"]), GetConfig().data["game.tcp.enablenagles"].ToLower() == "true");
  139. _connectionManager.Init();
  140.  
  141.  
  142.  
  143.  
  144. _game.StartGameLoop();
  145.  
  146. TimeSpan TimeUsed = DateTime.Now - ServerStarted;
  147.  
  148. Console.WriteLine();
  149.  
  150. log.Info("EMULATOR -> READY! (" + TimeUsed.Seconds + " s, " + TimeUsed.Milliseconds + " ms)");
  151. }
  152. catch (KeyNotFoundException e)
  153. {
  154. Logging.WriteLine("Please check your configuration file - some values appear to be missing.", ConsoleColor.Red);
  155. Logging.WriteLine("Press any key to shut down ...");
  156. Logging.WriteLine(e.ToString());
  157. Console.ReadKey(true);
  158. Environment.Exit(1);
  159. return;
  160. }
  161. catch (InvalidOperationException e)
  162. {
  163. Logging.WriteLine("Failed to initialize HabboEmulator: " + e.Message, ConsoleColor.Red);
  164. Logging.WriteLine("Press any key to shut down ...");
  165. Console.ReadKey(true);
  166. Environment.Exit(1);
  167. return;
  168. }
  169. catch (Exception e)
  170. {
  171. Logging.WriteLine("Fatal error during startup: " + e, ConsoleColor.Red);
  172. Logging.WriteLine("Press a key to exit");
  173.  
  174. Console.ReadKey();
  175. Environment.Exit(1);
  176. }
  177. }
  178.  
  179. public static RCONSocket GetRCONSocket()
  180. {
  181. return _rcon;
  182. }
  183.  
  184. internal static DateTime UnixToDateTime(double unixTimeStamp)
  185. {
  186. DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0);
  187. result = result.AddSeconds(unixTimeStamp).ToLocalTime();
  188. return result;
  189. }
  190. internal static int DateTimeToUnix(DateTime target)
  191. {
  192. DateTime d = new DateTime(1970, 1, 1, 0, 0, 0, target.Kind);
  193. return Convert.ToInt32((target - d).TotalSeconds);
  194. }
  195. public static bool EnumToBool(string Enum)
  196. {
  197. return (Enum == "1");
  198. }
  199.  
  200. public static string BoolToEnum(bool Bool)
  201. {
  202. return (Bool == true ? "1" : "0");
  203. }
  204. public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
  205. {
  206. // Unix timestamp is seconds past epoch
  207. System.DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
  208. dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
  209. return dtDateTime;
  210. }
  211. public static int GetRandomNumber(int Min, int Max)
  212. {
  213. return RandomNumber.GenerateNewRandom(Min, Max);
  214. }
  215.  
  216. public static int GetRandom(int Min, int Max)
  217. {
  218. Random rand3 = new Random();
  219. return rand3.Next(Min, Max);
  220. }
  221.  
  222. public static double GetUnixTimestamp()
  223. {
  224. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  225. return ts.TotalSeconds;
  226. }
  227.  
  228. internal static int GetIUnixTimestamp()
  229. {
  230. var ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  231. var unixTime = ts.TotalSeconds;
  232. return Convert.ToInt32(unixTime);
  233. }
  234.  
  235. public static bool _doubleCurrency
  236. {
  237. get { return DoubleCurrency; }
  238. set { DoubleCurrency = value; }
  239. }
  240.  
  241. public static long Now()
  242. {
  243. TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
  244. double unixTime = ts.TotalMilliseconds;
  245. return (long)unixTime;
  246. }
  247.  
  248. public static string FilterFigure(string figure)
  249. {
  250. foreach (char character in figure)
  251. {
  252. if (!IsValid(character))
  253. return "sh-3338-93.ea-1406-62.hr-831-49.ha-3331-92.hd-180-7.ch-3334-93-1408.lg-3337-92.ca-1813-62";
  254. }
  255.  
  256. return figure;
  257. }
  258.  
  259. private static bool IsValid(char character)
  260. {
  261. return Allowedchars.Contains(character);
  262. }
  263.  
  264. public static bool CheckUserForDupe(GameClient Session)
  265. {
  266. string timestampnew2 = DateTime.Today.ToString("MM/dd");
  267. string IPAddress = string.Empty;
  268. string GetRewardStamp = string.Empty;
  269.  
  270. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  271. {
  272. dbClient.SetQuery("SELECT `dailyGift` FROM `users` WHERE `id` = @id LIMIT 1");
  273. dbClient.AddParameter("id", Session.GetHabbo().Id);
  274. timestampnew2 = dbClient.getString();
  275.  
  276. dbClient.SetQuery("SELECT `ip_last` FROM `users` WHERE `id` = @id LIMIT 1");
  277. dbClient.AddParameter("id", Session.GetHabbo().Id);
  278. IPAddress = dbClient.getString();
  279.  
  280. dbClient.SetQuery("SELECT `ip_last`,`dailyGift` FROM `users` WHERE `ip_last` = @ip AND `dailyGift` = @time LIMIT 1");
  281. dbClient.AddParameter("time", timestampnew2);
  282. dbClient.AddParameter("ip", IPAddress);
  283. GetRewardStamp = dbClient.getString();
  284. }
  285.  
  286. if (GetRewardStamp.Length != 0)
  287. return false;
  288.  
  289. return true;
  290. }
  291.  
  292. public static bool CheckDupeUsers(GameClient User1, GameClient User2 = null)
  293. {
  294. String User1IP = String.Empty;
  295. string FirstUser = User1.GetHabbo().Username;
  296. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  297. {
  298. dbClient.SetQuery("SELECT `ip_last` FROM `users` WHERE `id` = '" + User1.GetHabbo().Id + "' LIMIT 1");
  299. User1IP = dbClient.getString();
  300. }
  301.  
  302. String User2IP = String.Empty;
  303. string SecondUser = User2.GetHabbo().Username;
  304. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  305. {
  306. dbClient.SetQuery("SELECT `ip_last` FROM `users` WHERE `id` = '" + User2.GetHabbo().Id + "' LIMIT 1");
  307. User2IP = dbClient.getString();
  308. }
  309. if (User1IP != User2IP)
  310. {
  311. return false;
  312. }
  313. return true;
  314. }
  315.  
  316. public static bool IsValidAlphaNumeric(string inputStr)
  317. {
  318. inputStr = inputStr.ToLower();
  319. if (string.IsNullOrEmpty(inputStr))
  320. {
  321. return false;
  322. }
  323.  
  324. for (int i = 0; i < inputStr.Length; i++)
  325. {
  326. if (!IsValid(inputStr[i]))
  327. {
  328. return false;
  329. }
  330. }
  331.  
  332. return true;
  333. }
  334.  
  335.  
  336.  
  337. public static string GetUsernameById(int UserId)
  338. {
  339. string Name = "Unknown User";
  340.  
  341. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  342. if (Client != null && Client.GetHabbo() != null)
  343. return Client.GetHabbo().Username;
  344.  
  345. UserCache User = HabboEnvironment.GetGame().GetCacheManager().GenerateUser(UserId);
  346. if (User != null)
  347. return User.Username;
  348.  
  349. using (IQueryAdapter dbClient = HabboEnvironment.GetDatabaseManager().GetQueryReactor())
  350. {
  351. dbClient.SetQuery("SELECT `username` FROM `users` WHERE id = @id LIMIT 1");
  352. dbClient.AddParameter("id", UserId);
  353. Name = dbClient.getString();
  354. }
  355.  
  356. if (string.IsNullOrEmpty(Name))
  357. Name = "Unknown User";
  358.  
  359. return Name;
  360. }
  361.  
  362. public static Habbo GetHabboById(int UserId)
  363. {
  364. try
  365. {
  366. GameClient Client = GetGame().GetClientManager().GetClientByUserID(UserId);
  367. if (Client != null)
  368. {
  369. Habbo User = Client.GetHabbo();
  370. if (User != null && User.Id > 0)
  371. {
  372. if (_usersCached.ContainsKey(UserId))
  373. _usersCached.TryRemove(UserId, out User);
  374. return User;
  375. }
  376. }
  377. else
  378. {
  379. try
  380. {
  381. if (_usersCached.ContainsKey(UserId))
  382. return _usersCached[UserId];
  383. else
  384. {
  385. UserData data = UserDataFactory.GetUserData(UserId);
  386. if (data != null)
  387. {
  388. Habbo Generated = data.user;
  389. if (Generated != null)
  390. {
  391. Generated.InitInformation(data);
  392. _usersCached.TryAdd(UserId, Generated);
  393. return Generated;
  394. }
  395. }
  396. }
  397. }
  398. catch { return null; }
  399. }
  400. return null;
  401. }
  402. catch
  403. {
  404. return null;
  405. }
  406. }
  407.  
  408.  
  409.  
  410. public static Habbo GetHabboByUsername(String UserName)
  411. {
  412. try
  413. {
  414. using (IQueryAdapter dbClient = GetDatabaseManager().GetQueryReactor())
  415. {
  416. dbClient.SetQuery("SELECT `id` FROM `users` WHERE `username` = @user LIMIT 1");
  417. dbClient.AddParameter("user", UserName);
  418. int id = dbClient.getInteger();
  419. if (id > 0)
  420. return GetHabboById(Convert.ToInt32(id));
  421. }
  422. return null;
  423. }
  424. catch { return null; }
  425. }
  426.  
  427.  
  428.  
  429. public static void PerformShutDown()
  430. {
  431. Console.Clear();
  432. log.Info("Server shutting down...");
  433. Console.Title = "HABBO EMULATOR: SHUTTING DOWN!";
  434.  
  435. HabboEnvironment.GetGame().GetClientManager().SendMessage(new BroadcastMessageAlertComposer(HabboEnvironment.GetGame().GetLanguageLocale().TryGetValue("shutdown_alert")));
  436. GetGame().StopGameLoop();
  437. Thread.Sleep(2500);
  438. GetConnectionManager().Destroy();//Stop listening.
  439. GetGame().GetPacketManager().UnregisterAll();//Unregister the packets.
  440. GetGame().GetPacketManager().WaitForAllToComplete();
  441. GetGame().GetClientManager().CloseAll();//Close all connections
  442. GetGame().GetRoomManager().Dispose();//Stop the game loop.
  443.  
  444.  
  445. using (IQueryAdapter dbClient = _manager.GetQueryReactor())
  446. {
  447. dbClient.RunQuery("TRUNCATE `catalog_marketplace_data`");
  448. dbClient.RunQuery("TRUNCATE `user_auth_ticket`");
  449. dbClient.RunQuery("UPDATE `users` SET online = '0'");
  450. dbClient.RunQuery("UPDATE `rooms` SET `users_now` = '0' WHERE `users_now` > '0'");
  451. dbClient.RunQuery("UPDATE `server_status` SET `users_online` = '0', `loaded_rooms` = '0'");
  452. }
  453.  
  454. log.Info("Habbo Emulator has successfully shutdown.");
  455.  
  456. Thread.Sleep(1000);
  457. Environment.Exit(0);
  458. }
  459.  
  460. internal static bool ShutdownStarted { get; set; }
  461.  
  462. public static ConfigurationData GetConfig()
  463. {
  464. return _configuration;
  465. }
  466.  
  467. public static ConfigData GetDBConfig()
  468. {
  469. return ConfigData;
  470. }
  471.  
  472. public static Encoding GetDefaultEncoding()
  473. {
  474. return _defaultEncoding;
  475. }
  476.  
  477. public static ConnectionHandling GetConnectionManager()
  478. {
  479. return _connectionManager;
  480. }
  481.  
  482.  
  483. public static Staff GetStaff()
  484. {
  485. return _staff;
  486. }
  487. public static Game GetGame()
  488. {
  489. return _game;
  490. }
  491.  
  492. public static LanguageManager GetLanguageManager()
  493. {
  494. return _languageManager;
  495. }
  496. public static DatabaseManager GetDatabaseManager()
  497. {
  498. return _manager;
  499. }
  500.  
  501. public static ICollection<Habbo> GetUsersCached()
  502. {
  503. return _usersCached.Values;
  504. }
  505.  
  506. public static bool RemoveFromCache(int Id, out Habbo Data)
  507. {
  508. return _usersCached.TryRemove(Id, out Data);
  509. }
  510. }
  511. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement