Exemplo n.º 1
0
        private void OnApproved(Message packet)
        {
            try
            {
                using (var approval = Approval.Deserialize(packet.read))
                {
                    ConsoleSystem.LogWarning(
                        $"[VirtualServer]: Подключились к: {(approval.official ? "[Oficial] " : "")}" +
                        approval.hostname);

                    if (_quitAfterConnected)
                    {
                        BaseClient.Disconnect("", true);
                        Framework.Quit();
                    }

                    BaseClient.Connection.encryptionLevel = approval.encryption;
                    BaseClient.Connection.decryptIncoming = true;

                    if (BaseClient.write.Start())
                    {
                        BaseClient.write.PacketId(Message.Type.Ready);
                        BaseClient.write.Send(new SendInfo(BaseClient.Connection));
                    }

                    packet.connection.encryptOutgoing = true;
                }
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[VirtualServer]: Исключение в OnApproved(): " + ex.Message);
            }
        }
Exemplo n.º 2
0
 public static void Run(uint uid, ERPCMethodType method, Message message)
 {
     if (ListRPCMethods.TryGetValue(method, out var methods))
     {
         if (BaseNetworkable.ListNetworkables.TryGetValue(uid, out var networkable))
         {
             var type      = networkable.GetType();
             var rpcmethod = methods.FirstOrDefault(p => p.Key == type || p.Key.IsSubclassOf(type)).Value;
             if (rpcmethod != null)
             {
                 try
                 {
                     using (new TimeDebugger($"{method}", 0.001f))
                     {
                         rpcmethod.Invoke(networkable, message);
                     }
                 }
                 catch (Exception ex)
                 {
                     ConsoleSystem.LogError("[Data.Base.Network Run] Exception: " + ex.Message + System.Environment.NewLine + ex.StackTrace);
                 }
             }
         }
         else
         {
             ConsoleSystem.LogWarning("[Data.Base.Network Run] Dont have networkable uid: " + uid);
         }
     }
     else
     {
         ConsoleSystem.LogWarning("[Data.Base.Network Run] Dont have released method: " + method + " from " + BaseNetworkable.ListNetworkables?[uid]);
     }
 }
Exemplo n.º 3
0
        public void Connect(string ip, int port)
        {
            try
            {
                ConsoleSystem.Log($"[VirtualServer]: Подключаемся к игровому серверу [{ip}:{port}]");
                if (BaseClient.Connect(ip, port))
                {
                    if (BaseClient.write.Start())
                    {
                        BaseClient.write.UInt8(19);
                        BaseClient.write.Send(new SendInfo(BaseClient.Connection));
                    }

                    ConsoleSystem.Log("[VirtualServer]: Инициализация подключения успешно завершена!");
                }
                else
                {
                    ConsoleSystem.LogError("[VirtualServer]: В попытке подключения отказано!");
                }
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[VirtualServer]: Исключение в OnNewConnection(): " + ex.Message);
            }
        }
Exemplo n.º 4
0
        public static void Initialize()
        {
            Type[] assemblyTypes = Assembly.GetExecutingAssembly().GetTypes()
                                   .Where(type => typeof(BaseNetworkable).IsAssignableFrom(type)).ToArray();

            for (int i = 0; i < assemblyTypes.Length; ++i)
            {
                var          type        = assemblyTypes[i];
                MethodInfo[] typeMethods = type.GetMethods(BindingFlags.CreateInstance | BindingFlags.Instance |
                                                           BindingFlags.NonPublic | BindingFlags.Static |
                                                           BindingFlags.Public);

                for (int j = 0; j < typeMethods.Length; ++j)
                {
                    var      method           = typeMethods[j];
                    object[] customAttributes = method.GetCustomAttributes(typeof(RPCMethodAttribute), true);

                    if (customAttributes.Length >= 1)
                    {
                        var methodName = ((RPCMethodAttribute)customAttributes[0]).MethodName;
                        var parameters = method.GetParameters();
                        if (parameters.Length != 2 || parameters[0].ParameterType != typeof(ERPCNetworkType) ||
                            parameters[1].ParameterType != typeof(Message))
                        {
                            ConsoleSystem.LogError($"[RPCManager]: Invalid Parameters for {type.Name}.{method.Name} " +
                                                   $"({string.Join(", ",parameters.Select(p=>p.ParameterType.Name).ToArray())})\n" +
                                                   $"Should be ({nameof(ERPCNetworkType)}, {nameof(Message)})");
                            continue;
                        }
                        RPCMethods[methodName] = new FastMethodInfo(method);
                    }
                }
            }
            ConsoleSystem.Log($"Loaded <{RPCMethods.Count}> RPCMethods!");
        }
Exemplo n.º 5
0
        public static UserInformation ParsePacket(Message message)
        {
            try
            {
                message.read.Position = 1;
                var userInformation = new UserInformation();
                userInformation.PacketProtocol     = message.read.UInt8();
                userInformation.SteamID            = message.read.UInt64();
                userInformation.ConnectionProtocol = message.read.UInt32();
                userInformation.OS         = message.read.String();
                userInformation.Username   = message.read.String();
                userInformation.Branch     = message.read.String();
                userInformation.SteamToken = message.read.BytesWithSize();

                message.peer.read.Position = 0L;
                using (BinaryReader br = new BinaryReader(message.peer.read))
                    userInformation.PacketBuffer = br.ReadBytes((int)message.peer.read.Length);


                return(userInformation);
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("Error to Struct.UserInformation.ParsePacket(): " + ex.Message);
            }
            return(default(UserInformation));
        }
Exemplo n.º 6
0
        private void InitializationNetwork()
        {
            try
            {
                ConsoleSystem.Log("[VirtualServer]: Служба Network запускается...");
                BaseServer = new RakNet.Server
                {
                    ip                      = "0.0.0.0",
                    port                    = 28001,
                    OnRakNetPacket          = OUT_OnRakNetMessage,
                    onMessage               = OUT_OnNetworkMessage,
                    OnNewConnectionCallback = OnNewConnection,
                    onDisconnected          = OUT_OnDisconnected
                };

                BaseClient = new RakNet.Client()
                {
                    onMessage      = IN_OnNetworkMessage,
                    OnRakNetPacket = IN_OnRakNetMessage,
                    onDisconnected = IN_OnDisconnected
                };
                BaseServer.cryptography = new NetworkCryptographyServer();
                BaseClient.cryptography = new NetworkCryptographyServer();

                BaseServer.Start();
                ConsoleSystem.Log("[VirtualServer]: Служба Network успешно запущена!");
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[VirtualServer]: Исключение в InitializationNetwork(): " + ex.Message);
            }
        }
Exemplo n.º 7
0
        private void OnApproved(Message packet)
        {
            try
            {
                using (Approval approval = Approval.Deserialize(packet.read))
                {
                    ConsoleSystem.LogWarning($"[VirtualServer]: Вы подключились к: {(approval.official ? "[Oficial] " : "")}" + approval.hostname);

                    BaseClient.Connection.encryptionLevel = approval.encryption;
                    BaseClient.Connection.decryptIncoming = true;

                    if (BaseServer.write.Start())
                    {
                        BaseServer.write.PacketID(Message.Type.Approved);
                        Approval.Serialize(BaseServer.write, approval);
                        BaseServer.Send();
                    }
                    BaseServer.SetEncryptionLevel(approval.encryption);
                }
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[VirtualServer]: Исключение в OnApproved(): " + ex.Message);
            }
        }
Exemplo n.º 8
0
        private static void HandleClientUpdate(ClientStatusUpdate <Client> clientStatus)
        {
            Client     clientObject = clientStatus.ClientObject;
            Connection connection   = GetConnection(clientObject);

            if (connection == null)
            {
                ConsoleSystem.LogError(string.Concat("EAC status update for invalid client: ", clientObject.ClientID));
            }
            else if (!ShouldIgnore(connection))
            {
                if (clientStatus.RequiresKick)
                {
                }
                else if (clientStatus.Status == ClientStatus.ClientAuthenticatedLocal)
                {
                    OnAuthenticatedLocal(connection);
                    easyAntiCheat.SetClientNetworkState(clientObject, false);
                }
                else if (clientStatus.Status == ClientStatus.ClientAuthenticatedRemote)
                {
                    OnAuthenticatedRemote(connection);
                }
                OnAuthenticatedLocal(connection);
                easyAntiCheat.SetClientNetworkState(clientObject, false);
            }
        }
Exemplo n.º 9
0
        private bool OnUnconnectedMessage(int _type, Read _read, uint _ip, int _port)
        {
            try
            {
                if (_type != 255 || _read.UInt8() != 255 || _read.UInt8() != 255 || _read.UInt8() != 255)
                {
                    return(false);
                }

                _read.Position = 0L;
                int unread = _read.unread;

                if (unread > 4096)
                {
                    return(true);
                }

                if (this.m_queryBuffer.Capacity < unread)
                {
                    this.m_queryBuffer.Capacity = unread;
                }

                int size = _read.Read(this.m_queryBuffer.GetBuffer(), 0, unread);
                SteamworksManager.BaseSteamServer.Query.Handle(this.m_queryBuffer.GetBuffer(), size, _ip, (ushort)_port);
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[NetworkManager]: Exception to NetworkManager.OnUnconnectedMessage: " + ex);
            }
            return(true);
        }
Exemplo n.º 10
0
 public uint TakeUID()
 {
     if (this.lastValueGiven > 4294967263u)
     {
         ConsoleSystem.LogError(string.Concat("TakeUID - hitting ceiling limit!", this.lastValueGiven));
     }
     this.lastValueGiven++;
     return(this.lastValueGiven);
 }
Exemplo n.º 11
0
        private static void SendToClient(Client client, byte[] message, int messageLength)
        {
            Connection connection = GetConnection(client);

            if (connection == null)
            {
                ConsoleSystem.LogError(string.Concat("EAC network packet for invalid client: ", client.ClientID));
                return;
            }
        }
Exemplo n.º 12
0
        public static void OnMessageReceived(Message message)
        {
            if (!connection2client.ContainsKey(message.connection))
            {
                ConsoleSystem.LogError(string.Concat("EAC network packet from invalid connection: ", message.connection.userid));
                return;
            }
            Client       client       = GetClient(message.connection);
            MemoryStream memoryStream = message.read.MemoryStreamWithSize();

            easyAntiCheat.PushNetworkMessage(client, memoryStream.GetBuffer(), (int)memoryStream.Length);
        }
Exemplo n.º 13
0
 private void InitializationEAC()
 {
     try
     {
         ConsoleSystem.Log("[VirtualServer]: ParseEncryptionHash запускается...");
         EACServer.DoStartup();
         Timer.SetInterval(EACServer.DoUpdate, 1f);
         ConsoleSystem.Log("[VirtualServer]: ParseEncryptionHash успешно запущен!");
     }
     catch (Exception ex)
     {
         ConsoleSystem.LogError("[VirtualServer]: Исключение в InitializationEAC(): " + ex.Message);
     }
 }
Exemplo n.º 14
0
        public override Vector3 GetHitPosition()
        {
            if (OreBonus == null)
            {
                FindBonus();
            }
            if (OreBonus != null)
            {
                return(OreBonus.Position);
            }

            ConsoleSystem.LogError($"[OreResource] GetHitPosition => OreBonus is null");
            return(base.GetHitPosition());
        }
Exemplo n.º 15
0
        public static void Respawn(ConsoleNetwork.Arg arg)
        {
            var player = arg.Connection.ToPlayer();

            if (player == null)
            {
                ConsoleSystem.LogError("[CMD=respawn] player missing!");
                return;
            }
            if (player.IsAlive)
            {
                return;
            }
            player.Respawn();
        }
Exemplo n.º 16
0
    private static void PrintLogType(LogType logType, string message, bool log = false)
    {
        if (global.logprint)
        {
            switch (logType)
            {
            case LogType.Error:
            {
                ConsoleSystem.LogError(message);
                return;
            }

            case LogType.Warning:
            {
                ConsoleSystem.LogWarning(message);
                return;
            }

            case LogType.Log:
            {
                ConsoleSystem.Log(message);
                return;
            }
            }
        }
        if (log && !ConsoleSystem.LogCallbackWritesToConsole)
        {
            try
            {
                ((logType != LogType.Log ? Console.Error : Console.Out)).WriteLine("Print{0}:{1}", logType, message);
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("PrintLogType Log Exception\n:{0}", exception);
            }
        }
        if (ConsoleSystem.RegisteredLogCallback)
        {
            try
            {
                ConsoleSystem.LogCallback(message, string.Empty, logType);
            }
            catch (Exception exception1)
            {
                Console.Error.WriteLine("PrintLogType Exception\n:{0}", exception1);
            }
        }
    }
Exemplo n.º 17
0
        public void OnNewConnection(Connection connection)
        {
            try
            {
                if (BaseServer.connections.Count <= 1)
                {
                    ConsoleSystem.Log($"[VirtualServer]: Есть новое подключение [{BaseServer.connections[0].ipaddress}]");
                    ConsoleSystem.Log($"[VirtualServer]: Подключаемся к игровому серверу [{Settings.TargetServer_IP}:{Settings.TargetServer_Port}]");
                    if (BaseClient.Connect(Settings.TargetServer_IP, Settings.TargetServer_Port))
                    {
                        BaseClient.Connection.ipaddress = "127.0.0.1";
                        BaseClient.Connection.userid    = Settings.Connection1_SteamID;
                        BaseClient.Connection.ownerid   = Settings.Connection1_SteamID;
                        BaseClient.Connection.username  = Settings.Connection1_Username;
                        BaseClient.Connection.authLevel = 1;
                        EACServer.OnJoinGame(BaseClient.Connection);
                        //EACServer.OnStartLoading(BaseClient.Connection);
                        //EACServer.OnFinishLoading(BaseClient.Connection);

                        BaseServer.connections[0].ipaddress = "127.0.0.1";
                        BaseServer.connections[0].userid    = Settings.Connection2_SteamID;
                        BaseServer.connections[0].ownerid   = Settings.Connection2_SteamID;
                        BaseServer.connections[0].username  = Settings.Connection2_Username;
                        BaseServer.connections[0].authLevel = 1;
                        EACServer.OnJoinGame(BaseServer.connections[0]);
                        //EACServer.OnStartLoading(BaseServer.connections[0]);
                        //EACServer.OnFinishLoading(BaseServer.connections[0]);
                        ConsoleSystem.Log("[VirtualServer]: Инициализация подключения успешно завершена!");
                    }
                    else
                    {
                        ConsoleSystem.LogError($"[VirtualServer]: В попытке подключения отказано!");
                    }
                }
                else
                {
                    ConsoleSystem.LogError($"[VirtualServer]: Уже есть одно подключение, больше подключений не может быть!");
                }
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[VirtualServer]: Исключение в OnNewConnection(): " + ex.Message);
            }
        }
Exemplo n.º 18
0
        protected void HandleMessage()
        {
            this.read.Start(base.Connection);
            byte b = this.read.PacketID();

            if (this.HandleRaknetPacket(b))
            {
                return;
            }
            b -= 140;
            if (b > 22)
            {
                ConsoleSystem.LogWarning("Invalid Packet (higher than " + Message.Type.EAC + ")");
                this.Disconnect(string.Concat(new object[]
                {
                    "Invalid Packet (",
                    b,
                    ") ",
                    this.peer.incomingBytes,
                    "b"
                }), true);
                return;
            }
            Message message = base.StartMessage((Message.Type)b, base.Connection);

            if (this.onMessage != null)
            {
                try
                {
                    using (TimeWarning.New("onMessage", 0.1f))
                    {
                        this.onMessage(message);
                    }
                }
                catch (Exception ex)
                {
                    ConsoleSystem.LogError(ex.Message);
                }
            }
            message.Clear();
            Pool.Free <Message>(ref message);
        }
Exemplo n.º 19
0
        private void InitializationNetwork()
        {
            try
            {
                ConsoleSystem.Log("[VirtualServer]: Служба Network запускается...");

                BaseClient = new RakNet.Client
                {
                    OnMessage      = IN_OnNetworkMessage,
                    onDisconnected = IN_OnDisconnected,
                    Cryptography   = new NetworkCryptographyClient()
                };

                ConsoleSystem.Log("[VirtualServer]: Служба Network успешно запущена!");
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[VirtualServer]: Исключение в InitializationNetwork(): " + ex.Message);
            }
        }
Exemplo n.º 20
0
        private void OnUpdateServerInformation()
        {
            try
            {
                BaseSteamServer.ServerName = Settings.Hostname;

                BaseSteamServer.MaxPlayers = Settings.Maxplayers;
                BaseSteamServer.Passworded = false;
                BaseSteamServer.MapName    = Settings.MapName;

                BaseSteamServer.GameTags = string.Format("mp{0},cp{1},qp{5},v{2}{3},h{4},{6},{7},oxide,modded", new object[]
                {
                    Settings.Maxplayers,
                    0,
                    Settings.GameVersion,
                    string.Empty,
                    "null",
                    0,
                    "stok",
                    "born1"
                });

                BaseSteamServer.SetKey("hash", "null");
                BaseSteamServer.SetKey("world.seed", Settings.MapSeed.ToString());
                BaseSteamServer.SetKey("world.size", Settings.MapSize.ToString());
                BaseSteamServer.SetKey("pve", "False");
                BaseSteamServer.SetKey("headerimage", Settings.ServerImage);
                BaseSteamServer.SetKey("url", Settings.ServerURL);
                BaseSteamServer.SetKey("uptime", ((int)DateTime.Now.Subtract(Framework.StartTimeApplication).TotalSeconds).ToString());
                BaseSteamServer.SetKey("gc_mb", "30");
                BaseSteamServer.SetKey("gc_cl", "30");
                BaseSteamServer.SetKey("fps", Framework.FPSLimit.ToString());
                BaseSteamServer.SetKey("fps_avg", Framework.FPSLimit.ToString());
                BaseSteamServer.SetKey("ent_cnt", "1");
                BaseSteamServer.SetKey("build", BuildingInformation.ApplicationVersion + ", build " + BuildingInformation.ApplicationBuild);
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("[Steamworks] Exception to SteamworksManager.OnUpdateSteamworksInformation(): " + ex);
            }
        }
Exemplo n.º 21
0
        public static IDatabaseObject[] LoadAll(Type _type)
        {
            List <IDatabaseObject> databaseObjects = new List <IDatabaseObject>();

            FileInfo[] files = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "/Database/" + _type.Name).GetFiles();
            for (var i = 0; i < files.Length; ++i)
            {
                try
                {
                    IDatabaseObject databaseObject = Load(_type, uint.Parse(files[i].Name.Substring(0, files[i].Name.IndexOf('.'))));
                    if (databaseObject != null)
                    {
                        databaseObjects.Add(databaseObject);
                    }
                }
                catch (Exception ex)
                {
                    ConsoleSystem.LogError($"[Database.Manager]: Exception from load {_type.Name} file {files[i].Name}: " + ex.Message);
                }
            }
            return(databaseObjects.ToArray());
        }
Exemplo n.º 22
0
        protected void HandleMessage()
        {
            read.Start(Connection);
            var b = read.PacketId();

            if (HandleRaknetPacket(b))
            {
                return;
            }

            b -= 140;
            if (b > 23)
            {
                ConsoleSystem.LogWarning("Invalid Packet (higher than " + Message.Type.EAC + ")");
                Disconnect(string.Concat("Invalid Packet (", b, ") ", _peer.IncomingBytes, "b"), true);
                return;
            }

            var message = StartMessage((Message.Type)b, Connection);

            if (OnMessage != null)
            {
                try
                {
                    using (TimeWarning.New("onMessage", 0.1f))
                    {
                        OnMessage(message);
                    }
                }
                catch (Exception ex)
                {
                    ConsoleSystem.LogError(ex.Message);
                }
            }

            message.Clear();
            Pool.Free(ref message);
        }
Exemplo n.º 23
0
        void OnRPC_PlayerAttack(Message packet)
        {
            BasePlayer player = packet.ToPlayer();

            using (PlayerAttack playerAttack = PlayerAttack.Deserialize(packet.read))
            {
                if (Find(playerAttack.attack.hitID, out BaseEntity hitEntity))
                {
                    if (hitEntity is BaseCombatEntity hitCombatEntity)
                    {
                        Item ActiveItem = player.ActiveItem;
                        if (ActiveItem.Information.IsHoldable())
                        {
                            hitCombatEntity.Hurt(ActiveItem.Information.BaseMelee.Damage);
                        }
                        else
                        {
                            ConsoleSystem.LogError($"[{nameof(OnRPC_PlayerAttack)}][NOT HELD ENTITY] Trying hit from <{ActiveItem.Information.ItemID}>");
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        private Item(ItemInformation _info, uint _amount, ulong _skinid)
        {
            this.UID = BaseNetworkable.TakeUID();
            ListItemsInWorld[this.UID] = this;

            this.Information = _info;

            this.SkinID    = _skinid;
            this.Condition = this.Information.MaxCondition;

            if (_amount <= 0)
            {
                this.Amount = 1;
            }
            else if (_amount > this.Information.MaxStack)
            {
                this.Amount = (uint)this.Information.MaxStack;
            }
            else
            {
                this.Amount = _amount;
            }

            if (this.Information.IsHoldable())
            {
                if (ItemInformation.GetHeldType(_info.HeldType, out Type type) == false)
                {
                    ConsoleSystem.LogError($"[{nameof(Item)}] Unrealized class for <{_info.Shortname}>");
                }
                this.HeldEntity = (BaseHeldEntity)Framework.Bootstraper.AddType(type);
                this.HeldEntity.Spawn(this.Information.HeldEntity.PrefabID);
                this.HeldEntity.SendNetworkUpdate();

                this.HeldEntity.ItemOwner = this;
                this.HeldEntity.Initialization();
            }
        }
Exemplo n.º 25
0
        public static UserInformation ParsePacket(Message message)
        {
            try
            {
                message.read.Position = 1;
                var userInformation = new UserInformation();
                userInformation.PacketProtocol     = message.read.UInt8();
                userInformation.SteamId            = message.read.UInt64();
                userInformation.ConnectionProtocol = message.read.UInt32();
                userInformation.Os         = message.read.String();
                userInformation.Username   = message.read.String();
                userInformation.Branch     = message.read.String();
                userInformation.SteamToken = message.read.BytesWithSize();

                message.peer.read.Position = 0L;
                return(userInformation);
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError("Error to Struct.UserInformation.ParsePacket(): " + ex.Message);
            }

            return(default(UserInformation));
        }
Exemplo n.º 26
0
        public static void Initialize()
        {
            try
            {
                serv.servData.SteamID        = 0L;
                serv.servData.Username       = "******";
                serv.servData.Flags          = UserFlags.admin;
                serv.servData.FirstConnectIP = "127.0.0.1";
                serv.servData.LastConnectIP  = "127.0.0.1";
                Core.RootPath = Directory.GetCurrentDirectory();
                Core.DataPath = Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location));
                Core.SavePath = Path.GetDirectoryName(ServerSaveManager.autoSavePath);
                Core.LogsPath = Path.Combine(Core.SavePath, Core.LogsPath);
                if (!Directory.Exists(Core.DataPath))
                {
                    Directory.CreateDirectory(Core.DataPath);
                }
                if (!Directory.Exists(Core.SavePath))
                {
                    Directory.CreateDirectory(Core.SavePath);
                }
                if (!Directory.Exists(Core.LogsPath))
                {
                    Directory.CreateDirectory(Core.LogsPath);
                }
                Helper.Log("The Server Will Start.", true);
                Helper.Initialize();
                Core.ServerIP = NetCull.config.localIP;
                if ((Core.ServerIP == "127.0.0.1") || (Core.ExternalIP == "127.0.0.1"))
                {
                    throw new ArgumentException(Helper.ServerDenyToStarted);
                }

                if ((NetCull.config.localIP != "") && (NetCull.config.localIP != Core.ServerIP))
                {
                    throw new ArgumentException(Helper.ServerDenyToStarted);
                }

                if (!Core.BetaVersion)
                {
                    Helper.Log("RustExtended Version " + Core.Version.ToString() + " (RELEASE)", true);
                }
                else
                {
                    Helper.LogWarning("RustExtended Version " + Core.Version.ToString() + " (BETA)", true);
                }

                Core.AssemblyVerifed = Helper.AssemblyVerify();
                if (!Core.AssemblyVerifed)
                {
                    throw new ArgumentException(Helper.AssemblyNotVerified);
                }
                Helper.Log("All assembly versions has successfully verified.", true);
                Config.Initialize();
                if (Environment.CommandLine.Contains("-debug"))
                {
                    Core.Debug = true;
                }
                Singleton = new GameObject(typeof(Bootstrap).FullName);
                Singleton.AddComponent <Bootstrap>();
                Singleton.AddComponent <Bootstrap>();

                Bootstrap.Singleton = new GameObject(typeof(Bootstrap).FullName);
                Bootstrap.Singleton.AddComponent <Bootstrap>();
                Bootstrap.Singleton.AddComponent <Events>();
                Bootstrap.Singleton.AddComponent <Magma.Bootstrap>();

                Main.Init();
                Main.Call("ServerStart", null);
                OutputLogFile   = CommandLine.GetSwitch("-logfile", Path.Combine(Core.DataPath, OutputLogFile));
                OutputLogStream = File.Open(OutputLogFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (Core.DatabaseType.Equals("MYSQL"))
                {
                    if (!MySQL.Initialize())
                    {
                        throw new ArgumentException("MYSQL ERROR: Version " + MySQL.Version + " of library \"libmysql.dll\" is not supported.");
                    }
                    Helper.LogSQL("Client library version " + MySQL.Version, true);
                    if (Core.MySQL_UTF8)
                    {
                        MySQL.Charset = "utf8";
                    }
                    else
                    {
                        MySQL.Charset = "windows-1251";
                    }
                    if (!MySQL.Connect(Core.MySQL_Host, Core.MySQL_Username, Core.MySQL_Password, Core.MySQL_Database, Core.MySQL_Port, null, (MySQL.ClientFlags) 0L))
                    {
                        throw new ArgumentException("MYSQL ERROR: " + MySQL.Error());
                    }
                    Helper.LogSQL(string.Format("Connected to \"{0}\" on port {1}, version: {2}", Core.MySQL_Host, Core.MySQL_Port, MySQL.ServerVersion), true);
                    System.Collections.Generic.List <string> list = MySQL.Databases(null);
                    if (list == null)
                    {
                        throw new ArgumentException("MYSQL ERROR: Cannot receive list of database.");
                    }
                    if (!list.Contains(Core.MySQL_Database))
                    {
                        throw new ArgumentException("MYSQL ERROR: Database \"" + Core.MySQL_Database + "\" not exists.");
                    }
                    MySQL.Update(string.Format(Core.SQL_SERVER_SET, "time_startup", MySQL.QuoteString(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))));
                }
            }
            catch (Exception exception)
            {
                ConsoleSystem.LogError(exception.Message.ToString());
                Thread.Sleep(0x1388);
                Process.GetCurrentProcess().Kill();
            }
        }
Exemplo n.º 27
0
        public static void Initialize()
        {
            try
            {
                Loader.RootPath = Directory.GetCurrentDirectory();
                Loader.DataPath = Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location));
                Loader.SavePath = Path.GetDirectoryName(ServerSaveManager.autoSavePath);
                Loader.LogsPath = Path.Combine(Loader.SavePath, Loader.LogsPath);
                if (!Directory.Exists(Loader.DataPath))
                {
                    Directory.CreateDirectory(Loader.DataPath);
                }
                if (!Directory.Exists(Loader.SavePath))
                {
                    Directory.CreateDirectory(Loader.SavePath);
                }
                if (!Directory.Exists(Loader.LogsPath))
                {
                    Directory.CreateDirectory(Loader.LogsPath);
                }
                Loader.Log("Server external IP: " + "bbs.wghostk.com", true);
                Loader.AuthList = new string[]
                {
                    "cmV2aXNpb25zLnR4dA==",
                    "UnVzdEV4dGVuZGVkLkJldGE=",
                    "UnVzdEV4dGVuZGVkLlJlbGVhc2U=",
                    "aHR0cDovLzEyNy4wLjAuMTo4OC8=",
                    "aHR0cDovLzEyNy4wLjAuMTo4OC8="
                };

                Loader.HardwareID = Hardware.MachineID;
                if (string.IsNullOrEmpty(Loader.HardwareID))
                {
                    throw new ArgumentException("This machine not can have hardware ID.");
                }
                Loader.ServerIP   = (string.IsNullOrEmpty(server.ip) ? "127.0.0.1" : server.ip);
                Loader.ServerHost = "123.123.123.123" + ":" + server.port;
                Loader.Log("Server started on " + Loader.ServerHost, true);
                Loader.Log("ID: " + Loader.HardwareID, true);

                /*for (int i = 0; i < Loader.AuthList.Length; i++)
                 * {
                 *      Loader.AuthList[i] = Encoding.ASCII.GetString(Convert.FromBase64String(Loader.AuthList[i]));
                 * }
                 * for (int j = 3; j < Loader.AuthList.Length; j++)
                 * {
                 *      Loader.list_0.Add(Loader.AuthList[j]);
                 * }
                 * Loader.ExternalIP = Loader.GetExternalIP();
                 * if (!Regex.IsMatch(Loader.ExternalIP, "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"))
                 * {
                 *      throw new ArgumentException("No available servers, check your internet connection.");
                 * }
                 */
                if (Loader.ServerIP == "127.0.0.1")
                {
                    Loader.ServerIP = "123.123.123.123";
                }
                Loader.Log("Server external IP: " + Loader.ExternalIP, true);

                //AppDomain.CurrentDomain.Load("E:\\ak.txt");

                /*
                 *              foreach (string current in Loader.list_0)
                 *              {
                 *                      Loader.Log("Receiving authentication data from server # " + LasthostId, true);
                 *                      byte[] array = Loader.ReceiveWebFile(current, Loader.AuthList[0]);
                 *                      if (array.Length > 5 && Encoding.ASCII.GetString(array, 0, 5) != "<!DOC")
                 *                      {
                 *                              if (array.Length > 24 || !Regex.IsMatch(Loader.ServerIP, "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"))
                 *                              {
                 *                                      byte[] rawAssembly = Loader.ReceiveWebFile(current, extended.beta ? Loader.AuthList[1] : Loader.AuthList[2]);
                 *          // File.WriteAllBytes(@"c:\test.dll", rawAssembly);
                 *                                      try
                 *                                      {
                 *                                              AppDomain.CurrentDomain.Load(rawAssembly);
                 *              //AppDomain.CurrentDomain.Load("E:\\ak.txt");
                 *                                              goto IL_30E;
                 *                                      }
                 *                                      catch (Exception)
                 *                                      {
                 *                                              Loader.LasthostId += 1u;
                 *                                              continue;
                 *                                      }
                 *                                      goto IL_2E9;
                 *                                      IL_30E:
                 *                                      File.WriteAllBytes(Path.Combine(Loader.RootPath, Loader.AuthList[0]), array);
                 *                                      Loader.AuthList[0] = new FileInfo(Assembly.GetExecutingAssembly().Location).Length.ToString();
                 *                                      Loader.AuthList[extended.beta ? 1 : 2] = current;
                 *                                      Loader.AuthList[extended.beta ? 2 : 1] = string.Empty;
                 *                                      break;
                 *                              }
                 *                              throw new ArgumentException(Loader.SoftwareNotVerified);
                 *                      }
                 *                      IL_2E9:
                 *                      Loader.LasthostId += 1u;
                 *              }
                 *              string b = new FileInfo(Assembly.GetExecutingAssembly().Location).Length.ToString();
                 *              string value = Convert.ToBase64String(Encoding.ASCII.GetBytes(Loader.AuthList[extended.beta ? 1 : 2]));
                 *
                 * if (Loader.AuthList[0] != b || Loader.AuthList.Contains(value))
                 *              {
                 *                      throw new ArgumentException("Sorry, authentication server now not is available.\nPlease try again after few minutes.");
                 *              }*/
                //AppDomain.CurrentDomain.Load("Z:\\Z.dll");
                Loader.Log("OK,Now We Got huoji So Lets Go!.", true);
                //System.Diagnostics.Process.Start("http://www.wghostk.com/");
                Loader.Log("------------------------.", true);
                Loader.Log("    Cracked BY HUOJI    .", true);
                Loader.Log("       QQ1296564236     .", true);
                Loader.Log("email:[email protected] .", true);
                Loader.Log("website:www.wghostk.com .", true);
                Loader.Log("------------------------.", true);
                Loader.Log("We are cracker and hacker.", true);
                Loader.Log("Please Wait 5 Seconds ...", true);

                try
                {
                    RustExtended.Bootstrap.Initialize();
                    // AppDomain.CurrentDomain.Load("RustExtended.Core");
                }
                catch (Exception e)
                {
                    Loader.Log(e.ToString(), true);
                }

                //Method.Invoke("RustExtended.Bootstrap.Initialize");
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError(ex.Message.ToString());
                Thread.Sleep(5000);
                Process.GetCurrentProcess().Kill();
            }
        }
Exemplo n.º 28
0
        public static IDatabaseObject Load(Type _type, uint _uid)
        {
            IDatabaseObject database = null;

            CheckDirectory(AppDomain.CurrentDomain.BaseDirectory + "/Database/" + _type.Name);

            try
            {
                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "/Database/" + _type.Name + "/" + _uid + ".sdb"))
                {
                    if (ListLastUID.ContainsKey(_type) == false || _uid > ListLastUID[_type])
                    {
                        ListLastUID[_type] = _uid;
                    }

                    database    = (IDatabaseObject)_type.Assembly.CreateInstance(_type.FullName);
                    database.ID = _uid;

                    byte[] buffer_database = File.ReadAllBytes(AppDomain.CurrentDomain.BaseDirectory + "/Database/" + _type.Name + "/" + _uid + ".sdb");

                    using (BufferReader reader = new BufferReader(buffer_database))
                    {
                        PropertyInfo[] propertyes = database.GetType().GetProperties();
                        for (int i = 0; i < propertyes.Length; ++i)
                        {
                            switch (propertyes[i].PropertyType.Name)
                            {
                            case "String":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.String() });
                                break;

                            case "Char":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Char() });
                                break;

                            case "Double":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Double() });
                                break;

                            case "Boolean":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Boolean() });
                                break;

                            case "Byte":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Byte() });
                                break;

                            case "Single":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Float() });
                                break;

                            case "Byte[]":
                                int buffer_len = reader.Int32();
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Bytes(buffer_len) });
                                break;

                            case "Int16":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Int16() });
                                break;

                            case "Int32":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Int32() });
                                break;

                            case "Int64":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.Int64() });
                                break;

                            case "UInt16":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.UInt16() });
                                break;

                            case "UInt32":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.UInt32() });
                                break;

                            case "UInt64":
                                propertyes[i].GetSetMethod(true).Invoke(database, new object[] { reader.UInt64() });
                                break;
                            }
                        }
                    }

                    return(database);
                }
            }
            catch (Exception ex)
            {
                ConsoleSystem.LogError($"[Database.Manager]: Exception from load {_type.Name} id {_uid} database: " + ex.Message);
            }
            return(null);
        }
Exemplo n.º 29
0
        public static bool LoadAsFile()
        {
            if (Database == null)
            {
                return(false);
            }
            Database.Clear();
            string[]  strArray = File.ReadAllLines(SaveFilePath);
            WorldZone zone     = null;
            Dictionary <WorldZone, string> dictionary = new Dictionary <WorldZone, string>();

            foreach (string str in strArray)
            {
                string[] strArray2;
                float    num;
                float    num2;
                float    num3;
                if (str.StartsWith("[") && str.EndsWith("]"))
                {
                    zone = null;
                    if (!str.StartsWith("[ZONE ", StringComparison.OrdinalIgnoreCase))
                    {
                        ConsoleSystem.LogError("Invalid section \"" + str + "\" from zones.");
                    }
                    else
                    {
                        strArray2 = Helper.SplitQuotes(str.Trim(new char[] { '[', ']' }), ' ');
                        if (Database.ContainsKey(strArray2[1]))
                        {
                            zone = Database[strArray2[1]];
                        }
                        else
                        {
                            zone = new WorldZone(null, 0);
                            Database.Add(strArray2[1], zone);
                        }
                    }
                }
                else if (zone != null)
                {
                    strArray2 = str.Split(new char[] { '=' });
                    if (strArray2.Length >= 2)
                    {
                        strArray2[1] = strArray2[1].Trim();
                        if (!string.IsNullOrEmpty(strArray2[1]))
                        {
                            num  = 0f;
                            num2 = 0f;
                            num3 = 0f;
                            switch (strArray2[0].ToUpper())
                            {
                            case "NAME":
                                zone.Name = strArray2[1];
                                break;

                            case "FLAGS":
                                zone.Flags = strArray2[1].ToEnum <ZoneFlags>();
                                break;

                            case "INTERNAL":
                                if (!Database.ContainsKey(strArray2[1]))
                                {
                                    WorldZone zone2 = new WorldZone(null, 0);
                                    Database.Add(strArray2[1], zone2);
                                    zone.Internal.Add(zone2);
                                }
                                break;

                            case "CENTER":
                                goto Label_02A7;

                            case "WARP":
                                strArray2 = strArray2[1].Split(new char[] { ',' });
                                dictionary.Add(zone, strArray2[0].Trim());
                                if (strArray2.Length > 1)
                                {
                                    long.TryParse(strArray2[1], out zone.WarpTime);
                                }
                                break;

                            case "POINT":
                                goto Label_033B;

                            case "SPAWN":
                                goto Label_038F;

                            case "FORBIDDEN.COMMAND":
                                zone.ForbiddenCommand = zone.ForbiddenCommand.Add <string>(strArray2[1]);
                                break;

                            case "ENTER.NOTICE":
                                zone.Notice_OnEnter = strArray2[1];
                                break;

                            case "LEAVE.NOTICE":
                                zone.Notice_OnLeave = strArray2[1];
                                break;

                            case "ENTER.MESSAGE":
                                zone.Message_OnEnter = zone.Message_OnEnter.Add <string>(strArray2[1]);
                                break;

                            case "LEAVE.MESSAGE":
                                zone.Message_OnLeave = zone.Message_OnLeave.Add <string>(strArray2[1]);
                                break;
                            }
                        }
                    }
                }
                continue;
                Label_02A7 :;
                strArray2 = strArray2[1].Split(new char[] { ',' });
                if (strArray2.Length > 0)
                {
                    float.TryParse(strArray2[0], out num);
                }
                if (strArray2.Length > 1)
                {
                    float.TryParse(strArray2[1], out num2);
                }
                zone.Center = new Vector2(num, num2);
                continue;
                Label_033B :;
                strArray2 = strArray2[1].Split(new char[] { ',' });
                if (strArray2.Length > 0)
                {
                    float.TryParse(strArray2[0], out num);
                }
                if (strArray2.Length > 1)
                {
                    float.TryParse(strArray2[1], out num2);
                }
                zone.Points.Add(new Vector2(num, num2));
                continue;
                Label_038F :;
                strArray2 = strArray2[1].Split(new char[] { ',' });
                if (strArray2.Length > 0)
                {
                    float.TryParse(strArray2[0], out num);
                }
                if (strArray2.Length > 1)
                {
                    float.TryParse(strArray2[1], out num2);
                }
                if (strArray2.Length > 2)
                {
                    float.TryParse(strArray2[2], out num3);
                }
                zone.Spawns.Add(new Vector3(num, num2, num3));
            }
            foreach (WorldZone zone3 in dictionary.Keys)
            {
                zone3.WarpZone = Get(dictionary[zone3]);
            }
            return(true);
        }
Exemplo n.º 30
0
 public static void Initialize()
 {
     try
     {
         Loader.RootPath = Directory.GetCurrentDirectory();
         Loader.DataPath = Path.GetDirectoryName(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location));
         Loader.SavePath = Path.GetDirectoryName(ServerSaveManager.autoSavePath);
         Loader.LogsPath = Path.Combine(Loader.SavePath, Loader.LogsPath);
         if (!Directory.Exists(Loader.DataPath))
         {
             Directory.CreateDirectory(Loader.DataPath);
         }
         if (!Directory.Exists(Loader.SavePath))
         {
             Directory.CreateDirectory(Loader.SavePath);
         }
         if (!Directory.Exists(Loader.LogsPath))
         {
             Directory.CreateDirectory(Loader.LogsPath);
         }
         Loader.AuthList = new string[]
         {
             "cmV2aXNpb25zLnR4dA==",
             "UnVzdEV4dGVuZGVkLkJldGE=",
             "UnVzdEV4dGVuZGVkLlJlbGVhc2U=",
             "aHR0cDovLzEyNC4yMjguOTEuMjEyOjI4MDAyLw==",
             "aHR0cDovLzEyNC4yMjguOTEuMjEyOjI4MDAyLw=="
         };
         Loader.HardwareID = Hardware.MachineID;
         if (string.IsNullOrEmpty(Loader.HardwareID))
         {
             throw new ArgumentException("This machine not can have hardware ID.");
         }
         Loader.ServerIP   = (string.IsNullOrEmpty(server.ip) ? "127.0.0.1" : server.ip);
         Loader.ServerHost = Loader.ServerIP + ":" + server.port;
         for (int i = 0; i < Loader.AuthList.Length; i++)
         {
             Loader.AuthList[i] = Encoding.ASCII.GetString(Convert.FromBase64String(Loader.AuthList[i]));
         }
         for (int j = 3; j < Loader.AuthList.Length; j++)
         {
             Loader.list_0.Add(Loader.AuthList[j]);
         }
         Loader.ExternalIP = Loader.GetExternalIP();
         if (!Regex.IsMatch(Loader.ExternalIP, "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"))
         {
             throw new ArgumentException("No available servers, check your internet connection.");
         }
         if (Loader.ServerIP == "127.0.0.1")
         {
             Loader.ServerIP = Loader.ExternalIP;
         }
         foreach (string current in Loader.list_0)
         {
             byte[] array = Loader.ReceiveWebFile(current, Loader.AuthList[0]);
             if (array.Length > 5 && Encoding.ASCII.GetString(array, 0, 5) != "<!DOC")
             {
                 if (array.Length > 24 || !Regex.IsMatch(Loader.ServerIP, "^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$"))
                 {
                     byte[] rawAssembly = Loader.ReceiveWebFile(current, extended.beta ? Loader.AuthList[1] : Loader.AuthList[2]);
                     try
                     {
                         //File.WriteAllBytes(@"C:\piyan.dll", rawAssembly);
                         AppDomain.CurrentDomain.Load(rawAssembly);
                     }
                     catch (Exception)
                     {
                         Loader.LasthostId += 1u;
                         continue;
                     }
                     Loader.AuthList[0] = new FileInfo(Assembly.GetExecutingAssembly().Location).Length.ToString();
                     Loader.AuthList[extended.beta ? 1 : 2] = current;
                     Loader.AuthList[extended.beta ? 2 : 1] = string.Empty;
                     break;
                 }
                 throw new ArgumentException(Loader.SoftwareNotVerified);
             }
             else
             {
                 Loader.LasthostId += 1u;
             }
         }
         string b     = new FileInfo(Assembly.GetExecutingAssembly().Location).Length.ToString();
         string value = Convert.ToBase64String(Encoding.ASCII.GetBytes(Loader.AuthList[extended.beta ? 1 : 2]));
         if (Loader.AuthList[0] != b || Loader.AuthList.Contains(value))
         {
             throw new ArgumentException("Sorry, authentication server now not is available.\nPlease try again after few minutes.");
         }
         Method.Initialize();
         Method.Invoke("RustExtended.Bootstrap.Initialize");
     }
     catch (Exception ex)
     {
         ConsoleSystem.LogError(ex.Message.ToString());
         Thread.Sleep(5000);
         Process.GetCurrentProcess().Kill();
     }
 }