private void TaskMonitor() { while (!_workerTerminateSignal) { Task t; lock (Task.Tasks) { t = Task.Next; } _waitHandle.WaitOne(t.TimeSpan); if (_workerTerminateSignal) { break; } if (_debug) { AppConsole.Log(String.Format("Running Task: {0} {1}", t.Command.Type, t.Command.Parameters), ConsoleColor.DarkMagenta); } else { _api.SendCommand(t.Command); } lock (Task.Tasks) { t.Increment(); } } }
public void Connect() { for (var tries = 1; tries <= _maxtries; tries++) { try { _beclient.Connect(); if (!_beclient.Connected) { throw new CoreException(); } break; } catch { AppConsole.Log(String.Format("Failed to connect to server. Attempt {0}/{1}", tries, _maxtries), ConsoleColor.Red); } Thread.Sleep(1000); } if (!_beclient.Connected) { throw new CoreException("Failed to connect to server."); } _connected = true; }
private void TaskMonitor() { var messagePointer = 0; while (!_workerTerminateSignal) { var next = _intervals[messagePointer]; messagePointer++; var ts = next - DateTime.Now; if (ts.TotalSeconds > 0) { _waitHandle.WaitOne(ts); if (_workerTerminateSignal) { break; } } var restart = _runtime - DateTime.Now; var message = String.Format(_message, restart.Humanize(2)); for (var i = 1; i <= _repeat; i++) { AppConsole.Log(String.Format("Sending Message: {0}", message), ConsoleColor.DarkMagenta); if (!_debug) { _api.SendCommand(new Command(String.Format("say -1 {0}", message))); } } } }
void _timer_Elapsed(object sender, ElapsedEventArgs e) { var message = _ini.GetSetting("Messages", _messages[_messagePointer]); _messagePointer++; if (String.IsNullOrWhiteSpace(message)) { return; } message = String.Format("{0} {1}", _prefix, message); AppConsole.Log(String.Format("{0}: {1}", Name, message), ConsoleColor.Magenta); var cmd = new Command() { Type = Command.CmdType.Say, Parameters = String.Format("-1 {0}", message) }; _api.SendCommand(cmd); if (_messagePointer >= _messages.Length) { if (_repeat) { _messagePointer = 0; } else { Kill(); } } }
public PluginManager(string pluginPath) { AppConsole.Log("Loading Plugins..."); var dirs = Directory.GetDirectories(pluginPath, "*", SearchOption.TopDirectoryOnly); var pluginType = typeof(IPlugin); foreach (var dir in dirs) { var name = Path.GetFileName(dir); var dll = Path.Combine(dir, String.Format("{0}.dll", name)); try { if (!File.Exists(dll)) { throw new CoreException(String.Format("The dll \"{0}\" was not found.", dll)); } var an = AssemblyName.GetAssemblyName(dll); var assembly = Assembly.Load(an); if (assembly == null) { continue; } var types = assembly.GetTypes(); foreach (var type in types) { if (type.IsInterface || type.IsAbstract) { continue; } if (type.GetInterface(pluginType.FullName) == null) { continue; } var pluginInstance = (IPlugin)Activator.CreateInstance(type); var plugin = new Plugin() { Instance = pluginInstance, DllPath = dir }; _pluginCollection.Add(plugin); } } catch (Exception ex) { AppConsole.Log(String.Format("Error loading plugin {0}: {1} - {2}", name, ex.Message, ex), ConsoleColor.Red); } } }
public void Init(IApi api, string dllpath) { _api = api; _dllpath = dllpath; try { _ini = new IniParser(_configPath); } catch (Exception ex) { throw new WebRconException(String.Format("Error loading config: {0}", ex.Message)); } _enabled = _ini.GetBoolSetting(Name, "Enabled"); if (!_enabled) { throw new WebRconException(String.Format("{0} has been disabled", Name)); } var port = _ini.GetSetting(Name, "Port"); try { _port = Convert.ToInt32(port); } catch (Exception ex) { throw new WebRconException(String.Format("Invalid port: {0}", ex.Message)); } _password = _ini.GetSetting(Name, "Password"); if (_password == "") { _password = Utils.GetRandomString(); } #if DEBUG _serverurl = String.Format("http://localhost:{0}/", _port); #else _serverurl = String.Format("http://*:{0}/", _port); #endif _webServer = new WebServer(HttpRequest, _serverurl); _webServer.Run(); AppConsole.Log(String.Format("Started HTTP server at {0}. Password: {1}", _serverurl, _password), ConsoleColor.Cyan); _port++; _socketServer = new WebSocketServer(_port); _socketServer.AddWebSocketService("/rcon", () => new SocketBehavior(_api, _password)); _socketServer.Start(); LoadHtdocsFiles(); }
private void FilterMonitor() { _modified = new Dictionary <string, DateTime>(); foreach (var f in _filters) { var file = Path.Combine(_api.Settings.BePath, f); if (!File.Exists(file)) { AppConsole.Log(String.Format("Could not find BEFilter: {0}", f)); continue; } var info = new FileInfo(file); _modified.Add(file, info.LastWriteTime); } while (!_workerTerminateSignal) { _waitHandle.WaitOne(_interval); if (_workerTerminateSignal) { break; } foreach (var key in new List <string>(_modified.Keys)) { var info = new FileInfo(key); if (info.LastWriteTime > _modified[key]) { _modified[key] = info.LastWriteTime; AppConsole.Log(String.Format("Filter {0} has been updated.", info.Name)); Command command; if (info.Name == "scripts") { command = new Command() { Type = Command.CmdType.LoadScripts }; } else { command = new Command() { Type = Command.CmdType.loadEvents }; } _api.SendCommand(command); } } } }
internal void Kill() { AppConsole.Log("Unloading MBCon"); try { _pluginManager.Kill(); _beclient.Disconnect(); _api.Dispose(); } catch { // ignored } }
public void Kill() { if (_worker != null) { _workerTerminateSignal = true; _waitHandle.Set(); if (!_worker.Join(TimeSpan.FromMinutes(1))) { AppConsole.Log("Worker busy, aborting the thread.", ConsoleColor.Red); _worker.Abort(); } _worker = null; } }
internal void Init(IApi _api) { foreach (var t in _pluginCollection.ToArray()) { try { t.Instance.Init(_api, t.DllPath); } catch (Exception ex) { AppConsole.Log(String.Format("Plugin {0} loading failed: {1}", t.Instance.Name, ex.Message), ConsoleColor.Yellow); _pluginCollection.Remove(t); } } }
void _be_MessageEventHandler(Message message) { var color = ConsoleColor.DarkGray; switch (message.Type) { case Message.MessageType.ConnectGUID: case Message.MessageType.ConnectIP: case Message.MessageType.ConnectLegacyGUID: color = ConsoleColor.Blue; break; case Message.MessageType.Disconnect: color = ConsoleColor.DarkBlue; break; case Message.MessageType.Kick: color = ConsoleColor.Red; break; case Message.MessageType.Chat: color = ConsoleColor.White; if (message.Content.StartsWith("(Side)")) { color = ConsoleColor.Cyan; } if (message.Content.StartsWith("(Vehicle)")) { color = ConsoleColor.Yellow; } if (message.Content.StartsWith("(Direct)")) { color = ConsoleColor.White; } if (message.Content.StartsWith("(Group)")) { color = ConsoleColor.Green; } if (message.Content.StartsWith("(Global)")) { color = ConsoleColor.Gray; } break; } AppConsole.Log(message.Content, color); }
void onBEMessageReceivedEvent(Message message) { if (!( message.Type == Message.MessageType.ConnectLegacyGUID || message.Type == Message.MessageType.ConnectGUID || (_checkip && message.Type == Message.MessageType.ConnectIP) )) { return; } Player player; try { player = new Player(message); } catch (Exception ex) { AppConsole.Log(String.Format("Error paring be message: {0}", ex.Message), ConsoleColor.Red); return; } bool check; try { check = _driver.CheckPlayer(player); } catch (Exception ex) { AppConsole.Log(String.Format("Error checking player: {0}", ex.Message), ConsoleColor.Red); Console.WriteLine(ex.StackTrace); return; } var kick = (check && _mode == Mode.Blacklist) || (!check && _mode == Mode.Whitelist); if (kick) { var cmd = new Command() { Type = Command.CmdType.Kick, Parameters = String.Format("{0} {1}", player.Id, _kickMessage) }; AppConsole.Log(String.Format("Kicking {0}", player.Name)); _api.SendCommand(cmd); } }
private void BattlEyeConnected(BattlEyeConnectEventArgs args) { if (args.ConnectionResult == BattlEyeConnectionResult.Success) { AppConsole.Log(String.Format("Connected to {0}:{1}", _settings.Address, _settings.Port)); } else { AppConsole.Log(String.Format("Connection to {0}:{1} failed: {2}", _settings.Address, _settings.Port, args.Message), ConsoleColor.Red); if (_connected) { Thread.Sleep(2000); Environment.Exit(0); } } }
internal void Kill() { AppConsole.Log("Unloading Plugins"); foreach (var t in _pluginCollection) { try { AppConsole.Log(String.Format("Unloading {0}", t.Instance.Name)); t.Instance.Kill(); } catch { // ignored } } }
private void SendLog(Job job) { try { using (var client = new WebClient()) { var reqparm = new NameValueCollection { { "message", job.message }, { "type", job.type } }; client.UploadValues(_uri, "POST", reqparm); } } catch (Exception ex) { AppConsole.Log(String.Format("Error posting log: {0}", ex.Message), ConsoleColor.Red); } }
private void ProcessLogin(LoginRequest req) { if (req.password == _password) { SendLoginResult(true); SendToken(); _authed = true; _api.OnBeMessageReceivedEvent += onBEMessageReceivedEvent; SendPlayerList(_api.Players); _api.OnPlayerListUpdatedEvent += onPlayerListUpdatedEvent; } else { AppConsole.Log("User tried tried to login with the wrong password."); SendLoginResult(false); } }
private BattlEyeClient BEClient() { AppConsole.Log("Loading BEClient..."); var login = new BattlEyeLoginCredentials { Host = _settings.Address, Port = _settings.Port, Password = _settings.RconPass }; var beclient = new BattlEyeClient(login) { ReconnectOnPacketLoss = true }; beclient.BattlEyeConnected += BattlEyeConnected; beclient.BattlEyeDisconnected += BattlEyeDisconnected; return(beclient); }
public WSBanListPacket(string[] bansfile) : base(4) { var i = 0; foreach (var line in bansfile) { var ban = line.Trim(); try { var row = new Dictionary <string, string>(); if (rx.IsMatch(ban)) { var match = rx.Match(ban); row.Add("data", match.Groups["data"].Value); row.Add("time", match.Groups["time"].Value); try { row.Add("reason", match.Groups["reason"].Value); } catch { row.Add("reason", ""); } } else { throw new ArgumentException("Input string is not valid"); } row.Add("id", i.ToString()); bans.Add(row); } catch (Exception ex) { AppConsole.Log(String.Format("Error parsing line '{0}'. {1}", ban, ex.Message), ConsoleColor.Red); } i++; } }
static void Main(string[] args) { Console.CancelKeyPress += delegate { core.Kill(); }; handler = ConsoleEventCallback; SetConsoleCtrlHandler(handler, true); Console.Title = "MBCon - Connected"; Console.OutputEncoding = Encoding.UTF8; core = new Core(); try { core.Run(args); } catch (CoreException ex) { core.Kill(); AppConsole.Log(String.Format("ERROR: {0}", ex.Message), ConsoleColor.Red); Thread.Sleep(5000); } }
new public void SetConfig(DriverSettings settings) { base.SetConfig(settings); var f = settings.Ini.GetSetting("File", "Path"); if (!Path.IsPathRooted(f)) { f = Path.Combine(settings.PluginPath, f); } if (!System.IO.File.Exists(f)) { throw new DriverException(String.Format("Could not load player list {0}", f)); } var file = new StreamReader(f); string line; while ((line = file.ReadLine()) != null) { _list.Add(line.Trim()); } AppConsole.Log(String.Format("PlayerCheck: Loaded {0} GUIDs into list.", _list.Count)); file.Close(); }
private void TaskMonitor() { while (!_workerTerminateSignal) { Task t; lock (Task.Tasks) { t = Task.Next; } if (t == null) { continue; } try { _waitHandle.WaitOne(t.TimeSpan); } catch (ArgumentOutOfRangeException ex) { throw new ScheduledTasksException(String.Format("t.TimeSpan is falling behind. (Start field is to soon?){0}", ex)); } catch (Exception ex) { throw new ScheduledTasksException(String.Format("{0}", ex)); } if (_workerTerminateSignal) { break; } if (_debug) { AppConsole.Log(String.Format("Running Task: {0} {1}", t.Command.Type, t.Command.Parameters), ConsoleColor.DarkMagenta); } else { if (t.Execute != null) { if (File.Exists(t.Execute.Trim().Replace("/", @"\"))) { AppConsole.Log(String.Format("Running Executefile: {0}", ConsoleColor.DarkMagenta)); ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.FileName = t.Execute.Trim().Replace("/", @"\"); processInfo.Arguments = ""; processInfo.CreateNoWindow = false; processInfo.UseShellExecute = true; processInfo.RedirectStandardError = false; processInfo.RedirectStandardOutput = false; Process process = Process.Start(processInfo); } else { AppConsole.Log(String.Format("Executefile doesn't exist: {0}", t.Execute.Trim().Replace("/", @"\")), ConsoleColor.DarkMagenta); } } if (t.Command != null) { _api.SendCommand(t.Command); } } lock (Task.Tasks) { t.Increment(); } } }
public Result Execute(Query query) { MySqlConnection connection = null; MySqlDataReader reader = null; var result = new Result(); try { connection = new MySqlConnection(String.Format( @"server={0};userid={1};password={2};database={3}", query.Conn.Host, query.Conn.User, query.Conn.Password, query.Conn.Database )); connection.Open(); var sql = query.Sql; var command = new MySqlCommand(sql, connection); foreach (var param in query.Params) { command.Parameters.AddWithValue(param.Key, param.Value); } if (query.QueryType != Query.Type.Select) { command.ExecuteNonQuery(); result.NoResult = true; } else { reader = command.ExecuteReader(); while (reader.Read()) { var line = new Dictionary <string, string>(); for (var i = 0; i < reader.FieldCount; i++) { var val = (!reader.IsDBNull(i)) ? reader.GetString(i) : ""; line.Add(reader.GetName(i), val); } result.Rows.Add(line); } } } catch (MySqlException ex) { AppConsole.Log(String.Format("MYSQL ERROR: {0}", ex.Message)); result.Error = true; } finally { if (reader != null) { reader.Close(); } if (connection != null) { connection.Close(); } } return(result); }
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args) { var e = (Exception)args.ExceptionObject; AppConsole.Log(String.Format("Unhandled Exception: {0} - {1}", e.Message, e.StackTrace)); }
public static void LoadTasks(IniParser ini) { var _i = -1; while (true) { var now = DateTime.Now; _i++; var command = ini.GetSetting("Tasks", String.Format("Command{0}", _i)); if (String.IsNullOrWhiteSpace(command)) { if (_i == 0) { continue; } else { AppConsole.Log("Finished loading tasks", ConsoleColor.DarkMagenta); break; } } Command cmd; DateTime nextRun; var interval = TimeSpan.FromDays(1); var loop = 1; try { cmd = new Command(command); } catch (CommandException ex) { AppConsole.Log(String.Format("Error loading task {0}: {1}", _i, ex.Message), ConsoleColor.Red); continue; } var time = ini.GetSetting("Tasks", String.Format("Time{0}", _i)); if (!String.IsNullOrWhiteSpace(time)) { try { var h = Convert.ToDouble(time.Substring(0, 2)); var m = Convert.ToDouble(time.Substring(2, 2)); nextRun = DateTime.Today; nextRun = nextRun.AddHours(h); nextRun = nextRun.AddMinutes(m); if (now > nextRun) { nextRun = nextRun.Add(interval); } } catch (Exception ex) { AppConsole.Log(String.Format("Error loading task: Bad String Time {0}", ex.Message), ConsoleColor.Red); continue; } } else { try { interval = TimeSpan.FromSeconds(Convert.ToInt32(ini.GetSetting("Tasks", String.Format("Interval{0}", _i)))); } catch (Exception ex) { AppConsole.Log(String.Format("Error loading task: Bad String Interval {0}", ex.Message), ConsoleColor.Red); continue; } TimeSpan delay; try { delay = TimeSpan.FromSeconds(Convert.ToDouble(ini.GetSetting("Tasks", String.Format("Delay{0}", _i), "0"))); } catch { delay = new TimeSpan(); } loop = (ini.GetBoolSetting("Tasks", String.Format("Repeat{0}", _i))) ? -1 : 1; nextRun = now.Add(delay); nextRun = nextRun.Add(interval); } var task = new Task() { _command = cmd, _nextRun = nextRun, _loop = loop, _interval = interval }; _tasks.Add(task); } AppConsole.Log(String.Format("Added {0} tasks", _tasks.Count), ConsoleColor.DarkMagenta); }
public static void LoadFromJSON(string jsonPath) { dynamic tasks; var now = DateTime.Now; try { var json = File.ReadAllText(jsonPath); tasks = JsonConvert.DeserializeObject(json); } catch (Exception ex) { throw new ScheduledTasksException(String.Format("Could not open or parse schedule json file: {0}", ex.Message)); } var i = 0; foreach (var item in tasks) { i++; string start; string execute; Command cmd; DateTime nextRun; int interval; int loop; try { start = item.start.ToString(); if (String.IsNullOrWhiteSpace(start)) { throw new ScheduledTasksException("Tasks need to have a start defined."); } } catch (Exception ex) { throw new ScheduledTasksException(String.Format("Could not parse command: {0}", ex.Message)); } try { if (item.execute != null) { execute = item.execute.ToString(); } else { execute = null; } } catch (CommandException ex) { AppConsole.Log(String.Format("Could not parse execute: {0}", ex.Message), ConsoleColor.Red); execute = ""; } try { if (item.cmd != null) { cmd = new Command(item.cmd.ToString()); } else { cmd = null; } } catch (CommandException ex) { AppConsole.Log(String.Format("Could not parse command: {0}", ex.Message), ConsoleColor.Red); cmd = null; } try { loop = Convert.ToInt16(item.loop.ToString()); } catch { loop = -1; } if (loop == 0) { throw new ScheduledTasksException("Loop can not be 0."); } try { interval = Convert.ToInt16(item.interval.ToString()); } catch { interval = -1; } if (Regex.Match(start, "^[0-9]{2}:[0-9]{2}:[0-9]{2}$", RegexOptions.IgnoreCase).Success) { // hh:mm:ss var h = Convert.ToDouble(start.Substring(0, 2)); var m = Convert.ToDouble(start.Substring(3, 2)); var s = Convert.ToDouble(start.Substring(6, 2)); nextRun = DateTime.Today; nextRun = nextRun.AddHours(h); nextRun = nextRun.AddMinutes(m); nextRun = nextRun.AddSeconds(s); interval = 86400; if (now > nextRun) { nextRun = nextRun.AddSeconds(interval); } } else if (Regex.Match(start, "^[0-9]+$", RegexOptions.IgnoreCase).Success) { // hhmmss nextRun = now.AddSeconds(Convert.ToDouble(start)); } else { throw new ScheduledTasksException("The time field is formatted incorrectly."); } var task = new Task() { _execute = execute, _command = cmd, _nextRun = nextRun, _interval = TimeSpan.FromSeconds(interval), _loop = loop }; _tasks.Add(task); } }
public void Init(IApi api, string dllpath) { _api = api; _dllpath = dllpath; try { _ini = new IniParser(_configPath); } catch (Exception ex) { throw new ScheduledTasksException(String.Format("Error loading config: {0}", ex.Message)); } _enabled = _ini.GetBoolSetting("ScheduledTasks", "Enabled"); if (!_enabled) { throw new ScheduledTasksException(String.Format("{0} has been disabled", Name)); } _debug = _ini.GetBoolSetting("ScheduledTasks", "Debug"); _schedule = _ini.GetSetting("ScheduledTasks", "Schedule"); if (_schedule == "") { throw new ScheduledTasksException(String.Format("{0} has been disabled. No schedule defined.", Name)); } if (!Path.IsPathRooted(_schedule)) { _schedule = Path.Combine(_dllpath, _schedule); } var ext = Path.GetExtension(_schedule); if (ext == ".json") { Task.LoadFromJSON(_schedule); } if (_debug) { var i = 0; AppConsole.Log("---------------", ConsoleColor.DarkMagenta); AppConsole.Log("Scheduled Tasks", ConsoleColor.DarkMagenta); AppConsole.Log("---------------", ConsoleColor.DarkMagenta); foreach (var t in Task.Tasks) { i++; AppConsole.Log(String.Format("Task {0}", i), ConsoleColor.DarkMagenta); AppConsole.Log(String.Format("Running in about {0}", t.TimeSpan.Humanize(2, true)), ConsoleColor.DarkMagenta); if (t.Loop != 1) { AppConsole.Log(String.Format("Repeating every {0}, {1} times", t.Interval.Humanize(2, true), t.Loop), ConsoleColor.DarkMagenta); } AppConsole.Log(String.Format("Command: {0} {1}", t.Command.Type, t.Command.Parameters), ConsoleColor.DarkMagenta); AppConsole.Log(""); } } if (Task.Tasks.Count == 0) { throw new ScheduledTasksException(String.Format("{0} has been disabled. No tasks found.", Name)); } _worker = new Thread(TaskMonitor); _worker.Start(); }
protected override void OnClose(CloseEventArgs e) { AppConsole.Log(String.Format("User disconnected from WebCon. {0}", e.Reason)); CloseConnection(); }
private void BattlEyeDisconnected(BattlEyeDisconnectEventArgs args) { AppConsole.Log("BE Disconnected", ConsoleColor.Yellow); Thread.Sleep(2000); Environment.Exit(0); }
public void Run(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Console.Title = "MBCon - Connecting..."; #if DEBUG AppConsole.Log(String.Format("MBCon - WARNING THIS IS A DEBUG APP!!!"), ConsoleColor.Red); AppConsole.Log(String.Format("MBCon - WARNING THIS IS A DEBUG APP!!!"), ConsoleColor.Red); AppConsole.Log(String.Format("MBCon - WARNING THIS IS A DEBUG APP!!!"), ConsoleColor.Red); AppConsole.Log(String.Format("MBCon - WARNING THIS IS A DEBUG APP!!!"), ConsoleColor.Red); AppConsole.Log(String.Format("MBCon - WARNING THIS IS A DEBUG APP!!!"), ConsoleColor.Red); #else AppConsole.Log(String.Format("=========================="), ConsoleColor.DarkCyan); AppConsole.Log(String.Format("MBCon - by maca134"), ConsoleColor.Cyan); AppConsole.Log(String.Format("*****@*****.**"), ConsoleColor.Gray); AppConsole.Log(String.Format("=========================="), ConsoleColor.DarkCyan); AppConsole.Log(""); Thread.Sleep(4000); #endif _args.Setup <string>("config") .Callback(val => _configPath = val) .SetDefault(Path.Combine(BasePath, "config.ini")); _args.Setup <int>("delay") .Callback(val => _startupDelay = val) .SetDefault(0); _args.Parse(args); if (!File.Exists(_configPath)) { throw new CoreException(String.Format("Config file \"{0}\" was not found.", _configPath)); } AppConsole.Log("Config file found, continuing to load..."); var ini = new IniParser(_configPath); try { _settings = new Settings(ini); } catch (SettingsException ex) { throw new CoreException(String.Format("Error Loading Settings: {0}", ex.Message)); } if (_startupDelay > 0) { AppConsole.Log(string.Format("Waiting for {0} seconds", _startupDelay)); Thread.Sleep(_startupDelay * 1000); } _beclient = BEClient(); _pluginManager = new PluginManager(PluginPath); _api = new Api(_beclient, _settings); _pluginManager.Init(_api); AppConsole.Log("Connecting to server..."); Connect(); }
private void CloseConnection() { AppConsole.Log("Removing BE event."); _api.OnBeMessageReceivedEvent -= onBEMessageReceivedEvent; _api.OnPlayerListUpdatedEvent -= onPlayerListUpdatedEvent; }