public void returnBlueprint(string printName, string printData) { var options = Options.Current; if (options.rconplayer != null) { var rcon = new Rcon(); var rconhost = new System.Net.IPEndPoint( System.Net.Dns.GetHostEntry(options.rconhost).AddressList[0], options.rconport); const string rconcommand = "/c remote.call('foreman','addBlueprint',game.players['{0}'],{1},{2})"; Console.WriteLine("Sending {0} to Foreman by RCON...", printName); rcon.ConnectBlocking(rconhost, options.rconpass); rcon.ServerCommandBlocking( string.Format(rconcommand, options.rconplayer, Compress(printData), printName)); rcon.Disconnect(); } else { Console.WriteLine(printName); //Console.WriteLine(printData); Console.WriteLine(Compress(printData)); Console.WriteLine(""); } }
private Task StartConnectionAsync() { var server = ServerQuery.GetServerInstance(EngineType.Source, this.endpoint); this.console = server.GetControl(this.password); return(Task.FromResult(true)); }
private bool Reconnect() { if (this.console != null) { this.console.Dispose(); this.console = null; } try { var endpoint = new IPEndPoint(IPAddress.Parse(this.snapshot.ServerIP), this.snapshot.RCONPort); var server = ServerQuery.GetServerInstance(EngineType.Source, endpoint); this.console = server.GetControl(this.snapshot.AdminPassword); return(true); } catch (Exception ex) { _logger.Debug("Failed to connect to RCON at {0}:{1} with {2}: {3}\n{4}", this.snapshot.ServerIP, this.snapshot.RCONPort, this.snapshot.AdminPassword, ex.Message, ex.StackTrace); return(false); } }
private void button2_Click_1(object sender, EventArgs e) { sr = new Rcon(); sr.ConnectionSuccess += new BoolInfo(sr_ConnectionSuccess); sr.ServerOutput += new RconOutput(sr_ServerOutput); sr.Errors += new RconOutput(sr_Errors); }
static void Main(string[] args) { // Initialise connection Rcon rcon = new Rcon("rust.yourserver.com", 26101, "your rcon passphrase"); // Single command rcon.Send("say \"Thank [color#FF0000]you [color#FFFFFF]for choosing this RCON class.\""); // Command with (multipart) reply Package command = new Package("banlistex"); command.RegisterCallback((Package result) => { rcon.Send(String.Format("say \"There are {0} entries on your ban list.\"", result.Response.Split('\n').Length)); }); // Note that result and command are the same object. rcon.SendPackage(command); // Handle passive traffic (eg. chat, join and quit messages, ...) Task passive = new Task(() => { while (true) { Package package = rcon.ReadPackage(); if (Regex.IsMatch(package.Response, "^\\[CHAT\\] \\\".*\\\":\\\".*\\\"$")) { Console.WriteLine("Chat message received."); } else if (Regex.IsMatch(package.Response, "^User Connected: .* \\(\\d+\\)$")) { Console.WriteLine("User connected."); } } }); passive.Start(); Task.WaitAll(new Task[] { passive }); }
public void Run(Rcon rcon) { this.rcon = rcon; new Task(() => { cron_announce(); }).Start(); new Task(() => { cron_airdrop(); }).Start(); new Task(() => { cron_count(); }).Start(); new Task(() => { cron_userstats(); }).Start(); new Task(() => { cron_hourly(); }).Start(); new Task(() => { cron_ig_hourly(); }).Start(); new Task(() => { cron_irc(); }).Start(); new Task(() => { cron_actions(); }).Start(); }
public bool ConnectRCON() { try { rcon = ServerQuery.GetServerInstance(EngineType.Source, loadedServer.getRCONIPEndPoint()).GetControl(loadedServer.RCONpw); WriteLog("Connected to RCON"); return(true); } catch { WriteLog("Connecting to RCON failed"); return(false); } }
public async Task <Rcon.RconResponse> Kick(int connection, string reason, int duration) { if (duration <= 0) { return new Rcon.RconResponse() { Success = false, Message = "Invalid duration." } } ; var response = await Rcon.Ban(connection, reason, BanType.IP, duration); OnKick?.Invoke(this, connection, reason, duration); return(response); }
public void Login() { while (true) { var result = Rcon.GetConsole(); var newName = Re.GetSubString(result, @"Server name '(.*?)'"); if (!String.IsNullOrWhiteSpace(newName)) { Name = newName; break; } else { Thread.Sleep(1000); } } }
public async Task <Rcon.RconResponse> Kick(int connection, string reason) { //TODO: Make this return a kick response code //https://www.youtube.com/watch?v=Qku9aoUlTXA if (Rcon == null) { Logger.LogWarning("Cannot kick a player because the RCON server is not enabled."); return(await Task.FromResult(new Rcon.RconResponse() { Success = false, Message = "Rcon not enabled" })); } //Kick the connection var response = await Rcon.Kick(connection, reason); OnKick?.Invoke(this, connection, reason, -1); return(response); }
/// <summary> /// Saves the starbound setting, making a backup of the previous one first. /// </summary> /// <param name="reload">Should RCON Reload be executed on success?</param> /// <returns>True if saved succesfully.</returns> public async Task <bool> SaveConfigurationAsync(bool reload = false) { Logger.Log("Writing configuration to file."); try { //Export the settings and then serialize it Settings settings = await Configurator.ExportSettingsAsync(); if (settings == null) { return(false); } string json = JsonConvert.SerializeObject(settings, Formatting.Indented, new Serializer.UserAccountsSerializer()); //Write all the text File.WriteAllText(ConfigurationFile, json); //Reload it if (reload) { Debug.Assert(Rcon != null); if (Rcon == null) { Logger.LogWarning("Cannot reload save because rcon does not exist."); } else { Logger.Log("Reloading the settings..."); await Rcon.ReloadServerAsync(); } } Logger.Log("Settings successfully saved."); return(true); } catch (Exception e) { Logger.LogError(e, "Exception Occured while saving: {0}"); return(false); } }
public Helper() { Settings = new Config(); loadedServer = null; rcon = null; //Config laden bzw. erstellen... if (!File.Exists(configPath)) { if (!Directory.Exists(Directory.GetParent(configPath).ToString())) { Directory.CreateDirectory(Directory.GetParent(configPath).ToString()); } SaveConfig(); } else { LoadConfig(); } }
public async Task RunRconCommand(ICommandContext context) { try { IGuildUser user = (IGuildUser)context.Message.Author; if (user.RoleIds.All(r => r != 592213288729968671)) { await context.Channel.SendMessageAsync("Code 4: Permission Denied."); return; } string[] args = context.Message.Content.Split(new[] { " " }, StringSplitOptions.None); string commandString = ConvertToString(args.Skip(1).ToArray()); Rcon rcon = server.Rcon; string response = rcon.SendCommand(commandString); if (string.IsNullOrEmpty(response)) { await context.Channel.SendMessageAsync("Command accepted, but no response from server was sent. This is *not* an error."); return; } if (response.Length > 2000) { IEnumerable <string> str = Split(response, 2000); foreach (string s in str) { await context.Channel.SendMessageAsync(s); } return; } await context.Channel.SendMessageAsync(response); } catch (Exception e) { Console.WriteLine(e); await context.Channel.SendMessageAsync("<@&530252029361127439> Code 0: Command failure!"); } }
private void btnConnectRCon_Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse("127.0.0.1"); int port = 12345; IPEndPoint ipe = new IPEndPoint(ip, port); sr = new Rcon(); sr.ConnectionSuccess += new BoolInfo(sr_ConnectionSuccess); sr.ServerOutput += new RconOutput(sr_ServerOutput); sr.Errors += new RconOutput(sr_Errors); sr.Connect(ipe, "12345"); while (!sr.Connected) { Thread.Sleep(10); } sr.ServerCommand("/p"); sr.ServerCommand("/p"); //playerBackGround.RunWorkerAsync(); }
public async Task <bool> SaveSettings(Settings settings, bool reload = false) { try { //Serialize it. Logger.Log("Serializing Settings..."); string json = await Task.Run <string>(() => JsonConvert.SerializeObject(settings, Formatting.Indented, new Serializer.UserAccountsSerializer())); //Save it Logger.Log("Writing Settings..."); File.WriteAllText(ConfigurationFile, json); //Reload it if (reload) { Debug.Assert(Rcon != null); if (Rcon == null) { Logger.LogWarning("Cannot reload save because rcon does not exist."); } else { Logger.Log("Reloading the settings..."); await Rcon.ReloadServerAsync(); } } Logger.Log("Settings successfully saved."); return(true); } catch (Exception e) { Logger.LogError(e, "Exception Occured while saving: {0}"); return(false); } }
private void button2_Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(IPBox.Text); int port = int.Parse(PortBox.Text); IPEndPoint ipe = new IPEndPoint(ip, port); sr = new Rcon(); sr.ConnectionSuccess += new BoolInfo(sr_ConnectionSuccess); sr.ServerOutput += new RconOutput(sr_ServerOutput); sr.Errors += new RconOutput(sr_Errors); sr.Connect(ipe, PasswordBox.Text); while (!sr.Connected) { Thread.Sleep(10); } sr.ServerCommand(Properties.Settings.Default.Players); sr.ServerCommand(Properties.Settings.Default.Players); playerBackGround.RunWorkerAsync(); //PlayerJob(); // Thread playerThread = new Thread(PlayerJob); // playerThread.Start(); }
static int Main(string[] args) { // Grab English strings for the interface. ILanguage lang = new English(); string password, command; IPAddress ip; int port; bool interactive; // Parse command-line to tell if we're doing a one-shot command or if we're running interactive. if (args.Length > 0) { // There are arguments, so not interactive. interactive = false; // Four arguments indicates this is a one-shot command. if (args.Length == 4) { try { ip = IPAddress.Parse(args[0]); port = int.Parse(args[1]); } catch (FormatException fe) { Console.WriteLine(lang["invalidparams"], fe.Message); return -1; } catch (OverflowException oe) { Console.WriteLine(lang["invalidparams"], oe.Message); return -1; } password = args[2]; command = args[3]; } else { // Print out the usage instructions. Console.WriteLine(lang["usage_instructions"]); return 1; } } else { interactive = true; #if DEBUG Console.WriteLine("Use quick debug? Press y, else anything else!"); if (Console.ReadKey().KeyChar == 'y') { Console.ReadLine(); Console.WriteLine(); ip = IPAddress.Parse("192.168.2.6"); port = 27015; password = "******"; } else { #endif // Walk the user through entering parameters, & prevent them from entering anything invalid: do { Console.WriteLine(lang["enterip"]); } while (!IPAddress.TryParse(Console.ReadLine(), out ip)); do { do { Console.WriteLine(lang["enterport"]); } while (!int.TryParse(Console.ReadLine(), out port)); } while (port < IPEndPoint.MinPort && port > IPEndPoint.MaxPort); // Valve's problem to stop people breaking the server with malformed passwords, not mine! Console.WriteLine(lang["enterpassword"]); password = Console.ReadLine(); #if DEBUG } #endif command = null; } using (Rcon Sr = new Rcon()) { #if DEBUG // Wire up our event handlers to receive errors from the server: Sr.Errors += (MessageCode, Message) => Console.WriteLine(lang["error"], MessageCode.ToString()); #endif bool IsConnected = false; // Now, we'll actually try to connect! try { IsConnected = Sr.ConnectBlocking(new IPEndPoint(ip, (int)port), password); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(lang["invalidparams"], e.Message); return -1; } if (IsConnected) { if (interactive) { Console.WriteLine(lang["commandready"]); // Just pull lines from the input and send them off. while (true) { // Sr.ServerCommand(Console.ReadLine()); Console.WriteLine(Sr.ServerCommandBlocking(Console.ReadLine())); } } else { // Fire a one-shot command. Console.WriteLine(Sr.ServerCommandBlocking(command)); } } else { // Not connected, so complain about it. Console.WriteLine(lang["noconn"]); } return 0; } }
static void Main(string[] args) { Rcon rcon = new Rcon("...", 0, "..."); Language.init(); Commands commands = new Commands(rcon); Cron cron = new Cron(); int prev_save = 0; Task passives = new Task(() => { while (true) { Package package = rcon.ReadPackage(); if (package == null) { Thread.Sleep(1000 / fps); continue; } // Handle passive traffic new Task(() => { try { /* * IP Filter in Chat */ if (Regex.IsMatch(package.Response, validations["ips"])) { Match match = Regex.Match(package.Response, validations["ips"]); User user = Data.Instance.GetUserByName(match.Groups[1].Value); Commands.warn(user, rcon); Data.Instance.HardLog(String.Format("Received IP in chat from user {0}, issuing warning.", user.Name)); } /* * Commands */ else if (Regex.IsMatch(package.Response, validations["command"])) { Match match = Regex.Match(package.Response.Replace("\\\"", "\""), validations["command"]); User user = User.GetUserByName(match.Groups[1].Value); if (user == null) { return; } string command = match.Groups[2].Value.Trim().ToLower(); while (command.Contains(' ')) { command = command.Substring(0, command.IndexOf(' ')); } string parameter = match.Groups[2].Value.Trim().Substring(command.Length).Trim(); string[] parameters = parameter.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Data.Instance.WriteToIRC(new ChatLog() { Text = String.Format("/{0}", match.Groups[2].Value), User = user, Time = DateTime.Now }); Data.Instance.HardLog(String.Format("Received command {0} from user {1}", command, user.Name)); new Task(() => { commands.Run(user, command, parameter, parameters); }).Start(); } /* * Join messages */ else if (Regex.IsMatch(package.Response, validations["join"])) { Match match = Regex.Match(package.Response, validations["join"]); User userbyid = User.GetUserById(match.Groups[2].Value); User userbyname = User.GetUserByName(match.Groups[1].Value); Data.Instance.HardLog(String.Format("Detected join of {0} ({1})", match.Groups[1].Value, match.Groups[2].Value)); // User already online if (userbyid != null && userbyid.Online) { Data.Instance.HardLog(String.Format("But {0} is already online, ignoring join.", userbyid.Name)); return; } // Nick already in use? if (userbyid != null && userbyname != null && userbyid.ID != userbyname.ID) { Data.Instance.WriteViolation(userbyid, 900001); rcon.Send("sleepers.on false"); rcon.Send(String.Format("kick \"{0}\"", userbyname.SafeName)); rcon.Send(Language.Say("kick-name", null, userbyname.SafeName)); rcon.Send("sleepers.on true"); Data.Instance.WriteToIRC(new ChatLog() { Text = String.Format("Duplicate nick: {0}", userbyid.Name), User = new User("-1", "#KICK"), Time = DateTime.Now }); Data.Instance.HardLog(String.Format("Duplicate name {0}, kicking both without sleeper", userbyname.Name)); return; } // Nick changed? if (userbyid != null && userbyname == null) { Data.Instance.HardLog(String.Format("Nick changed from {0} to {1}", userbyid.Name, match.Groups[1].Value)); rcon.Send(Language.Say("nick-change", userbyid, userbyid.Colour, userbyid.Name, match.Groups[1].Value)); userbyid.Name = match.Groups[1].Value; userbyid.Save(); } // No such user? if (userbyid == null && userbyname == null) { string id = match.Groups[2].Value; Package createUser = new Package("status"); createUser.RegisterCallback((Package result) => { match = null; MatchCollection matches = Regex.Matches(result.Response, validations["user-lines"]); foreach (Match submatch in matches) { if (submatch.Groups[1].Value == id) { match = submatch; break; } } if (match == null) { Data.Instance.HardLog(String.Format("New user {0} does not show up in status, aborting", match.Groups[1].Value)); throw new Exception("New user joined but did not show up in status."); } userbyid = new User(match.Groups[1].Value, match.Groups[2].Value, match.Groups[4].Value, match.Groups[5].Value); if (!whiteCountries.Contains(userbyid.Country)) { Data.Instance.HardLog(String.Format("User {0} joined from {1} which is blacklisted", userbyid.Name, userbyid.Country)); rcon.Send(Language.Say("blacklist", userbyid, match.Groups[2].Value, userbyid.Country)); rcon.Send(String.Format("banid {0} \"Blacklisted country: {1}\" \"{2}\"", match.Groups[1].Value, userbyid.Country, match.Groups[2].Value)); rcon.Send(String.Format("kick \"{0}\"", match.Groups[2].Value)); Data.Instance.WriteToIRC(new ChatLog() { Text = String.Format("Backlisted: {0} ({1})", userbyid.Name, userbyid.Country), User = new User("-1", "#KICK"), Time = DateTime.Now }); return; } VACResult vac = VACCheck.Check(userbyid.ID); if (vac.Count > 0 && vac.Days < 366) { Data.Instance.HardLog(String.Format("User {0} has {1} VACs in {2} days", userbyid.Name, vac.Count, vac.Days)); rcon.Send(Language.Say("vacd", userbyid, userbyid.Name, vac.Count, vac.Days)); rcon.Send(String.Format("banid {0} \"{1} VAC bans on record ({2} days)\" \"{3}\"", userbyid.ID, vac.Count, vac.Days, userbyid.SafeName)); rcon.Send(String.Format("kick \"{0}\"", userbyid.SafeName)); Data.Instance.WriteToIRC(new ChatLog() { Text = String.Format("VAC: {0} has {1} in {2} days", userbyid.Name, vac.Count, vac.Days), User = new User("-1", "#KICK"), Time = DateTime.Now }); return; } else if (vac.Count > 0) { rcon.Send(Language.Say("vacok", userbyid, userbyid.Colour, userbyid.Name, vac.Count, vac.Days)); } /*VACResult cheatpunch = VACCheck.CheatPunchCheck(userbyid.ID); * if (cheatpunch.Count > 0 && cheatpunch.Days > 0) * { * rcon.Send(Language.Say("cpd", userbyid, userbyid.Name)); * * rcon.Send(String.Format("banid {0} \"CheatPunch'd\"", userbyid.ID)); * rcon.Send(String.Format("kick \"{0}\"", userbyid.SafeName)); * return; * }*/ userbyid.Online = true; userbyid.Save(); rcon.Send(Language.Say("join", userbyid, userbyid.Colour, userbyid.Name, userbyid.Country)); rcon.Send(Language.Say("firstwelcome", userbyid, userbyid.Name)); rcon.Send(Language.Say("firstgreeting", userbyid)); Data.Instance.HardLog("New user creation successful."); Data.Instance.WriteJoin(userbyid); Data.Instance.WriteToIRC(new ChatLog() { Text = String.Format("{0} ({1}) (new)", userbyid.Name, userbyid.Country), User = new User("-1", "#JOIN"), Time = DateTime.Now }); }); rcon.SendPackage(createUser); return; } Data.Instance.HardLog("Old user activation successful."); userbyid.Online = true; userbyid.Save(); Data.Instance.WriteJoin(userbyid); rcon.Send(Language.Say("join", userbyid, userbyid.Colour, userbyid.Name, userbyid.Country)); rcon.Send(Language.Say("welcome", userbyid, userbyid.Colour, userbyid.Name)); Data.Instance.WriteToIRC(new ChatLog() { Text = String.Format("{0} ({1})", userbyid.Name, userbyid.Country), User = new User("-1", "#JOIN"), Time = DateTime.Now }); } /* * Quit messages */ else if (Regex.IsMatch(package.Response, validations["quit"])) { Match match = Regex.Match(package.Response, validations["quit"]); Data.Instance.HardLog(String.Format("Detected disconnect of {0}", match.Groups[1].Value)); User user = User.GetUserByName(match.Groups[1].Value); if (user != null && user.Online) { Package checkUserQuit = new Package("status"); checkUserQuit.RegisterCallback((Package result) => { match = null; MatchCollection matches = Regex.Matches(result.Response, validations["user-lines"]); foreach (Match submatch in matches) { if (submatch.Groups[1].Value == user.ID) { match = submatch; break; } } if (match != null) { Data.Instance.HardLog("But user is still connected..."); return; // User still connected } // TODO: Scenario: // User A and user B have the same nick, they have never been on the server // A joins, gets the nick registered and alt tabs out of the game // B joins, same nick is detected, kick is issued // User Disconnected message for user B with nick of both A and B // A is not in the status list, as he has tabbed out // A is detected as having disconnected, breaking time counting and commands user.Last = DateTime.Now.Ticks; rcon.Send(Language.Say("quit", user, user.Colour, user.Name)); user.Online = false; user.Save(); Data.Instance.WriteQuit(user); Data.Instance.WriteToIRC(new ChatLog() { Text = user.Name, User = new User("-1", "#QUIT"), Time = DateTime.Now }); Data.Instance.HardLog("Successfully disconnected"); }); rcon.SendPackage(checkUserQuit); } } /* * Chat log */ else if (Regex.IsMatch(package.Response, validations["chat"])) { Match match = Regex.Match(package.Response, validations["chat"]); User user = Data.Instance.GetUserByName(match.Groups[1].Value); Data.Instance.WriteChatLine(user, match.Groups[2].Value); Data.Instance.WriteToIRC(new ChatLog() { Text = match.Groups[2].Value, User = user, Time = DateTime.Now }); if (match.Groups[2].Value.ToLower().Contains("admin")) { rcon.Send(Language.Say("admhelp", user, user.Colour, user.Name)); } } /* * Suicide messages */ else if (Regex.IsMatch(package.Response, validations["suicide"])) { Match match = Regex.Match(package.Response, validations["suicide"]); User user = Data.Instance.GetUserByName(match.Groups[1].Value); rcon.Send(Language.Say("suicided", user, user.Colour, user.Name)); Data.Instance.WriteToIRC(new ChatLog() { Text = user.Name, User = new User("-1", "#SUICIDE"), Time = DateTime.Now }); Data.Instance.HardLog(String.Format("Suicide {0}", user.Name)); } /* * Violation messages */ else if (Regex.IsMatch(package.Response, validations["violation"])) { Match match = Regex.Match(package.Response, validations["violation"]); User user = Data.Instance.GetUserById(match.Groups[3].Value); rcon.Send(Language.Say("violation", user, user.Colour, user.Name, match.Groups[1].Value)); Data.Instance.WriteViolation(user, int.Parse(match.Groups[1].Value)); Data.Instance.WriteToIRC(new ChatLog() { Text = String.Format("Violation {0}: {1}", match.Groups[1].Value, user.Name), User = new User("-1", "#KICK"), Time = DateTime.Now }); Data.Instance.HardLog(String.Format("Violation {0} by user {1}", match.Groups[1].Value, user.Name)); } /* * Save messages */ else if (Regex.IsMatch(package.Response, validations["save"])) { Match match = Regex.Match(package.Response, validations["save"]); rcon.Send(Language.Say("save", null, match.Groups[1].Value)); Data.Instance.HardLog(String.Format("Saved {0} objects (diff {1})", match.Groups[1].Value, int.Parse(match.Groups[1].Value) - prev_save)); prev_save = int.Parse(match.Groups[1].Value); } /* * Save2 messages */ else if (Regex.IsMatch(package.Response, validations["save2"])) { // Ignore. } /* * Ticket cancelled messages */ else if (Regex.IsMatch(package.Response, validations["ticket"])) { Match match = Regex.Match(package.Response, validations["ticket"]); User user = Data.Instance.GetUserById(match.Groups[2].Value); rcon.Send(Language.Say("ticket", user, user.Colour, user.Name)); Data.Instance.HardLog(String.Format("Ticket for {0} was cancelled", user.Name)); } /* * Entry denied messages */ else if (Regex.IsMatch(package.Response, validations["entry"])) { Match match = Regex.Match(package.Response, validations["entry"]); User user = Data.Instance.GetUserById(match.Groups[1].Value); rcon.Send(Language.Say("entry", user, user.Colour, user.Name)); Data.Instance.HardLog(String.Format("Entry for {0} was denied", user.Name)); } /* * Validation messages */ else if (Regex.IsMatch(package.Response, validations["validator"])) { // TODO: handle. } /* * global.say messages */ else if (Regex.IsMatch(package.Response, validations["globalsay"])) { // TODO: handle. } /* * status messages */ else if (Regex.IsMatch(package.Response, validations["status"])) { // TODO: handle. } /* * time messages */ else if (Regex.IsMatch(package.Response, validations["time"])) { // TODO: handle. } /* * items messages */ else if (Regex.IsMatch(package.Response, validations["items"])) { // TODO: handle. } /* * topos messages */ else if (Regex.IsMatch(package.Response, validations["topos"])) { // TODO: handle. Data.Instance.HardLog(package.Response); } /* * move messages */ else if (Regex.IsMatch(package.Response, validations["moved"])) { // TODO: handle. Data.Instance.HardLog(package.Response); } /* * ondestroy messages */ else if (Regex.IsMatch(package.Response, validations["disposed"])) { commands.cmd_report(new User("-1", "CRITICAL"), "report", "SERVER WENT DOWN", new string[] { "SERVER", "WENT", "DOWN" }); Data.Instance.HardLog("SERVER WENT DOWN"); } /* * Everything else */ else { Console.WriteLine("Unhandled package:"); Data.Instance.HardLog("Unhandled package received"); Console.WriteLine(package.Response); } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); if (e.InnerException != null) { Console.WriteLine(e.InnerException.Message); } Data.Instance.HardLog(e.Message); } }).Start(); } }); Task crons = new Task(() => { cron.Run(rcon); }); passives.Start(); crons.Start(); Task.WaitAll(new Task[] { passives, crons }); }
internal async Task SendCommandAsync(string command) { await Rcon.SendCommandAsync(command); return; }
private void Announce_Broadcast(object sender, EventArgs e) { Rcon.Say(((AnnounceEventArgs)e).Announce.ParseMessage(this)); }
private void UpdateOnlinePlayers(object sender) { bool playerListChanged = false; var server = sender as Server; if (sender == null || !server.IsRconConnected || Rcon == null) { return; } var newList = Rcon.GetPlayerList().With(list => list.Where(p => p != null)); if (newList == null) { return; } if (newList.Count() == 0) { lock (server.lockOnlinePlayers) OnlinePlayers.Clear(); if (OnPlayerListChange != null) { OnPlayerListChange(OnlinePlayers.ToList(), this); } return; } HashSet <Guid> onlineIds = new HashSet <Guid> (newList.Select(player => player.NickId)); lock (server.lockOnlinePlayers) { playerListChanged = OnlinePlayers.Count(p => !onlineIds.Contains(p.NickId)) > 0; OnlinePlayers.RemoveAll(player => !onlineIds.Contains(player.NickId)); foreach (var player in newList) { var existing = OnlinePlayers.FirstOrDefault(p => p.NickId.Equals(player.NickId)); if (existing == null) { OnlinePlayers.Add(player); playerListChanged = true; } else { if (!playerListChanged) { playerListChanged = existing.Ping != player.Ping || existing.Status != player.Status || existing.CoalitionIndex != player.CoalitionIndex; } existing.Ping = player.Ping; existing.Status = player.Status; existing.ClientId = player.ClientId; existing.CoalitionIndex = player.CoalitionIndex; } } if (playerListChanged && OnPlayerListChange != null) { OnPlayerListChange(OnlinePlayers.ToList(), this); } } }
internal void ParseFromBytes(byte[] bytes, Rcon parent) { int BPtr = 0; ArrayList stringcache; ASCIIEncoding Ascii = new ASCIIEncoding(); // First 4 bytes are ReqId. RequestId = BitConverter.ToInt32(bytes, BPtr); BPtr += 4; // Next 4 are server data. ServerDataReceived = (SERVERDATA_rec)BitConverter.ToInt32(bytes, BPtr); BPtr += 4; // string1 till /0 stringcache = new ArrayList(); while (bytes[BPtr] != 0) { stringcache.Add(bytes[BPtr]); BPtr++; } String1 = Ascii.GetString((byte[])stringcache.ToArray(typeof(byte))); BPtr++; // string2 till /0 stringcache = new ArrayList(); while (bytes[BPtr] != 0) { stringcache.Add(bytes[BPtr]); BPtr++; } String2 = Ascii.GetString((byte[])stringcache.ToArray(typeof(byte))); BPtr++; // Repeat if there's more data? if (BPtr != bytes.Length) { parent.OnError(MessageCode.TooMuchData, null); } }
private void btnConnect_Click(object sender, EventArgs e) { try { //Hostname auflösen ip = Dns.GetHostAddresses(textBoxIp.Text)[0]; IPEndPoint address = new IPEndPoint(ip, Convert.ToInt32(numericPort.Value)); //Prüfen, ob Server antwortet if (!Helper.Instance.ServerAvailable(address)) { MessageBox.Show("Hostname/IP-Adresse bzw. Port ungültig!", "Ungültige Daten", MessageBoxButtons.OK, MessageBoxIcon.Error); } //Prüfen, ob es sich um Ark handelt else if (Helper.Instance.ServerIsArk(address)) { //Prüfen, ob RCON-pw korrekt IPEndPoint rconAddress = new IPEndPoint(ip, Convert.ToInt32(numericRCONPort.Value)); Server svrRcon = ServerQuery.GetServerInstance(EngineType.Source, rconAddress, false, 500, 500); try { Rcon rcon = svrRcon.GetControl(textBoxPassword.Text); //ServerId zum Speichern finden int id; if (Helper.Instance.Settings.Servers.Count > 0) { id = Helper.Instance.Settings.Servers[Helper.Instance.Settings.Servers.Count - 1].Id + 1; } else { id = 0; } //Wenn ausgewählt, Passwort speichern if (checkBoxSavePw.Checked) { Helper.Instance.Settings.Servers.Add(new ArkServer(id, textBoxName.Text, address.Address.ToString(), address.Port, rconAddress.Port, textBoxPassword.Text, textBoxUsername.Text)); } else { Helper.Instance.Settings.Servers.Add(new ArkServer(id, textBoxName.Text, address.Address.ToString(), address.Port, rconAddress.Port, textBoxUsername.Text)); } //Einstellungen speichern Helper.Instance.SaveConfig(); Close(); } catch { MessageBox.Show("Ungültiges RCON-Passwort oder ungültiger Port", "Ungültige RCON-Daten", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { MessageBox.Show("Das ist kein Ark!", "Falsches Spiel", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch { MessageBox.Show("Hostname/IP-Adresse bzw. Port ungültig!", "Ungültige Daten", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static int Main(string[] args) { // Grab English strings for the interface. ILanguage lang = new English(); string password, command; IPAddress ip; int port; bool interactive; // Parse command-line to tell if we're doing a one-shot command or if we're running interactive. if (args.Length > 0) { // There are arguments, so not interactive. interactive = false; // Four arguments indicates this is a one-shot command. if (args.Length == 4) { try { ip = IPAddress.Parse(args[0]); port = int.Parse(args[1]); } catch (FormatException fe) { Console.WriteLine(lang["invalidparams"], fe.Message); return(-1); } catch (OverflowException oe) { Console.WriteLine(lang["invalidparams"], oe.Message); return(-1); } password = args[2]; command = args[3]; } else { // Print out the usage instructions. Console.WriteLine(lang["usage_instructions"]); return(1); } } else { interactive = true; #if DEBUG Console.WriteLine("Use quick debug? Press y, else anything else!"); if (Console.ReadKey().KeyChar == 'y') { Console.ReadLine(); Console.WriteLine(); ip = IPAddress.Parse("192.168.2.6"); port = 27015; password = "******"; } else { #endif // Walk the user through entering parameters, & prevent them from entering anything invalid: do { Console.WriteLine(lang["enterip"]); }while (!IPAddress.TryParse(Console.ReadLine(), out ip)); do { do { Console.WriteLine(lang["enterport"]); }while (!int.TryParse(Console.ReadLine(), out port)); }while (port < IPEndPoint.MinPort && port > IPEndPoint.MaxPort); // Valve's problem to stop people breaking the server with malformed passwords, not mine! Console.WriteLine(lang["enterpassword"]); password = Console.ReadLine(); #if DEBUG } #endif command = null; } using (Rcon Sr = new Rcon()) { #if DEBUG // Wire up our event handlers to receive errors from the server: Sr.Errors += (MessageCode, Message) => Console.WriteLine(lang["error"], MessageCode.ToString()); #endif bool IsConnected = false; // Now, we'll actually try to connect! try { IsConnected = Sr.ConnectBlocking(new IPEndPoint(ip, (int)port), password); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(lang["invalidparams"], e.Message); return(-1); } if (IsConnected) { if (interactive) { Console.WriteLine(lang["commandready"]); // Just pull lines from the input and send them off. while (true) { // Sr.ServerCommand(Console.ReadLine()); Console.WriteLine(Sr.ServerCommandBlocking(Console.ReadLine())); } } else { // Fire a one-shot command. Console.WriteLine(Sr.ServerCommandBlocking(command)); } } else { // Not connected, so complain about it. Console.WriteLine(lang["noconn"]); } return(0); } }
private void Form1_Load(object sender, EventArgs e) { sr = new Rcon(); sr.ConnectionSuccess += new BoolInfo(sr_ConnectionSuccess); sr.ServerOutput += new RconOutput(sr_ServerOutput); sr.Errors += new RconOutput(sr_Errors); }