Example #1
0
        public NetOutgoingMessage ConvertToOutgoingMessage <TPackage>(TPackage package)
            where TPackage : class
        {
            var id = container.GetIdFromType(typeof(TPackage));
            var om = Host.CreateMessage();

            om.Write(id);

            var packageInfo = container.GetPackageInfoFromByte(id);

            if (packageInfo == null)
            {
                string errorMsg = $"The package {typeof(TPackage)} was not registered";
                Out.Error(errorMsg);
                throw new Exception(errorMsg);
            }
            try
            {
                packageInfo.Serializer.Encode(package, om);
            }
            catch (Exception ex)
            {
                Out.Error($"Unable to encode {typeof(TPackage)} with {packageInfo.Serializer.GetType()}. {ex.Message}");
                throw ex;
            }
            return(om);
        }
Example #2
0
        public void Initialize(string ip, int port)
        {
            DateTime startTime = DateTime.Now;

            Out.Info("Initializing server...");
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
                socket.Listen(100);
                Ip   = ip;
                Port = port;
            }
            catch (SocketException e)
            {
                Out.Error(e.Message);
                Dispose();
                return;
            }
            Clients = new Dictionary <Socket, IBaseClient>();
            Servers = new Dictionary <int, WorldServer>();
            Out.Info("Loading Config...");
            if (!File.Exists("config.txt"))
            {
                Out.Error("Can't load 'config.txt' !");
                Dispose();
                return;
            }
            Config = ConfigManager.GetConfig();
            if (Config.ContainsKey("Debug") && Config["Debug"] == "true")
            {
                Out.DebugMode = true;
            }
            if (Config.ContainsKey("Maintenance") && Config["Maintenance"] == "true")
            {
                onMaintenance = true;
            }
            ProtocolVersion = int.Parse(Config["ProtocolVersion"]);
            if (!ConfigManager.CheckConfig(Config))
            {
                Dispose();
                return;
            }
            Out.Info("Initializing database...");
            DatabaseManager.Initialize(Config["Database_Host"], Config["Database_User"], Config["Database_Password"], Config["Database_Auth"]);
            if (Config.ContainsKey("AuthServer_Name"))
            {
                Console.Title = Config["AuthServer_Name"];
            }
            AccountManager.Initialize(DatabaseManager.connection);
            ServersManager.Initialize(DatabaseManager.connection);
            LoadData();

            Out.Info($"Server started successfuly (Elapsed time : {DateTime.Now.Subtract(startTime).TotalMilliseconds.ToString("### ###")} ms)");
            socket.BeginAccept(AcceptCallBack, null);
            Out.Debug("Waiting for clients...");
        }
Example #3
0
 public void Connect <TConnectionApprovalMsg>(string ipOrHost, int port, TConnectionApprovalMsg msg)
     where TConnectionApprovalMsg : class
 {
     try
     {
         Host.Connect(new IPEndPoint(NetUtility.Resolve(ipOrHost), port), ConvertToOutgoingMessage(msg));
     }
     catch (Exception ex)
     {
         Out.Error($"Unable to connect to {ipOrHost}:{port}. {ex.Message}");
         throw ex;
     }
 }
Example #4
0
        private void ReceiveCallBack(IAsyncResult result)
        {
            try
            {
                int    size   = socket.EndReceive(result);
                byte[] buffer = new byte[size];
                Array.Copy(_buffer, buffer, size);

                NewPacket(buffer);
            }
            catch (Exception e)
            {
                Out.Error($"InterServer\t>Error while handling a packet : {e.Message}");
            }
        }
Example #5
0
        public void Start(NetDeliveryMethod defaultDeliveryMethod, int defaultChannel)

        {
            DeliveryMethod = defaultDeliveryMethod;
            Channel        = defaultChannel;
            try
            {
                Host.Start();
            }
            catch (Exception ex)
            {
                Out.Error($"Unable to connect to start network server. {ex.Message}");
                throw ex;
            }
        }
Example #6
0
 public static void Initialize(string host, string user, string password, string database)
 {
     try
     {
         Out.Debug($"Connecting to:\n\t\tHOST = {host}\n\t\tUSER = {user}\n\t\tPWD = {password}\n\t\tDATABASE = {database}");
         string m_mysql = string.Format($"server={host};database={database};uid={user};pwd={password};Allow User Variables=True");
         connection = new MySqlConnection(m_mysql);
         connection.Open();
         Out.Debug($"Connection to database {database} openned");
     }
     catch (MySqlException e)
     {
         Out.Error(e.ToString());
     }
 }
Example #7
0
        static void HandleCommand(string[] cmd)
        {
            switch (cmd[0])
            {
            case "rl":
                ServersManager.Initialize(DatabaseManager.connection);
                auth.Servers = ServersManager.GetServers();
                foreach (AuthClient client in auth.Clients.Values)
                {
                    foreach (Common.Database.Modeles.Auth.WorldServer s in auth.Servers.Values)
                    {
                        client.Send(new ServerStatusUpdateMessage(new Protocol.Types.GameServerInformations(s.ServerId, s.Status, s.Completion, true, 14)));
                    }
                }
                break;

            case "test":
                Out.WriteLine("TEST !!!", ConsoleColor.Yellow);
                break;

            case "exit":
                auth.Dispose();
                Out.WriteLine("Auth server stopped successfully", ConsoleColor.Cyan);
                break;

            case "start":
                if (auth.Clients != null)
                {
                    Out.Error("Server already started");
                    break;
                }
                auth.Initialize(ip, port);
                break;

            case "world":
                if (cmd.Length > 1 && cmd[1] == "start")
                {
                    world = new WorldServer();
                }
                break;

            default:
                Out.WriteLine($"Unknown command {cmd[0]}", ConsoleColor.Red);
                break;
            }
        }
Example #8
0
 public void AcceptCallBack(IAsyncResult result)
 {
     try
     {
         WorldClient _newClient = new WorldClient(_world.EndAccept(result), this);
         Out.Debug($"New socket [{_newClient.socket.RemoteEndPoint}]");
         Clients.Add(_newClient);
     }
     catch (Exception e)
     {
         if (Clients != null)
         {
             Out.Error(e.Message);
         }
     }
     _world.BeginAccept(AcceptCallBack, null);
 }
Example #9
0
        public static List <string> GetBlockedIps()
        {
            List <string> ips = new List <string>();
            var           Ips = database.Query("SELECT distinct IpAddress FROM ipblock", null);

            foreach (var ip in Ips)
            {
                try
                {
                    ips.Add(ip.IpAddress);
                }
                catch (Exception e)
                {
                    Out.Error($"Couldn't add {ip} to BlockedIps");
                }
            }
            return(ips);
        }
Example #10
0
 public void Initialize()
 {
     try
     {
         //TODO HANDLE WORLD CONNECTION
         Send(new ProtocolRequired(1375, 1375));
         Send(new HelloGameMessage());
         Send(new BasicTimeMessage(1, 0));
         Send(new AccountCapabilitiesMessage(1, false, 16383, 4095)); //-> Binary (each bit correspond to one class)
         Send(new TrustStatusMessage(true));
         socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveCallBack, socket);
     }
     catch (Exception e)
     {
         Out.Debug($"User {Ip} disconnected because of an error");
         Out.Error(e.Message);
         Disconnect();
     }
 }
Example #11
0
        public TPackage ReadAs <TPackage>(NetIncomingMessage im)
        {
            var packageInfo = container.GetPackageInfoFromByte(im.ReadByte());

            if (packageInfo == null)
            {
                string errorMsg = $"The package {typeof(TPackage)} was not registered";
                Out.Error(errorMsg);
                throw new Exception(errorMsg);
            }
            try
            {
                return((TPackage)packageInfo.Serializer.Decode(im, packageInfo.Type));
            }
            catch (Exception ex)
            {
                Out.Error($"Unable to decode {typeof(TPackage)} with {packageInfo.Serializer.GetType()}. {ex.Message}");
                throw ex;
            }
        }
Example #12
0
        private void LoadEndpoints()
        {
            IList <Endpoint> endpoints = new List <Endpoint>();

            try
            {
                endpoints = YamlParser.FromFile(_arguments.Data);
            }
            catch (FileNotFoundException)
            {
                Out.Warn("File '" + _arguments.Data + "' couldn't be found. Ignoring...");
            }
            catch (YamlException ex)
            {
                Out.Error(ex.Message);
                throw new EndpointParsingException("Could not parse endpoints due to YAML errors.", ex);
            }

            _endpointDb.Delete();
            _endpointDb.Insert(endpoints);
        }
Example #13
0
        public void AcceptCallBack(IAsyncResult result)
        {
            try
            {
                AuthClient _newClient = new AuthClient(socket.EndAccept(result), this)
                {
                    Ticket = Tools.RandomString(32, false)
                };
                Out.Debug($"New socket [{_newClient.socket.RemoteEndPoint}]");
                //_newClient.Initialize();
                Clients.Add(_newClient.socket, _newClient);

                socket.BeginAccept(AcceptCallBack, null);
            }catch (Exception e)
            {
                if (Clients != null)
                {
                    Out.Error(e.Message);
                }
            }
        }
Example #14
0
        private static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.White;
            Console.Title           = "ENVIUM DEDICATED SERVER";

            Out.MsgC(ConsoleColor.Green, "Initializing the server ...");

            _buffer        = new byte[4096];
            _boundEndPoint = new IPEndPoint(IPAddress.Any, 644);

            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            try {
                _socket.Bind(_boundEndPoint);
            } catch (SocketException ex) {
                Out.Error("Network: Cannot bound at address {0}: {1}", _boundEndPoint, ex.Message);
                Console.ReadLine();
                return;
            }

            Out.Msg("Network: Socket bounded at {0}", _socket.LocalEndPoint as IPEndPoint);

            FrameSnapshotManager = new FrameSnapshotManager();
            ServerPluginHandler  = new ServerPlugin();
            Server = new GameServer(_socket)
            {
                State        = EServerState.Loading,
                TickInterval = GetTickInterval()
            };

            Networking.Initialize();

            new Thread(GameTick)
            {
                IsBackground = true
            }.Start();
            Server.State = EServerState.Active;
            Out.Msg("Done loading.");

            var clientEp = (EndPoint) new IPEndPoint(IPAddress.Any, 0);

            _socket.BeginReceiveFrom(_buffer, 0, _buffer.Length, SocketFlags.None, ref clientEp, DoReceiveFrom, clientEp);

            string read;

            while ((read = Console.ReadLine()) != "exit")
            {
                if (read == "help")
                {
                    continue;
                }

                if (read == "curtime")
                {
                    var time = Utils.SysTime();
                    Console.WriteLine("Current server time: {0}", time);
                    continue;
                }

                Console.WriteLine("Unknown command \"{0}\".", read);
            }
        }
Example #15
0
        public static bool AddCertificateToStore(uint httpsPort)
        {
            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            try {
                store.Open(OpenFlags.ReadWrite);
            } catch {
                Out.Error(AuthenticationNeeded);
                return(false);
            }

            var cert = new X509Certificate2(
                CreateSelfSignCertificatePfx(X509SubjectName, DateTime.Now.AddDays(-1), DateTime.Now.AddYears(1), CertificatePassword),
                CertificatePassword,
                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);

            cert.FriendlyName = "Stubby4net Certificate";

            var existingCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.Subject, false);

            if (existingCerts.Count == 0)
            {
                store.Add(cert);
            }
            else
            {
                cert = existingCerts[0];
            }
            store.Close();

            var netshArgs = String.Format(NetshArgs, httpsPort, cert.GetCertHashString(), "{" + Stubby.Guid + "}");
            var netsh     = new ProcessStartInfo("netsh", netshArgs)
            {
                Verb            = "runas",
                CreateNoWindow  = true,
                WindowStyle     = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            };

            try {
                var process = Process.Start(netsh);
                process.WaitForExit();
                Console.Out.WriteLine(process.ExitCode);
                if (process.ExitCode == 0)
                {
                    return(true);
                }
            } catch {
            }

            var httpcfgArgs = String.Format(HttpcfgArgs, httpsPort, cert.GetCertHashString());
            var httpcfg     = new ProcessStartInfo("httpcfg", httpcfgArgs)
            {
                Verb            = "runas",
                CreateNoWindow  = true,
                WindowStyle     = ProcessWindowStyle.Hidden,
                UseShellExecute = true
            };

            try {
                var process = Process.Start(httpcfg);
                process.WaitForExit();
                return(process.ExitCode == 0);
            } catch {
                return(false);
            }
        }
Example #16
0
 public void Errorln(string s) => Out.Error(s, true);
Example #17
0
        public static void HandleCharacterCreation(BigEndianReader reader, WorldClient client, WorldServer server)
        {
            try
            {
                CharacterCreationRequestMessage message = new CharacterCreationRequestMessage();
                message.Unpack(reader);
                client.Send(new CharacterCreationResultMessage(0));
                Thread.Sleep(1000);
                int   y      = 0;
                int[] colors = new int[5];
                foreach (int x in message.colors)
                {
                    if (y < 5 && x != -1)
                    {
                        colors[y] = (y + 1 & 255) << 24 | x & 16777215;
                        //((nb & 255) << 24 | color & 16777215)
                        y++;
                    }
                    else
                    {
                        break;
                    }
                }

                for (int x = 0; x < colors.Length; x++)
                {
                    Out.Debug(colors[x].ToString(), "Colors");
                }
                //x => x.Key << 24 | x.Value.ToArgb() & 0xFFFFFF

                int style = message.breed * 10;
                if (message.sex)
                {
                    style++;
                }

                Char = new CharacterBaseInformations(
                    1,
                    200,
                    message.name,
                    new EntityLook(1, new short[] { (short)style }, colors, new short[] { 125 }, new SubEntity[] { }),
                    message.breed,
                    message.sex);

                IEnumerable <CharacterBaseInformations> chars = new List <CharacterBaseInformations>()
                {
                    Char
                };

                client.Send(new CharactersListMessage(false, chars));
            }
            catch (Exception e)
            {
                Out.Error(e.Message);
            }
            //var_character =
            //{
            //    Level = 1,
            //    Name = message.name,
            //    Breed = message.breed,
            //    Sex = message.sex,
            //    EntityLook = EntityManager.Instance.BuildEntityLook(message.breed, message.sex, message.colors.ToList()),
            //    MapId = BreedManager.Instance.GetStartMap(message.breed),
            //    CellId = BreedManager.Instance.GetStartCell(message.breed),
            //    Direction = BreedManager.Instance.GetStartDirection(message.breed),
            //    SpellsPoints = 1
            //};
        }
Example #18
0
 public void Error(string s, bool lineBreak = false) => Out.Error(s, lineBreak);