예제 #1
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);

            Log.Texte("", "-------------------- Lobby Server ---------------------", ConsoleColor.DarkRed);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <LobbyConfigs>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "LobbyServer"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Client = new RpcClient("LobbyServer", Config.RpcInfo.RpcLocalIp, 1);
            if (!Client.Start(Config.RpcInfo.RpcServerIp, Config.RpcInfo.RpcServerPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            if (!TCPManager.Listen <TCPServer>(Config.ClientPort, "LobbyServer"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Server = TCPManager.GetTcp <TCPServer>("LobbyServer");



            Log.Debug($"LobbyServer", $"RpcClient on Local Ip {Config.RpcInfo.RpcLocalIp}");
            Log.Debug($"LobbyServer", $"RpcClient Connect (Start) to {Config.RpcInfo.RpcServerIp}:{ Config.RpcInfo.RpcServerPort}");
            Log.Debug($"LobbyServer", $"TcpServer on Port {Config.ClientPort}");

            ConsoleMgr.Start();
        }
예제 #2
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);

            Log.Texte("", "-------------------- Account Cacher -------------------", ConsoleColor.Blue);



            Log.Texte("", "---Dawn of Reckoning project since 2008-2019 BY LEO228---", ConsoleColor.Red);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <AccountConfigs>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "AccountCacher"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            AccountMgr.Database = DBManager.Start(Config.AccountDB.Total(), ConnectionType.DATABASE_MYSQL, "Accounts");
            if (AccountMgr.Database == null)
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Server = new RpcServer(Config.RpcInfo.RpcClientStartingPort, 1);
            if (!Server.Start(Config.RpcInfo.RpcIp, Config.RpcInfo.RpcPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            AcctMgr = Server.GetLocalObject <AccountMgr>();
            AcctMgr.LoadRealms();

            ConsoleMgr.Start();
        }
예제 #3
0
    /// <summary>
    /// 载入本地版本文件
    /// </summary>
    public static IEnumerator LoadVersionFile()
    {
        // 本地版本文件不存在
        string filePath = string.Format("{0}/{1}.bytes", ConfigMgr.ASSETBUNDLES_PATH, VERSION_NAME);

        if (!File.Exists(filePath))
        {
            NIDebug.Log("找不到本地版本文件");
            yield break;
        }

        // 载入文件
        WWW www = new WWW(ConfigMgr.GetLocalRootPathWWW(string.Format("{0}/{1}.bytes", ConfigMgr.ASSETBUNDLES_NAME, VERSION_NAME)));

        yield return(www);

        // 等待资源加载完成
        while (!www.isDone)
        {
            yield return(null);
        }

        // 文件载入失败, 获取文件不存在
        if (!string.IsNullOrEmpty(www.error) || www.bytes.Length <= 0)
        {
            yield break;
        }

        // 反序列化
        MemoryStream csvStr = new MemoryStream(www.bytes, 0, www.bytes.Length, true, true);

        mVersionCsv = CsvFileMgr.Deserialize(csvStr);
        csvStr.Close();

        // 释放www
        www.Dispose();
    }
예제 #4
0
        /// <summary>
        /// 判断当前请求是否还了用户登录的cookie信息,如果带了,则再判断服务器缓存中记录是否有该用户的登录信息并是否一致
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cuser"></param>
        /// <returns></returns>
        private bool IsSignIn(HttpRequestBase request, out CurrentUser cuser)
        {
            cuser = null;
            string cookieLoginInfo = CookieMgr.Get(UserBLL.LoginCookieName);

            if (!string.IsNullOrEmpty(cookieLoginInfo))
            {
                var CrypteKey = ConfigMgr.GetAppSettingString("CrypteKey");
                cuser = JsonConvert.DeserializeObject <CurrentUser>(Cryptor.DesDecrypt(cookieLoginInfo, CrypteKey));
                string cacheLoginInfo = CacheMaker.RedisCache.Get <string>("sidkey" + cuser.UserID);
                if (!string.IsNullOrEmpty(cacheLoginInfo))
                {
                    return(cookieLoginInfo.Equals(cacheLoginInfo));
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
예제 #5
0
        public IEnumerator Shuffle()
        {
            DisassemblygirlGoldConfigTable goldTable = ConfigMgr.GetInstance().DisassemblygirlGold;

            int lastValue = default(int);

            while (true)
            {
                int value = Random.Range(1, goldTable.configs.Count);
                if (value == lastValue)
                {
                    value = (value == goldTable.configs.Count ? value - 1 : value + 1);
                }

                lastValue = value;

                DisassemblygirlGoldConfig config = goldTable.GetConfigById(lastValue);
                iconImg.spriteName = config.iconID;
                data.name          = goldTable.GetConfigById(lastValue).name;
                data.value         = config.value;

                yield return(new WaitForSeconds(0.08f));
            }
        }
예제 #6
0
        public bool Update()
        {
            Log.outInfo(LogFilter.SqlUpdates, $"Updating {_database.GetDatabaseName()} database...");

            string sourceDirectory = GetSourceDirectory();

            if (!Directory.Exists(sourceDirectory))
            {
                Log.outError(LogFilter.SqlUpdates, $"DBUpdater: Given source directory {sourceDirectory} does not exist, skipped!");
                return(false);
            }

            var availableFiles = GetFileList();
            var appliedFiles   = ReceiveAppliedFiles();

            bool redundancyChecks   = ConfigMgr.GetDefaultValue("Updates.Redundancy", true);
            bool archivedRedundancy = ConfigMgr.GetDefaultValue("Updates.Redundancy", true);

            UpdateResult result = new UpdateResult();

            // Count updates
            foreach (var entry in appliedFiles)
            {
                if (entry.Value.State == State.RELEASED)
                {
                    ++result.recent;
                }
                else
                {
                    ++result.archived;
                }
            }

            foreach (var availableQuery in availableFiles)
            {
                Log.outDebug(LogFilter.SqlUpdates, $"Checking update \"{availableQuery.GetFileName()}\"...");

                var applied = appliedFiles.LookupByKey(availableQuery.GetFileName());
                if (applied != null)
                {
                    // If redundancy is disabled skip it since the update is already applied.
                    if (!redundancyChecks)
                    {
                        Log.outDebug(LogFilter.SqlUpdates, "Update is already applied, skipping redundancy checks.");
                        appliedFiles.Remove(availableQuery.GetFileName());
                        continue;
                    }

                    // If the update is in an archived directory and is marked as archived in our database skip redundancy checks (archived updates never change).
                    if (!archivedRedundancy && (applied.State == State.ARCHIVED) && (availableQuery.state == State.ARCHIVED))
                    {
                        Log.outDebug(LogFilter.SqlUpdates, "Update is archived and marked as archived in database, skipping redundancy checks.");
                        appliedFiles.Remove(availableQuery.GetFileName());
                        continue;
                    }
                }

                // Calculate hash
                string hash = CalculateHash(availableQuery.path);

                UpdateMode mode = UpdateMode.Apply;

                // Update is not in our applied list
                if (applied == null)
                {
                    // Catch renames (different filename but same hash)
                    var hashIter = appliedFiles.Values.FirstOrDefault(p => p.Hash == hash);
                    if (hashIter != null)
                    {
                        // Check if the original file was removed if not we've got a problem.
                        var renameFile = availableFiles.Find(p => p.GetFileName() == hashIter.Name);
                        if (renameFile != null)
                        {
                            Log.outWarn(LogFilter.SqlUpdates, $"Seems like update \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\' was renamed, but the old file is still there! " +
                                        $"Trade it as a new file! (Probably its an unmodified copy of file \"{renameFile.GetFileName()}\")");
                        }
                        // Its save to trade the file as renamed here
                        else
                        {
                            Log.outInfo(LogFilter.SqlUpdates, $"Renaming update \"{hashIter.Name}\" to \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\'.");

                            RenameEntry(hashIter.Name, availableQuery.GetFileName());
                            appliedFiles.Remove(hashIter.Name);
                            continue;
                        }
                    }
                    // Apply the update if it was never seen before.
                    else
                    {
                        Log.outInfo(LogFilter.SqlUpdates, $"Applying update \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\'...");
                    }
                }
                // Rehash the update entry if it is contained in our database but with an empty hash.
                else if (ConfigMgr.GetDefaultValue("Updates.AllowRehash", true) && string.IsNullOrEmpty(applied.Hash))
                {
                    mode = UpdateMode.Rehash;

                    Log.outInfo(LogFilter.SqlUpdates, $"Re-hashing update \"{availableQuery.GetFileName()}\" \'{hash.Substring(0, 7)}\'...");
                }
                else
                {
                    // If the hash of the files differs from the one stored in our database reapply the update (because it was changed).
                    if (applied.Hash != hash && applied.State != State.ARCHIVED)
                    {
                        Log.outInfo(LogFilter.SqlUpdates, $"Reapplying update \"{availableQuery.GetFileName()}\" \'{applied.Hash.Substring(0, 7)}\' . \'{hash.Substring(0, 7)}\' (it changed)...");
                    }
                    else
                    {
                        // If the file wasn't changed and just moved update its state if necessary.
                        if (applied.State != availableQuery.state)
                        {
                            Log.outDebug(LogFilter.SqlUpdates, $"Updating state of \"{availableQuery.GetFileName()}\" to \'{availableQuery.state}\'...");

                            UpdateState(availableQuery.GetFileName(), availableQuery.state);
                        }

                        Log.outDebug(LogFilter.SqlUpdates, $"Update is already applied and is matching hash \'{hash.Substring(0, 7)}\'.");

                        appliedFiles.Remove(applied.Name);
                        continue;
                    }
                }

                uint             speed = 0;
                AppliedFileEntry file  = new AppliedFileEntry(availableQuery.GetFileName(), hash, availableQuery.state, 0);

                switch (mode)
                {
                case UpdateMode.Apply:
                    speed = ApplyTimedFile(availableQuery.path);
                    goto case UpdateMode.Rehash;

                case UpdateMode.Rehash:
                    UpdateEntry(file, speed);
                    break;
                }

                if (applied != null)
                {
                    appliedFiles.Remove(applied.Name);
                }

                if (mode == UpdateMode.Apply)
                {
                    ++result.updated;
                }
            }

            // Cleanup up orphaned entries if enabled
            if (!appliedFiles.Empty())
            {
                int  cleanDeadReferencesMaxCount = ConfigMgr.GetDefaultValue("Updates.CleanDeadRefMaxCount", 3);
                bool doCleanup = (cleanDeadReferencesMaxCount < 0) || (appliedFiles.Count <= cleanDeadReferencesMaxCount);

                foreach (var entry in appliedFiles)
                {
                    Log.outWarn(LogFilter.SqlUpdates, $"File \'{entry.Key}\' was applied to the database but is missing in your update directory now!");

                    if (doCleanup)
                    {
                        Log.outInfo(LogFilter.SqlUpdates, $"Deleting orphaned entry \'{entry.Key}\'...");
                    }
                }

                if (doCleanup)
                {
                    CleanUp(appliedFiles);
                }
                else
                {
                    Log.outError(LogFilter.SqlUpdates, $"Cleanup is disabled! There are {appliedFiles.Count} dirty files that were applied to your database but are now missing in your source directory!");
                }
            }

            string info = $"Containing {result.recent} new and {result.archived} archived updates.";

            if (result.updated == 0)
            {
                Log.outInfo(LogFilter.SqlUpdates, $"{_database.GetDatabaseName()} database is up-to-date! {info}");
            }
            else
            {
                Log.outInfo(LogFilter.SqlUpdates, $"Applied {result.updated} query(s). {info}");
            }

            return(true);
        }
예제 #7
0
        public void AddDatabase <T>(MySqlBase <T> database, string baseDBName)
        {
            bool updatesEnabled = database.IsAutoUpdateEnabled(_updateFlags);

            _open.Add(() =>
            {
                MySqlConnectionInfo connectionObject = new MySqlConnectionInfo
                {
                    Host     = ConfigMgr.GetDefaultValue(baseDBName + "DatabaseInfo.Host", ""),
                    Port     = ConfigMgr.GetDefaultValue(baseDBName + "DatabaseInfo.Port", ""),
                    Username = ConfigMgr.GetDefaultValue(baseDBName + "DatabaseInfo.Username", ""),
                    Password = ConfigMgr.GetDefaultValue(baseDBName + "DatabaseInfo.Password", ""),
                    Database = ConfigMgr.GetDefaultValue(baseDBName + "DatabaseInfo.Database", "")
                };

                var error = database.Initialize(connectionObject);
                if (error != MySqlErrorCode.None)
                {
                    // Database does not exist
                    if (error == MySqlErrorCode.UnknownDatabase && updatesEnabled && _autoSetup)
                    {
                        Log.outInfo(LogFilter.ServerLoading, $"Database \"{connectionObject.Database}\" does not exist, do you want to create it? [yes (default) / no]: ");

                        string answer = Console.ReadLine();
                        if (string.IsNullOrEmpty(answer) || answer[0] != 'y')
                        {
                            return(false);
                        }

                        Log.outInfo(LogFilter.ServerLoading, $"Creating database \"{connectionObject.Database}\"...");
                        string sqlString = $"CREATE DATABASE `{connectionObject.Database}` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci";
                        // Try to create the database and connect again if auto setup is enabled
                        if (database.Apply(sqlString) && database.Initialize(connectionObject) == MySqlErrorCode.None)
                        {
                            error = MySqlErrorCode.None;
                        }
                    }

                    // If the error wasn't handled quit
                    if (error != MySqlErrorCode.None)
                    {
                        Log.outError(LogFilter.ServerLoading, $"\nDatabase {connectionObject.Database} NOT opened. There were errors opening the MySQL connections. Check your SQLErrors for specific errors.");
                        return(false);
                    }

                    Log.outInfo(LogFilter.ServerLoading, "Done.");
                }
                return(true);
            });

            if (updatesEnabled)
            {
                // Populate and update only if updates are enabled for this pool
                _populate.Add(() =>
                {
                    if (!database.GetUpdater().Populate())
                    {
                        Log.outError(LogFilter.ServerLoading, $"Could not populate the {database.GetDatabaseName()} database, see log for details.");
                        return(false);
                    }
                    return(true);
                });

                _update.Add(() =>
                {
                    if (!database.GetUpdater().Update())
                    {
                        Log.outError(LogFilter.ServerLoading, $"Could not update the {database.GetDatabaseName()} database, see log for details.");
                        return(false);
                    }
                    return(true);
                });
            }

            _prepare.Add(() =>
            {
                database.LoadPreparedStatements();
                return(true);
            });
        }
예제 #8
0
파일: Server.cs 프로젝트: lyosky/CypherCore
        static void Main()
        {
            //Set Culture
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            if (!ConfigMgr.Load("BNetServer.conf"))
            {
                ExitNow();
            }

            // Initialize the database
            if (!StartDB())
            {
                ExitNow();
            }

            FixLegacyAuthHashes();

            string bindIp = ConfigMgr.GetDefaultValue("BindIP", "0.0.0.0");

            var restSocketServer = new SocketManager <RestSession>();
            int restPort         = ConfigMgr.GetDefaultValue("LoginREST.Port", 8081);

            if (restPort < 0 || restPort > 0xFFFF)
            {
                Log.outError(LogFilter.Network, $"Specified login service port ({restPort}) out of allowed range (1-65535), defaulting to 8081");
                restPort = 8081;
            }

            if (!restSocketServer.StartNetwork(bindIp, restPort))
            {
                Log.outError(LogFilter.Server, "Failed to initialize Rest Socket Server");
                ExitNow();
            }

            // Get the list of realms for the server
            Global.RealmMgr.Initialize(ConfigMgr.GetDefaultValue("RealmsStateUpdateDelay", 10));
            Global.LoginServiceMgr.Initialize();

            var sessionSocketServer = new SocketManager <Session>();
            // Start the listening port (acceptor) for auth connections
            int bnPort = ConfigMgr.GetDefaultValue("BattlenetPort", 1119);

            if (bnPort < 0 || bnPort > 0xFFFF)
            {
                Log.outError(LogFilter.Server, $"Specified battle.net port ({bnPort}) out of allowed range (1-65535)");
                ExitNow();
            }

            if (!sessionSocketServer.StartNetwork(bindIp, bnPort))
            {
                Log.outError(LogFilter.Network, "Failed to start BnetServer Network");
                ExitNow();
            }

            uint _banExpiryCheckInterval = ConfigMgr.GetDefaultValue("BanExpiryCheckInterval", 60u);

            _banExpiryCheckTimer          = new Timer(_banExpiryCheckInterval);
            _banExpiryCheckTimer.Elapsed += BanExpiryCheckTimer_Elapsed;
            _banExpiryCheckTimer.Start();
        }
예제 #9
0
        static void Main()
        {
            Console.CancelKeyPress += (o, e) =>
            {
                Global.RealmMgr.Close();

                Log.outInfo(LogFilter.Server, "Halting process...");
                Environment.Exit(-1);
            };

            if (!ConfigMgr.Load(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".conf"))
            {
                ExitNow();
            }

            // Initialize the database connection
            if (!StartDB())
            {
                ExitNow();
            }

            string bindIp = ConfigMgr.GetDefaultValue("BindIP", "0.0.0.0");

            var restSocketServer = new SocketManager <RestSession>();
            int restPort         = ConfigMgr.GetDefaultValue("LoginREST.Port", 8081);

            if (restPort < 0 || restPort > 0xFFFF)
            {
                Log.outError(LogFilter.Network, "Specified login service port ({0}) out of allowed range (1-65535), defaulting to 8081", restPort);
                restPort = 8081;
            }

            if (!restSocketServer.StartNetwork(bindIp, restPort))
            {
                Log.outError(LogFilter.Server, "Failed to initialize Rest Socket Server");
                ExitNow();
            }

            // Get the list of realms for the server
            Global.RealmMgr.Initialize(ConfigMgr.GetDefaultValue("RealmsStateUpdateDelay", 10));
            Global.SessionMgr.Initialize();

            var sessionSocketServer = new SocketManager <Session>();
            // Start the listening port (acceptor) for auth connections
            int bnPort = ConfigMgr.GetDefaultValue("BattlenetPort", 1119);

            if (bnPort < 0 || bnPort > 0xFFFF)
            {
                Log.outError(LogFilter.Server, "Specified battle.net port ({0}) out of allowed range (1-65535)", bnPort);
                ExitNow();
            }

            if (!sessionSocketServer.StartNetwork(bindIp, bnPort))
            {
                Log.outError(LogFilter.Network, "Failed to start BnetServer Network");
                ExitNow();
            }

            uint _banExpiryCheckInterval = ConfigMgr.GetDefaultValue("BanExpiryCheckInterval", 60u);

            _banExpiryCheckTimer          = new Timer(_banExpiryCheckInterval);
            _banExpiryCheckTimer.Elapsed += _banExpiryCheckTimer_Elapsed;

            while (true)
            {
                ;
            }
        }
예제 #10
0
파일: Log.cs 프로젝트: spadd/CypherCore
    static void CreateAppenderFromConfig(string appenderName)
    {
        if (string.IsNullOrEmpty(appenderName))
        {
            return;
        }

        string options = ConfigMgr.GetDefaultValue(appenderName, "");
        var    tokens  = new StringArray(options, ',');
        string name    = appenderName.Substring(9);

        if (tokens.Length < 2)
        {
            Console.WriteLine("Log.CreateAppenderFromConfig: Wrong configuration for appender {0}. Config line: {1}", name, options);
            return;
        }

        AppenderFlags flags = AppenderFlags.None;
        AppenderType  type  = (AppenderType)uint.Parse(tokens[0]);
        LogLevel      level = (LogLevel)uint.Parse(tokens[1]);

        if (level > LogLevel.Fatal)
        {
            Console.WriteLine("Log.CreateAppenderFromConfig: Wrong Log Level {0} for appender {1}\n", level, name);
            return;
        }

        if (tokens.Length > 2)
        {
            flags = (AppenderFlags)uint.Parse(tokens[2]);
        }

        byte id = NextAppenderId();

        switch (type)
        {
        case AppenderType.Console:
        {
            var appender = new ConsoleAppender(id, name, level, flags);
            appenders[id] = appender;
            break;
        }

        case AppenderType.File:
        {
            string filename;
            if (tokens.Length < 4)
            {
                if (name != "Server")
                {
                    Console.WriteLine("Log.CreateAppenderFromConfig: Missing file name for appender {0}", name);
                    return;
                }

                filename = Process.GetCurrentProcess().ProcessName + ".log";
            }
            else
            {
                filename = tokens[3];
            }

            appenders[id] = new FileAppender(id, name, level, filename, m_logsDir, flags);
            break;
        }

        case AppenderType.DB:
        {
            appenders[id] = new DBAppender(id, name, level);
            break;
        }

        default:
            Console.WriteLine("Log.CreateAppenderFromConfig: Unknown type {0} for appender {1}", type, name);
            break;
        }
    }
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(OnClose);

            Log.Texte("", "-------------------- World Server ---------------------", ConsoleColor.DarkRed);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <WorldConfigs>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "WorldServer"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

#if DEBUG
            API.Server api = null;
            if (Config.EnableAPI)
            {
                try
                {
                    api = new API.Server(Config.APIAddress, Config.APIPort, 100);
                }
                catch (Exception e)
                {
                    Log.Error("API", "Unable to start API server: " + e.Message);
                }
            }
#endif

            CharMgr.Database = DBManager.Start(Config.CharacterDatabase.Total(), Config.CharacterDatabase.ConnectionType, "Characters", Config.CharacterDatabase.Database);
            if (CharMgr.Database == null)
            {
                ConsoleMgr.WaitAndExit(2000);
            }
            else if (!Config.PreloadAllCharacters)
            {
                CharMgr.Database.RegisterAction(CharMgr.LoadPendingCharacters);
            }

            _timer = new Timer(AuctionHouse.CheckAuctionExpiry, null, new TimeSpan(0, 12, 0, 0), new TimeSpan(0, 24, 0, 0));

            WorldMgr.Database = DBManager.Start(Config.WorldDatabase.Total(), Config.CharacterDatabase.ConnectionType, "World", Config.WorldDatabase.Database);
            if (WorldMgr.Database == null)
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            WorldMgr.StartingPairing = WorldMgr.Database.ExecuteQueryInt("SELECT FLOOR(RAND() * 3) + 1");


            WorldMgr.UpperTierBattlefrontManager = new UpperTierBattlefrontManager();
            WorldMgr.UpperTierBattlefrontManager.SetInitialPairActive();
            Log.Texte("Creating Upper Tier Battlefront Manager", WorldMgr.UpperTierBattlefrontManager.GetActivePairing().PairingName, ConsoleColor.Cyan);

            WorldMgr.LowerTierBattlefrontManager = new LowerTierBattlefrontManager();
            WorldMgr.LowerTierBattlefrontManager.SetInitialPairActive();
            Log.Texte("Creating Lower Tier Battlefront Manager", WorldMgr.LowerTierBattlefrontManager.GetActivePairing().PairingName, ConsoleColor.Cyan);


            Log.Texte("StartingPairing: ", WorldMgr.StartingPairing.ToString(), ConsoleColor.Cyan);

            Client = new RpcClient("WorldServer-" + Config.RealmId, Config.AccountCacherInfo.RpcLocalIp, 1);
            if (!Client.Start(Config.AccountCacherInfo.RpcServerIp, Config.AccountCacherInfo.RpcServerPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Rm = AcctMgr.GetRealm(Config.RealmId);

            if (Rm == null)
            {
                Log.Error("WorldServer", "Realm (" + Config.RealmId + ") not found");
                return;
            }

            LoaderMgr.Start();

            if (!TCPManager.Listen <TCPServer>(Rm.Port, "World"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Server = TCPManager.GetTcp <TCPServer>("World");

            AcctMgr.UpdateRealm(Client.Info, Rm.RealmId);
            AcctMgr.UpdateRealmCharacters(Rm.RealmId, (uint)CharMgr.Database.GetObjectCount <Character>("Realm=1"), (uint)CharMgr.Database.GetObjectCount <Character>("Realm=2"));

            ConsoleMgr.Start();
        }
예제 #12
0
 public void SetHostIp(string hostIp)
 {
     ConfigMgr.UpdateHostAddress(hostIp);
 }
예제 #13
0
    /// <summary>
    /// 载入有文本资源
    /// 1. Etc目录下的所有资源csv资源
    /// 2. Etc目录下的所有资源txt资源
    /// 3. Language目录下的所有资源txt资源
    /// 4. ActionSet目录下的所有资源xml资源
    /// </summary>
    /// <returns>The all text.</returns>
    public IEnumerator LoadEtcText()
    {
        // 本地版本文件不存在
        string filePath = string.Format("{0}/{1}", ConfigMgr.ASSETBUNDLES_PATH, ETC_BUNDLE);

        if (!File.Exists(filePath))
        {
            // 载入etc资源线程
            Thread loadEtcTextThread = new Thread(new ParameterizedThreadStart(DeLoadEtcTextThread));
            loadEtcTextThread.Start(ConfigMgr.ETC_PATH);

            // 等待载入资源完毕
            while (loadEtcTextThread.IsAlive)
            {
                yield return(null);
            }

            // 开启线程载入资源
            yield break;
        }

        // www载入资源
        WWW www = new WWW(ConfigMgr.GetLocalRootPathWWW(string.Format("{0}/{1}", ConfigMgr.ASSETBUNDLES_NAME, ETC_BUNDLE)));

        // 等待资源载入完成
        yield return(www);

        // 解密资源
        byte[] unEncyptbytes = Encypt(www.bytes);

        // 直接载入etc.ab资源
        AssetBundle ab = AssetBundle.LoadFromMemory(unEncyptbytes);

        // 资源载入失败
        if (ab == null)
        {
            yield break;
        }

        // 异步载入该ab下所有子资源
        AssetBundleRequest assetLoadRequest = ab.LoadAllAssetsAsync();

        yield return(assetLoadRequest);

        // 遍历各个资源进行分类处理
        // bytes需要和其他资源区分开
        foreach (string assetPath in ab.GetAllAssetNames())
        {
            // 载入资源
            TextAsset textAsset = ab.LoadAsset <TextAsset>(assetPath);
            if (textAsset == null)
            {
                continue;
            }

            // 获取资源扩展名
            string ex = Path.GetExtension(assetPath);

            // 文本资源分类CSV_EXT需要和其他资源区分开
            if (string.Equals(ex, CsvFileMgr.CSV_EXT))
            {
                etcBtyeAssetMap.Add(assetPath, textAsset.bytes);
            }
            else if (string.Equals(ex, ".xml") && Path.GetFileName(assetPath).Contains("skill_action"))
            {
                etcSkillActionList.Add(textAsset.text);
            }
            else if (Path.GetFileName(assetPath).Contains(".lua.txt"))
            {
                string scriptName = Path.GetFileName(assetPath);
                string strSptNo   = scriptName.Replace(".lua.txt", "");
                int    sptNo;
                if (!int.TryParse(strSptNo, out sptNo))
                {
                    // 如果是lua脚本公式
                    //FormulaMgr.AddLuaFormula(strSptNo, textAsset.text);
                }
                else
                {
                    // 如果是lua脚本
                    //ScriptMgr.AddLuaScript(sptNo, textAsset.text);
                }
            }
            else
            {
                etcTextAssetMap.Add(assetPath, textAsset.text);
            }
        }

        // 释放etc.ab资源
        ab.Unload(false);
    }
예제 #14
0
    /// <summary>
    /// 更新资源
    /// </summary>
    /// <returns>The daemon.</returns>
    private IEnumerator UpdateAllResources()
    {
        // 重置下载字节数标识
        DownloadedBytes = 0;

        // 获取资源下载地址
        IList abUrls = (IList)ConfigMgr.Get <JsonData> ("ab_urls", null);

        // 没有资源更新地址
        if (abUrls == null || abUrls.Count == 0 || VersionMgr.UpdateResDict.Count == 0)
        {
            // 标识资源更新完成
            isUpdateResOk = true;

            yield break;
        }

        // 抛出开始下载资源事件
        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_UPDATE, ResourceLoadingStateConst.LOAD_STATE_UPDATE);

        // 获取需要更新资源大小
        int totalDownloadBytes = VersionMgr.DownloadSize;
        int downloadedBytes    = 0;
        int idx = 0;

        // 逐个资源下载
        foreach (string fileName in VersionMgr.UpdateResDict.Keys)
        {
            // 获取资源名
            if (string.IsNullOrEmpty(fileName))
            {
                continue;
            }

            // 保证该资源的download成功
            while (true)
            {
                // 如果idx已经超过了abUrls范围修正一下
                if (idx >= abUrls.Count)
                {
                    idx = 0;
                }

                // 创建下载器
                Download download = new Download(
                    string.Format("{0}/{1}", abUrls[idx], fileName),
                    10,
                    ConfigMgr.DOWNLOAD_PATH + fileName);

                Debug.Log(string.Format("下载补丁包 {0}", download.url));

                // 等待获取头部
                download.StartGetResponse();
                while (!download.isGetResponse && !download.isTimeOut && download.error == 0)
                {
                    yield return(null);
                }

                // GetResponse失败,使用新的链接地址重新下载
                if (!download.isGetResponse || download.error != 0 || download.isTimeOut)
                {
                    // 如果是磁盘空间满的情况,直接退出游戏
                    if (download.error == -2)
                    {
                        // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
                        bool isConfirmed = false;
                        //DialogMgr.ShowSimpleSingleBtnDailog(
                        //    new CallBack((para, obj) =>{ isConfirmed = true; }),
                        //    LocalizationMgr.Get("ResourceCheckWnd_8", LocalizationConst.START));

                        // 等到玩家确认
                        while (!isConfirmed)
                        {
                            yield return(null);
                        }

                        // 退出应用
                        Application.Quit();
                        yield break;
                    }

                    idx++;
                    download.Clear();

                    // 等待一会重试
                    yield return(new UnityEngine.WaitForSeconds(0.1f)); // 等待一会重试

                    continue;
                }

                // 开始下载资源
                download.StartDownload();

                // 等待资源下载完成
                while (!download.isDownloaded && !download.isTimeOut && download.error == 0)
                {
                    // 等待0.1s,尽量不要一帧等待
                    yield return(new UnityEngine.WaitForSeconds(0.1f));

                    DownloadedBytes = download.GetTotleDownloadSize() + downloadedBytes;
                    //LoadingMgr.SetProgress (DownloadedBytes/(float)totalDownloadBytes);
                }

                // 如果下载资源失败
                if (download.isTimeOut || download.error != 0)
                {
                    // 如果是磁盘空间满的情况,直接退出游戏
                    if (download.error == -2)
                    {
                        // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
                        bool isConfirmed = false;
                        //DialogMgr.ShowSimpleSingleBtnDailog(
                        //    new CallBack((para, obj) =>{ isConfirmed = true; }),
                        //    LocalizationMgr.Get("ResourceCheckWnd_8", LocalizationConst.START));

                        // 等到玩家确认
                        while (!isConfirmed)
                        {
                            yield return(null);
                        }

                        Application.Quit();
                        yield break;
                    }

                    idx++;
                    download.Clear();

                    NIDebug.Log("{0}响应超时或错误", fileName);
                    continue;
                }

                // 累计下载进度
                downloadedBytes += download.GetTotleDownloadSize();

                NIDebug.Log("downloadedBytes 大小{0},oldLoadedBytes 大小为{1}", download.downloadedBytes, download.oldLoadedBytes);
                NIDebug.Log("已下载总量{0}", downloadedBytes);

                // 释放下载器
                download.Clear();

                // 退出循环
                break;
            }
        }

        // 设定更新总进度
        //LoadingMgr.SetProgress (1.0f);

        //// 等待进度条结束
        //while(!LoadingMgr.IsLoadingEnd(LoadingType.LOAD_TYPE_UPDATE_RES,
        //    ResourceLoadingConst.LOAD_TYPE_UPDATE))
        //    yield return null;

        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_DECOMPRESS, ResourceLoadingStateConst.LOAD_STATE_CHECK);

        //// 切换流程
        //LoadingMgr.ChangeState(ResourceLoadingConst.LOAD_TYPE_DECOMPRESS, ResourceLoadingStateConst.LOAD_STATE_UPDATE);

        // 当前解压缩文件进度
        int    unzipSize     = 0;
        bool   isUnzipFailed = false;
        string targetPath    = ConfigMgr.ASSETBUNDLES_PATH + "/";

        // 资源解压缩
        foreach (string fileName in VersionMgr.UpdateResDict.Keys)
        {
            // 文件名为空
            if (string.IsNullOrEmpty(fileName))
            {
                continue;
            }

            // 构建解压缩
            Unzip zip = new Unzip(
                ConfigMgr.GetLocalRootPathWWW(ConfigMgr.DOWNLOAD_NAME + "/" + fileName),
                targetPath,
                VersionMgr.UpdateResDict[fileName]);

            // 开始解压缩
            zip.Start();

            // 等待解压缩结束
            while (!zip.IsUnziped)
            {
                // 更新进度
                //LoadingMgr.SetProgress((float)(unzipSize + zip.UnzipBytes) / VersionMgr.UnzipSize);
                yield return(null);
            }

            // 累计解压缩数量
            unzipSize += zip.UnzipBytes;
            //LoadingMgr.SetProgress((float)unzipSize / VersionMgr.UnzipSize);

            // 释放zip
            zip.Clear();

            // 回收内存
            DoRecycleGC();

            // 解压缩文件成功
            if (zip.Error == 0)
            {
                // 解压缩成功, 删除补丁文件
                // FileMgr.DeleteFile(ConfigMgr.DOWNLOAD_PATH + "/" + fileName);

                // 更新本地版本文件
                VersionMgr.SyncVersion(VersionMgr.UpdateResDict[fileName]);

                continue;
            }

            // 如果解压缩失败
            /// 0  : 解压缩成功
            /// -1 : 压缩文件载入失败
            /// -2 : 内存分配失败
            /// -3 : 文件写入失败
            /// -4 : 其他异常信息
            string msg = string.Empty;
            //if (zip.Error == -2)
            //    msg = LocalizationMgr.Get("ResourceCheckWnd_22", LocalizationConst.START);
            //else if (zip.Error == -3)
            //    msg = LocalizationMgr.Get("ResourceCheckWnd_8", LocalizationConst.START);

            // 给出提示信息
            if (!string.IsNullOrEmpty(msg))
            {
                // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
                bool isConfirmed = false;
                //DialogMgr.ShowSimpleSingleBtnDailog(new CallBack((para, obj) =>
                //        {
                //            isConfirmed = true;
                //        }), msg);

                // 等到玩家确认
                while (!isConfirmed)
                {
                    yield return(null);
                }

                // 退出游戏
                Application.Quit();
                yield break;
            }

            // 标识有资源解压缩失败
            isUnzipFailed = true;

            // 解压缩成功, 删除补丁文件
            //FileMgr.DeleteFile(ConfigMgr.DOWNLOAD_NAME + "/" + fileName);

            // 给出提示信息
            Debug.Log(string.Format("补丁包{0}结果解压缩{1}", fileName, zip.Error));
        }

        // 如果有资源解压缩失败,需要玩家确认重启游戏重新下载资源
        //if (isUnzipFailed)
        //{
        //    // 弹出窗口玩家让玩家确认一下,玩家确认后等待一下会在重试
        //    bool isConfirmed = false;
        //    DialogMgr.ShowSimpleSingleBtnDailog(new CallBack((para, obj) =>
        //        {
        //            isConfirmed = true;
        //        }), LocalizationMgr.Get("ResourceCheckWnd_9", LocalizationConst.START));

        //    // 等到玩家确认
        //    while (! isConfirmed)
        //        yield return null;

        //    // 退出游戏
        //    Application.Quit();
        //    yield break;
        //}


        //// 等待进度条结束
        //while(!LoadingMgr.IsLoadingEnd(LoadingType.LOAD_TYPE_UPDATE_RES,
        //    ResourceLoadingConst.LOAD_TYPE_DECOMPRESS))
        yield return(null);

        // 标识资源更新完成
        isUpdateResOk = true;
    }
예제 #15
0
 public static SkillData FromConfig(int id)
 {
     return(FromConfig(ConfigMgr.GetInstance().DisassemblygirlSkill.GetConfigById(id)));
 }
예제 #16
0
 void Awake()
 {
     Inst           = this;
     Log.saveToFile = runtimeConfig.saveToFile;
 }
예제 #17
0
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(onError);
            Console.CancelKeyPress += new ConsoleCancelEventHandler(OnClose);

            Log.Info("", "-------------------- World Server ---------------------", ConsoleColor.DarkRed);

            // Default the server to DEV mode.
            if (args.Length == 0)
            {
                WorldMgr.ServerMode = "DEV";
            }
            else
            {
                if (args.Length == 1)
                {
                    if (args[0] == "DEV")
                    {
                        WorldMgr.ServerMode = "DEV";
                    }
                    if (args[0] == "PRD")
                    {
                        WorldMgr.ServerMode = "PRD";
                    }
                }
                else
                {
                    WorldMgr.ServerMode = "DEV";
                }
            }

            Log.Info("", "SERVER running in " + WorldMgr.ServerMode + " mode", ConsoleColor.Cyan);


            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <WorldConfigs>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "WorldServer"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

#if DEBUG
            API.Server api = null;
            if (Config.EnableAPI)
            {
                try
                {
                    api = new API.Server(Config.APIAddress, Config.APIPort, 100);
                }
                catch (Exception e)
                {
                    Log.Error("API", "Unable to start API server: " + e.Message);
                }
            }
#endif

            CharMgr.Database = DBManager.Start(Config.CharacterDatabase.Total(), Config.CharacterDatabase.ConnectionType, "Characters", Config.CharacterDatabase.Database);
            if (CharMgr.Database == null)
            {
                ConsoleMgr.WaitAndExit(2000);
            }
            else if (!Config.PreloadAllCharacters)
            {
                CharMgr.Database.RegisterAction(CharMgr.LoadPendingCharacters);
            }

            _timer = new Timer(AuctionHouse.CheckAuctionExpiry, null, new TimeSpan(0, 12, 0, 0), new TimeSpan(0, 24, 0, 0));

            WorldMgr.Database = DBManager.Start(Config.WorldDatabase.Total(), Config.CharacterDatabase.ConnectionType, "World", Config.WorldDatabase.Database);
            if (WorldMgr.Database == null)
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            WorldMgr.StartingPairing = WorldMgr.Database.ExecuteQueryInt("SELECT FLOOR(RAND() * 3) + 1");

            // Ensure directory structure is correct
            if (!Directory.Exists("Zones"))
            {
                Log.Error("Directory Check", "Zones directory does not exist");
                ConsoleMgr.WaitAndExit(2000);
            }
            if (!Directory.Exists("Scripts"))
            {
                Log.Error("Directory Check", "Scripts directory does not exist");
                ConsoleMgr.WaitAndExit(2000);
            }
            if (!Directory.Exists("World"))
            {
                Log.Error("Directory Check", "World directory does not exist");
                ConsoleMgr.WaitAndExit(2000);
            }
            if (!Directory.Exists("Abilities"))
            {
                Log.Error("Directory Check", "Abilities directory does not exist");
                ConsoleMgr.WaitAndExit(2000);
            }



            Client = new RpcClient("WorldServer-" + Config.RealmId, Config.AccountCacherInfo.RpcLocalIp, 1);
            if (!Client.Start(Config.AccountCacherInfo.RpcServerIp, Config.AccountCacherInfo.RpcServerPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Rm = AcctMgr.GetRealm(Config.RealmId);

            if (Rm == null)
            {
                Log.Error("WorldServer", "Realm (" + Config.RealmId + ") not found");
                return;
            }

            LoaderMgr.Start();
            // Clean up rvr_metrics
            Log.Info("Battlefront Manager", "Clearing rvr_metrics", ConsoleColor.Cyan);
            WorldMgr.Database.ExecuteNonQuery("DELETE FROM rvr_metrics WHERE TIMESTAMP NOT BETWEEN DATE_SUB(UTC_TIMESTAMP(), INTERVAL 60 DAY) AND UTC_TIMESTAMP()");

            Log.Info("Battlefront Manager", "Creating Upper Tier Campaign Manager", ConsoleColor.Cyan);
            if (RVRProgressionService._RVRProgressions.Count == 0)
            {
                Log.Error("RVR Progression", "NO RVR Progressions in DB");
                return;
            }
            WorldMgr.UpperTierCampaignManager = new UpperTierCampaignManager(RVRProgressionService._RVRProgressions.Where(x => x.Tier == 4).ToList(), WorldMgr._Regions);
            Log.Info("Battlefront Manager", "Creating Lower Tier Campaign Manager", ConsoleColor.Cyan);
            WorldMgr.LowerTierCampaignManager = new LowerTierCampaignManager(RVRProgressionService._RVRProgressions.Where(x => x.Tier == 1).ToList(), WorldMgr._Regions);
            Log.Info("Battlefront Manager", "Getting Progression based upon rvr_progression.LastOpenedZone", ConsoleColor.Cyan);
            WorldMgr.UpperTierCampaignManager.GetActiveBattleFrontFromProgression();
            WorldMgr.LowerTierCampaignManager.GetActiveBattleFrontFromProgression();
            Log.Info("Battlefront Manager", "Attaching Campaigns to Regions", ConsoleColor.Cyan);
            // Attach Battlefronts to regions
            WorldMgr.AttachCampaignsToRegions();

            Log.Info("Battlefront Manager", "Locking Battlefronts", ConsoleColor.Cyan);
            WorldMgr.UpperTierCampaignManager.LockBattleFrontsAllRegions(4);
            WorldMgr.LowerTierCampaignManager.LockBattleFrontsAllRegions(1);

            Log.Info("Battlefront Manager", "Opening Active battlefronts", ConsoleColor.Cyan);
            WorldMgr.UpperTierCampaignManager.OpenActiveBattlefront();
            WorldMgr.LowerTierCampaignManager.OpenActiveBattlefront();

            WorldMgr.UpdateRegionCaptureStatus(WorldMgr.LowerTierCampaignManager, WorldMgr.UpperTierCampaignManager);

            if (!TCPManager.Listen <TCPServer>(Rm.Port, "World"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            Server = TCPManager.GetTcp <TCPServer>("World");

            AcctMgr.UpdateRealm(Client.Info, Rm.RealmId);
            AcctMgr.UpdateRealmCharacters(Rm.RealmId, (uint)CharMgr.Database.GetObjectCount <Character>("Realm=1"), (uint)CharMgr.Database.GetObjectCount <Character>("Realm=2"));

            ConsoleMgr.Start();
        }
예제 #18
0
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (new_form_tab != null && new_form_tab.IsSelected && isSourceFromOtherTab)
                {
                    isSourceFromOtherTab = false;
                }
                else if (new_form_tab != null && new_form_tab.IsSelected && e.Source.GetType() == typeof(TabControl))
                {
                    ClearNewClientFormTab();
                    case_owner.ItemsSource = Enums.CaseOwners;
                    case_type.ItemsSource  = CaseDetails.CaseTypes;
                    court_name.ItemsSource = Enums.CourtsNames;
                }
                else if (check_list_tab != null && check_list_tab.IsSelected && e.Source.GetType() == typeof(TabControl))
                {
                    // TODO: on select tab
                }
                else if (clients_status_tab != null && clients_status_tab.IsSelected && e.Source.GetType() == typeof(TabControl))
                {
                    IClientDAO    clientDAO = new ClientFileDAO(new ConfigMgr());
                    List <Client> clients   = clientDAO.GetClients();

                    Predicate <object> allClientDefaultFilter = new Predicate <object>(item => (true));
                    UpdateDataGridItems <Client>(clients_status_DataGrid, clients, allClientDefaultFilter);

                    clients_status_cell.ItemsSource = Enums.CaseStatuses;

                    clients_status_filter_case_owner.ItemsSource = new string[] { "הכל" }.Concat(Enums.CaseOwners);
                    clients_status_filter_case_type.ItemsSource  = new string[] { "הכל" }.Concat(CaseDetails.CaseTypes);
                }
                else if (working_schedule_search_grid_tab != null && working_schedule_search_grid_tab.IsSelected && e.Source.GetType() == typeof(TabControl))
                {
                    IClientDAO            clientDAO = new ClientFileDAO(new ConfigMgr());
                    List <Client>         clients   = clientDAO.GetClients();
                    IEnumerable <dynamic> clientsWorkingReportDataGrid = getWorkPropertiesDatagrid(clients);
                    UpdateDataGridItems(clients_working_data_grid, clientsWorkingReportDataGrid, new Predicate <object>(x => true));
                    clients_working_grid_search_case_owner.ItemsSource = new string[] { "הכל" }.Concat(Enums.CaseOwners);
                }
                else if (dashboard_tab != null && dashboard_tab.IsSelected && e.Source.GetType() == typeof(TabControl))
                {
                    IClientDAO    clientDAO = new ClientFileDAO(new ConfigMgr());
                    List <Client> clients   = clientDAO.GetClients();

                    dashboard_chart_by_owner.ItemsSource = clients.GroupBy(client => client.ContactForm.CaseOwnerValue)
                                                           .Select(group => new
                    {
                        Metric = group.Key,
                        Count  = group.Count()
                    });
                    dashboard_chart_by_status.ItemsSource = clients.GroupBy(client => client.StatusValue)
                                                            .Select(group => new
                    {
                        Metric = group.Key,
                        Count  = group.Count()
                    });
                    dashboard_chart_by_create_time.ItemsSource = clients.Where(client => client.ContactForm.CreationDate.Year == DateTime.Now.Year).GroupBy(client => $"{client.ContactForm.CreationDate:MM/yyyy}")
                                                                 .Select(group => new
                    {
                        Metric = group.Key,
                        Count  = group.Count()
                    }).OrderBy((group) =>
                    {
                        CultureInfo provider = CultureInfo.InvariantCulture;
                        return(DateTime.ParseExact(group.Metric, "MM/yyyy", CultureInfo.InvariantCulture));
                    });
                    dashboard_chart_by_case_type.ItemsSource = clients.GroupBy(client => client.ContactForm.CaseInfo.CaseTypeValue)
                                                               .Select(group => new
                    {
                        Metric = group.Key,
                        Count  = group.Count()
                    });
                }
                else if (settings_tab != null && settings_tab.IsSelected && e.Source.GetType() == typeof(TabControl))
                {
                    ConfigMgr configMgr = new ConfigMgr();
                    destenation_folder.Text        = configMgr.GetDestenationPath();
                    clients_archive_file_path.Text = configMgr.GetClientArchivePathPath();
                    system_version_name.Text       = $"גרסת מערכת: {configMgr.GetSystemVersionName()}";
                    case_owners_edit_list.Text     = string.Join(',', Enums.CaseOwners);
                }
            }
            catch (FileNotFoundException)
            {
                DisplaySnackbar("הקובץ לקוחות לא נמצא, בדוק בהגדרות מערכת את ההגדרות שלך");
            }
            catch (Exception ex)
            {
                DisplaySnackbar("שגיאה כללית במערכת, אנא נסה שוב");
                Logger log = new Logger(new ConfigMgr());
                log.Error("general error on load tab", ex);
            }
        }
예제 #19
0
        public void HandleLoginRequest(HttpHeader request)
        {
            LogonData   loginForm   = Json.CreateObject <LogonData>(request.Content);
            LogonResult loginResult = new LogonResult();

            if (loginForm == null)
            {
                loginResult.AuthenticationState = "LOGIN";
                loginResult.ErrorCode           = "UNABLE_TO_DECODE";
                loginResult.ErrorMessage        = "There was an internal error while connecting to Battle.net. Please try again later.";
                SendResponse(HttpCode.BadRequest, loginResult);
                return;
            }

            string login    = "";
            string password = "";

            for (int i = 0; i < loginForm.Inputs.Count; ++i)
            {
                switch (loginForm.Inputs[i].Id)
                {
                case "account_name":
                    login = loginForm.Inputs[i].Value;
                    break;

                case "password":
                    password = loginForm.Inputs[i].Value;
                    break;
                }
            }

            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_AUTHENTICATION);

            stmt.AddValue(0, login);

            SQLResult result = DB.Login.Query(stmt);

            if (!result.IsEmpty())
            {
                uint   accountId         = result.Read <uint>(0);
                string pass_hash         = result.Read <string>(1);
                uint   failedLogins      = result.Read <uint>(2);
                string loginTicket       = result.Read <string>(3);
                uint   loginTicketExpiry = result.Read <uint>(4);
                bool   isBanned          = result.Read <ulong>(5) != 0;

                if (CalculateShaPassHash(login, password) == pass_hash)
                {
                    if (loginTicket.IsEmpty() || loginTicketExpiry < Time.UnixTime)
                    {
                        byte[] ticket = new byte[0].GenerateRandomKey(20);
                        loginTicket = "TC-" + ticket.ToHexString();
                    }

                    stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_AUTHENTICATION);
                    stmt.AddValue(0, loginTicket);
                    stmt.AddValue(1, Time.UnixTime + 3600);
                    stmt.AddValue(2, accountId);

                    DB.Login.Execute(stmt);
                    loginResult.LoginTicket = loginTicket;
                }
                else if (!isBanned)
                {
                    uint maxWrongPassword = ConfigMgr.GetDefaultValue("WrongPass.MaxCount", 0u);

                    if (ConfigMgr.GetDefaultValue("WrongPass.Logging", false))
                    {
                        Log.outDebug(LogFilter.Network, "[{0}, Account {1}, Id {2}] Attempted to connect with wrong password!", request.Host, login, accountId);
                    }

                    if (maxWrongPassword != 0)
                    {
                        SQLTransaction trans = new SQLTransaction();
                        stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_FAILED_LOGINS);
                        stmt.AddValue(0, accountId);
                        trans.Append(stmt);

                        ++failedLogins;

                        Log.outDebug(LogFilter.Network, "MaxWrongPass : {0}, failed_login : {1}", maxWrongPassword, accountId);

                        if (failedLogins >= maxWrongPassword)
                        {
                            BanMode banType = ConfigMgr.GetDefaultValue("WrongPass.BanType", BanMode.Ip);
                            int     banTime = ConfigMgr.GetDefaultValue("WrongPass.BanTime", 600);

                            if (banType == BanMode.Account)
                            {
                                stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_BNET_ACCOUNT_AUTO_BANNED);
                                stmt.AddValue(0, accountId);
                            }
                            else
                            {
                                stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_IP_AUTO_BANNED);
                                stmt.AddValue(0, request.Host);
                            }

                            stmt.AddValue(1, banTime);
                            trans.Append(stmt);

                            stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_RESET_FAILED_LOGINS);
                            stmt.AddValue(0, accountId);
                            trans.Append(stmt);
                        }

                        DB.Login.CommitTransaction(trans);
                    }
                }

                loginResult.AuthenticationState = "DONE";
                SendResponse(HttpCode.Ok, loginResult);
            }
            else
            {
                loginResult.AuthenticationState = "LOGIN";
                loginResult.ErrorCode           = "UNABLE_TO_DECODE";
                loginResult.ErrorMessage        = "There was an internal error while connecting to Battle.net. Please try again later.";
                SendResponse(HttpCode.BadRequest, loginResult);
            }
        }
예제 #20
0
        //udp socket 回调函数,接收客户端数据,把数据放到消息队列等待处理
        static void server_OnDataReceived(object sender, AsyncSocketUDPEventArgs e)
        {
            string card = ConfigMgr.byteToHexStr(e._state.buffer, 7);

            BusinessInfoHelper.Instance.AddQueue(card, (e._state.remote as IPEndPoint));
        }
예제 #21
0
        static void Main()
        {
            Console.CancelKeyPress += (o, e) => Global.WorldMgr.StopNow(ShutdownExitCode.Shutdown);

            if (!ConfigMgr.Load(System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".conf"))
            {
                ExitNow();
            }

            var WorldSocketMgr = new WorldSocketManager();

            if (!StartDB())
            {
                ExitNow();
            }

            // set server offline (not connectable)
            DB.Login.Execute("UPDATE realmlist SET flag = (flag & ~{0}) | {1} WHERE id = '{2}'", (uint)RealmFlags.VersionMismatch, (uint)RealmFlags.Offline, Global.WorldMgr.GetRealm().Id.Realm);

            Global.RealmMgr.Initialize(ConfigMgr.GetDefaultValue("RealmsStateUpdateDelay", 10));

            Global.WorldMgr.SetInitialWorldSettings();

            // Launch the worldserver listener socket
            int    worldPort     = WorldConfig.GetIntValue(WorldCfg.PortWorld);
            string worldListener = ConfigMgr.GetDefaultValue("BindIP", "0.0.0.0");

            int networkThreads = ConfigMgr.GetDefaultValue("Network.Threads", 1);

            if (networkThreads <= 0)
            {
                Log.outError(LogFilter.Server, "Network.Threads must be greater than 0");
                ExitNow();
                return;
            }

            if (!WorldSocketMgr.StartNetwork(worldListener, worldPort, networkThreads))
            {
                Log.outError(LogFilter.Network, "Failed to start Realm Network");
                ExitNow();
            }

            // set server online (allow connecting now)
            DB.Login.Execute("UPDATE realmlist SET flag = flag & ~{0}, population = 0 WHERE id = '{1}'", (uint)RealmFlags.Offline, Global.WorldMgr.GetRealm().Id.Realm);
            Global.WorldMgr.GetRealm().PopulationLevel = 0.0f;
            Global.WorldMgr.GetRealm().Flags           = Global.WorldMgr.GetRealm().Flags & ~RealmFlags.VersionMismatch;

            //Set Culture
            CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;

            //- Launch CliRunnable thread
            if (ConfigMgr.GetDefaultValue("Console.Enable", true))
            {
                Thread commandThread = new Thread(CommandManager.InitConsole);
                commandThread.Start();
            }

            WorldUpdateLoop();

            try
            {
                // Shutdown starts here
                Global.WorldMgr.KickAll();                                     // save and kick all players
                Global.WorldMgr.UpdateSessions(1);                             // real players unload required UpdateSessions call

                // unload Battlegroundtemplates before different singletons destroyed
                Global.BattlegroundMgr.DeleteAllBattlegrounds();

                WorldSocketMgr.StopNetwork();

                Global.MapMgr.UnloadAll();                     // unload all grids (including locked in memory)
                Global.ScriptMgr.Unload();

                // set server offline
                DB.Login.Execute("UPDATE realmlist SET flag = flag | {0} WHERE id = '{1}'", (uint)RealmFlags.Offline, Global.WorldMgr.GetRealm().Id.Realm);
                Global.RealmMgr.Close();

                ClearOnlineAccounts();

                ExitNow();
            }
            catch (Exception ex)
            {
                Log.outException(ex);
            }
        }
예제 #22
0
        public ExportCSV(ConfigMgr configMgr, string fileName, CSVExportType exportType)
        {
            string fileSuffix = exportType == CSVExportType.SCHEDULE_WORKING ? "working_schedule" : "clients";

            targetPath = $"{configMgr.GetDestenationPath()}/{fileName}_{fileSuffix}.csv";
        }
예제 #23
0
        static void Main(string[] args)
        {
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", "          _____   _____ ", ConsoleColor.Cyan);
            Log.Texte("", "    /\\   |  __ \\ / ____|", ConsoleColor.Cyan);
            Log.Texte("", "   /  \\  | |__) | (___  ", ConsoleColor.Cyan);
            Log.Texte("", "  / /\\ \\ |  ___/ \\___ \\ ", ConsoleColor.Cyan);
            Log.Texte("", " / ____ \\| |     ____) |", ConsoleColor.Cyan);
            Log.Texte("", "/_/    \\_\\_|    |_____/ APB-Lobby", ConsoleColor.Cyan);
            Log.Texte("", "http://AllPrivateServer.com", ConsoleColor.DarkCyan);
            Log.Texte("", "-------------------------------", ConsoleColor.DarkBlue);

            Log.Info("LobbyServer", "Starting ...");

            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <LobbyServerConfig>();

            if (!Log.InitLog(Config.LogLevel, "LobbyServer"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            FileServerClient = new RpcClient("LobbyServer-File", Config.FileServerRpc.RpcLocalIp, 1);
            if (!FileServerClient.Start(Config.FileServerRpc.RpcServerIp, Config.FileServerRpc.RpcServerPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            CharacterServerClient = new RpcClient("LobbyServer-Char", Config.CharacterServerRpc.RpcLocalIp, 0);
            if (!CharacterServerClient.Start(Config.CharacterServerRpc.RpcServerIp, Config.CharacterServerRpc.RpcServerPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            if (!TCPManager.Listen <TcpServer>(Config.ClientServerPort, "Lobby"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            CharMgr = CharacterServerClient.GetServerObject <CharacterMgr>();
            FileMgr = FileServerClient.GetServerObject <FileManager>();

            DBAccount Acct = CharMgr.GetAccount(1);

            string[] sVersion = Config.ClientVersion.Split('.');
            Build = Config.ClientBuild;

            Version = new byte[sVersion.Length];

            for (int i = 0; i < Version.Length; ++i)
            {
                Version[i] = byte.Parse(sVersion[i]);
            }

            Log.Info("LobbyServer", "Version = " + Version[0] + "." + Version[1] + "." + Version[2] + " : Build = " + Build);


            Log.Success("LobbyServer", "Server loaded.");

            ConsoleMgr.Start();
        }
예제 #24
0
파일: Program.cs 프로젝트: harpernz/RiftEMU
        static void Main(string[] args)
        {
            Log.Texte("", "---------------------------------------------------------------", ConsoleColor.DarkBlue);
            Log.Texte("", " _______ _________ _______ _________ _______  _______          ", ConsoleColor.Cyan);
            Log.Texte("", "(  ____ )\__   __/(  ____ \\__   __/(  ____ \(       )|\     /|", ConsoleColor.Cyan);
            Log.Texte("", "| (    )|   ) (   | (    \/   ) (   | (    \/| () () || )   ( |", ConsoleColor.Cyan);
            Log.Texte("", "| (____)|   | |   | (__       | |   | (__    | || || || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "|     __)   | |   |  __)      | |   |  __)   | |(_)| || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "| (\ (      | |   | (         | |   | (      | |   | || |   | |", ConsoleColor.Cyan);
            Log.Texte("", "| ) \ \_____) (___| )         | |   | (____/\| )   ( || (___) |", ConsoleColor.Cyan);
            Log.Texte("", "|/   \__/\_______/|/          )_(   (_______/|/     \|(_______)", ConsoleColor.Cyan);
            Log.Texte("", "www.Strawberry-Pr0jcts.com", ConsoleColor.DarkCyan);
            Log.Texte("", "---------------------------------------------------------------", ConsoleColor.DarkBlue);

            // Loading all configs files
            ConfigMgr.LoadConfigs();
            Config = ConfigMgr.GetConfig <MapConfig>();

            // Loading log level from file
            if (!Log.InitLog(Config.LogLevel, "Map"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }


            FileStream Str = File.Open("player.cache", FileMode.Open);

            BuildPlayer = new byte[Str.Length];
            Str.Read(BuildPlayer, 0, BuildPlayer.Length);

            /*// Listening Client
             * if (!TCPManager.Listen<RiftServer>(Config.ServerInfo.MapPort, "CharacterServer"))
             *  ConsoleMgr.WaitAndExit(2000);
             *
             * PacketInStream Entity = new PacketInStream(BuildPlayer,BuildPlayer.Length);
             * WorldEntityUpdate Update = PacketProcessor.ReadPacket(ref Entity) as WorldEntityUpdate;
             * Log.Info("Entity", "GUID = " + Update.GUID + " List Lengh = " + Update.Field1.Count);
             * Console.ReadKey();
             * Environment.Exit(0);*/

            // Starting Remote Client
            Client = new RpcClient("Map-" + Config.ServerInfo.MapAdress, Config.ClientInfo.RpcLocalIp, 2);
            if (!Client.Start(Config.ClientInfo.RpcServerIp, Config.ClientInfo.RpcServerPort))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            // Listening Client
            if (!TCPManager.Listen <RiftServer>(Config.ServerInfo.MapPort, "CharacterServer"))
            {
                ConsoleMgr.WaitAndExit(2000);
            }

            MapMgr.Client          = Client;
            MapMgr.MapInfo         = Config.ServerInfo;
            MapMgr.MapInfo.RpcInfo = Client.Info;
            Rm = Client.GetServerObject <CharactersMgr>().GetRealm();

            Log.Success("Realm", "Connected to : " + Rm.Name);

            World.RegisterMaps(Config.ServerInfo, Client.Info);

            ConsoleMgr.Start();
        }
예제 #25
0
 public DatabaseLoader(DatabaseTypeFlags defaultUpdateMask)
 {
     _autoSetup   = ConfigMgr.GetDefaultValue("Updates.AutoSetup", true);
     _updateFlags = ConfigMgr.GetDefaultValue("Updates.EnableDatabases", defaultUpdateMask);
 }
예제 #26
0
 private Config_func()
 {
     bLastNight  = Convert.ToBoolean(ConfigMgr.GetAppConfig("LastNight"));
     bStrictTime = Convert.ToBoolean(ConfigMgr.GetAppConfig("StrictTime"));
 }
예제 #27
0
 string GetSourceDirectory()
 {
     return(ConfigMgr.GetDefaultValue("Updates.SourcePath", "../../../"));
 }
예제 #28
0
        public void HandleLoginRequest(HttpHeader request)
        {
            LogonData   loginForm   = Json.CreateObject <LogonData>(request.Content);
            LogonResult loginResult = new LogonResult();

            if (loginForm == null)
            {
                loginResult.AuthenticationState = "LOGIN";
                loginResult.ErrorCode           = "UNABLE_TO_DECODE";
                loginResult.ErrorMessage        = "There was an internal error while connecting to Battle.net. Please try again later.";
                SendResponse(HttpCode.BadRequest, loginResult);
                return;
            }

            string login    = "";
            string password = "";

            for (int i = 0; i < loginForm.Inputs.Count; ++i)
            {
                switch (loginForm.Inputs[i].Id)
                {
                case "account_name":
                    login = loginForm.Inputs[i].Value;
                    break;

                case "password":
                    password = loginForm.Inputs[i].Value;
                    break;
                }
            }

            PreparedStatement stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_ACCOUNT_INFO);

            stmt.AddValue(0, login);

            SQLResult result = DB.Login.Query(stmt);

            if (result.IsEmpty())
            {
                loginResult.AuthenticationState = "LOGIN";
                loginResult.ErrorCode           = "UNABLE_TO_DECODE";
                loginResult.ErrorMessage        = "There was an internal error while connecting to Battle.net. Please try again later.";
                SendResponse(HttpCode.BadRequest, loginResult);

                return;
            }

            string pass_hash = result.Read <string>(13);

            var accountInfo = new AccountInfo();

            accountInfo.LoadResult(result);

            if (CalculateShaPassHash(login, password) == pass_hash)
            {
                stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_CHARACTER_COUNTS_BY_BNET_ID);
                stmt.AddValue(0, accountInfo.Id);

                SQLResult characterCountsResult = DB.Login.Query(stmt);
                if (!characterCountsResult.IsEmpty())
                {
                    do
                    {
                        accountInfo.GameAccounts[characterCountsResult.Read <uint>(0)]
                        .CharacterCounts[new RealmHandle(characterCountsResult.Read <byte>(3), characterCountsResult.Read <byte>(4), characterCountsResult.Read <uint>(2)).GetAddress()] = characterCountsResult.Read <byte>(1);
                    } while (characterCountsResult.NextRow());
                }


                stmt = DB.Login.GetPreparedStatement(LoginStatements.SEL_BNET_LAST_PLAYER_CHARACTERS);
                stmt.AddValue(0, accountInfo.Id);

                SQLResult lastPlayerCharactersResult = DB.Login.Query(stmt);
                if (!lastPlayerCharactersResult.IsEmpty())
                {
                    RealmHandle realmId = new RealmHandle(lastPlayerCharactersResult.Read <byte>(1), lastPlayerCharactersResult.Read <byte>(2), lastPlayerCharactersResult.Read <uint>(3));

                    LastPlayedCharacterInfo lastPlayedCharacter = new LastPlayedCharacterInfo();
                    lastPlayedCharacter.RealmId        = realmId;
                    lastPlayedCharacter.CharacterName  = lastPlayerCharactersResult.Read <string>(4);
                    lastPlayedCharacter.CharacterGUID  = lastPlayerCharactersResult.Read <ulong>(5);
                    lastPlayedCharacter.LastPlayedTime = lastPlayerCharactersResult.Read <uint>(6);

                    accountInfo.GameAccounts[lastPlayerCharactersResult.Read <uint>(0)].LastPlayedCharacters[realmId.GetSubRegionAddress()] = lastPlayedCharacter;
                }

                byte[] ticket = new byte[0].GenerateRandomKey(20);
                loginResult.LoginTicket = "TC-" + ticket.ToHexString();

                Global.SessionMgr.AddLoginTicket(loginResult.LoginTicket, accountInfo);
            }
            else if (!accountInfo.IsBanned)
            {
                uint maxWrongPassword = ConfigMgr.GetDefaultValue("WrongPass.MaxCount", 0u);

                if (ConfigMgr.GetDefaultValue("WrongPass.Logging", false))
                {
                    Log.outDebug(LogFilter.Network, "[{0}, Account {1}, Id {2}] Attempted to connect with wrong password!", request.Host, login, accountInfo.Id);
                }

                if (maxWrongPassword != 0)
                {
                    SQLTransaction trans = new SQLTransaction();
                    stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_FAILED_LOGINS);
                    stmt.AddValue(0, accountInfo.Id);
                    trans.Append(stmt);

                    ++accountInfo.FailedLogins;

                    Log.outDebug(LogFilter.Network, "MaxWrongPass : {0}, failed_login : {1}", maxWrongPassword, accountInfo.Id);

                    if (accountInfo.FailedLogins >= maxWrongPassword)
                    {
                        BanMode banType = ConfigMgr.GetDefaultValue("WrongPass.BanType", BanMode.Ip);
                        int     banTime = ConfigMgr.GetDefaultValue("WrongPass.BanTime", 600);

                        if (banType == BanMode.Account)
                        {
                            stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_BNET_ACCOUNT_AUTO_BANNED);
                            stmt.AddValue(0, accountInfo.Id);
                        }
                        else
                        {
                            stmt = DB.Login.GetPreparedStatement(LoginStatements.INS_IP_AUTO_BANNED);
                            stmt.AddValue(0, request.Host);
                        }

                        stmt.AddValue(1, banTime);
                        trans.Append(stmt);

                        stmt = DB.Login.GetPreparedStatement(LoginStatements.UPD_BNET_RESET_FAILED_LOGINS);
                        stmt.AddValue(0, accountInfo.Id);
                        trans.Append(stmt);
                    }

                    DB.Login.CommitTransaction(trans);
                }
            }

            loginResult.AuthenticationState = "DONE";
            SendResponse(HttpCode.Ok, loginResult);
        }
예제 #29
0
        //private readonly string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

        public DocxGenerator(ContactFormPerson contactForm, ConfigMgr configMgr)
        {
            contactFormPerson = contactForm;
            targetPath        = configMgr.GetDestenationPath();
        }
예제 #30
0
        static bool PLimit(StringArguments args, CommandHandler handler)
        {
            if (!args.Empty())
            {
                string paramStr = args.NextString();
                if (string.IsNullOrEmpty(paramStr))
                {
                    return(false);
                }

                switch (paramStr.ToLower())
                {
                case "player":
                    Global.WorldMgr.SetPlayerSecurityLimit(AccountTypes.Player);
                    break;

                case "moderator":
                    Global.WorldMgr.SetPlayerSecurityLimit(AccountTypes.Moderator);
                    break;

                case "gamemaster":
                    Global.WorldMgr.SetPlayerSecurityLimit(AccountTypes.GameMaster);
                    break;

                case "administrator":
                    Global.WorldMgr.SetPlayerSecurityLimit(AccountTypes.Administrator);
                    break;

                case "reset":
                    Global.WorldMgr.SetPlayerAmountLimit(ConfigMgr.GetDefaultValue <uint>("PlayerLimit", 100));
                    Global.WorldMgr.LoadDBAllowedSecurityLevel();
                    break;

                default:
                    if (!int.TryParse(paramStr, out int value))
                    {
                        return(false);
                    }

                    if (value < 0)
                    {
                        Global.WorldMgr.SetPlayerSecurityLimit((AccountTypes)(-value));
                    }
                    else
                    {
                        Global.WorldMgr.SetPlayerAmountLimit((uint)value);
                    }
                    break;
                }
            }

            uint         playerAmountLimit  = Global.WorldMgr.GetPlayerAmountLimit();
            AccountTypes allowedAccountType = Global.WorldMgr.GetPlayerSecurityLimit();
            string       secName            = "";

            switch (allowedAccountType)
            {
            case AccountTypes.Player:
                secName = "Player";
                break;

            case AccountTypes.Moderator:
                secName = "Moderator";
                break;

            case AccountTypes.GameMaster:
                secName = "Gamemaster";
                break;

            case AccountTypes.Administrator:
                secName = "Administrator";
                break;

            default:
                secName = "<unknown>";
                break;
            }
            handler.SendSysMessage("Player limits: amount {0}, min. security level {1}.", playerAmountLimit, secName);

            return(true);
        }