public void KickPlayer(string commandArgs) { string playerName = commandArgs; string reason = ""; if (commandArgs.Contains(" ")) { playerName = commandArgs.Substring(0, commandArgs.IndexOf(" ")); reason = commandArgs.Substring(commandArgs.IndexOf(" ") + 1); } ClientObject player = null; if (playerName != "") { player = GetClientByName(playerName); if (player != null) { DarkLog.Normal("Kicking " + playerName + " from the server"); if (reason == "") { reason = "no reason specified"; } m_server.Kick(player.Id, "You are banned from the server : " + reason); } } else { DarkLog.Error("Syntax error. Usage: /kick playername [reason]"); } }
public static void KickPlayer(string commandArgs) { string playerName = commandArgs; string reason = ""; if (commandArgs.Contains(" ")) { playerName = commandArgs.Substring(0, commandArgs.IndexOf(" ", StringComparison.Ordinal)); reason = commandArgs.Substring(commandArgs.IndexOf(" ", StringComparison.Ordinal) + 1); } ClientObject player = null; if (playerName != "") { player = ClientHandler.GetClientByName(playerName); if (player != null) { DarkLog.Normal("Kicking " + playerName + " from the server"); if (reason != "") { Messages.ConnectionEnd.SendConnectionEnd(player, "Kicked from the server, " + reason); } else { Messages.ConnectionEnd.SendConnectionEnd(player, "Kicked from the server"); } } } else { DarkLog.Error("Syntax error. Usage: /kick playername [reason]"); } }
public static void HandleServerInput(string input) { string commandPart = input; string argumentPart = ""; if (commandPart.Contains(" ")) { if (commandPart.Length > commandPart.IndexOf(' ') + 1) { argumentPart = commandPart.Substring(commandPart.IndexOf(' ') + 1); } commandPart = commandPart.Substring(0, commandPart.IndexOf(' ')); } if (commandPart.Length > 0) { if (commands.ContainsKey(commandPart)) { try { commands[commandPart].func(argumentPart); } catch (Exception e) { DarkLog.Error("Error handling server command " + commandPart + ", Exception " + e); } } else { DarkLog.Normal("Unknown server command: " + commandPart); } } }
private static void StartHTTPServer() { if (Settings.settingsStore.httpPort > 0) { DarkLog.Normal("Starting HTTP server..."); httpListener = new HttpListener(); try { if (Settings.settingsStore.address != "0.0.0.0") { httpListener.Prefixes.Add("http://" + Settings.settingsStore.address + ":" + Settings.settingsStore.httpPort + '/'); } else { httpListener.Prefixes.Add("http://*:" + Settings.settingsStore.httpPort + '/'); } httpListener.Start(); httpListener.BeginGetContext(asyncHTTPCallback, httpListener); } catch (Exception e) { DarkLog.Error("Error while starting HTTP server: " + e + "\nPlease try running the server as an administrator."); } } }
public static void ExpireLogs() { if (!Directory.Exists(logDirectory)) { //Screenshot directory is missing so there will be no screenshots to delete. return; } string[] logFiles = Directory.GetFiles(logDirectory); foreach (string logFile in logFiles) { //Check if the expireScreenshots setting is enabled if (Settings.settingsStore.expireLogs > 0) { //If the file is older than a day, delete it if (File.GetCreationTime(logFile).AddDays(Settings.settingsStore.expireLogs) < DateTime.Now) { DarkLog.Debug("Deleting saved log '" + logFile + "', reason: Expired!"); try { File.Delete(logFile); } catch (Exception e) { DarkLog.Error("Exception while trying to delete '" + logFile + "'!, Exception: " + e.Message); } } } } }
public static void ExpireScreenshots() { if (!Directory.Exists(screenshotDirectory)) { //Screenshot directory is missing so there will be no screenshots to delete. return; } string[] screenshotFiles = Directory.GetFiles(screenshotDirectory); foreach (string screenshotFile in screenshotFiles) { string cacheFile = Path.Combine(screenshotDirectory, screenshotFile + ".png"); //Check if the expireScreenshots setting is enabled if (Settings.settingsStore.expireScreenshots > 0) { //If the file is older than a day, delete it if (File.GetCreationTime(cacheFile).AddDays(Settings.settingsStore.expireScreenshots) < DateTime.Now) { DarkLog.Debug("Deleting saved screenshot '" + screenshotFile + "', reason: Expired!"); try { File.Delete(cacheFile); } catch (Exception e) { DarkLog.Error("Exception while trying to delete " + cacheFile + "!, Exception: " + e.Message); } } } } }
private static void asyncHTTPCallback(IAsyncResult result) { try { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); string responseText = new ServerInfo(Settings.settingsStore).GetJSON(); byte[] buffer = Encoding.UTF8.GetBytes(responseText); context.Response.ContentLength64 = buffer.LongLength; context.Response.OutputStream.Write(buffer, 0, buffer.Length); context.Response.OutputStream.Close(); listener.BeginGetContext(asyncHTTPCallback, listener); } catch (Exception e) { //Ignore the EngGetContext throw while shutting down the HTTP server. if (Server.serverRunning) { DarkLog.Error("Exception while listening to HTTP server!, Exception:\n" + e); } } }
protected override void ProcessNetwork() { NetIncomingMessage inc; while ((inc = m_server.ReadMessage()) != null) { switch (inc.MessageType) { case NetIncomingMessageType.StatusChanged: NetConnectionStatus status = (NetConnectionStatus)inc.ReadByte(); switch (status) { case NetConnectionStatus.Connected: Trigger(new GameServerConnectionEvent { Id = inc.SenderConnection.RemoteUniqueIdentifier }); break; case NetConnectionStatus.Disconnected: m_connections.Remove(inc.SenderConnection.RemoteUniqueIdentifier); Trigger(new GameServerDisconnectionEvent { Id = inc.SenderConnection.RemoteUniqueIdentifier }); break; case NetConnectionStatus.Disconnecting: case NetConnectionStatus.InitiatedConnect: case NetConnectionStatus.RespondedConnect: break; } break; //Check for client attempting to connect case NetIncomingMessageType.ConnectionApproval: HandleConnectionChallenge(inc); break; case NetIncomingMessageType.Data: HandleData(inc); break; case NetIncomingMessageType.VerboseDebugMessage: case NetIncomingMessageType.DebugMessage: DarkLog.Debug(inc.ReadString()); break; case NetIncomingMessageType.WarningMessage: DarkLog.Normal(inc.ReadString()); break; case NetIncomingMessageType.ErrorMessage: DarkLog.Error(inc.ReadString()); break; } m_server.Recycle(inc); } }
public BanList() { DarkLog.Debug("Loading bans"); m_bannedNames = new List <string>(); m_bannedIps = new List <IPAddress>(); m_bannedPublicKeys = new List <string>(); if (File.Exists(banlistFile)) { foreach (string line in File.ReadAllLines(banlistFile)) { m_bannedNames.Add(line); } } else { File.Create(banlistFile); } if (File.Exists(ipBanlistFile)) { foreach (string line in File.ReadAllLines(ipBanlistFile)) { IPAddress banIPAddr = null; if (IPAddress.TryParse(line, out banIPAddr)) { m_bannedIps.Add(banIPAddr); } else { DarkLog.Error("Error in IP ban list file, " + line + " is not an IP address"); } } } else { File.Create(ipBanlistFile); } if (File.Exists(publicKeyBanlistFile)) { foreach (string bannedPublicKey in File.ReadAllLines(publicKeyBanlistFile)) { m_bannedPublicKeys.Add(bannedPublicKey); } } else { File.Create(publicKeyBanlistFile); } }
private static IDMPPlugin ActivatePluginType(Type loadedType) { try { //"as IDMPPlugin" will cast or return null if the type is not a IDMPPlugin IDMPPlugin pluginInstance = Activator.CreateInstance(loadedType) as IDMPPlugin; return(pluginInstance); } catch (Exception e) { DarkLog.Error("Cannot activate plugin " + loadedType.Name + ", Exception: " + e.ToString()); return(null); } }
static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { //This will find and return the assembly requested if it is already loaded foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies()) { if (assembly.FullName == args.Name) { DarkLog.Debug("Resolved plugin assembly reference: " + args.Name + " (referenced by " + args.RequestingAssembly.FullName + ")"); return(assembly); } } DarkLog.Error("Could not resolve assembly " + args.Name + " referenced by " + args.RequestingAssembly.FullName); return(null); }
public static void HandleServerInput(string input, RCON.CommandCallback outputCallback = null) { // capture command output for RCON // this might capture unrelated output, but this is the only way without rewriting the command handling system List <string> commandOutput = new List <string>(); void OnLog(string message) { commandOutput.Add(message); }; DarkLog.OnLog += OnLog; string commandPart = input; string argumentPart = ""; if (commandPart.Contains(" ")) { if (commandPart.Length > commandPart.IndexOf(' ') + 1) { argumentPart = commandPart.Substring(commandPart.IndexOf(' ') + 1); } commandPart = commandPart.Substring(0, commandPart.IndexOf(' ')); } if (commandPart.Length > 0) { if (commands.ContainsKey(commandPart)) { try { commands[commandPart].func(argumentPart); } catch (Exception e) { DarkLog.Error("Error handling server command " + commandPart + ", Exception " + e); } } else { DarkLog.Normal("Unknown server command: " + commandPart); } } // remove event listener DarkLog.OnLog -= OnLog; // send output back to rcon outputCallback?.Invoke(string.Join("\n", commandOutput)); }
/// <summary> /// Start the RCON server /// </summary> public static void Start() { if (Settings.settingsStore.rconPassword == "changeme") { DarkLog.Error("RCON password has not been changed - RCON disabled."); return; } _tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, Settings.settingsStore.rconPort)); _tcpListener.Start(); _running = true; _tcpListener.BeginAcceptTcpClient(AcceptTcpClient, null); DarkLog.Normal("Started RCON server on port " + Settings.settingsStore.rconPort); }
public void Update() { try { m_clients.Flush(); // TODO: Save subspace if player leaves and count == 0 m_server.Run(); // Dispatch events Run(); //Check timers NukeKSC.CheckTimer(); Dekessler.CheckTimer(); //Run plugin update DMPPluginHandler.FireOnUpdate(); } catch (Exception e) { DarkLog.Error("Fatal error thrown, exception: " + e); Server.ShutDown("Crashed!"); } }
public bool SaveModObject(byte[] data, string sha256sum) { if (data == null) { data = new byte[0]; } if (Common.CalculateSHA256Hash(data) != sha256sum) { return(false); } string tryWrite = null; try { foreach (KeyValuePair <string, string> kvp in clientData) { tryWrite = Path.Combine(modpackPath, kvp.Key); if (kvp.Value == sha256sum) { clientReceived++; new FileInfo(tryWrite).Directory.Create(); if (File.Exists(tryWrite)) { File.Delete(tryWrite); } File.WriteAllBytes(tryWrite, data); } } } catch (Exception e) { DarkLog.Error("Cannot write file " + tryWrite + ", error: " + e); return(false); } return(true); }
public static void LoadPlugins() { DarkLog.Debug("Loading plugins!"); //Load all the assemblies just in case they depend on each other during instantation List <Assembly> loadedAssemblies = new List <Assembly>(); string[] pluginFiles = Directory.GetFiles(Server.pluginDirectory, "*", SearchOption.AllDirectories); foreach (string pluginFile in pluginFiles) { if (Path.GetExtension(pluginFile).ToLower() == ".dll") { try { Assembly loadedAssembly = Assembly.LoadFile(pluginFile); loadedAssemblies.Add(loadedAssembly); DarkLog.Debug("Loaded " + pluginFile); } catch { DarkLog.Debug("Error loading " + pluginFile); } } } //Add all the event types pluginEvents.Add(typeof(DMPUpdate), new List <Delegate>()); pluginEvents.Add(typeof(DMPOnServerStart), new List <Delegate>()); pluginEvents.Add(typeof(DMPOnServerStop), new List <Delegate>()); pluginEvents.Add(typeof(DMPOnClientConnect), new List <Delegate>()); pluginEvents.Add(typeof(DMPOnClientAuthenticated), new List <Delegate>()); pluginEvents.Add(typeof(DMPOnClientDisconnect), new List <Delegate>()); pluginEvents.Add(typeof(DMPOnMessageReceived), new List <Delegate>()); //Iterate through the assemblies looking for the DMPPlugin attribute foreach (Assembly loadedAssembly in loadedAssemblies) { Type[] loadedTypes = loadedAssembly.GetExportedTypes(); foreach (Type loadedType in loadedTypes) { if (loadedType.IsDefined(typeof(DMPPluginAttribute), false)) { DarkLog.Debug("Loading " + loadedType.Name); object pluginInstance = Activator.CreateInstance(loadedType); MethodInfo[] methodInfos = loadedType.GetMethods(BindingFlags.Public | BindingFlags.Instance); foreach (MethodInfo methodInfo in methodInfos) { try { foreach (Type evT in pluginEvents.Keys) { if (evT.Name.Substring(3) == methodInfo.Name) { DarkLog.Debug("Event registered : " + evT.Name); Delegate deg = Delegate.CreateDelegate(evT, pluginInstance, methodInfo); DMPEventInfo info = new DMPEventInfo(); info.loadedAssembly = loadedAssembly.FullName; info.loadedType = loadedType.Name; delegateInfo.Add(deg, info); pluginEvents[evT].Add(deg); } } } catch (Exception e) { DarkLog.Error("Error loading " + methodInfo.Name + " from " + loadedType.Name + ", Exception: " + e.Message); } } } } } DarkLog.Debug("Done!"); }
public static void LoadPlugins() { string pluginDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugins"); if (!Directory.Exists(pluginDirectory)) { Directory.CreateDirectory(pluginDirectory); } DarkLog.Debug("Loading plugins!"); //Load all the assemblies just in case they depend on each other during instantation List <Assembly> loadedAssemblies = new List <Assembly>(); string[] pluginFiles = Directory.GetFiles(pluginDirectory, "*", SearchOption.AllDirectories); foreach (string pluginFile in pluginFiles) { if (Path.GetExtension(pluginFile).ToLower() == ".dll") { try { //UnsafeLoadFrom will not throw an exception if the dll is marked as unsafe, such as downloaded from internet in Windows //See http://stackoverflow.com/a/15238782 Assembly loadedAssembly = Assembly.UnsafeLoadFrom(pluginFile); loadedAssemblies.Add(loadedAssembly); DarkLog.Debug("Loaded " + pluginFile); } catch (NotSupportedException) { //This should only occur if using Assembly.LoadFrom() above instead of Assembly.UnsafeLoadFrom() DarkLog.Debug("Can't load dll, perhaps it is blocked: " + pluginFile); } catch { DarkLog.Debug("Error loading " + pluginFile); } } } //Iterate through the assemblies looking for classes that have the IDMPPlugin interface Type dmpInterfaceType = typeof(IDMPPlugin); foreach (Assembly loadedAssembly in loadedAssemblies) { Type[] loadedTypes = loadedAssembly.GetExportedTypes(); foreach (Type loadedType in loadedTypes) { Type[] typeInterfaces = loadedType.GetInterfaces(); bool containsDMPInterface = false; foreach (Type typeInterface in typeInterfaces) { if (typeInterface == dmpInterfaceType) { containsDMPInterface = true; } } if (containsDMPInterface) { DarkLog.Debug("Loading plugin: " + loadedType.FullName); try { IDMPPlugin pluginInstance = ActivatePluginType(loadedType); if (pluginInstance != null) { DarkLog.Debug("Loaded plugin: " + loadedType.FullName); loadedPlugins.Add(pluginInstance); } } catch (Exception ex) { DarkLog.Error("Error loading plugin " + loadedType.FullName + "(" + loadedType.Assembly.FullName + ") Exception: " + ex.ToString()); } } } } DarkLog.Debug("Done!"); }
public void Load() { if (Settings.settingsStore.modpackMode == DarkMultiPlayerCommon.ModpackMode.GAMEDATA) { DarkLog.Debug("Loading GameData mod list"); if (File.Exists(modpackServerCacheObjects)) { File.Delete(modpackServerCacheObjects); } hashCount = 0; modpackData.Clear(); objectData.Clear(); string[] modFiles = Directory.GetFiles(modpackPath, "*", SearchOption.AllDirectories); foreach (string filePath in modFiles) { hashCount++; if (!filePath.ToLower().StartsWith(modpackPath.ToLower(), StringComparison.Ordinal)) { DarkLog.Error("Not adding file that is in GameData, symlinks are not supported."); DarkLog.Error("File was: " + filePath); continue; } string trimmedPath = filePath.Substring(modpackPath.Length + 1).Replace('\\', '/'); bool skipFile = false; foreach (string excludePath in excludeList) { if (trimmedPath.ToLower().StartsWith(excludePath, StringComparison.Ordinal)) { skipFile = true; } } foreach (string excludePath in containsExcludeList) { if (trimmedPath.ToLower().Contains(excludePath)) { skipFile = true; } } if (skipFile) { continue; } string sha256sum = Common.CalculateSHA256Hash(filePath); if (!modpackData.ContainsKey(trimmedPath)) { if (DateTime.UtcNow.Ticks > nextHashTime) { nextHashTime = DateTime.UtcNow.Ticks + TimeSpan.TicksPerSecond; DarkLog.Debug("Hashing: " + hashCount + "/" + modFiles.Length); } modpackData.Add(trimmedPath, sha256sum); } //Need to check because we may have a duplicate file in GameData if (!objectData.ContainsKey(sha256sum)) { objectData.Add(sha256sum, trimmedPath); } } DarkLog.Debug("Hashed " + modFiles.Length + " files"); using (StreamWriter sw = new StreamWriter(modpackServerCacheObjects)) { foreach (KeyValuePair <string, string> kvp in modpackData) { sw.WriteLine("{0}={1}", kvp.Key, kvp.Value); } } } }