public void Initialize() { TShock.Config = new ConfigFile(); TShock.Config.StorageType = "sqlite"; DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", "tshock.test.sqlite")); DB.Open(); Bans = new BanManager(DB); }
public override void Initialize() { if (!Directory.Exists(SavePath)) { Directory.CreateDirectory(SavePath); } #if DEBUG Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All, false); #else Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All & ~LogLevel.Debug, false); #endif AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; try { if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) { Log.ConsoleInfo("TShock was improperly shut down. Deleting invalid pid file..."); File.Delete(Path.Combine(SavePath, "tshock.pid")); } File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString()); ConfigFile.ConfigRead += OnConfigRead; FileTools.SetupConfig(); HandleCommandLine(Environment.GetCommandLineArgs()); if (Config.StorageType.ToLower() == "sqlite") { string sql = Path.Combine(SavePath, "tshock.sqlite"); DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); } else if (Config.StorageType.ToLower() == "mysql") { try { var hostport = Config.MySqlHost.Split(':'); DB = new MySqlConnection(); DB.ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", hostport[0], hostport.Length > 1 ? hostport[1] : "3306", Config.MySqlDbName, Config.MySqlUsername, Config.MySqlPassword ); } catch (MySqlException ex) { Log.Error(ex.ToString()); throw new Exception("MySql not setup correctly"); } } else { throw new Exception("Invalid storage type"); } Backups = new BackupManager(Path.Combine(SavePath, "backups")); Backups.KeepFor = Config.BackupKeepFor; Backups.Interval = Config.BackupInterval; Bans = new BanManager(DB); Warps = new WarpManager(DB); Users = new UserManager(DB); Groups = new GroupManager(DB); Groups.LoadPermisions(); Regions = new RegionManager(DB); Itembans = new ItemManager(DB); RememberedPos = new RemeberedPosManager(DB); RestApi = new SecureRest(Netplay.serverListenIP, 8080); RestApi.Verify += RestApi_Verify; RestApi.Port = Config.RestApiPort; RestManager = new RestManager(RestApi); RestManager.RegisterRestfulCommands(); var geoippath = Path.Combine(SavePath, "GeoIP.dat"); if (Config.EnableGeoIP && File.Exists(geoippath)) { Geo = new MaxMind.GeoIPCountry(geoippath); } Log.ConsoleInfo(string.Format("TShock Version {0} ({1}) now running.", Version, VersionCodename)); GameHooks.PostInitialize += OnPostInit; GameHooks.Update += OnUpdate; ServerHooks.Join += OnJoin; ServerHooks.Leave += OnLeave; ServerHooks.Chat += OnChat; ServerHooks.Command += ServerHooks_OnCommand; NetHooks.GetData += OnGetData; NetHooks.SendData += NetHooks_SendData; NetHooks.GreetPlayer += OnGreetPlayer; NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); //RconHandler.StartThread(); if (Config.BufferPackets) { PacketBuffer = new PacketBufferer(); } Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); if (Initialized != null) { Initialized(); } } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); Environment.Exit(1); } }
private bool TCPCmdPacketEvent(object sender, int doType) { TCPInPacket tcpInPacket = sender as TCPInPacket; if (0 == doType) { int thisTimeCheckTicks = 0; int checkErrorCode = 0; byte[] bytesData = this.CheckClientDataValid((int)tcpInPacket.PacketCmdID, tcpInPacket.GetPacketBytes(), tcpInPacket.PacketDataSize, tcpInPacket.LastCheckTicks, out thisTimeCheckTicks, out checkErrorCode); if (null == bytesData) { TMSKSocket _s = tcpInPacket.CurrentSocket; string uid = (_s != null) ? GameManager.OnlineUserSession.FindUserID(_s) : "socket is nil"; LogManager.WriteLog(LogTypes.Error, string.Format("校验客户端发送的指令数据完整性失败: {0},{1}, 错误码:{2}, uid={3}, 关闭连接", new object[] { (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket, false), checkErrorCode, uid }), null, true); return(false); } tcpInPacket.LastCheckTicks = thisTimeCheckTicks; tcpInPacket.CurrentSocket.ClientCmdSecs = thisTimeCheckTicks; TCPSession session = null; if (null != tcpInPacket.CurrentSocket) { session = tcpInPacket.CurrentSocket.session; } if (null == session) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket, false), checkErrorCode), null, true); return(false); } int posCmdNum = 0; session.CheckCmdNum((int)tcpInPacket.PacketCmdID, (long)thisTimeCheckTicks, out posCmdNum); if (posCmdNum > 0) { int banSpeedUpMinutes = GameManager.PlatConfigMgr.GetGameConfigItemInt("ban-speed-up-minutes2", 10); GameClient client = GameManager.ClientMgr.FindClient(tcpInPacket.CurrentSocket); if (null != client) { if (GameManager.PlatConfigMgr.GetGameConfigItemInt("ban_speed_up_delay", 0) == 0 || client.CheckCheatData.ProcessBooster) { GameManager.ClientMgr.NotifyImportantMsg(this.MySocketListener, this.tcpOutPacketPool, client, StringUtil.substitute(GLang.GetLang(663, new object[0]), new object[] { banSpeedUpMinutes }), GameInfoTypeIndexes.Error, ShowGameInfoTypes.HintAndBox, 0); BanManager.BanRoleName(Global.FormatRoleName(client, client.ClientData.RoleName), banSpeedUpMinutes, 1); LogManager.WriteLog(LogTypes.Error, string.Format("通过POSITION指令判断客户端加速: {0}, 指令个数:{1}, 断开连接", Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket, false), posCmdNum), null, true); return(false); } if (client.CheckCheatData.ProcessBoosterTicks == 0L) { client.CheckCheatData.ProcessBoosterTicks = TimeUtil.NOW(); } } } TCPOutPacket tcpOutPacket = null; long processBeginTime = TimeUtil.NowEx(); TCPProcessCmdResults result = TCPCmdHandler.ProcessCmd(this, tcpInPacket.CurrentSocket, this.tcpClientPool, this.tcpRandKey, this.tcpOutPacketPool, (int)tcpInPacket.PacketCmdID, bytesData, tcpInPacket.PacketDataSize - 1 - 4, out tcpOutPacket); long processTime = TimeUtil.NowEx() - processBeginTime; if (GameManager.StatisticsMode > 0 || processTime > 50L || result == TCPProcessCmdResults.RESULT_FAILED) { TCPManager.RecordCmdDetail((int)tcpInPacket.PacketCmdID, processTime, (long)tcpInPacket.PacketDataSize, result); } if (result == TCPProcessCmdResults.RESULT_DATA && null != tcpOutPacket) { this.socketListener.SendData(tcpInPacket.CurrentSocket, tcpOutPacket, true); } else { if (result == TCPProcessCmdResults.RESULT_FAILED) { if (tcpInPacket.PacketCmdID != 22) { LogManager.WriteLog(LogTypes.Error, string.Format("解析并执行命令失败: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket, false)), null, true); } return(false); } if (result == TCPProcessCmdResults.RESULT_DATA_CLOSE && null != tcpOutPacket) { this.socketListener.SendData(tcpInPacket.CurrentSocket, tcpOutPacket, true); tcpInPacket.CurrentSocket.DelayClose = 250; } } } else { if (1 != doType) { LogManager.WriteLog(LogTypes.Error, string.Format("解析并执行命令时类型未知: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket, false)), null, true); return(false); } this.DirectSendPolicyFileData(tcpInPacket); } return(true); }
public override void Initialize() { try { HandleCommandLine(Environment.GetCommandLineArgs()); if (Version.Major >= 4) getTShockAscii(); if (!Directory.Exists(SavePath)) Directory.CreateDirectory(SavePath); ConfigFile.ConfigRead += OnConfigRead; FileTools.SetupConfig(); DateTime now = DateTime.Now; string logFilename; string logPathSetupWarning = null; // Log path was not already set by the command line parameter? if (LogPath == LogPathDefault) LogPath = Config.LogPath; try { logFilename = Path.Combine(LogPath, now.ToString(LogFormat)+".log"); if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath); } catch(Exception ex) { logPathSetupWarning = "Could not apply the given log path / log format, defaults will be used. Exception details:\n" + ex; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(logPathSetupWarning); Console.ForegroundColor = ConsoleColor.Gray; // Problem with the log path or format use the default logFilename = Path.Combine(LogPathDefault, now.ToString(LogFormatDefault) + ".log"); } #if DEBUG Log.Initialize(logFilename, LogLevel.All, false); #else Log.Initialize(logFilename, LogLevel.All & ~LogLevel.Debug, LogClear); #endif if (logPathSetupWarning != null) Log.Warn(logPathSetupWarning); AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; } catch(Exception ex) { // Will be handled by the server api and written to its crashlog.txt. throw new Exception("Fatal TShock initialization exception. See inner exception for details.", ex); } // Further exceptions are written to TShock's log from now on. try { if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) { Log.ConsoleInfo( "TShock was improperly shut down. Please use the exit command in the future to prevent this."); File.Delete(Path.Combine(SavePath, "tshock.pid")); } File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture)); HandleCommandLinePostConfigLoad(Environment.GetCommandLineArgs()); if (Config.StorageType.ToLower() == "sqlite") { string sql = Path.Combine(SavePath, "tshock.sqlite"); DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); } else if (Config.StorageType.ToLower() == "mysql") { try { var hostport = Config.MySqlHost.Split(':'); DB = new MySqlConnection(); DB.ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", hostport[0], hostport.Length > 1 ? hostport[1] : "3306", Config.MySqlDbName, Config.MySqlUsername, Config.MySqlPassword ); } catch (MySqlException ex) { Log.Error(ex.ToString()); throw new Exception("MySql not setup correctly"); } } else { throw new Exception("Invalid storage type"); } Backups = new BackupManager(Path.Combine(SavePath, "backups")); Backups.KeepFor = Config.BackupKeepFor; Backups.Interval = Config.BackupInterval; Bans = new BanManager(DB); Warps = new WarpManager(DB); Regions = new RegionManager(DB); Users = new UserManager(DB); Groups = new GroupManager(DB); Itembans = new ItemManager(DB); RememberedPos = new RememberedPosManager(DB); InventoryDB = new InventoryManager(DB); RestApi = new SecureRest(Netplay.serverListenIP, Config.RestApiPort); RestApi.Port = Config.RestApiPort; RestManager = new RestManager(RestApi); RestManager.RegisterRestfulCommands(); var geoippath = Path.Combine(SavePath, "GeoIP.dat"); if (Config.EnableGeoIP && File.Exists(geoippath)) Geo = new GeoIPCountry(geoippath); Log.ConsoleInfo(string.Format("|> Version {0} ({1}) now running.", Version, VersionCodename)); GameHooks.PostInitialize += OnPostInit; GameHooks.Update += OnUpdate; GameHooks.HardUpdate += OnHardUpdate; GameHooks.StatueSpawn += OnStatueSpawn; ServerHooks.Connect += OnConnect; ServerHooks.Join += OnJoin; ServerHooks.Leave += OnLeave; ServerHooks.Chat += OnChat; ServerHooks.Command += ServerHooks_OnCommand; NetHooks.GetData += OnGetData; NetHooks.SendData += NetHooks_SendData; NetHooks.GreetPlayer += OnGreetPlayer; NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc; NpcHooks.SetDefaultsInt += OnNpcSetDefaults; ProjectileHooks.SetDefaults += OnProjectileSetDefaults; WorldHooks.StartHardMode += OnStartHardMode; WorldHooks.SaveWorld += SaveManager.Instance.OnSaveWorld; WorldHooks.ChristmasCheck += OnXmasCheck; NetHooks.NameCollision += NetHooks_NameCollision; TShockAPI.Hooks.PlayerHooks.PlayerPostLogin += OnPlayerLogin; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); //RconHandler.StartThread(); if (Config.RestApiEnabled) RestApi.Start(); if (Config.BufferPackets) PacketBuffer = new PacketBufferer(); Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); if (Initialized != null) Initialized(); } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); Environment.Exit(1); } }
public override void run() { try { bool isD3D9Valid = DirectXML.IsValid(this.d3d9MD5); if (!isD3D9Valid) { Logger.warning("No listed: " + this.d3d9MD5); } ServerConfig config = LoginManager.Config; string reason; if (!this.IsPacketDataValid(config, isD3D9Valid, out reason)) { Logger.LogLogin(reason); this._client.SendPacket((SendPacket) new SERVER_MESSAGE_DISCONNECT_PAK(2147483904U, false)); this._client.Close(1000, true); } else { this._client._player = AccountManager.getInstance().getAccountDB((object)this.login, (object)null, 0, 0); if (this._client._player == null && ConfigGA.AUTO_ACCOUNTS && !AccountManager.getInstance().CreateAccount(out this._client._player, this.login, this.passEnc, this._client.GetAddress())) { Logger.LogLogin("Falha ao criar conta automaticamente [" + this.login + "]"); this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(EventErrorEnum.Login_USER_PASS_FAIL, this.login, 0L)); this._client.Close(1000, false); } else { Account player = this._client._player; if (player == null || !player.ComparePassword(this.passEnc)) { string str = ""; if (player == null) { str = "Conta retornada da DB é nula"; } else if (!player.ComparePassword(this.passEnc)) { str = "Senha inválida"; } Logger.LogLogin(str + " [" + this.login + "]"); this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(EventErrorEnum.Login_USER_PASS_FAIL, this.login, 0L)); this._client.Close(1000, false); } else if (player.access >= 0) { if (player.MacAddress != this.MacAddress) { ComDiv.updateDB("accounts", "last_mac", (object)this.MacAddress, "player_id", (object)player.player_id); } bool validMac; bool validIp; BanManager.GetBanStatus(this.MacAddress.ToString(), this.PublicIP, out validMac, out validIp); if (validMac | validIp) { if (validMac) { Logger.LogLogin("MAC banido [" + this.login + "]"); } else { Logger.LogLogin("IP banido [" + this.login + "]"); } this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(validIp ? EventErrorEnum.Login_BLOCK_IP : EventErrorEnum.Login_BLOCK_ACCOUNT, this.login, 0L)); this._client.Close(1000, false); } else if (player.IsGM() && config.onlyGM || player.access >= 0 && !config.onlyGM) { Account account = AccountManager.getInstance().getAccount(player.player_id, true); if (!player._isOnline) { if (BanManager.GetAccountBan(player.ban_obj_id).endDate > DateTime.Now) { Logger.LogLogin("Conta com banimento ativo [" + this.login + "]"); this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(EventErrorEnum.Login_BLOCK_ACCOUNT, this.login, 0L)); this._client.Close(1000, false); } else { player.SetPlayerId(player.player_id, 31); player._clanPlayers = ClanManager.getClanPlayers(player.clan_id, player.player_id); this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(0, this.login, player.player_id)); this._client.SendPacket((SendPacket) new AUTH_WEB_CASH_PAK(0, 0, 0)); if (player.clan_id > 0) { this._client.SendPacket((SendPacket) new BASE_USER_CLAN_MEMBERS_PAK(player._clanPlayers)); } player._status.SetData(uint.MaxValue, player.player_id); player._status.updateServer((byte)0); player.setOnlineStatus(true); if (account != null) { account._connection = this._client; } SEND_REFRESH_ACC.RefreshAccount(player, true); } } else { Logger.LogLogin("Conta online [" + this.login + "]"); this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(EventErrorEnum.Login_ALREADY_LOGIN_WEB, this.login, 0L)); if (account != null && account._connection != null) { account.SendPacket((SendPacket) new AUTH_ACCOUNT_KICK_PAK(1)); account.SendPacket((SendPacket) new SERVER_MESSAGE_ERROR_PAK(2147487744U)); account.Close(1000); } else { Auth_SyncNet.SendLoginKickInfo(player); } this._client.Close(1000, false); } } else { Logger.LogLogin("Nível de acesso inválido [" + this.login + "]"); this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(EventErrorEnum.Login_TIME_OUT_2, this.login, 0L)); this._client.Close(1000, false); } } else { Logger.LogLogin("Banido permanente [" + this.login + "]"); this._client.SendPacket((SendPacket) new BASE_LOGIN_PAK(EventErrorEnum.Login_BLOCK_ACCOUNT, this.login, 0L)); this._client.Close(1000, false); } } } } catch (Exception ex) { Logger.warning("[BASE_LOGIN_REC] " + ex.ToString()); } }
/// <summary> /// Invokes a <see cref="ICommand"/> /// </summary> public void Invoke(MessageCreateEventArgs e) { try { if (e == null) { return; } DiscordGuildConfig config = null; char guildPrefix = CommandPrefix; if (e.Guild != null) { using DBContext c = new DBContext(); config = c.DiscordGuildConfig.FirstOrDefault(dgc => dgc.GuildId == (long)e.Guild.Id); User user = c.User.FirstOrDefault(u => u.DiscordUserId == (long)e.Author.Id); long osuId = user == null ? 0 : user.OsuUserId; List <BannedUser> bans = BanManager.GetBansForUser((long)e.Author.Id, osuId, e.Guild == null ? 0 : (long)e.Guild.Id); if (bans.Count > 0) { OnBannedUserDetected(e, bans); return; } if (config != null && config.Prefix.HasValue) { guildPrefix = config.Prefix.Value; } } if (!e.Message.Content[0].Equals(guildPrefix)) { return; } List <string> parameters = e.Message.Content.Split(' ').Skip(0).ToList(); if (parameters == null) { parameters = new List <string>(); } string command; if (parameters.Count == 0) { command = e.Message.Content; } else { command = parameters[0]; } command = command.TrimStart(guildPrefix); AccessLevel access = GetAccessLevel(e.Author.Id, e.Guild?.Id ?? 0); if (!_commandTypes.TryGetValue(command.ToLower(System.Globalization.CultureInfo.CurrentCulture), out ICommand cmd) || config != null && access <= AccessLevel.VIP && config.CommandChannelId > 0 && config.CommandChannelId != (long)e.Channel.Id) { return; } else if (cmd.IsDisabled) { e.Channel.SendMessageAsync("Command is currently disabled"); return; } switch (cmd.CommandType) { default: case CommandType.None: break; case CommandType.Private: if (e.Guild != null) { e.Channel.SendMessageAsync("You can only use this command in a private chat!"); return; } break; case CommandType.Public: if (e.Guild == null) { e.Channel.SendMessageAsync("You can only use this command in a server chat!"); return; } break; } AccessLevel cmdAccess = e.Guild == null ? cmd.AccessLevel : GetCommandAccessLevel(cmd, e.Guild.Id); if (access < cmdAccess) { OnException(e.Channel, cmd, "You do not have enough permissions to use this command"); return; } if (parameters.Count > 0) { parameters.RemoveAt(0); } if (cmd.MinParameters > 0 && parameters.Count < cmd.MinParameters) { OnException(e.Channel, cmd, "Not enough parameters"); return; } string afterCmd = e.Message.Content; if (afterCmd.Length > cmd.Command.Length + 1) { afterCmd = afterCmd.Remove(0, cmd.Command.Length + 2); } else { afterCmd = string.Empty; } DiscordMember member = null; if (e.Guild != null) { try { member = e.Guild.GetMemberAsync(e.Author.Id).ConfigureAwait(false).GetAwaiter().GetResult(); } catch (AggregateException ex) { if (!ex.InnerExceptions.Any(e => e is NotFoundException)) { throw; } } } CommandEventArg arg = new CommandEventArg(e.Guild, e.Channel, e.Author, member, e.Message, access, parameters, afterCmd, config); ThreadPool.QueueUserWorkItem(new WaitCallback(o => { try { cmd.Invoke(DiscordHandler, this, arg); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { if (ex is UnauthorizedException) { OnException?.Invoke(e.Channel, cmd, "Unauthorized, please allow direct messages (if you have direct messages enabled and this keeps happening, please report it)"); Logger.Log($"Unauthorized: " + ex, LogLevel.Warning); return; } string debugMsg = $"Something went wrong while invoking command {cmd.Command}, message: {arg.Message.Content} from {arg.User.Username}#{arg.User.Discriminator} ({arg.User.Id}):\n {ex.ToString()}"; Logger.Log(debugMsg, LogLevel.Warning); if (arg.Config != null && arg.Config.Debug) { OnException?.Invoke(e.Channel, cmd, GetDebugExceptionMessage(ex)); if (arg.Config.DebugChannel != 0) { try { var dchannel = arg.Guild.GetChannel((ulong)arg.Config.DebugChannel); dchannel.SendMessageAsync(debugMsg).ConfigureAwait(false); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception) #pragma warning restore CA1031 // Do not catch general exception types { //If we catch an exception here, there is nothing we can do, so just ignore it } } } else { OnException?.Invoke(e.Channel, cmd, $"Something went wrong executing this command"); } } })); } #pragma warning disable CA1031 // Do not catch general exception types catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { Logger.Log(ex, LogLevel.Error); } string GetDebugExceptionMessage(Exception ex) { return($"Something went wrong executing this command (L: {ex.GetLineNumber()} At: {ex.TargetSite.DeclaringType}.{ex.TargetSite.Name}: {ex.Message})"); } }
public override void Handle(ReBornWarRock_PServer.GameServer.Virtual_Objects.User.virtualUser User) { int UserID = Convert.ToInt32(getBlock(1)); if (BanManager.isBlocked(UserID) == false) { string LoginName = getBlock(3); int AccessLevel = Convert.ToInt32(getBlock(8)); string[] UserData = DB.runReadRow("SELECT id, username, nickname, exp, dinar, kills, deaths, premium, premiumExpire, cash, rank, coupons, todaycoupon, pc, clanID, clanrank, loginevent, logineventcheck, online, password, salt, country, infinity FROM users WHERE id='" + UserID + "' AND username='******'"); string[] Event = DB.runReadRow("SELECT userid, eventid FROM users_events WHERE userid='" + UserID + "'"); if (UserData.Length > 0) { if (Event.Length > 0) { if (Event[1] == "5") { User.ReceivedRandomBox = true; } } User.UserID = Convert.ToInt32(UserData[0]); User.Username = UserData[1]; User.Nickname = UserData[2]; User.Exp = Convert.ToInt32(UserData[3]); User.Dinar = Convert.ToInt32(UserData[4]); User.Kills = Convert.ToInt32(UserData[5]); User.Deaths = Convert.ToInt32(UserData[6]); User.Premium = Convert.ToInt32(UserData[7]); User.PremiumExpire = long.Parse(UserData[8]); User.Cash = Convert.ToInt32(UserData[9]); User.Rank = Convert.ToInt32(UserData[10]); User.Coupons = Convert.ToInt32(UserData[11]); User.TodayCoupon = Convert.ToInt32(UserData[12]); User.PCItem = (Convert.ToInt32(UserData[13]) == 1) ? true : false; User.PCItem1 = (Convert.ToInt32(UserData[13]) == 2) ? true : false; User.PCItem2 = (Convert.ToInt32(UserData[13]) == 3) ? true : false; User.ClanID = Convert.ToInt32(UserData[14]); User.Country = UserData[21]; User.InfinityPremium = int.Parse(UserData[22]); User.LoginCountry = Structure.LookupModule.getCountry(User.IPAddr); if (User.Country == "") { DB.runQuery("UPDATE users SET country='" + User.LoginCountry.getCode() + "' WHERE id='" + User.UserID + "'"); DB.runQuery("UPDATE countrys SET count=count+1 WHERE code='" + User.LoginCountry.getCode() + "'"); } string[] HeadshotData = DB.runReadRow("SELECT headshots FROM users WHERE id='" + User.UserID + "'"); User.Headshots = Convert.ToInt32(HeadshotData[0]); if (User.Rank > 4) { User.Nickname = "[GM]" + User.Nickname; } else if (User.Rank > 2) { User.Nickname = "[MOD]" + User.Nickname; } else if (User.Rank == 2) { User.Nickname = "[ESL]" + User.Nickname; } DB.runQuery("UPDATE users SET lasthwid='" + User.HWID + "' WHERE id='" + User.UserID + "'"); if (User.ClanID != -1) { User.ClanRank = Convert.ToInt32(UserData[15]); } User.LoginEvent = Convert.ToInt32(UserData[16]); User.LoginEventCheck = Convert.ToInt32(UserData[17]); if (Convert.ToInt32(UserData[18]) == 1) { Log.AppendError(User.Nickname + " tried to double login!"); DB.runQuery("UPDATE users SET online='0' WHERE id='" + User.UserID + "'"); User.disconnect(); } for (int I = 0; I < User.EndGameWord.Length; I++) { User.EndGameWord[I] = "/"; } if (User.Rank > 1) { User.MaxSlots = 80; } if (Structure.Debug > 1 && User.Rank < 3) { User.send(new PACKET_CHAT(User, PACKET_CHAT.ChatType.Notice1, "NOTA: Stiamo facendo modifiche al server, attendere prego", User.SessionID, User.Nickname)); return; } User.uniqID = Convert.ToInt32(getBlock(5)); // 1 User.uniqID2 = Convert.ToInt32(getBlock(6)); // 0 User.uniqIDisCRC = Convert.ToInt32(getBlock(7)); // 910 string LastJoin = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); DB.runQuery("UPDATE users SET lasthwid='" + User.HWID + "', lastjoin='" + LastJoin + "' WHERE id='" + User.UserID + "'"); DateTime current = DateTime.Now; int StartTime = Convert.ToInt32(String.Format("{0:yyMMddHH}", current)); string[] Skin = DB.runReadRow("SELECT class_0,class_1,class_2,class_3,class_4 FROM users_costumes WHERE ownerid='" + User.UserID + "'"); if (Skin.Length > 0) { User.CostumeE = Skin[0]; User.CostumeM = Skin[1]; User.CostumeS = Skin[2]; User.CostumeA = Skin[3]; User.CostumeH = Skin[4]; } else { DB.runQuery("INSERT INTO users_costumes(ownerid) VALUES ('" + User.UserID + "')"); } if (User.ClanID != -1) { string[] Clan = DB.runReadRow("SELECT clanname, iconid FROM clans WHERE id='" + User.ClanID + "'"); if (Clan.Length > 0) { User.Clan = ClanManager.getClan(User.ClanID); User.ClanName = Clan[0]; User.ClanIconID = Convert.ToInt32(Clan[1]); } string[] checkClanUser = DB.runReadRow("SELECT * FROM users WHERE clanrank='2' AND clanid='" + User.ClanID + "'"); if (checkClanUser.Length == 0) { DB.runQuery("UPDATE users SET clanrank='-1', clanid='-1' WHERE clanid='" + User.ClanID + "'"); DB.runQuery("DELETE FROM clans WHERE id='" + User.ClanID + "'"); } } else { DB.runQuery("UPDATE users SET clanID='-1', clanRank='1' WHERE id='" + User.UserID + "'"); } bool isEventMessage = false; for (int i = 0; i < 5; i++) { User.cCodes6th[i] = "^"; } User.LoadItems(); int[] checkItemIDs = DB.runReadColumn("SELECT id FROM inventory WHERE ownerid='" + UserID.ToString() + "' AND deleted='0'", 0, null); for (int I = 0; I < checkItemIDs.Length; I++) { string[] itemData = DB.runReadRow("SELECT expiredate, itemcode FROM inventory WHERE id=" + checkItemIDs[I].ToString()); if (Convert.ToInt32(itemData[0]) < StartTime) { int InvItems = 0; foreach (InventoryItem _InvItem in User.Inventory) { if (_InvItem != null) { InvItems++; } } if (InvItems > User.MaxSlots) { DB.runQuery("DELETE FROM inventory WHERE ownerid='" + UserID.ToString() + "'"); User.send(new PACKET_CHAT("SYSTEM", PACKET_CHAT.ChatType.Room_ToAll, "SYSTEM >> Your inventory's was resetted due too many items!", 999, "NULL")); User.Inventory = new InventoryItem[105]; } string itemID = User.getInventoryID(itemData[1]); DB.runQuery("DELETE FROM inventory WHERE ownerid='" + UserID.ToString() + "' AND itemcode='" + itemData[1] + "'"); User.LeftItems.Add(itemData[1]); User.ExpiredWeapon = true; } } int[] checkCostumeIDs = DB.runReadColumn("SELECT id FROM inventory_costume WHERE ownerid='" + UserID.ToString() + "' AND deleted='0'", 0, null); for (int I = 0; I < checkCostumeIDs.Length; I++) { string[] itemData = DB.runReadRow("SELECT expiredate, itemcode FROM inventory_costume WHERE id=" + checkCostumeIDs[I].ToString()); if (Convert.ToInt32(itemData[0]) < StartTime) { int InvItems = 0; foreach (CostumeItem _InvItem in User.Costume) { if (_InvItem != null) { InvItems++; } } if (InvItems > User.MaxSlots) { DB.runQuery("DELETE FROM inventory_costume WHERE ownerid='" + UserID.ToString() + "'"); User.send(new PACKET_CHAT("SYSTEM", PACKET_CHAT.ChatType.Room_ToAll, "SYSTEM >> Your costume's was resetted due too many items!", 999, "NULL")); User.Costume = new CostumeItem[105]; } DB.runQuery("DELETE FROM inventory_costume WHERE ownerid='" + UserID.ToString() + "' AND itemcode='" + itemData[1] + "'"); User.LeftItems.Add(itemData[1]); User.ExpiredWeapon = true; } } // Check for expired weapons if (User.ExpiredWeapon == true) { User.LoadEquipment(); int ItemCount = User.LeftItems.Count; foreach (string sItem in User.LeftItems) { string inventoryID = User.getInventoryID(sItem); for (int Class = 0; Class < 5; Class++) { for (int Slot = 0; Slot < 8; Slot++) { if (User.Equipment[Class, Slot].Contains(inventoryID)) { User.Equipment[Class, Slot] = "^"; } } } } User.SaveEquipment(); User.send(new PACKET_EXPIRE_ITEM(User)); User.reloadEquipment(ItemCount); User.Inventory = new InventoryItem[105]; User.LoadItems(); } User.CheckForFirstLogin(); /*Login Event*/ int EventID = 6; bool EventEnabled = false; if (User.CheckForEvent(EventID) == false && EventEnabled) { int InvItems = User.InventorySlots; if (InvItems > 0) { User.AddOutBoxItem("CB09", -1, 1); DB.runQuery("INSERT INTO users_events (eventid, userid) VALUES ('" + EventID + "','" + User.UserID + "')"); } else { User.send(new PACKET_ITEMSHOP(PACKET_ITEMSHOP.ErrorCodes.InventoryFull, "NULL")); } } User.PremiumTimeLeft(); User.LoadRetails(); User.KillEventLoad2(); User.send(new PACKET_CLIENT_PACKET(0)); // Welcome sound UserManager.addUser(User); if (isEventMessage == true) { User.send(new PACKET_MESSAGE_BOX("Check_your_inventory!_:)")); } User.send(new PACKET_CREDITS(User)); User.send(new PACKET_CHARACTER_INFO(User)); User.send(new PACKET_PING(User)); User.reloadCash(); } } else { User.send(new PACKET_CHARACTER_INFO(73030)); User.disconnect(); } }
public override void Initialize() { HandleCommandLine(Environment.GetCommandLineArgs()); if (!Directory.Exists(SavePath)) Directory.CreateDirectory(SavePath); #if DEBUG Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All, false); #else Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All & ~LogLevel.Debug, false); #endif AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; try { if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) { Log.ConsoleInfo( "TShock was improperly shut down. Please avoid this in the future, world corruption may result from this."); File.Delete(Path.Combine(SavePath, "tshock.pid")); } File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture)); ConfigFile.ConfigRead += OnConfigRead; FileTools.SetupConfig(); HandleCommandLine_Port(Environment.GetCommandLineArgs()); if (Config.StorageType.ToLower() == "sqlite") { string sql = Path.Combine(SavePath, "tshock.sqlite"); DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); } else if (Config.StorageType.ToLower() == "mysql") { try { var hostport = Config.MySqlHost.Split(':'); DB = new MySqlConnection(); DB.ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", hostport[0], hostport.Length > 1 ? hostport[1] : "3306", Config.MySqlDbName, Config.MySqlUsername, Config.MySqlPassword ); } catch (MySqlException ex) { Log.Error(ex.ToString()); throw new Exception("MySql not setup correctly"); } } else { throw new Exception("Invalid storage type"); } Backups = new BackupManager(Path.Combine(SavePath, "backups")); Backups.KeepFor = Config.BackupKeepFor; Backups.Interval = Config.BackupInterval; Bans = new BanManager(DB); Warps = new WarpManager(DB); Users = new UserManager(DB); Groups = new GroupManager(DB); Groups.LoadPermisions(); Regions = new RegionManager(DB); Itembans = new ItemManager(DB); RememberedPos = new RemeberedPosManager(DB); Inventory = new InventoryManager(DB); HomeManager = new HomeManager(DB); ArmorShopManager = new ArmorShopManager(DB); WeaponShopManager = new WeaponShopManager(DB); ItemShopManager = new ItemShopManager(DB); BlockShopManager = new BlockShopManager(DB); OtherShopManager = new OtherShopManager(DB); Towns = new TownManager(DB); Chat = new ChatManager(DB); Restart = new RestartManager(); RestApi = new SecureRest(Netplay.serverListenIP, 8080); RestApi.Verify += RestApi_Verify; RestApi.Port = Config.RestApiPort; RestManager = new RestManager(RestApi); RestManager.RegisterRestfulCommands(); var geoippath = Path.Combine(SavePath, "GeoIP.dat"); if (Config.EnableGeoIP && File.Exists(geoippath)) Geo = new GeoIPCountry(geoippath); profiles = @"Z:\profiles\"; temp = @"Z:\profiles\temp\"; Console.Title = string.Format("TerrariaShock Version {0} ({1})", Version, VersionCodename); Log.ConsoleInfo(string.Format("TerrariaShock Version {0} ({1}) now running.", Version, VersionCodename)); GameHooks.PostInitialize += OnPostInit; GameHooks.Update += OnUpdate; ServerHooks.Connect += OnConnect; ServerHooks.Join += OnJoin; ServerHooks.Leave += OnLeave; ServerHooks.Chat += OnChat; ServerHooks.Command += ServerHooks_OnCommand; NetHooks.GetData += OnGetData; NetHooks.SendData += NetHooks_SendData; NetHooks.GreetPlayer += OnGreetPlayer; NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc; NpcHooks.SetDefaultsInt += OnNpcSetDefaults; ProjectileHooks.SetDefaults += OnProjectileSetDefaults; WorldHooks.StartHardMode += OnStartHardMode; WorldHooks.SaveWorld += OnSaveWorld; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); if (Config.BufferPackets) PacketBuffer = new PacketBufferer(); Users.DeletePlayersAfterMinutes(TShock.Config.DeleteUserAfterMinutes, 30, false); Users.DeletePlayersAfterMinutes(TShock.Config.DeleteUserAfterMinutes * 2, 100, false); Users.DeletePlayersAfterMinutes(TShock.Config.DeleteUserAfterMinutes * 3, 10000, true); Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); if (Initialized != null) Initialized(); } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); TShock.Backups.Backup(); Environment.Exit(1); } }
/// <summary> /// 命令包接收完毕后的回调事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private bool TCPCmdPacketEvent(object sender, int doType) { TCPInPacket tcpInPacket = sender as TCPInPacket; if (0 == doType) //正常的登录指令包 { int thisTimeCheckTicks = 0; int checkErrorCode = 0; //这里实际上是有一个指令流的拷贝,占用的很零碎的内存,这个是否考虑使用内存池???? byte[] bytesData = CheckClientDataValid(tcpInPacket.PacketCmdID, tcpInPacket.GetPacketBytes(), tcpInPacket.PacketDataSize, tcpInPacket.LastCheckTicks, out thisTimeCheckTicks, out checkErrorCode); if (null != bytesData) { tcpInPacket.LastCheckTicks = thisTimeCheckTicks; //记忆此次的心跳数据 //#if false if (UseWorkerPool) { //杰隆的异步处理指令入口代码 TCPCmdWrapper wrapper = TCPCmdWrapper.Get(this, tcpInPacket.CurrentSocket, tcpClientPool, tcpRandKey, tcpOutPacketPool, tcpInPacket.PacketCmdID, bytesData, tcpInPacket.PacketDataSize - 1 - 4); TCPSession session = null; if (GameManager.FlagOptimizeLock3) { if (null != tcpInPacket.CurrentSocket) { session = tcpInPacket.CurrentSocket.session; } if (null == session) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } else { lock (tcpSessions) { if (!tcpSessions.TryGetValue(tcpInPacket.CurrentSocket, out session)) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } } int posCmdNum = 0; session.addTCPCmdWrapper(wrapper, out posCmdNum); if (posCmdNum > 0) { int banSpeedUpMinutes = GameManager.GameConfigMgr.GetGameConfigItemInt("ban-speed-up-minutes2", 10); //加速禁止登陆的时间 GameClient client = GameManager.ClientMgr.FindClient(tcpInPacket.CurrentSocket); if (null != client) { GameManager.ClientMgr.NotifyImportantMsg(this.MySocketListener, tcpOutPacketPool, client, StringUtil.substitute(Global.GetLang("本游戏禁止使用加速软件,{0}分钟内将禁止登陆!"), banSpeedUpMinutes), GameInfoTypeIndexes.Error, ShowGameInfoTypes.HintAndBox); BanManager.BanRoleName(Global.FormatRoleName(client, client.ClientData.RoleName), banSpeedUpMinutes); } LogManager.WriteLog(LogTypes.Error, string.Format("通过POSITION指令判断客户端加速: {0}, 指令个数:{1}, 断开连接", Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), posCmdNum)); return(false); } taskExecutor.execute(new ProcessSessionTask(session)); } //#else else { TCPSession session = null; if (GameManager.FlagOptimizeLock3) { if (null != tcpInPacket.CurrentSocket) { session = tcpInPacket.CurrentSocket.session; } if (null == session) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } else { lock (tcpSessions) { if (!tcpSessions.TryGetValue(tcpInPacket.CurrentSocket, out session)) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } } int posCmdNum = 0; session.CheckCmdNum(tcpInPacket.PacketCmdID, out posCmdNum); if (posCmdNum > 0) { int banSpeedUpMinutes = GameManager.GameConfigMgr.GetGameConfigItemInt("ban-speed-up-minutes2", 10); //加速禁止登陆的时间 GameClient client = GameManager.ClientMgr.FindClient(tcpInPacket.CurrentSocket); if (null != client) { GameManager.ClientMgr.NotifyImportantMsg(this.MySocketListener, tcpOutPacketPool, client, StringUtil.substitute(Global.GetLang("本游戏禁止使用加速软件,{0}分钟内将禁止登陆!"), banSpeedUpMinutes), GameInfoTypeIndexes.Error, ShowGameInfoTypes.HintAndBox); BanManager.BanRoleName(Global.FormatRoleName(client, client.ClientData.RoleName), banSpeedUpMinutes); } LogManager.WriteLog(LogTypes.Error, string.Format("通过POSITION指令判断客户端加速: {0}, 指令个数:{1}, 断开连接", Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), posCmdNum)); return(false); } TCPOutPacket tcpOutPacket = null; long processBeginTime = TimeUtil.NowEx(); TCPProcessCmdResults result = TCPCmdHandler.ProcessCmd(this, tcpInPacket.CurrentSocket, tcpClientPool, tcpRandKey, tcpOutPacketPool, tcpInPacket.PacketCmdID, bytesData, tcpInPacket.PacketDataSize - 1 - 4, out tcpOutPacket); long processTime = (TimeUtil.NowEx() - processBeginTime); if (GameManager.StatisticsMode > 0 || processTime > 50 || result == TCPProcessCmdResults.RESULT_FAILED) { lock (ProcessSessionTask.cmdMoniter) //锁定命令监控对象 { int cmdID = tcpInPacket.PacketCmdID; PorcessCmdMoniter moniter = null; if (!ProcessSessionTask.cmdMoniter.TryGetValue(cmdID, out moniter)) { moniter = new PorcessCmdMoniter(cmdID, processTime); ProcessSessionTask.cmdMoniter.Add(cmdID, moniter); } moniter.onProcessNoWait(processTime, result); } } if (result == TCPProcessCmdResults.RESULT_DATA && null != tcpOutPacket) { //向登陆客户端返回数据 socketListener.SendData(tcpInPacket.CurrentSocket, tcpOutPacket); } else if (result == TCPProcessCmdResults.RESULT_FAILED)//解析失败, 直接关闭连接 { LogManager.WriteLog(LogTypes.Error, string.Format("解析并执行命令失败: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket))); return(false); } } //#endif } else { LogManager.WriteLog(LogTypes.Error, string.Format("校验客户端发送的指令数据完整性失败: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } else if (1 == doType) //正常的登录指令包//策略验证请求 { //直接发送策略数据 DirectSendPolicyFileData(tcpInPacket); } else { LogManager.WriteLog(LogTypes.Error, string.Format("解析并执行命令时类型未知: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket))); //socketListener.CloseSocket(tcpInPacket.CurrentSocket); return(false); } return(true); }
protected override IServer CreateServer(bool passwordCheckSucceedIfNotFound = true) { PasswordManager = new PasswordManager { CheckSucceedIfNotFound = passwordCheckSucceedIfNotFound }; BanManager = new BanManager(BanFilename); ClientManager = new ClientManager(10); AdminManager = new AdminManager(10); GameManager = new GameManager(10); return new Server(new Factory(), PasswordManager, BanManager, ClientManager, AdminManager, GameManager); }
private void CheckBanTrade(int roleId) { TradeBlackObject obj = this.LoadTradeBlackObject(roleId, true); if (obj != null) { int kick_out_minutes = -1; lock (obj) { if (obj.BanTradeToTicks <= 0L) { List <TradeConfigItem> items = this.TradeCfgItems; TradeConfigItem tradeConfigItem; if (items == null) { tradeConfigItem = null; } else { tradeConfigItem = items.Find((TradeConfigItem _i) => _i.MinVip <= obj.VipLevel && _i.MaxVip >= obj.VipLevel && _i.UnionMinLevel <= Global.GetUnionLevel(obj.ChangeLife, obj.Level, false) && _i.UnionMaxLevel >= Global.GetUnionLevel(obj.ChangeLife, obj.Level, false)); } TradeConfigItem item = tradeConfigItem; if (item != null) { long totalInPrice = 0L; long totalOutPrice = 0L; long totalTimes = 0L; foreach (TradeBlackHourItem hourItem in obj.HourItems) { if (hourItem != null) { totalInPrice += hourItem.MarketInPrice + hourItem.TradeInPrice; totalOutPrice += hourItem.MarketOutPrice + hourItem.TradeOutPrice; totalTimes += (long)(hourItem.MarketTimes + hourItem.TradeTimes); } } if (totalInPrice >= (long)item.MaxPrice || totalOutPrice >= (long)item.MaxPrice || totalTimes >= (long)item.MaxTimes) { int _banTradeSec = Math.Max(this.BanTradeSec, 0); if (_banTradeSec > 0) { long toTicks = TimeUtil.NowDateTime().AddSeconds((double)_banTradeSec).Ticks; this.SetBanTradeToTicks(roleId, toTicks); } if (this.BanTradeLog == 1) { LogManager.WriteLog(LogTypes.Analysis, string.Format("tradeblack player={0} inprice={1} outprice={2} times={3} bansec={4}", new object[] { roleId, totalInPrice, totalOutPrice, totalTimes, _banTradeSec }), null, true); } kick_out_minutes = Math.Max(this.BanTradeLogin, 0) / 60; if (kick_out_minutes > 0) { BanManager.BanRoleName(Global.FormatRoleName3(obj.ZoneId, obj.RoleName), kick_out_minutes, 3); } } } } } if (kick_out_minutes > 0) { GameClient client = GameManager.ClientMgr.FindClient(roleId); if (client != null) { GameManager.ClientMgr.NotifyImportantMsg(Global._TCPManager.MySocketListener, Global._TCPManager.TcpOutPacketPool, client, StringUtil.substitute(GLang.GetLang(36, new object[0]), new object[] { kick_out_minutes }), GameInfoTypeIndexes.Error, ShowGameInfoTypes.HintAndBox, 0); Global.ForceCloseClient(client, "交易封禁", true); } } } }
public BanController() { _banManager = new BanManager(new AdoBanDal()); }
private static void Main() { Log.Default.Logger = new NLogger(); Log.Default.Initialize(@"D:\TEMP\LOG\", "TETRINET2_SERVER.LOG"); IFactory factory = new Factory(); IPasswordManager passwordManager = new PasswordManager(); IBanManager banManager = new BanManager(@"D:\TEMP\ban.lst"); IClientManager clientManager = new ClientManager(50); IAdminManager adminManager = new AdminManager(5); IGameManager gameManager = new GameManager(10); IHost wcfHost = new WCFHost.WCFHost(banManager, clientManager, adminManager, gameManager) { Port = 7788 }; IServer server = new Server(factory, passwordManager, banManager, clientManager, adminManager, gameManager); server.AddHost(wcfHost); server.SetVersion(1, 0); server.SetAdminPassword("admin1", "123456"); server.PerformRestartServer += ServerOnPerformRestartServer; // try { server.Start(); } catch (Exception ex) { Log.Default.WriteLine(LogLevels.Error, "Cannot start server. Exception: {0}", ex); return; } bool stopped = false; while (!stopped) { if (Console.KeyAvailable) { ConsoleKeyInfo cki = Console.ReadKey(true); switch (cki.Key) { default: DisplayHelp(); break; case ConsoleKey.X: server.Stop(); stopped = true; break; case ConsoleKey.D: Console.WriteLine("Clients:"); foreach (IClient client in clientManager.Clients) Console.WriteLine("{0}) {1} [{2}] {3} {4} {5} {6:HH:mm:ss.fff} {7:HH:mm:ss.fff}", client.Id, client.Name, client.Team, client.State, client.Game == null ? "no in game" : client.Game.Name, client.PieceIndex, client.LastActionFromClient, client.LastActionToClient); Console.WriteLine("Admins:"); foreach (IAdmin admin in adminManager.Admins) Console.WriteLine("{0}) {1}", admin.Id, admin.Name); Console.WriteLine("Games:"); foreach (IGame game in gameManager.Games) Console.WriteLine("{0}) {1} {2} {3} #players:{4} #spectators:{5} password:{6} {7:HH:mm:ss}", game.Id, game.Name, game.State, game.Rule, game.PlayerCount, game.SpectatorCount, game.Password, game.CreationTime); break; } } else System.Threading.Thread.Sleep(100); } }
private void DisplayReports(object sender, RoutedEventArgs e) { BanManager.GetReportedList(); }
public FrmBanManagement() { InitializeComponent(); _banManager = new BanManager(new AdoBanDal()); }
/// <summary> /// 检查封禁交易 /// </summary> /// <param name="roleId"></param> private void CheckBanTrade(int roleId) { TradeBlackObject obj = LoadTradeBlackObject(roleId); if (obj == null) { return; } int kick_out_minutes = -1; lock (obj) { if (obj.BanTradeToTicks <= 0) { List <TradeConfigItem> items = this.TradeCfgItems; TradeConfigItem item = items != null?items.Find(_i => { return(_i.MinVip <= obj.VipLevel && _i.MaxVip >= obj.VipLevel && _i.UnionMinLevel <= Global.GetUnionLevel(obj.ChangeLife, obj.Level) && _i.UnionMaxLevel >= Global.GetUnionLevel(obj.ChangeLife, obj.Level)); }) : null; if (item != null) { long totalInPrice = 0, totalOutPrice = 0, totalTimes = 0; foreach (var hourItem in obj.HourItems) { if (hourItem == null) { continue; } totalInPrice += hourItem.MarketInPrice + hourItem.TradeInPrice; totalOutPrice += hourItem.MarketOutPrice + hourItem.TradeOutPrice; totalTimes += hourItem.MarketTimes + hourItem.TradeTimes; } if (totalInPrice >= item.MaxPrice || totalOutPrice >= item.MaxPrice || totalTimes >= item.MaxTimes) { int _banTradeSec = Math.Max(this.BanTradeSec, 0); if (_banTradeSec > 0) { long toTicks = TimeUtil.NowDateTime().AddSeconds(_banTradeSec).Ticks; SetBanTradeToTicks(roleId, toTicks); } if (this.BanTradeLog == 1) { LogManager.WriteLog(LogTypes.Analysis, string.Format("tradeblack player={0} inprice={1} outprice={2} times={3} bansec={4}", roleId, totalInPrice, totalOutPrice, totalTimes, _banTradeSec)); } kick_out_minutes = Math.Max(this.BanTradeLogin, 0) / 60; if (kick_out_minutes > 0) { BanManager.BanRoleName(Global.FormatRoleName3(obj.ZoneId, obj.RoleName), kick_out_minutes, (int)BanManager.BanReason.TradeException); } } } } } if (kick_out_minutes > 0) { GameClient client = GameManager.ClientMgr.FindClient(roleId); if (client != null) { GameManager.ClientMgr.NotifyImportantMsg(Global._TCPManager.MySocketListener, Global._TCPManager.TcpOutPacketPool, client, StringUtil.substitute(Global.GetLang("系统检测到您交易异常,您的帐号将被禁止登录{0}分钟!"), kick_out_minutes), GameInfoTypeIndexes.Error, ShowGameInfoTypes.HintAndBox); Global.ForceCloseClient(client, "交易封禁"); /* * string gmCmdData = string.Format("-kick {0}", obj.RoleName); * //转发GM消息到DBServer * GameManager.DBCmdMgr.AddDBCmd((int)TCPGameServerCmds.CMD_SPR_CHAT, * string.Format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}:{8}", obj.RoleId, "", 0, "", 0, gmCmdData, 0, 0, GameManager.ServerLineID), * null, GameManager.LocalServerId); */ } } }
public void Shutdown() { //we dont wnat dispose gameclientmanager if (this.GameCycleTimer != null) { this.GameCycleTimer.Stop(); } this.GameCycleTimer = null; if (this.NavigatorManager != null) { this.NavigatorManager.Shutdown(); } this.NavigatorManager = null; if (this.RoomManager != null) { this.RoomManager.Shutdown(); } this.RoomManager = null; if (this.ItemManager != null) { this.ItemManager.Shutdown(); } this.ItemManager = null; if (this.CatalogManager != null) { this.CatalogManager.Shutdown(); } this.CatalogManager = null; if (this.PermissionManager != null) { this.PermissionManager.Shutdown(); } this.PermissionManager = null; if (this.BanManager != null) { this.BanManager.Shutdown(); } this.BanManager = null; if (this.ModerationToolManager != null) { this.ModerationToolManager.Shutdown(); } this.ModerationToolManager = null; if (this.CautionManager != null) { this.CautionManager.Shutdown(); } this.CautionManager = null; if (this.HelpManager != null) { this.HelpManager.Shutdown(); } this.HelpManager = null; if (this.ChatlogManager != null) { this.ChatlogManager.Shutdown(); } this.ChatlogManager = null; if (this.RoomvisitManager != null) { this.RoomvisitManager.Shutdown(); } this.RoomvisitManager = null; if (this.AchievementManager != null) { this.AchievementManager.Shutdown(); } this.AchievementManager = null; }
public void Init() { using (DatabaseClient dbClient = Skylight.GetDatabaseManager().GetClient()) { ServerConfiguration.LoadConfigsFromDB(dbClient); this.GameClientManager = new GameClientManager(); this.NavigatorManager = new NavigatorManager(); this.NavigatorManager.LoadPublicRooms(dbClient); this.NavigatorManager.LoadFlatCats(dbClient); this.RoomManager = new RoomManager(); this.RoomManager.LoadRoomModels(dbClient); this.RoomManager.LoadNewbieRooms(dbClient); this.ItemManager = new ItemManager(); this.ItemManager.LoadItems(dbClient); this.ItemManager.LoadSoundtracks(dbClient); this.ItemManager.LoadNewbieRoomItems(dbClient); this.CatalogManager = new CatalogManager(); this.CatalogManager.LoadCatalogItems(dbClient); this.CatalogManager.LoadCatalogPages(dbClient); this.CatalogManager.LoadPetRaces(dbClient); this.CatalogManager.LoadPresents(dbClient); this.CatalogManager.GetMarketplaceManager().LoadMarketplaceOffers(dbClient); this.PermissionManager = new PermissionManager(); this.PermissionManager.LoadRanks(dbClient); this.BanManager = new BanManager(); this.BanManager.LoadBans(dbClient); this.ModerationToolManager = new ModerationToolManager(); this.ModerationToolManager.LoadIssues(dbClient); this.ModerationToolManager.LoadPresents(dbClient); this.ModerationToolManager.LoadSupportTickets(dbClient); this.CautionManager = new CautionManager(); this.CautionManager.LoadCauctions(dbClient); this.HelpManager = new HelpManager(); this.HelpManager.LoadFAQs(dbClient); this.ChatlogManager = new ChatlogManager(); this.RoomvisitManager = new RoomvisitManager(); this.AchievementManager = new AchievementManager(); this.AchievementManager.LoadAchievements(dbClient); this.BotManager = new BotManager(); this.BotManager.LoadBots(dbClient); this.BotManager.LoadNewbieBotActions(dbClient); TextUtilies.LoadWordfilter(dbClient); this.QuestManager = new QuestManager(); this.QuestManager.LoadQuests(dbClient); this.TalentManager = new TalentManager(); this.TalentManager.LoadTalents(dbClient); this.FastFoodManager = new FastFoodManager(); this.FastFoodManager.CreateNewConnection(); this.UserProfileManager = new UserProfileManager(); this.GuideManager = new GuideManager(); } this.ClientPingEnabled = TextUtilies.StringToBool(Skylight.GetConfig()["client.ping.enabled"]); this.AutoRestartEnabled = TextUtilies.StringToBool(Skylight.GetConfig()["auto.restart.enabled"]); if (this.AutoRestartEnabled) { this.AutoRestartBackup = TextUtilies.StringToBool(Skylight.GetConfig()["auto.restart.backup"]); this.AutoRestartBackupCompress = TextUtilies.StringToBool(Skylight.GetConfig()["auto.restart.backup.compress"]); this.AutoRestartTime = DateTime.ParseExact(Skylight.GetConfig()["auto.restart.time"], "HH:mm", CultureInfo.InvariantCulture); } this.LastUpdateEmulatorStatus = Stopwatch.StartNew(); this.LastActivityBonusesCheck = Stopwatch.StartNew(); this.LastTimeoutCheck = Stopwatch.StartNew(); this.GameCycleTimer = new System.Timers.Timer(); this.GameCycleTimer.Elapsed += this.GameCycle; this.GameCycleTimer.AutoReset = true; this.GameCycleTimer.Interval = 1; //moved from 25ms, 40 times in a second to 1ms, 1000 times in second to help keep everything be in sync this.GameCycleTimer.Start(); GC.KeepAlive(this.GameCycleTimer); //IK timer adds itself to the gc already, but just for sure ;P }
public override void Initialize() { if (!Directory.Exists(SavePath)) Directory.CreateDirectory(SavePath); #if DEBUG Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All, false); #else Log.Initialize(Path.Combine(SavePath, "log.txt"), LogLevel.All & ~LogLevel.Debug, false); #endif AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; try { if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) { Log.ConsoleInfo("TShock was improperly shut down. Deleting invalid pid file..."); File.Delete(Path.Combine(SavePath, "tshock.pid")); } File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString()); ConfigFile.ConfigRead += OnConfigRead; FileTools.SetupConfig(); HandleCommandLine(Environment.GetCommandLineArgs()); if (Config.StorageType.ToLower() == "sqlite") { string sql = Path.Combine(SavePath, "tshock.sqlite"); DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); } else if (Config.StorageType.ToLower() == "mysql") { try { var hostport = Config.MySqlHost.Split(':'); DB = new MySqlConnection(); DB.ConnectionString = String.Format("Server='{0}'; Port='{1}'; Database='{2}'; Uid='{3}'; Pwd='{4}';", hostport[0], hostport.Length > 1 ? hostport[1] : "3306", Config.MySqlDbName, Config.MySqlUsername, Config.MySqlPassword ); } catch (MySqlException ex) { Log.Error(ex.ToString()); throw new Exception("MySql not setup correctly"); } } else { throw new Exception("Invalid storage type"); } Backups = new BackupManager(Path.Combine(SavePath, "backups")); Backups.KeepFor = Config.BackupKeepFor; Backups.Interval = Config.BackupInterval; Bans = new BanManager(DB); Warps = new WarpManager(DB); Users = new UserManager(DB); Groups = new GroupManager(DB); Groups.LoadPermisions(); Regions = new RegionManager(DB); Itembans = new ItemManager(DB); RememberedPos = new RemeberedPosManager(DB); Log.ConsoleInfo(string.Format("TShock Version {0} ({1}) now running.", Version, VersionCodename)); GameHooks.PostInitialize += OnPostInit; GameHooks.Update += OnUpdate; ServerHooks.Join += OnJoin; ServerHooks.Leave += OnLeave; ServerHooks.Chat += OnChat; ServerHooks.Command += ServerHooks_OnCommand; NetHooks.GetData += GetData; NetHooks.GreetPlayer += OnGreetPlayer; NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); //RconHandler.StartThread(); if (Config.BufferPackets) bufferer = new PacketBufferer(); Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); Environment.Exit(1); } }
public HomeController(PlayerManager playerManager, BanManager banManager) { this.playerManager = playerManager; this.banManager = banManager; }
public override void Initialize() { string logFilename; string logPathSetupWarning; try { HandleCommandLine(Environment.GetCommandLineArgs()); if (!Directory.Exists(SavePath)) Directory.CreateDirectory(SavePath); ConfigFile.ConfigRead += OnConfigRead; FileTools.SetupConfig(); Main.ServerSideCharacter = ServerSideCharacterConfig.Enabled; DateTime now = DateTime.Now; // Log path was not already set by the command line parameter? if (LogPath == LogPathDefault) LogPath = Config.LogPath; try { logFilename = Path.Combine(LogPath, now.ToString(LogFormat) + ".log"); if (!Directory.Exists(LogPath)) Directory.CreateDirectory(LogPath); } catch (Exception ex) { logPathSetupWarning = "Could not apply the given log path / log format, defaults will be used. Exception details:\n" + ex; ServerApi.LogWriter.PluginWriteLine(this, logPathSetupWarning, TraceLevel.Error); // Problem with the log path or format use the default logFilename = Path.Combine(LogPathDefault, now.ToString(LogFormatDefault) + ".log"); } AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; } catch (Exception ex) { // Will be handled by the server api and written to its crashlog.txt. throw new Exception("Fatal TShock initialization exception. See inner exception for details.", ex); } // Further exceptions are written to TShock's log from now on. try { if (Config.StorageType.ToLower() == "sqlite") { string sql = Path.Combine(SavePath, "tshock.sqlite"); DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); } else if (Config.StorageType.ToLower() == "mysql") { try { var hostport = Config.MySqlHost.Split(':'); DB = new MySqlConnection(); DB.ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", hostport[0], hostport.Length > 1 ? hostport[1] : "3306", Config.MySqlDbName, Config.MySqlUsername, Config.MySqlPassword ); } catch (MySqlException ex) { ServerApi.LogWriter.PluginWriteLine(this, ex.ToString(), TraceLevel.Error); throw new Exception("MySql not setup correctly"); } } else { throw new Exception("Invalid storage type"); } if (Config.UseSqlLogs) Log = new SqlLog(DB, logFilename, LogClear); else Log = new TextLog(logFilename, LogClear); if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) { Log.ConsoleInfo( "TShock was improperly shut down. Please use the exit command in the future to prevent this."); File.Delete(Path.Combine(SavePath, "tshock.pid")); } File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture)); HandleCommandLinePostConfigLoad(Environment.GetCommandLineArgs()); Backups = new BackupManager(Path.Combine(SavePath, "backups")); Backups.KeepFor = Config.BackupKeepFor; Backups.Interval = Config.BackupInterval; Bans = new BanManager(DB); Warps = new WarpManager(DB); Regions = new RegionManager(DB); Users = new UserManager(DB); Groups = new GroupManager(DB); Itembans = new ItemManager(DB); ProjectileBans = new ProjectileManagager(DB); TileBans = new TileManager(DB); RememberedPos = new RememberedPosManager(DB); CharacterDB = new CharacterManager(DB); RestApi = new SecureRest(Netplay.ServerIP, Config.RestApiPort); RestManager = new RestManager(RestApi); RestManager.RegisterRestfulCommands(); var geoippath = Path.Combine(SavePath, "GeoIP.dat"); if (Config.EnableGeoIP && File.Exists(geoippath)) Geo = new GeoIPCountry(geoippath); Log.ConsoleInfo("TShock {0} ({1}) now running.", Version, VersionCodename); ServerApi.Hooks.GamePostInitialize.Register(this, OnPostInit); ServerApi.Hooks.GameUpdate.Register(this, OnUpdate); ServerApi.Hooks.GameHardmodeTileUpdate.Register(this, OnHardUpdate); ServerApi.Hooks.GameStatueSpawn.Register(this, OnStatueSpawn); ServerApi.Hooks.ServerConnect.Register(this, OnConnect); ServerApi.Hooks.ServerJoin.Register(this, OnJoin); ServerApi.Hooks.ServerLeave.Register(this, OnLeave); ServerApi.Hooks.ServerChat.Register(this, OnChat); ServerApi.Hooks.ServerCommand.Register(this, ServerHooks_OnCommand); ServerApi.Hooks.NetGetData.Register(this, OnGetData); ServerApi.Hooks.NetSendData.Register(this, NetHooks_SendData); ServerApi.Hooks.NetGreetPlayer.Register(this, OnGreetPlayer); ServerApi.Hooks.NpcStrike.Register(this, NpcHooks_OnStrikeNpc); ServerApi.Hooks.ProjectileSetDefaults.Register(this, OnProjectileSetDefaults); ServerApi.Hooks.WorldStartHardMode.Register(this, OnStartHardMode); ServerApi.Hooks.WorldSave.Register(this, SaveManager.Instance.OnSaveWorld); ServerApi.Hooks.WorldChristmasCheck.Register(this, OnXmasCheck); ServerApi.Hooks.WorldHalloweenCheck.Register(this, OnHalloweenCheck); ServerApi.Hooks.NetNameCollision.Register(this, NetHooks_NameCollision); Hooks.PlayerHooks.PlayerPreLogin += OnPlayerPreLogin; Hooks.PlayerHooks.PlayerPostLogin += OnPlayerLogin; Hooks.AccountHooks.AccountDelete += OnAccountDelete; Hooks.AccountHooks.AccountCreate += OnAccountCreate; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); if (Config.RestApiEnabled) RestApi.Start(); if (Config.BufferPackets) PacketBuffer = new PacketBufferer(this); Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); if (Initialized != null) Initialized(); Log.ConsoleInfo("Welcome to TShock for Terraria. Initialization complete."); } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); Environment.Exit(1); } }
/// <summary> /// 命令包接收完毕后的回调事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private bool TCPCmdPacketEvent(object sender, int doType) { TCPInPacket tcpInPacket = sender as TCPInPacket; if (0 == doType) //正常的登录指令包 { int thisTimeCheckTicks = 0; int checkErrorCode = 0; if (0xffff == tcpInPacket.PacketCmdID) { String cmdData = new UTF8Encoding().GetString(tcpInPacket.GetPacketBytes(), 0, tcpInPacket.PacketDataSize); if (cmdData == "serveripinfo") { String strinfo = string.Format("{0}_{1}", ServerPort, Global.GetLocalAddressIPs()); byte [] arrSendData = Encoding.UTF8.GetBytes(strinfo); if (null != arrSendData) { tcpInPacket.CurrentSocket.Send(arrSendData, arrSendData.Length, SocketFlags.None); } } return(false); } //这里实际上是有一个指令流的拷贝,占用的很零碎的内存,这个是否考虑使用内存池???? byte[] bytesData = CheckClientDataValid(tcpInPacket.PacketCmdID, tcpInPacket.GetPacketBytes(), tcpInPacket.PacketDataSize, tcpInPacket.LastCheckTicks, out thisTimeCheckTicks, out checkErrorCode); if (null != bytesData) { tcpInPacket.LastCheckTicks = thisTimeCheckTicks; //记忆此次的心跳数据 //#if false if (UseWorkerPool) { //杰隆的异步处理指令入口代码 TCPCmdWrapper wrapper = TCPCmdWrapper.Get(this, tcpInPacket.CurrentSocket, tcpClientPool, tcpRandKey, tcpOutPacketPool, tcpInPacket.PacketCmdID, bytesData, tcpInPacket.PacketDataSize - 1 - 4); TCPSession session = null; if (GameManager.FlagOptimizeLock3) { if (null != tcpInPacket.CurrentSocket) { session = tcpInPacket.CurrentSocket.session; } if (null == session) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } else { lock (tcpSessions) { if (!tcpSessions.TryGetValue(tcpInPacket.CurrentSocket, out session)) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } } int posCmdNum = 0; session.addTCPCmdWrapper(wrapper, out posCmdNum); if (posCmdNum > 0) { int banSpeedUpMinutes = GameManager.PlatConfigMgr.GetGameConfigItemInt(PlatConfigNames.BanSpeedUpMinutes2, 10); //加速禁止登陆的时间 GameClient client = GameManager.ClientMgr.FindClient(tcpInPacket.CurrentSocket); if (null != client) { GameManager.ClientMgr.NotifyImportantMsg(this.MySocketListener, tcpOutPacketPool, client, StringUtil.substitute(Global.GetLang("本游戏禁止使用加速软件,{0}分钟内将禁止登陆!"), banSpeedUpMinutes), GameInfoTypeIndexes.Error, ShowGameInfoTypes.HintAndBox); BanManager.BanRoleName(Global.FormatRoleName(client, client.ClientData.RoleName), banSpeedUpMinutes); } LogManager.WriteLog(LogTypes.Error, string.Format("通过POSITION指令判断客户端加速: {0}, 指令个数:{1}, 断开连接", Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), posCmdNum)); return(false); } taskExecutor.execute(new ProcessSessionTask(session)); } //#else else { TCPSession session = null; if (GameManager.FlagOptimizeLock3) { if (null != tcpInPacket.CurrentSocket) { session = tcpInPacket.CurrentSocket.session; } if (null == session) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } else { lock (tcpSessions) { if (!tcpSessions.TryGetValue(tcpInPacket.CurrentSocket, out session)) { LogManager.WriteLog(LogTypes.Error, string.Format("未与客户端建立会话: {0},{1}, 错误码:{2}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode)); return(false); } } } int posCmdNum = 0; session.CheckCmdNum(tcpInPacket.PacketCmdID, out posCmdNum); if (posCmdNum > 0) { int banSpeedUpMinutes = GameManager.PlatConfigMgr.GetGameConfigItemInt(PlatConfigNames.BanSpeedUpMinutes2, 10); //加速禁止登陆的时间 GameClient client = GameManager.ClientMgr.FindClient(tcpInPacket.CurrentSocket); if (null != client) { if (client.CheckCheatData.ProcessBooster) { GameManager.ClientMgr.NotifyImportantMsg(this.MySocketListener, tcpOutPacketPool, client, StringUtil.substitute(Global.GetLang("本游戏禁止使用加速软件,{0}分钟内将禁止登陆!"), banSpeedUpMinutes), GameInfoTypeIndexes.Error, ShowGameInfoTypes.HintAndBox); BanManager.BanRoleName(Global.FormatRoleName(client, client.ClientData.RoleName), banSpeedUpMinutes); LogManager.WriteLog(LogTypes.Error, string.Format("通过POSITION指令判断客户端加速: {0}, 指令个数:{1}, 断开连接", Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), posCmdNum)); return(false); } else if (client.CheckCheatData.ProcessBoosterTicks == 0) { client.CheckCheatData.ProcessBoosterTicks = TimeUtil.NOW(); } } } TCPOutPacket tcpOutPacket = null; TCPProcessCmdResults result = TCPProcessCmdResults.RESULT_FAILED; long processBeginTime = TimeUtil.NowEx(); if (tcpInPacket.PacketCmdID > 30000) { result = CCTCPCmdHandler.CCProcessCmd(this, tcpInPacket.CurrentSocket, tcpClientPool, tcpRandKey, tcpOutPacketPool, tcpInPacket.PacketCmdID, bytesData, tcpInPacket.PacketDataSize - 1 - 4, out tcpOutPacket); } else { result = TCPCmdHandler.ProcessCmd(this, tcpInPacket.CurrentSocket, tcpClientPool, tcpRandKey, tcpOutPacketPool, tcpInPacket.PacketCmdID, bytesData, tcpInPacket.PacketDataSize - 1 - 4, out tcpOutPacket); } long processTime = (TimeUtil.NowEx() - processBeginTime); if (GameManager.StatisticsMode > 0 || processTime > 50 || result == TCPProcessCmdResults.RESULT_FAILED) { RecordCmdDetail(tcpInPacket.PacketCmdID, processTime, tcpInPacket.PacketDataSize, result); } if (result == TCPProcessCmdResults.RESULT_DATA && null != tcpOutPacket) { // Console.WriteLine("===>>> tcpOutPacket==== " + tcpOutPacket.PacketCmdID.ToString()); //向登陆客户端返回数据 socketListener.SendData(tcpInPacket.CurrentSocket, tcpOutPacket); } else if (result == TCPProcessCmdResults.RESULT_FAILED)//解析失败, 直接关闭连接 { if (tcpInPacket.PacketCmdID != (int)TCPGameServerCmds.CMD_LOG_OUT) { SysConOut.WriteLine(string.Format("解析并执行命令失败: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket))); LogManager.WriteLog(LogTypes.Error, string.Format("解析并执行命令失败: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket))); } return(false); } } //#endif } else { var _s = tcpInPacket.CurrentSocket; string uid = _s != null?GameManager.OnlineUserSession.FindUserID(_s) : "socket is nil"; SysConOut.WriteLine(string.Format("校验客户端发送的指令数据完整性失败: {0},{1}, 错误码:{2}, uid={3}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode, uid)); LogManager.WriteLog(LogTypes.Error, string.Format("校验客户端发送的指令数据完整性失败: {0},{1}, 错误码:{2}, uid={3}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket), checkErrorCode, uid)); return(false); } } else if (1 == doType) //正常的登录指令包//策略验证请求 { //直接发送策略数据 DirectSendPolicyFileData(tcpInPacket); } else { SysConOut.WriteLine(string.Format("解析并执行命令时类型未知: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket))); LogManager.WriteLog(LogTypes.Error, string.Format("解析并执行命令时类型未知: {0},{1}, 关闭连接", (TCPGameServerCmds)tcpInPacket.PacketCmdID, Global.GetSocketRemoteEndPoint(tcpInPacket.CurrentSocket))); //socketListener.CloseSocket(tcpInPacket.CurrentSocket); return(false); } return(true); }
public override void Initialize() { HandleCommandLine(Environment.GetCommandLineArgs()); if (!Directory.Exists(SavePath)) Directory.CreateDirectory(SavePath); DateTime now = DateTime.Now; string logFilename; try { logFilename = Path.Combine(SavePath, now.ToString(LogFormat)+".log"); } catch(Exception) { // Problem with the log format use the default logFilename = Path.Combine(SavePath, now.ToString(LogFormatDefault) + ".log"); } #if DEBUG Log.Initialize(logFilename, LogLevel.All, false); #else Log.Initialize(logFilename, LogLevel.All & ~LogLevel.Debug, LogClear); #endif AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; try { if (File.Exists(Path.Combine(SavePath, "tshock.pid"))) { Log.ConsoleInfo( "TShock was improperly shut down. Please use the exit command in the future to prevent this."); File.Delete(Path.Combine(SavePath, "tshock.pid")); } File.WriteAllText(Path.Combine(SavePath, "tshock.pid"), Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture)); ConfigFile.ConfigRead += OnConfigRead; FileTools.SetupConfig(); HandleCommandLinePostConfigLoad(Environment.GetCommandLineArgs()); if (Config.StorageType.ToLower() == "sqlite") { string sql = Path.Combine(SavePath, "tshock.sqlite"); DB = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); } else if (Config.StorageType.ToLower() == "mysql") { try { var hostport = Config.MySqlHost.Split(':'); DB = new MySqlConnection(); DB.ConnectionString = String.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", hostport[0], hostport.Length > 1 ? hostport[1] : "3306", Config.MySqlDbName, Config.MySqlUsername, Config.MySqlPassword ); } catch (MySqlException ex) { Log.Error(ex.ToString()); throw new Exception("MySql not setup correctly"); } } else { throw new Exception("Invalid storage type"); } Backups = new BackupManager(Path.Combine(SavePath, "backups")); Backups.KeepFor = Config.BackupKeepFor; Backups.Interval = Config.BackupInterval; Bans = new BanManager(DB); Warps = new WarpManager(DB); Users = new UserManager(DB); Groups = new GroupManager(DB); Regions = new RegionManager(DB); Itembans = new ItemManager(DB); RememberedPos = new RemeberedPosManager(DB); InventoryDB = new InventoryManager(DB); RestApi = new SecureRest(Netplay.serverListenIP, Config.RestApiPort); RestApi.Verify += RestApi_Verify; RestApi.Port = Config.RestApiPort; RestManager = new RestManager(RestApi); RestManager.RegisterRestfulCommands(); var geoippath = Path.Combine(SavePath, "GeoIP.dat"); if (Config.EnableGeoIP && File.Exists(geoippath)) Geo = new GeoIPCountry(geoippath); Log.ConsoleInfo(string.Format("TerrariaShock Version {0} ({1}) now running.", Version, VersionCodename)); GameHooks.PostInitialize += OnPostInit; GameHooks.Update += OnUpdate; ServerHooks.Connect += OnConnect; ServerHooks.Join += OnJoin; ServerHooks.Leave += OnLeave; ServerHooks.Chat += OnChat; ServerHooks.Command += ServerHooks_OnCommand; NetHooks.GetData += OnGetData; NetHooks.SendData += NetHooks_SendData; NetHooks.GreetPlayer += OnGreetPlayer; NpcHooks.StrikeNpc += NpcHooks_OnStrikeNpc; NpcHooks.SetDefaultsInt += OnNpcSetDefaults; ProjectileHooks.SetDefaults += OnProjectileSetDefaults; WorldHooks.StartHardMode += OnStartHardMode; WorldHooks.SaveWorld += SaveManager.Instance.OnSaveWorld; GetDataHandlers.InitGetDataHandler(); Commands.InitCommands(); //RconHandler.StartThread(); if (Config.RestApiEnabled) RestApi.Start(); if (Config.BufferPackets) PacketBuffer = new PacketBufferer(); Log.ConsoleInfo("AutoSave " + (Config.AutoSave ? "Enabled" : "Disabled")); Log.ConsoleInfo("Backups " + (Backups.Interval > 0 ? "Enabled" : "Disabled")); if (Initialized != null) Initialized(); } catch (Exception ex) { Log.Error("Fatal Startup Exception"); Log.Error(ex.ToString()); Environment.Exit(1); } }
private void BanPlayer(object sender, RoutedEventArgs e) { selectedReport = (Reporte)tableOfReports.SelectedItem; bannedPlayer = selectedReport.Reportado; BanManager.BanPlayer(bannedPlayer.Apodo); }