Advertisement
Guest User

Untitled

a guest
Jul 17th, 2019
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 10.02 KB | None | 0 0
  1. /*
  2.  * This file is part of the OpenNos Emulator Project. See AUTHORS file for Copyright information
  3.  *
  4.  * This program is free software; you can redistribute it and/or modify
  5.  * it under the terms of the GNU General Public License as published by
  6.  * the Free Software Foundation; either version 2 of the License, or
  7.  * (at your option) any later version.
  8.  *
  9.  * This program is distributed in the hope that it will be useful,
  10.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.  * GNU General Public License for more details.
  13.  */
  14.  
  15. using log4net;
  16. using OpenNos.ChatLog.Networking;
  17. using OpenNos.Core;
  18. using OpenNos.DAL;
  19. using OpenNos.DAL.EF.Helpers;
  20. using OpenNos.Data;
  21. using System.Threading.Tasks;
  22. using OpenNos.GameObject;
  23. using OpenNos.Handler;
  24. using OpenNos.Master.Library.Client;
  25. using OpenNos.Master.Library.Data;
  26. using System;
  27. using System.Configuration;
  28. using System.Diagnostics;
  29. using System.Globalization;
  30. using System.Linq;
  31. using System.Net;
  32. using System.Net.Sockets;
  33. using System.Reflection;
  34. using System.Runtime.InteropServices;
  35. using System.Text;
  36. using System.Threading;
  37. using OpenNos.GameObject.Networking;
  38.  
  39. namespace OpenNos.World
  40. {
  41.     public static class Program
  42.     {
  43.         #region Members
  44.  
  45.         private static readonly ManualResetEvent _run = new ManualResetEvent(true);
  46.  
  47.         private static EventHandler _exitHandler;
  48.  
  49.         private static bool _isDebug;
  50.  
  51.         private static byte isGlacernon;
  52.  
  53.         private static bool _ignoreTelemetry;
  54.  
  55.         public static int _port;
  56.  
  57.         #endregion
  58.  
  59.         #region Delegates
  60.  
  61.         public delegate bool EventHandler(CtrlType sig);
  62.  
  63.         #endregion
  64.  
  65.         #region Enums
  66.  
  67.         public enum CtrlType
  68.         {
  69.             CTRL_C_EVENT = 0,
  70.             CTRL_BREAK_EVENT = 1,
  71.             CTRL_CLOSE_EVENT = 2,
  72.             CTRL_LOGOFF_EVENT = 5,
  73.             CTRL_SHUTDOWN_EVENT = 6
  74.         }
  75.  
  76.         #endregion
  77.  
  78.         #region Methods
  79.  
  80.         public static void Main(string[] args)
  81.         {
  82. #if DEBUG
  83.             _isDebug = true;
  84.             Thread.Sleep(1000);
  85. #endif
  86.             bug:
  87.  
  88.             bool timeDone = false;
  89.             Console.WriteLine("Is Glacernon? ( 0 / 1 ): ");
  90.  
  91.             if (isGlacernon != 0)
  92.             {
  93.                 try
  94.                 {
  95.                     isGlacernon = Convert.ToByte(Console.ReadLine());
  96.                 }
  97.                 catch (Exception e)
  98.                 {
  99.                     goto bug;
  100.                 }
  101.             }
  102.             CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-US");
  103.             Console.Title = $"OpenNos World Server{(_isDebug ? " Development Environment" : string.Empty)}";
  104.             bool ignoreStartupMessages = false;
  105.             bug2:
  106.             isGlacernon = 0;
  107.             if (isGlacernon == 0 || timeDone == true)
  108.             {
  109.                 _port = Convert.ToInt32(ConfigurationManager.AppSettings["WorldPort"]);
  110.             }
  111.             else if (isGlacernon == 1)
  112.             {
  113.                 _port = 5001;
  114.             }
  115.             int portArgIndex = Array.FindIndex(args, s => s == "--port");
  116.             if (portArgIndex != -1
  117.                 && args.Length >= portArgIndex + 1
  118.                 && int.TryParse(args[portArgIndex + 1], out _port))
  119.             {
  120.                 Console.WriteLine("Port override: " + _port);
  121.             }
  122.             foreach (string arg in args)
  123.             {
  124.                 switch (arg)
  125.                 {
  126.                     case "--nomsg":
  127.                         ignoreStartupMessages = true;
  128.                         break;
  129.  
  130.                     case "--notelemetry":
  131.                         _ignoreTelemetry = true;
  132.                         break;
  133.                 }
  134.             }
  135.  
  136.             // initialize Logger
  137.             Logger.InitializeLogger(LogManager.GetLogger(typeof(Program)));
  138.  
  139.             if (!ignoreStartupMessages)
  140.             {
  141.                 Assembly assembly = Assembly.GetExecutingAssembly();
  142.                 FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
  143.                 string text = $"WORLD SERVER v{fileVersionInfo.ProductVersion}dev - PORT : {_port} by OpenNos Team";
  144.                 int offset = (Console.WindowWidth / 2) + (text.Length / 2);
  145.                 string separator = new string('=', Console.WindowWidth);
  146.                 Console.WriteLine(separator + string.Format("{0," + offset + "}\n", text) + separator);
  147.             }
  148.  
  149.             // initialize api
  150.             string authKey = ConfigurationManager.AppSettings["MasterAuthKey"];
  151.             if (CommunicationServiceClient.Instance.Authenticate(authKey))
  152.             {
  153.                 Logger.Info(Language.Instance.GetMessageFromKey("API_INITIALIZED"));
  154.             }
  155.  
  156.             // initialize DB
  157.             if (DataAccessHelper.Initialize())
  158.             {
  159.                 // initialilize maps
  160.                 ServerManager.Instance.Initialize();
  161.             }
  162.             else
  163.             {
  164.                 Console.ReadKey();
  165.                 return;
  166.             }
  167.  
  168.             // TODO: initialize ClientLinkManager initialize PacketSerialization
  169.             PacketFactory.Initialize<WalkPacket>();
  170.  
  171.             try
  172.             {
  173.                 _exitHandler += ExitHandler;
  174.                 AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
  175.                 NativeMethods.SetConsoleCtrlHandler(_exitHandler, true);
  176.             }
  177.             catch (Exception ex)
  178.             {
  179.                 Logger.Error("General Error", ex);
  180.             }
  181.             NetworkManager<WorldCryptography> networkManager = null;
  182.             string ipAddress = ConfigurationManager.AppSettings["IPAddress"];
  183.             portloop:
  184.             try
  185.             {
  186.                 networkManager = new NetworkManager<WorldCryptography>(ipAddress, _port, typeof(CommandPacketHandler), typeof(LoginCryptography), true);
  187.             }
  188.             catch (SocketException ex)
  189.             {
  190.                 if (ex.ErrorCode == 10048)
  191.                 {
  192.                     _port++;
  193.                     Logger.Info("Port already in use! Incrementing...");
  194.                     goto portloop;
  195.                 }
  196.                 Logger.Error("General Error", ex);
  197.                 Environment.Exit(ex.ErrorCode);
  198.             }
  199.  
  200.             ServerManager.Instance.ServerGroup = ConfigurationManager.AppSettings["ServerGroup"];
  201.             const int sessionLimit = 100; // Needs workaround
  202.             int? newChannelId = CommunicationServiceClient.Instance.RegisterWorldServer(new SerializableWorldServer(ServerManager.Instance.WorldId, ipAddress, _port, sessionLimit, ServerManager.Instance.ServerGroup));
  203.             if (newChannelId.HasValue)
  204.             {
  205.                 ServerManager.Instance.ChannelId = newChannelId.Value;
  206.                 MailServiceClient.Instance.Authenticate(authKey, ServerManager.Instance.WorldId);
  207.                 ConfigurationServiceClient.Instance.Authenticate(authKey, ServerManager.Instance.WorldId);
  208.                 ServerManager.Instance.Configuration = ConfigurationServiceClient.Instance.GetConfigurationObject();
  209.                 if (ServerManager.Instance.Configuration.UseChatLogService)
  210.                 {
  211.                     ChatLogServiceClient.Instance.Authenticate(ConfigurationManager.AppSettings["ChatLogKey"]);
  212.                 }
  213.                 ServerManager.Instance.MallApi = new GameObject.Helpers.MallAPIHelper(ServerManager.Instance.Configuration.MallBaseURL);
  214.             }
  215.             else
  216.             {
  217.                 Logger.Error("Could not retrieve ChannelId from Web API.");
  218.                 Console.ReadKey();
  219.             }
  220.         }
  221.  
  222.         private static bool ExitHandler(CtrlType sig)
  223.         {
  224.             CommunicationServiceClient.Instance.UnregisterWorldServer(ServerManager.Instance.WorldId);
  225.             ServerManager.Shout(string.Format(Language.Instance.GetMessageFromKey("SHUTDOWN_SEC"), 5));
  226.             ServerManager.Instance.SaveAll();
  227.             Thread.Sleep(5000);
  228.             return false;
  229.         }
  230.  
  231.         private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
  232.         {
  233.             ServerManager.Instance.InShutdown = true;
  234.             Logger.Error((Exception)e.ExceptionObject);
  235.  
  236.             string pathd = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  237.             using (System.IO.StreamWriter writer = System.IO.File.AppendText(pathd + @"\CRASHLOG.txt"))
  238.             {
  239.                 writer.WriteLine((Exception)e.ExceptionObject);
  240.                 writer.Close();
  241.             }
  242.  
  243.             try
  244.             {
  245.                 if (!_ignoreTelemetry)
  246.                 {
  247.                    
  248.                 }
  249.             }
  250.             catch (Exception ex)
  251.             {
  252.                 Logger.Error(ex);
  253.                 string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
  254.                 using (System.IO.StreamWriter writer = System.IO.File.AppendText(path + @"\CRASHLOG.txt"))
  255.                 {
  256.                     writer.WriteLine(ex);
  257.                 }
  258.             }
  259.  
  260.             Logger.Debug("Server crashed! Rebooting gracefully...");
  261.  
  262.            
  263.             CommunicationServiceClient.Instance.UnregisterWorldServer(ServerManager.Instance.WorldId);
  264.             ServerManager.Shout(string.Format(Language.Instance.GetMessageFromKey("SHUTDOWN_SEC"), 5));
  265.             ServerManager.Instance.SaveAll();
  266.             isGlacernon = 0;
  267.             Process.Start("OpenNos.World.exe", $"--nomsg --port 1337");
  268.             Environment.Exit(1);
  269.         }
  270.  
  271.         #endregion
  272.  
  273.         #region Classes
  274.  
  275.         public static class NativeMethods
  276.         {
  277.             #region Methods
  278.  
  279.             [DllImport("Kernel32")]
  280.             internal static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
  281.  
  282.             #endregion
  283.         }
  284.  
  285.         #endregion
  286.     }
  287. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement