public Player(string strName, MCServer s) { this.Username = strName; this.Server = s; this.Level = Database.GetPlayerLevel(strName, s.ServerID); if (this.Level == null) { //We're letting anyone in these days, so add to the DB Database.AddUser(this.Username, this.Server.ServerID); this.Level = "guest"; } //check the op list if (Util.SearchFile(s.ServerDirectory + "ops.txt", strName)) { this.Level = "op"; } //Emulate MOTD if (Database.GetSetting("motd", "MC", this.Server.ServerID) != "") { this.SendMessage(Database.GetSetting("motd", "MC", this.Server.ServerID)); } }
public ProtocolHandler(TcpClient client, MCServer server) { this.Client = client; this._Server = server; Lobby = Data.Servers.servers[ServerData.LobbyServer]; Dimensions = new Dictionary <int, string>(); Dimensions.Add(1, "default"); Dimensions.Add(-1, "default"); Dimensions.Add(0, "default"); }
public void PingTest() { // Note: make a better test with TcpListener and some fake handshake to test this method var address = "mc.hypixel.net"; var port = 25565; var server = new MCServer(address, port); var ping = server.Ping(); if (ping <= 0) { throw new InvalidDataException("Ping cannot be equal to or less than 0."); } }
public void StatusTest() { // Note: make a better test with TcpListener and some fake handshake to test this method var address = "mc.hypixel.net"; var port = 25565; var server = new MCServer(address, port); var response = server.Status(); if (response == null) { throw new InvalidDataException("Returned server status was empty or null."); } // Don't catch JsonException, test will detect this throw // Parse to expected minimal server status }
static void Main() { //Start DB Connection Database.init(); Database.AddLog("Starting Up"); //Is this the first run? if (Database.GetSetting("FirstRun", "YAMS") != "true") { YAMS.Util.FirstRun(); } Database.SaveSetting("AdminPassword", "password"); Database.AddLog("Reading minecraft servers!", "app", "debug"); MySqlDataReader readerServers = Database.GetServers(); ArrayList ServerIDs = new ArrayList(); while (readerServers.Read()) { int ServerID = Convert.ToInt32(readerServers.GetString("ServerID")); ServerIDs.Add(ServerID); } readerServers.Close(); System.Collections.IEnumerator enu = ServerIDs.GetEnumerator(); while (enu.MoveNext()) { int ServerID = Convert.ToInt32(enu.Current); MCServer myServer = new MCServer(ServerID); Core.Servers.Add(ServerID, myServer); } //Start Webserver WebServer.Init(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); }
//Set this class's server public App(MCServer s, string strBaseName, string strMainExe, string strName, bool bolRequiresClient, string strParams) { //set up runtime actions this.BaseName = strBaseName; this.MainExe = strMainExe; this.Name = strName; this.RequiresClient = bolRequiresClient; this.FullFolderPath = Core.RootFolder + @"\apps\" + this.BaseName; this.FullExePath = this.FullFolderPath + @"\" + this.MainExe; //have we had any options set? if (strParams != "") { string[] arrKeys = strParams.Split('&'); foreach (string strKey in arrKeys) { string[] arrValues = strKey.Split('='); if (arrValues.Length == 2) { this.jobParams.Add(arrValues[0], arrValues[1]); } else { Database.AddLog("Params failed on " + this.Name + ". String was " + strParams, this.BaseName, "warn"); } } } //Is it installed? if (File.Exists(this.FullExePath)) { this.IsInstalled = true; this.Server = s; } else { Database.AddLog(this.Name + " is not installed", "addons", "error"); } }
static void Main() { //Start DB Connection Database.init(); Database.AddLog("Starting Up"); //Is this the first run? if (Database.GetSetting("FirstRun", "YAMS") != "true") { YAMS.Util.FirstRun(); } Database.SaveSetting("AdminPassword", "password"); SqlCeDataReader readerServers = YAMS.Database.GetServers(); while (readerServers.Read()) { Database.AddLog("Starting Server " + readerServers["ServerID"]); MCServer myServer = new MCServer(Convert.ToInt32(readerServers["ServerID"])); if (Convert.ToBoolean(readerServers["ServerAutostart"])) { myServer.Start(); } Core.Servers.Add(Convert.ToInt32(readerServers["ServerID"]), myServer); } //Start job engine JobEngine.Init(); //Start Webserver WebServer.Init(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); }
public c10t(MCServer s, string strParams = "night=false&mode=normal") : base(s, "c10t", @"c10t.exe", "c10t", true, strParams) {}
public Overviewer(MCServer s, string strParams = "rendermodes=normal,lighting,night") : base(s, "overviewer", @"overviewer.exe", "Overviewer", true, strParams) { }
public ProcessingResult Process(RequestContext context) { //it's a public request, work out what they want // / = list servers // /[0-9]+/ = server home page including chat log // /[0-9]+/map = Google Map // /[0-9]+/renders = c10t renders Regex regRoot = new Regex(@"^/$"); Regex regServerList = new Regex(@"^/servers/$"); Regex regServerHome = new Regex(@"^/servers/([0-9]+)/$"); Regex regServerGMap = new Regex(@"^/servers/([0-9]+)/map/"); Regex regServerRenders = new Regex(@"^/servers/([0-9]+)/renders/"); if (regServerGMap.Match(context.Request.Uri.AbsolutePath).Success || regServerRenders.Match(context.Request.Uri.AbsolutePath).Success) { return(ProcessingResult.Continue); } else { string strTemplate = "No matching Template"; Dictionary <string, string> dicTags = new Dictionary <string, string>(); if (regRoot.Match(context.Request.Uri.AbsolutePath).Success) { //Server Root strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\root.html"); dicTags.Add("PageTitle", "YAMS Hosted Server"); dicTags.Add("PageBody", "test"); } else if (regServerList.Match(context.Request.Uri.AbsolutePath).Success) { //List of Servers strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\server-list.html"); dicTags.Add("PageTitle", "Server List"); dicTags.Add("PageBody", "test"); } else if (regServerHome.Match(context.Request.Uri.AbsolutePath).Success) { //Individual Server home Match matServerHome = regServerHome.Match(context.Request.Uri.AbsolutePath); int intServerID = Convert.ToInt32(matServerHome.Groups[1].Value); MCServer s = Core.Servers[intServerID]; string strOverviewer = ""; string strTectonicus = ""; string strImages = ""; string strBackups = ""; if (File.Exists(s.ServerDirectory + @"\renders\overviewer\output\index.html")) { strOverviewer = "<h3>Overviewer Map</h3><div><a href=\"renders/overviewer/output/index.html\">Click here to open map</a>"; } if (File.Exists(s.ServerDirectory + @"\renders\tectonicus\map.html")) { strTectonicus = "<h3>Tectonicus Map</h3><div><a href=\"renders/tectonicus/map.html\">Click here to open map</a>"; } strImages = "<h3>Images</h3><ul>"; DirectoryInfo di = new DirectoryInfo(s.ServerDirectory + @"\renders\"); FileInfo[] fileEntries = di.GetFiles(); foreach (FileInfo fi in fileEntries) { strImages += "<li><a href=\"renders/" + fi.Name + "\">" + fi.Name + "</a></li>"; } strImages += "</ul>"; strBackups = "<h3>Backups</h3><ul>"; DirectoryInfo di2 = new DirectoryInfo(s.ServerDirectory + @"\backups\"); FileInfo[] fileEntries2 = di2.GetFiles(); foreach (FileInfo fi in fileEntries2) { strBackups += "<li><a href=\"backups/" + fi.Name + "\">" + fi.Name + "</a></li>"; } strBackups += "</ul>"; strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\server-home.html"); dicTags.Add("PageTitle", s.ServerTitle); dicTags.Add("RenderOverviewer", strOverviewer); dicTags.Add("RenderTectonicus", strTectonicus); dicTags.Add("RenderImages", strImages); dicTags.Add("BackupList", strBackups); dicTags.Add("PageBody", "Body"); } else { //Unknown context.Response.Status = HttpStatusCode.NotFound; strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\server-home.html"); dicTags.Add("PageTitle", "404"); dicTags.Add("PageBody", "<h1>404 - Not Found</h1>"); } //Run through our replacer strTemplate = WebTemplate.ReplaceTags(strTemplate, dicTags); //And send to the browser context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(strTemplate); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } }
public BiomeExtractor(MCServer s, string strParams = "") : base(s, "biome-extractor", @"MinecraftBiomeExtractor.jar", "Biome Extractor", true, strParams) { }
public Tectonicus(MCServer s, string strParams = "") : base(s, "tectonicus", @"tectonicus.jar", "Tectonicus", true, strParams) { }
public c10t(MCServer s, string strParams = "night=false&mode=normal") : base(s, "c10t", @"c10t.exe", "c10t", true, strParams) { }
public static void Handler(TcpClient client, MCServer server) { ProtocolHandler connection = new ProtocolHandler(client, server); ThreadPool.QueueUserWorkItem(new WaitCallback(connection.DoShakeHands)); }
public Overviewer(MCServer s, string strParams = "overworld=nst") : base(s, "overviewer", @"overviewer.exe", "Overviewer", true, strParams) { }
public NBToolkit(MCServer s, string strParams = "mode=oregen") : base(s, "nbtoolkit", @"NBToolkit.exe", "NBToolkit", true, strParams) { }
public BiomeExtractor(MCServer s, string strParams = "") : base(s, "biome-extractor", @"MinecraftBiomeExtractor.jar", "Biome Extractor", true, strParams) {}
public ProcessingResult Process(RequestContext context) { int intServerID = 0; MCServer s; string json; JObject jProps; if (context.Request.Uri.AbsoluteUri.Contains(@"/api/")) { //must be authenticated //what is the action? if (context.Request.Method == Method.Post && WebSession.Current.UserName == "admin") { String strResponse = ""; IParameterCollection param = context.Request.Parameters; switch (context.Request.Parameters["action"]) { case "log": //grabs lines from the log. int intStartID = Convert.ToInt32(context.Request.Parameters["start"]); int intNumRows = Convert.ToInt32(context.Request.Parameters["rows"]); int intServer = Convert.ToInt32(context.Request.Parameters["serverid"]); string strLevel = context.Request.Parameters["level"]; DataSet ds = Database.ReturnLogRows(intStartID, intNumRows, strLevel, intServer); strResponse = JsonConvert.SerializeObject(ds, Formatting.Indented); break; case "list": //List available servers strResponse = "{ \"servers\" : ["; foreach (KeyValuePair <int, MCServer> kvp in Core.Servers) { strResponse += "{ \"id\" : " + kvp.Value.ServerID + ", " + "\"title\" : \"" + kvp.Value.ServerTitle + "\", " + "\"ver\" : \"" + kvp.Value.ServerVersion + "\" } ,"; } ; strResponse = strResponse.Remove(strResponse.Length - 1); strResponse += "]}"; break; case "status": //Get status of a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; strResponse = "{ \"serverid\" : " + s.ServerID + "," + "\"status\" : \"" + s.Running + "\"," + "\"ram\" : " + s.GetMemory() + "," + "\"vm\" : " + s.GetVMemory() + "," + "\"restartneeded\" : \"" + s.RestartNeeded + "\"," + "\"restartwhenfree\" : \"" + s.RestartWhenFree + "\"," + "\"gamemode\" : \"" + s.GameMode + "\"," + "\"players\" : ["; if (s.Players.Count > 0) { foreach (KeyValuePair <string, Objects.Player> kvp in s.Players) { strResponse += " { \"name\": \"" + kvp.Value.Username + "\", \"level\": \"" + kvp.Value.Level + "\" },"; } ; strResponse = strResponse.Remove(strResponse.Length - 1); } strResponse += "]}"; break; case "overviewer": //Maps a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; string strRenderModes = ""; if (param["normal"] == "true") { strRenderModes += "normal"; } if (param["lighting"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "lighting"; } if (param["night"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "night"; } if (param["spawn"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "spawn"; } if (param["cave"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "cave"; } AddOns.Overviewer over = new AddOns.Overviewer(s, "rendermodes=" + strRenderModes); over.Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "c10t": //Images a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; AddOns.c10t c10t = new AddOns.c10t(s, "night=" + param["night"] + "&mode=" + param["mode"]); c10t.Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "tectonicus": //Maps a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; AddOns.Tectonicus tecton = new AddOns.Tectonicus(s, "lighting=" + param["lighting"] + "&night=" + param["night"] + "&delete=" + param["delete"]); tecton.Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "start": //Starts a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "stop": //Stops a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Stop(); strResponse = "{ \"result\" : \"sent\" }"; break; case "restart": //Restarts a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Restart(); strResponse = "{ \"result\" : \"sent\" }"; break; case "delayed-restart": //Restarts a server after a specified time and warns players Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].DelayedRestart(Convert.ToInt32(param["delay"])); strResponse = "{ \"result\" : \"sent\" }"; break; case "restart-when-free": Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].RestartIfEmpty(); strResponse = "{ \"result\" : \"sent\" }"; break; case "command": //Sends literal command to a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Send(context.Request.Parameters["message"]); strResponse = "{ \"result\" : \"sent\" }"; break; case "get-yams-settings": DataSet dsSettings = Database.ReturnSettings(); JsonConvert.SerializeObject(dsSettings, Formatting.Indented); break; case "save-yams-settings": //Settings update foreach (Parameter p in param) { if (p.Name != "action") { Database.SaveSetting(p.Name, p.Value); } } break; case "get-server-settings": //retrieve all server settings as JSON intServerID = Convert.ToInt32(param["serverid"]); strResponse = "{ \"serverid\" : " + intServerID + "," + "\"title\" : \"" + Database.GetSetting(intServerID, "ServerTitle") + "\"," + "\"optimisations\" : \"" + Database.GetSetting(intServerID, "ServerEnableOptimisations") + "\"," + "\"memory\" : \"" + Database.GetSetting(intServerID, "ServerAssignedMemory") + "\"," + "\"autostart\" : \"" + Database.GetSetting(intServerID, "ServerAutoStart") + "\"," + "\"type\" : \"" + Database.GetSetting(intServerID, "ServerType") + "\"," + "\"motd\" : \"" + Database.GetSetting("motd", "MC", intServerID) + "\""; strResponse += "}"; break; case "get-mc-settings": //retrieve all server settings as JSON intServerID = Convert.ToInt32(param["serverid"]); json = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json"); jProps = JObject.Parse(json); strResponse = ""; foreach (JObject option in jProps["options"]) { strResponse += "<p><label for=\"" + (string)option["key"] + "\" title=\"" + (string)option["description"] + "\">" + (string)option["name"] + "</label>"; string strValue = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty((string)option["key"]); switch ((string)option["type"]) { case "string": strResponse += "<input type=\"text\" name=\"" + (string)option["key"] + "\" value=\"" + strValue + "\" />"; break; case "boolean": strResponse += "<select name=\"" + (string)option["key"] + "\">"; strResponse += "<option value=\"true\""; if (strValue == "true") { strResponse += " selected"; } strResponse += ">True</option>"; strResponse += "<option value=\"false\""; if (strValue == "false") { strResponse += " selected"; } strResponse += ">False</option>"; strResponse += "</select>"; break; case "integer": strResponse += "<select name=\"" + (string)option["key"] + "\">"; int intValue = Convert.ToInt32(strValue); for (var i = Convert.ToInt32((string)option["min"]); i <= Convert.ToInt32((string)option["max"]); i++) { strResponse += "<option value=\"" + i.ToString() + "\""; if (intValue == i) { strResponse += " selected"; } strResponse += ">" + i.ToString() + "</option>"; } strResponse += "</select>"; break; case "array": strResponse += "<select name=\"" + (string)option["key"] + "\">"; string strValues = (string)option["values"]; string[] elements = strValues.Split(','); foreach (string values in elements) { string[] options = values.Split('|'); strResponse += "<option value=\"" + options[0] + "\""; if (strValue == options[0]) { strResponse += " selected"; } strResponse += ">" + options[1] + "</option>"; } strResponse += "</select>"; break; } strResponse += "</p>"; } break; case "save-server-settings": intServerID = Convert.ToInt32(param["serverid"]); Database.UpdateServer(intServerID, "ServerTitle", param["title"]); Database.UpdateServer(intServerID, "ServerType", param["type"]); Database.UpdateServer(intServerID, "ServerAssignedMemory", Convert.ToInt32(param["memory"])); if (param["optimisations"] == "true") { Database.UpdateServer(intServerID, "ServerEnableOptimisations", true); } else { Database.UpdateServer(intServerID, "ServerEnableOptimisations", false); } if (param["autostart"] == "true") { Database.UpdateServer(intServerID, "ServerAutoStart", true); } else { Database.UpdateServer(intServerID, "ServerAutoStart", false); } Database.SaveSetting(intServerID, "motd", param["message"]); //Save the server's MC settings MCServer thisServer = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; json = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json"); jProps = JObject.Parse(json); strResponse = ""; foreach (JObject option in jProps["options"]) { thisServer.SaveProperty((string)option["key"], param[(string)option["key"]]); } if (thisServer.Running) { thisServer.RestartIfEmpty(); } break; case "get-config-file": List <string> listConfig = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ReadConfig(param["file"]); strResponse = JsonConvert.SerializeObject(listConfig, Formatting.Indented); break; case "upload-world": var test = context.Request.Files["new-world"]; break; case "delete-world": bool bolRandomSeed = false; if (param["randomseed"] == "true") { bolRandomSeed = true; } Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ClearWorld(bolRandomSeed); strResponse = "{ \"result\" : \"sent\" }"; break; case "about": Dictionary <string, string> dicAbout = new Dictionary <string, string> { { "dll", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Library.dll")).FileVersion }, { "svc", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Service.exe")).FileVersion }, { "gui", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Updater.exe")).FileVersion }, { "db", Database.GetSetting("DBSchema", "YAMS") } }; strResponse = JsonConvert.SerializeObject(dicAbout, Formatting.Indented); break; case "installed-apps": Dictionary <string, string> dicApps = new Dictionary <string, string> { { "bukkit", Database.GetSetting("BukkitInstalled", "YAMS") }, { "overviewer", Database.GetSetting("OverviewerInstalled", "YAMS") }, { "c10t", Database.GetSetting("C10tInstalled", "YAMS") }, { "biomeextractor", Database.GetSetting("BiomeExtractorInstalled", "YAMS") }, { "tectonicus", Database.GetSetting("TectonicusInstalled", "YAMS") }, { "nbtoolkit", Database.GetSetting("NBToolkitInstalled", "YAMS") } }; strResponse = JsonConvert.SerializeObject(dicApps, Formatting.Indented); break; case "update-apps": Database.SaveSetting("OverviewerInstalled", param["overviewer"]); Database.SaveSetting("C10tInstalled", param["c10t"]); Database.SaveSetting("BiomeExtractorInstalled", param["biomeextractor"]); Database.SaveSetting("TectonicusInstalled", param["tectonicus"]); Database.SaveSetting("NBToolkitInstalled", param["nbtoolkit"]); Database.SaveSetting("BukkitInstalled", param["bukkit"]); strResponse = "done"; break; case "force-autoupdate": AutoUpdate.CheckUpdates(); break; default: return(ProcessingResult.Abort); } context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(strResponse); context.Response.Body.Write(buffer, 0, buffer.Length); } else { // not a post, so say bye bye! return(ProcessingResult.Abort); } return(ProcessingResult.SendResponse); } else if (context.Request.Uri.AbsoluteUri.Contains(@"/admin")) { if (WebSession.Current.UserName != "admin") { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } else { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\index.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } } else if (context.Request.Uri.AbsoluteUri.Contains(@"/login")) { //This is a login request, check it's legit string userName = context.Request.Form["strUsername"]; string password = context.Request.Form["strPassword"]; if (userName == "admin" && password == Database.GetSetting("AdminPassword", "YAMS")) { WebSession.Create(); WebSession.Current.UserName = "******"; context.Response.Redirect(@"/admin"); return(ProcessingResult.SendResponse); } else { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } } else if (context.Request.Uri.AbsoluteUri.Equals(@"/")) { context.Response.Redirect(@"/admin"); return(ProcessingResult.SendResponse); } else { return(ProcessingResult.Abort); } }
public NBToolkit(MCServer s, string strParams = "mode=oregen") : base(s, "nbtoolkit", @"NBToolkit.exe", "NBToolkit", true, strParams) {}
public ProcessingResult Process(RequestContext context) { int intServerID = 0; MCServer s; string json; JObject jProps; if (context.Request.Uri.AbsoluteUri.Contains(@"/api/")) { //must be authenticated //what is the action? if ((WebSession.Current.UserName == "admin" || context.Request.Parameters["PSK"] == Database.GetSetting("PSK", "YAMS"))) { String strResponse = ""; IParameterCollection param = context.Request.Parameters; switch (context.Request.Parameters["action"]) { case "log": //grabs lines from the log. int intStartID = Convert.ToInt32(context.Request.Parameters["start"]); int intNumRows = Convert.ToInt32(context.Request.Parameters["rows"]); int intServer = Convert.ToInt32(context.Request.Parameters["serverid"]); string strLevel = context.Request.Parameters["level"]; DataSet ds = Database.ReturnLogRows(intStartID, intNumRows, strLevel, intServer); strResponse = JsonConvert.SerializeObject(ds, Formatting.Indented); break; case "list": //List available servers strResponse = "{ \"servers\" : ["; foreach (KeyValuePair <int, MCServer> kvp in Core.Servers) { strResponse += "{ \"id\" : " + kvp.Value.ServerID + ", " + "\"title\" : \"" + kvp.Value.ServerTitle + "\", " + "\"ver\" : \"" + kvp.Value.ServerVersion + "\" } ,"; } ; strResponse = strResponse.Remove(strResponse.Length - 1); strResponse += "]}"; break; case "status": //Get status of a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; strResponse = "{ \"serverid\" : " + s.ServerID + "," + "\"status\" : \"" + s.Running + "\"," + "\"ram\" : " + s.GetMemory() + "," + "\"vm\" : " + s.GetVMemory() + "}"; break; case "start": //Starts a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "stop": //Stops a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Stop(); strResponse = "{ \"result\" : \"sent\" }"; break; case "restart": //Restarts a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Restart(); strResponse = "{ \"result\" : \"sent\" }"; break; case "delayed-restart": //Restarts a server after a specified time and warns players Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].DelayedRestart(Convert.ToInt32(param["delay"])); strResponse = "{ \"result\" : \"sent\" }"; break; case "command": //Sends literal command to a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Send(context.Request.Parameters["message"]); strResponse = "{ \"result\" : \"sent\" }"; break; case "get-yams-settings": DataSet dsSettings = Database.ReturnSettings(); JsonConvert.SerializeObject(dsSettings, Formatting.Indented); break; case "save-yams-settings": //Settings update foreach (Parameter p in param) { if (p.Name != "action") { Database.SaveSetting(p.Name, p.Value); } } break; case "get-server-settings": //retrieve all server settings as JSON List <string> listIPsMC = new List <string>(); IPHostEntry ipListenMC = Dns.GetHostEntry(""); foreach (IPAddress ipaddress in ipListenMC.AddressList) { if (ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { listIPsMC.Add(ipaddress.ToString()); } } intServerID = Convert.ToInt32(param["serverid"]); strResponse = "{ \"serverid\" : " + intServerID + "," + "\"title\" : \"" + Database.GetSetting(intServerID, "ServerTitle") + "\"," + "\"optimisations\" : \"" + Database.GetSetting(intServerID, "ServerEnableOptimisations") + "\"," + "\"memory\" : \"" + Database.GetSetting(intServerID, "ServerAssignedMemory") + "\"," + "\"autostart\" : \"" + Database.GetSetting(intServerID, "ServerAutoStart") + "\"," + "\"type\" : \"" + Database.GetSetting(intServerID, "ServerType") + "\"," + "\"motd\" : \"" + Database.GetSetting("motd", "MC", intServerID) + "\"," + "\"listen\" : \"" + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-ip") + "\"," + "\"port\" : \"" + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-port") + "\"," + "\"IPs\": " + JsonConvert.SerializeObject(listIPsMC, Formatting.None); strResponse += "}"; break; case "get-server-connections": intServerID = Convert.ToInt32(param["serverid"]); strResponse = "{ \"dnsname\" : \"" + Database.GetSetting("DNSName", "YAMS") + "\", " + "\"externalip\" : \"" + Networking.GetExternalIP().ToString() + "\", " + "\"mcport\" : " + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-port") + ", " + "\"publicport\" : " + Database.GetSetting("PublicListenPort", "YAMS") + " }"; break; case "get-mc-settings": //retrieve all server settings as JSON intServerID = Convert.ToInt32(param["serverid"]); json = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json"); jProps = JObject.Parse(json); strResponse = ""; foreach (JObject option in jProps["options"]) { strResponse += "<p><label for=\"" + (string)option["key"] + "\" title=\"" + (string)option["description"] + "\">" + (string)option["name"] + "</label>"; string strValue = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty((string)option["key"]); switch ((string)option["type"]) { case "string": strResponse += "<input type=\"text\" name=\"" + (string)option["key"] + "\" value=\"" + strValue + "\" />"; break; case "boolean": strResponse += "<select name=\"" + (string)option["key"] + "\">"; strResponse += "<option value=\"true\""; if (strValue == "true") { strResponse += " selected"; } strResponse += ">True</option>"; strResponse += "<option value=\"false\""; if (strValue == "false") { strResponse += " selected"; } strResponse += ">False</option>"; strResponse += "</select>"; break; case "integer": strResponse += "<select name=\"" + (string)option["key"] + "\">"; int intValue = Convert.ToInt32(strValue); for (var i = Convert.ToInt32((string)option["min"]); i <= Convert.ToInt32((string)option["max"]); i++) { strResponse += "<option value=\"" + i.ToString() + "\""; if (intValue == i) { strResponse += " selected"; } strResponse += ">" + i.ToString() + "</option>"; } strResponse += "</select>"; break; case "array": strResponse += "<select name=\"" + (string)option["key"] + "\">"; string strValues = (string)option["values"]; string[] elements = strValues.Split(','); foreach (string values in elements) { string[] options = values.Split('|'); strResponse += "<option value=\"" + options[0] + "\""; if (strValue == options[0]) { strResponse += " selected"; } strResponse += ">" + options[1] + "</option>"; } strResponse += "</select>"; break; } strResponse += "</p>"; } break; case "save-server-settings": intServerID = Convert.ToInt32(param["serverid"]); Database.UpdateServer(intServerID, "ServerTitle", param["title"]); Database.UpdateServer(intServerID, "ServerType", param["type"]); Database.UpdateServer(intServerID, "ServerAssignedMemory", Convert.ToInt32(param["memory"])); if (param["optimisations"] == "true") { Database.UpdateServer(intServerID, "ServerEnableOptimisations", true); } else { Database.UpdateServer(intServerID, "ServerEnableOptimisations", false); } if (param["autostart"] == "true") { Database.UpdateServer(intServerID, "ServerAutoStart", true); } else { Database.UpdateServer(intServerID, "ServerAutoStart", false); } Database.SaveSetting(intServerID, "motd", param["message"]); //Save the server's MC settings MCServer thisServer = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; thisServer.SaveProperty("server-ip", param["cfg_listen-ip"]); thisServer.SaveProperty("server-port", param["cfg_port"]); json = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json"); jProps = JObject.Parse(json); strResponse = ""; foreach (JObject option in jProps["options"]) { thisServer.SaveProperty((string)option["key"], param[(string)option["key"]]); } break; case "get-config-file": List <string> listConfig = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ReadConfig(param["file"]); strResponse = JsonConvert.SerializeObject(listConfig, Formatting.Indented); break; case "get-server-whitelist": strResponse = "{ \"enabled\" : " + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("white-list") + " }"; break; case "network-settings": List <string> listIPs = new List <string>(); IPHostEntry ipListen = Dns.GetHostEntry(""); foreach (IPAddress ipaddress in ipListen.AddressList) { if (ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { listIPs.Add(ipaddress.ToString()); } } Dictionary <string, string> dicNetwork = new Dictionary <string, string> { { "portForwarding", Database.GetSetting("EnablePortForwarding", "YAMS") }, { "openFirewall", Database.GetSetting("EnableOpenFirewall", "YAMS") }, { "publicEnable", Database.GetSetting("EnablePublicSite", "YAMS") }, { "adminPort", Database.GetSetting("AdminListenPort", "YAMS") }, { "currentIP", Database.GetSetting("YAMSListenIP", "YAMS") }, { "IPs", JsonConvert.SerializeObject(listIPs, Formatting.None) } }; strResponse = JsonConvert.SerializeObject(dicNetwork, Formatting.Indented).Replace(@"\", "").Replace("\"[", "[").Replace("]\"", "]"); break; case "save-network-settings": int intTester = 0; try { //Try to convert to integers to make sure something silly isn't put in. TODO: Javascript validation intTester = Convert.ToInt32(param["adminPort"]); intTester = Convert.ToInt32(param["publicPort"]); IPAddress ipTest = IPAddress.Parse(param["listenIp"]); } catch (Exception e) { YAMS.Database.AddLog("Invalid input on network settings: " + e.Message, "web", "warn"); return(ProcessingResult.Abort); } Database.SaveSetting("EnablePortForwarding", param["portForwarding"]); Database.SaveSetting("EnableOpenFirewall", param["openFirewall"]); //Database.SaveSetting("EnablePublicSite", param["publicEnable"]); Database.SaveSetting("AdminListenPort", param["adminPort"]); //Database.SaveSetting("PublicListenPort", param["publicPort"]); Database.SaveSetting("YAMSListenIP", param["listenIp"]); Database.AddLog("Network settings have been saved, to apply changes a service restart is required. Please check they are correct before restarting", "web", "warn"); break; case "logout": WebSession.Current.UserName = ""; break; default: return(ProcessingResult.Abort); } context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(strResponse); context.Response.Body.Write(buffer, 0, buffer.Length); } else { // not a post, so say bye bye! return(ProcessingResult.Abort); } return(ProcessingResult.SendResponse); } else if (context.Request.Uri.AbsoluteUri.Contains(@"/admin")) { if (WebSession.Current.UserName != "admin") { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } else { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\index.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } } else if (context.Request.Uri.AbsoluteUri.Contains(@"/login")) { //This is a login request, check it's legit string userName = context.Request.Form["strUsername"]; string password = context.Request.Form["strPassword"]; if (userName == "admin" && password == Database.GetSetting("AdminPassword", "YAMS")) { WebSession.Create(); WebSession.Current.UserName = "******"; context.Response.Redirect(@"/admin"); return(ProcessingResult.SendResponse); } else { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } } else if (context.Request.Uri.AbsoluteUri.Equals(@"/")) { context.Response.Redirect(@"/admin"); return(ProcessingResult.SendResponse); } else { return(ProcessingResult.Abort); } }
public ProcessingResult Process(RequestContext context) { //it's a public request, work out what they want // / = list servers // /[0-9]+/ = server home page including chat log // /[0-9]+/map = Google Map // /[0-9]+/renders = c10t renders Regex regRoot = new Regex(@"^/$"); Regex regServerList = new Regex(@"^/servers/$"); Regex regServerHome = new Regex(@"^/servers/([0-9]+)/$"); Regex regServerGMap = new Regex(@"^/servers/([0-9]+)/map/"); Regex regServerRenders = new Regex(@"^/servers/([0-9]+)/renders/"); Regex regServerAPI = new Regex(@"^/servers/([0-9]+)/api/"); if (regServerGMap.Match(context.Request.Uri.AbsolutePath).Success || regServerRenders.Match(context.Request.Uri.AbsolutePath).Success) { return(ProcessingResult.Continue); } else { string strTemplate = "No matching Template"; Dictionary <string, string> dicTags = new Dictionary <string, string>(); if (regRoot.Match(context.Request.Uri.AbsolutePath).Success) { //Server Root strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\root.html"); dicTags.Add("PageTitle", "YAMS Hosted Server"); dicTags.Add("PageBody", "test"); } else if (regServerList.Match(context.Request.Uri.AbsolutePath).Success) { //List of Servers strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\server-list.html"); dicTags.Add("PageTitle", "Server List"); string strServerList; strServerList = "<ul>"; foreach (KeyValuePair <int, MCServer> kvp in Core.Servers) { strServerList += "<li><a href=\"" + kvp.Value.ServerID + "/\">" + kvp.Value.ServerTitle + "</a></li>"; } ; strServerList += "</ul>"; dicTags.Add("ServerList", strServerList); } else if (regServerHome.Match(context.Request.Uri.AbsolutePath).Success) { //Individual Server home Match matServerHome = regServerHome.Match(context.Request.Uri.AbsolutePath); int intServerID = Convert.ToInt32(matServerHome.Groups[1].Value); MCServer s = Core.Servers[intServerID]; string strOverviewer = ""; string strImages = ""; string strBackups = ""; if (File.Exists(s.ServerDirectory + @"\renders\overviewer\output\index.html")) { strOverviewer = "<div><a href=\"renders/overviewer/output/index.html\">Click here to open map</a></div>"; } strImages = "<ul>"; DirectoryInfo di = new DirectoryInfo(s.ServerDirectory + @"\renders\"); IEnumerable <FileInfo> fileEntries = di.GetFiles(); var imageFiles = fileEntries.OrderByDescending(f => f.CreationTime).Take(20); foreach (FileInfo fi in imageFiles) { strImages += "<li><a href=\"renders/" + fi.Name + "\">" + fi.Name + "</a></li>"; } strImages += "</ul>"; strBackups = "<ul>"; DirectoryInfo di2 = new DirectoryInfo(s.ServerDirectory + @"\backups\"); IEnumerable <FileInfo> fileEntries2 = di2.GetFiles(); var backupFiles = fileEntries2.OrderByDescending(f => f.CreationTime).Take(20); foreach (FileInfo fi in backupFiles) { strBackups += "<li><a href=\"backups/" + fi.Name + "\">" + fi.Name + "</a></li>"; } strBackups += "</ul>"; //Determine if they need a special client URL string strClientURL = ""; if (s.ServerType == "pre") { string json = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\versions.json"); //Dictionary<string, string> dicVers = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); JObject jVers = JObject.Parse(json); strClientURL = "This server is running the weekly snapshots, <a href=\"" + (string)jVers["pre-client"] + "\">download current client</a>."; } //List out players online string strPlayers = ""; if (s.Players.Count > 0) { strPlayers = "<ul>"; foreach (KeyValuePair <string, Player> kvp in s.Players) { Vector playerPos = kvp.Value.Position; strPlayers += "<li>"; if (kvp.Value.Level == "op") { strPlayers += "<span class=\"label label-important\">op</span> "; } strPlayers += kvp.Value.Username + " <span class=\"label\">" + playerPos.x.ToString("0.##") + ", " + playerPos.y.ToString("0.##") + ", " + playerPos.z.ToString("0.##") + "</span>"; strPlayers += "</li>"; } ; strPlayers += "</ul>"; } else { strPlayers = "No players online right now"; } //Connection Addresses string strConnectAddress = ""; if (Database.GetSetting("DNSName", "YAMS") != "") { strConnectAddress = Database.GetSetting("DNSName", "YAMS") + ".yams.in"; } else { strConnectAddress = Networking.GetExternalIP().ToString(); } if (s.GetProperty("server-port") != "25565") { strConnectAddress += ":" + s.GetProperty("server-port"); } strConnectAddress += "<input type=\"hidden\" id=\"server-host\" value=\"" + Networking.GetExternalIP().ToString() + "\" />" + "<input type=\"hidden\" id=\"server-port\" value=\"" + s.GetProperty("server-port") + "\" />"; strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\server-home.html"); dicTags.Add("PageTitle", s.ServerTitle); dicTags.Add("RenderOverviewer", strOverviewer); dicTags.Add("RenderImages", strImages); dicTags.Add("BackupList", strBackups); dicTags.Add("ServerConnectAddress", strConnectAddress); //TODO dicTags.Add("ClientURL", strClientURL); dicTags.Add("PlayersOnline", strPlayers); dicTags.Add("PageBody", Database.GetSetting(intServerID, "ServerWebBody").ToString()); } else if (regServerAPI.Match(context.Request.Uri.AbsolutePath).Success) { string strResponse = ""; IParameterCollection param = context.Request.Parameters; Match matServerAPI = regServerAPI.Match(context.Request.Uri.AbsolutePath); int intServerID = Convert.ToInt32(matServerAPI.Groups[1].Value); MCServer s = Core.Servers[intServerID]; switch (context.Request.Parameters["action"]) { case "players": strResponse = "{\"players\" : ["; if (s.Players.Count > 0) { foreach (KeyValuePair <string, Player> kvp in s.Players) { Vector playerPos = kvp.Value.Position; strResponse += " { \"name\": \"" + kvp.Value.Username + "\", " + "\"level\": \"" + kvp.Value.Level + "\", " + "\"x\": \"" + playerPos.x.ToString("0.##") + "\", " + "\"y\": \"" + playerPos.y.ToString("0.##") + "\", " + "\"z\": \"" + playerPos.z.ToString("0.##") + "\" },"; } ; strResponse = strResponse.Remove(strResponse.Length - 1); } strResponse += "]}"; break; } strTemplate = strResponse; } else { //Unknown context.Response.Status = HttpStatusCode.NotFound; strTemplate = File.ReadAllText(Core.RootFolder + @"\web\templates\server-home.html"); dicTags.Add("PageTitle", "404"); dicTags.Add("PageBody", "<h1>404 - Not Found</h1>"); } //Run through our replacer strTemplate = WebTemplate.ReplaceTags(strTemplate, dicTags); //And send to the browser context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(strTemplate); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } }
public Tectonicus(MCServer s, string strParams = "") : base(s, "tectonicus", @"tectonicus.jar", "Tectonicus", true, strParams) {}
public ProcessingResult Process(RequestContext context) { int intServerID = 0; MCServer s; string json; JObject jProps; if (context.Request.Uri.AbsoluteUri.Contains(@"/api/")) { //must be authenticated //what is the action? if (context.Request.Method == Method.Post && WebSession.Current.UserName == "admin") { String strResponse = ""; IParameterCollection param = context.Request.Parameters; switch (context.Request.Parameters["action"]) { case "log": //grabs lines from the log. int intStartID = Convert.ToInt32(context.Request.Parameters["start"]); int intNumRows = Convert.ToInt32(context.Request.Parameters["rows"]); int intServer = Convert.ToInt32(context.Request.Parameters["serverid"]); string strLevel = context.Request.Parameters["level"]; DataSet ds = Database.ReturnLogRows(intStartID, intNumRows, strLevel, intServer); strResponse = JsonConvert.SerializeObject(ds, Formatting.Indented); break; case "list": //List available servers strResponse = "{ \"servers\" : ["; foreach (KeyValuePair <int, MCServer> kvp in Core.Servers) { strResponse += "{ \"id\" : " + kvp.Value.ServerID + ", " + "\"title\" : \"" + kvp.Value.ServerTitle + "\", " + "\"ver\" : \"" + kvp.Value.ServerVersion + "\" } ,"; } ; strResponse = strResponse.Remove(strResponse.Length - 1); strResponse += "]}"; break; case "status": //Get status of a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; strResponse = "{ \"serverid\" : " + s.ServerID + "," + "\"status\" : \"" + s.Running + "\"," + "\"ram\" : " + s.GetMemory() + "," + "\"vm\" : " + s.GetVMemory() + "," + "\"restartneeded\" : \"" + s.RestartNeeded + "\"," + "\"restartwhenfree\" : \"" + s.RestartWhenFree + "\"," + "\"gamemode\" : \"" + s.GameMode + "\"," + "\"players\" : ["; if (s.Players.Count > 0) { foreach (KeyValuePair <string, Player> kvp in s.Players) { Vector playerPos = kvp.Value.Position; strResponse += " { \"name\": \"" + kvp.Value.Username + "\", " + "\"level\": \"" + kvp.Value.Level + "\", " + "\"x\": \"" + playerPos.x.ToString("0.##") + "\", " + "\"y\": \"" + playerPos.y.ToString("0.##") + "\", " + "\"z\": \"" + playerPos.z.ToString("0.##") + "\" },"; } ; strResponse = strResponse.Remove(strResponse.Length - 1); } strResponse += "]}"; break; case "get-players": DataSet dsPlayers = Database.GetPlayers(Convert.ToInt32(context.Request.Parameters["serverid"])); JsonConvert.SerializeObject(dsPlayers, Formatting.Indented); break; case "overviewer": //Maps a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; string strRenderModes = ""; if (param["normal"] == "true") { strRenderModes += "normal"; } if (param["lighting"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "lighting"; } if (param["night"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "night"; } if (param["spawn"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "spawn"; } if (param["cave"] == "true") { if (strRenderModes != "") { strRenderModes += ","; } strRenderModes += "cave"; } AddOns.Overviewer over = new AddOns.Overviewer(s, "rendermodes=" + strRenderModes); over.Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "c10t": //Images a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; AddOns.c10t c10t = new AddOns.c10t(s, "night=" + param["night"] + "&mode=" + param["mode"]); c10t.Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "tectonicus": //Maps a server s = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; AddOns.Tectonicus tecton = new AddOns.Tectonicus(s, "lighting=" + param["lighting"] + "&night=" + param["night"] + "&delete=" + param["delete"]); tecton.Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "start": //Starts a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Start(); strResponse = "{ \"result\" : \"sent\" }"; break; case "stop": //Stops a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Stop(); strResponse = "{ \"result\" : \"sent\" }"; break; case "forcestop": //Force stops a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ForceStop(); strResponse = "{ \"result\" : \"sent\" }"; break; case "restart": //Restarts a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Restart(); strResponse = "{ \"result\" : \"sent\" }"; break; case "delayed-restart": //Restarts a server after a specified time and warns players Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].DelayedRestart(Convert.ToInt32(param["delay"])); strResponse = "{ \"result\" : \"sent\" }"; break; case "restart-when-free": Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].RestartIfEmpty(); strResponse = "{ \"result\" : \"sent\" }"; break; case "command": //Sends literal command to a server Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Send(context.Request.Parameters["message"]); strResponse = "{ \"result\" : \"sent\" }"; break; case "get-yams-settings": DataSet dsSettings = Database.ReturnSettings(); JsonConvert.SerializeObject(dsSettings, Formatting.Indented); break; case "save-yams-settings": //Settings update foreach (Parameter p in param) { if (p.Name != "action") { Database.SaveSetting(p.Name, p.Value); } } break; case "get-server-settings": //retrieve all server settings as JSON List <string> listIPsMC = new List <string>(); IPHostEntry ipListenMC = Dns.GetHostEntry(""); foreach (IPAddress ipaddress in ipListenMC.AddressList) { if (ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { listIPsMC.Add(ipaddress.ToString()); } } intServerID = Convert.ToInt32(param["serverid"]); strResponse = "{ \"serverid\" : " + intServerID + "," + "\"title\" : \"" + Database.GetSetting(intServerID, "ServerTitle") + "\"," + "\"optimisations\" : \"" + Database.GetSetting(intServerID, "ServerEnableOptimisations") + "\"," + "\"memory\" : \"" + Database.GetSetting(intServerID, "ServerAssignedMemory") + "\"," + "\"autostart\" : \"" + Database.GetSetting(intServerID, "ServerAutoStart") + "\"," + "\"type\" : \"" + Database.GetSetting(intServerID, "ServerType") + "\"," + "\"motd\" : \"" + Database.GetSetting("motd", "MC", intServerID) + "\"," + "\"listen\" : \"" + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-ip") + "\"," + "\"port\" : \"" + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-port") + "\"," + "\"IPs\": " + JsonConvert.SerializeObject(listIPsMC, Formatting.None); strResponse += "}"; break; case "get-server-connections": intServerID = Convert.ToInt32(param["serverid"]); strResponse = "{ \"dnsname\" : \"" + Database.GetSetting("DNSName", "YAMS") + "\", " + "\"externalip\" : \"" + Networking.GetExternalIP().ToString() + "\", " + "\"mcport\" : " + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("server-port") + ", " + "\"publicport\" : " + Database.GetSetting("PublicListenPort", "YAMS") + " }"; break; case "get-mc-settings": //retrieve all server settings as JSON intServerID = Convert.ToInt32(param["serverid"]); json = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json"); jProps = JObject.Parse(json); strResponse = ""; foreach (JObject option in jProps["options"]) { strResponse += "<p><label for=\"" + (string)option["key"] + "\" title=\"" + (string)option["description"] + "\">" + (string)option["name"] + "</label>"; string strValue = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty((string)option["key"]); switch ((string)option["type"]) { case "string": strResponse += "<input type=\"text\" name=\"" + (string)option["key"] + "\" value=\"" + strValue + "\" />"; break; case "boolean": strResponse += "<select name=\"" + (string)option["key"] + "\">"; strResponse += "<option value=\"true\""; if (strValue == "true") { strResponse += " selected"; } strResponse += ">True</option>"; strResponse += "<option value=\"false\""; if (strValue == "false") { strResponse += " selected"; } strResponse += ">False</option>"; strResponse += "</select>"; break; case "integer": strResponse += "<select name=\"" + (string)option["key"] + "\">"; int intValue = Convert.ToInt32(strValue); for (var i = Convert.ToInt32((string)option["min"]); i <= Convert.ToInt32((string)option["max"]); i++) { strResponse += "<option value=\"" + i.ToString() + "\""; if (intValue == i) { strResponse += " selected"; } strResponse += ">" + i.ToString() + "</option>"; } strResponse += "</select>"; break; case "array": strResponse += "<select name=\"" + (string)option["key"] + "\">"; string strValues = (string)option["values"]; string[] elements = strValues.Split(','); foreach (string values in elements) { string[] options = values.Split('|'); strResponse += "<option value=\"" + options[0] + "\""; if (strValue == options[0]) { strResponse += " selected"; } strResponse += ">" + options[1] + "</option>"; } strResponse += "</select>"; break; } strResponse += "</p>"; } break; case "save-server-settings": intServerID = Convert.ToInt32(param["serverid"]); Database.UpdateServer(intServerID, "ServerTitle", param["title"]); Database.UpdateServer(intServerID, "ServerType", param["type"]); Database.UpdateServer(intServerID, "ServerAssignedMemory", Convert.ToInt32(param["memory"])); if (param["optimisations"] == "true") { Database.UpdateServer(intServerID, "ServerEnableOptimisations", true); } else { Database.UpdateServer(intServerID, "ServerEnableOptimisations", false); } if (param["autostart"] == "true") { Database.UpdateServer(intServerID, "ServerAutoStart", true); } else { Database.UpdateServer(intServerID, "ServerAutoStart", false); } Database.SaveSetting(intServerID, "motd", param["message"]); //Save the server's MC settings MCServer thisServer = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])]; thisServer.SaveProperty("server-ip", param["cfg_listen-ip"]); thisServer.SaveProperty("server-port", param["cfg_port"]); json = File.ReadAllText(YAMS.Core.RootFolder + @"\lib\properties.json"); jProps = JObject.Parse(json); strResponse = ""; foreach (JObject option in jProps["options"]) { thisServer.SaveProperty((string)option["key"], param[(string)option["key"]]); } //If they've selected a Bukkit but not chosen to have them installed, do it for them if (param["type"] == "bukkit") { if (Database.GetSetting("BukkitInstalled", "YAMS") == "false") { Database.SaveSetting("BukkitInstalled", "true"); AutoUpdate.CheckUpdates(); } } else if (param["type"] == "bukkit-beta") { if (Database.GetSetting("BukkitBetaInstalled", "YAMS") == "false") { Database.SaveSetting("BukkitBetaInstalled", "true"); AutoUpdate.CheckUpdates(); } } else if (param["type"] == "bukkit-dev") { if (Database.GetSetting("BukkitDevInstalled", "YAMS") == "false") { Database.SaveSetting("BukkitDevInstalled", "true"); AutoUpdate.CheckUpdates(); } } if (thisServer.Running) { thisServer.RestartIfEmpty(); } break; case "get-config-file": List <string> listConfig = Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ReadConfig(param["file"]); strResponse = JsonConvert.SerializeObject(listConfig, Formatting.Indented); break; case "get-server-whitelist": strResponse = "{ \"enabled\" : " + Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].GetProperty("white-list") + " }"; break; case "upload-world": var test = context.Request.Files["new-world"]; break; case "delete-world": bool bolRandomSeed = false; if (param["randomseed"] == "true") { bolRandomSeed = true; } Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].ClearWorld(bolRandomSeed); strResponse = "{ \"result\" : \"sent\" }"; break; case "remove-server": Core.Servers[Convert.ToInt32(context.Request.Parameters["serverid"])].Stop(); Core.Servers.Remove(Convert.ToInt32(context.Request.Parameters["serverid"])); Database.DeleteServer(Convert.ToInt32(context.Request.Parameters["serverid"])); strResponse = "{ \"result\" : \"removed\" }"; break; case "about": Dictionary <string, string> dicAbout = new Dictionary <string, string> { { "dll", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Library.dll")).FileVersion }, { "svc", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Service.exe")).FileVersion }, { "gui", FileVersionInfo.GetVersionInfo(Path.Combine(Core.RootFolder, "YAMS-Updater.exe")).FileVersion }, { "db", Database.GetSetting("DBSchema", "YAMS") } }; strResponse = JsonConvert.SerializeObject(dicAbout, Formatting.Indented); break; case "installed-apps": Dictionary <string, string> dicApps = new Dictionary <string, string> { { "bukkit", Database.GetSetting("BukkitInstalled", "YAMS") }, { "bukkitBeta", Database.GetSetting("BukkitBetaInstalled", "YAMS") }, { "bukkitDev", Database.GetSetting("BukkitDevInstalled", "YAMS") }, { "overviewer", Database.GetSetting("OverviewerInstalled", "YAMS") }, { "c10t", Database.GetSetting("C10tInstalled", "YAMS") }, { "biomeextractor", Database.GetSetting("BiomeExtractorInstalled", "YAMS") }, { "tectonicus", Database.GetSetting("TectonicusInstalled", "YAMS") }, { "nbtoolkit", Database.GetSetting("NBToolkitInstalled", "YAMS") } }; strResponse = JsonConvert.SerializeObject(dicApps, Formatting.Indented); break; case "update-apps": Database.SaveSetting("OverviewerInstalled", param["overviewer"]); Database.SaveSetting("C10tInstalled", param["c10t"]); Database.SaveSetting("BiomeExtractorInstalled", param["biomeextractor"]); Database.SaveSetting("BukkitInstalled", param["bukkit"]); Database.SaveSetting("BukkitBetaInstalled", param["bukkitBeta"]); Database.SaveSetting("BukkitDevInstalled", param["bukkitDev"]); strResponse = "done"; break; case "force-autoupdate": AutoUpdate.CheckUpdates(false, true); break; case "network-settings": List <string> listIPs = new List <string>(); IPHostEntry ipListen = Dns.GetHostEntry(""); foreach (IPAddress ipaddress in ipListen.AddressList) { if (ipaddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { listIPs.Add(ipaddress.ToString()); } } Dictionary <string, string> dicNetwork = new Dictionary <string, string> { { "portForwarding", Database.GetSetting("EnablePortForwarding", "YAMS") }, { "openFirewall", Database.GetSetting("EnableOpenFirewall", "YAMS") }, { "publicEnable", Database.GetSetting("EnablePublicSite", "YAMS") }, { "adminPort", Database.GetSetting("AdminListenPort", "YAMS") }, { "publicPort", Database.GetSetting("PublicListenPort", "YAMS") }, { "currentIP", Database.GetSetting("YAMSListenIP", "YAMS") }, { "telnetEnable", Database.GetSetting("EnableTelnet", "YAMS") }, { "telnetPort", Database.GetSetting("TelnetPort", "YAMS") }, { "IPs", JsonConvert.SerializeObject(listIPs, Formatting.None) } }; strResponse = JsonConvert.SerializeObject(dicNetwork, Formatting.Indented).Replace(@"\", "").Replace("\"[", "[").Replace("]\"", "]"); break; case "save-network-settings": int intTester = 0; try { //Try to convert to integers to make sure something silly isn't put in. TODO: Javascript validation intTester = Convert.ToInt32(param["adminPort"]); intTester = Convert.ToInt32(param["publicPort"]); IPAddress ipTest = IPAddress.Parse(param["listenIp"]); } catch (Exception e) { YAMS.Database.AddLog("Invalid input on network settings", "web", "warn"); return(ProcessingResult.Abort); } Database.SaveSetting("EnablePortForwarding", param["portForwarding"]); Database.SaveSetting("EnableOpenFirewall", param["openFirewall"]); Database.SaveSetting("EnablePublicSite", param["publicEnable"]); Database.SaveSetting("AdminListenPort", param["adminPort"]); Database.SaveSetting("PublicListenPort", param["publicPort"]); Database.SaveSetting("YAMSListenIP", param["listenIp"]); Database.SaveSetting("EnableTelnet", param["telnetEnable"]); Database.SaveSetting("TelnetPort", param["telnetPort"]); Database.AddLog("Network settings have been saved, to apply changes a service restart is required. Please check they are correct before restarting", "web", "warn"); break; case "job-list": DataSet rdJobs = Database.ListJobs(); strResponse = JsonConvert.SerializeObject(rdJobs, Formatting.Indented); break; case "delete-job": string strJobID = param["jobid"]; Database.DeleteJob(strJobID); strResponse = "done"; break; case "add-job": intServerID = Convert.ToInt32(param["job-server"]); int intHour = Convert.ToInt32(param["job-hour"]); int intMinute = Convert.ToInt32(param["job-minute"]); Database.AddJob(param["job-type"], intHour, intMinute, param["job-params"], intServerID); break; case "logout": WebSession.Current.UserName = ""; break; case "newserver": var NewServer = new List <KeyValuePair <string, string> >(); NewServer.Add(new KeyValuePair <string, string>("motd", "Welcome to a YAMS server!")); NewServer.Add(new KeyValuePair <string, string>("server-ip", Networking.GetListenIP().ToString())); NewServer.Add(new KeyValuePair <string, string>("server-name", param["name"])); NewServer.Add(new KeyValuePair <string, string>("server-port", Networking.TcpPort.FindNextAvailablePort(25565).ToString())); Database.NewServerWeb(NewServer, param["name"], 1024); strResponse = "done"; break; case "updateDNS": Database.SaveSetting("DNSName", param["dns-name"]); Database.SaveSetting("DNSSecret", param["dns-secret"]); Database.SaveSetting("LastExternalIP", param["dns-external"]); strResponse = "done"; break; case "getDNS": strResponse = "{ \"name\":\"" + Database.GetSetting("DNSName", "YAMS") + "\", \"secret\": \"" + Database.GetSetting("DNSSecret", "YAMS") + "\", \"external\" : \"" + Networking.GetExternalIP().ToString() + "\" }"; break; case "backup-now": Backup.BackupNow(Core.Servers[Convert.ToInt32(param["serverid"])], param["title"]); strResponse = "{ \"result\" : \"sent\" }"; break; default: return(ProcessingResult.Abort); } context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(strResponse); context.Response.Body.Write(buffer, 0, buffer.Length); } else { // not a post, so say bye bye! return(ProcessingResult.Abort); } return(ProcessingResult.SendResponse); } else if (context.Request.Uri.AbsoluteUri.Contains(@"/admin")) { if (WebSession.Current.UserName != "admin") { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } else { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\index.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } } else if (context.Request.Uri.AbsoluteUri.Contains(@"/login")) { //This is a login request, check it's legit string userName = context.Request.Form["strUsername"]; string password = context.Request.Form["strPassword"]; if (userName == "admin" && password == Database.GetSetting("AdminPassword", "YAMS")) { WebSession.Create(); WebSession.Current.UserName = "******"; context.Response.Redirect(@"/admin"); return(ProcessingResult.SendResponse); } else { context.Response.Reason = "Completed - YAMS"; context.Response.Connection.Type = ConnectionType.Close; byte[] buffer = Encoding.UTF8.GetBytes(File.ReadAllText(YAMS.Core.RootFolder + @"\web\admin\login.html")); context.Response.Body.Write(buffer, 0, buffer.Length); return(ProcessingResult.SendResponse); } } else if (context.Request.Uri.AbsoluteUri.Equals(@"/")) { context.Response.Redirect(@"/admin"); return(ProcessingResult.SendResponse); } else { return(ProcessingResult.Abort); } }
public Overviewer(MCServer s, string strParams = "rendermodes=normal,lighting,night") : base(s, "overviewer", @"overviewer.exe", "Overviewer", true, strParams) {}