public virtual void LoadPlugin() { PointBlankLogging.Log("Loading rocket plugin: " + Name); try { Load(); } catch (Exception ex) { PointBlankLogging.LogError("Failed to load rocket plugin " + Name + ", unloading...", ex); try { PointBlankLogging.LogError("Failed to unload rocket plugin " + Name, ex); UnloadPlugin(PluginState.Failure); return; } catch (Exception ex1) { PointBlankLogging.LogError("Failed to unload rocket plugin " + Name, ex1); } } bool cancel = false; OnPluginLoading?.Invoke(this, ref cancel); if (cancel) { return; } _State = PluginState.Loaded; }
/// <summary> /// Executes an SQL command on the server and returns the output /// </summary> /// <param name="command">The command to execute</param> /// <param name="output">The data returned by the SQL server</param> /// <param name="behaviour">The behaviour of the server</param> /// <param name="paramaters">The paramaters in the command</param> /// <returns>If the command was ran successfully</returns> public bool SendCommand(string command, out SqlDataReader output, CommandBehavior behaviour = CommandBehavior.Default, Dictionary <string, string> paramaters = null) { try { Command.CommandText = command; // Set the command text Command.Parameters.Clear(); // Clear the paramaters if (paramaters != null) { foreach (KeyValuePair <string, string> kvp in paramaters) { Command.Parameters.AddWithValue(kvp.Key, kvp.Value); // Add the paramater } } output = Command.ExecuteReader(behaviour); // Execute the reader return(true); } catch (Exception ex) { PointBlankLogging.LogError("Could not send command in SQL server: " + Server, ex, false, false); output = null; return(false); } }
public bool Stop() { if (!Enabled) // Don't stop if it isn't running { return(true); } PointBlankLogging.Log("Stopping service: " + ServiceClass.Name); // Call the important functions try { PointBlankServiceEvents.RunServiceStop(ServiceClass); // Run the pre-stop event ServiceClass.Unload(); // Run the code PointBlankServiceEvents.RunServiceUnloaded(ServiceClass); // Run the post-stop event } catch (Exception ex) { PointBlankLogging.LogError("Error when stopping service: " + ServiceClass.Name, ex); } // Set the variables Enabled = false; PointBlankLogging.Log("Stopped service: " + ServiceClass.Name); return(true); }
public void LoadCommand(Type _class) { if (!typeof(CMD).IsAssignableFrom(_class)) { return; } if (_class == typeof(CMD)) { return; } if (Commands.Count(a => a.GetType().Name == _class.Name && a.GetType().Assembly == _class.Assembly) > 0) { return; } try { string name = _class.Assembly.GetName().Name + "." + _class.Name; JObject objConfig = ((JArray)JSONConfig.Document["Commands"]).FirstOrDefault(a => (string)a["Name"] == name) as JObject; if (objConfig == null) { objConfig = new JObject(); ((JArray)JSONConfig.Document["Commands"]).Add(objConfig); } CommandWrapper wrapper = new CommandWrapper(_class, objConfig); Commands.Add(wrapper); } catch (Exception ex) { PointBlankLogging.LogError("Error loading command: " + _class.Name, ex); } }
public void Shutdown() { PointBlankLogging.LogImportant("Shutting down " + PointBlankInfo.Name + " v" + PointBlankInfo.Version + "..."); // Uninit Enabled = false; Instance = null; // Run the shutdowns Environment.runtimeObjects["Framework"].GetCodeObject <ServiceManager>().Shutdown(); Environment.runtimeObjects["Framework"].GetCodeObject <InterfaceManager>().Shutdown(); // Remove the runtime objects Environment.runtimeObjects["Framework"].RemoveCodeObject <ServiceManager>(); Environment.runtimeObjects["Framework"].RemoveCodeObject <InterfaceManager>(); // Remove the runtime objects Environment.runtimeObjects.Remove("Plugins"); Environment.runtimeObjects.Remove("Services"); Environment.runtimeObjects.Remove("Extensions"); Environment.runtimeObjects.Remove("Framework"); // Run the required functions RunRequirementsShutdown(); PointBlankLogging.LogImportant("Shut down " + PointBlankInfo.Name + " v" + PointBlankInfo.Version + "!"); }
public void LoadDetour(MethodInfo method) { // Setup variables DetourAttribute attribute = (DetourAttribute)Attribute.GetCustomAttribute(method, typeof(DetourAttribute)); // Do checks if (attribute == null) { return; } if (!attribute.MethodFound) { return; } if (Detours.Count(a => a.Key.Method == attribute.Method) > 0) { return; } try { DetourWrapper wrapper = new DetourWrapper(attribute.Method, method, attribute); wrapper.Detour(); Detours.Add(attribute, wrapper); } catch (Exception ex) { PointBlankLogging.LogError("Error detouring: " + method.Name, ex); } }
private static void RunAsync() { while (Enviroment.Running) { while (_AsyncCommands.Count > 0) { AsyncCommand command = _AsyncCommands.Dequeue(); try { if (command.CallBack == null) { command.Command.ExecuteNonQuery(); } else { command.CallBack(command.Command.ExecuteReader(command.Behaviour)); } } catch (Exception ex) { PointBlankLogging.LogError("Could not send async command to server!", ex, false, false); } } } }
public bool Unload() { try { if (!Enabled) { return(true); } PointBlankLogging.Log("Stopping " + Name + "..."); SaveConfiguration(); // Save the configuration SaveTranslation(); // Save the translation PointBlankPluginEvents.RunPluginStop(PluginClass); // Run the stop event PluginClass.Unload(); // Run the unload function PointBlankPluginEvents.RunPluginUnloaded(PluginClass); // Run the unloaded event Enviroment.runtimeObjects["Plugins"].RemoveCodeObject(PluginClass.GetType().Name); // Remove the plugin from gameobject Enabled = false; // Set the enabled to false t.Abort(); // Abort the thread return(true); } catch (Exception ex) { PointBlankLogging.LogError("Error stopping plugin: " + Name, ex); return(false); } }
internal void LoadConfiguration() { if (ConfigurationData.CreatedNew) { SaveConfiguration(); return; } foreach (JProperty obj in ConfigurationData.Document.Properties()) { if (PluginClass.Configurations[obj.Name] == null) { continue; } try { PluginClass.Configurations[obj.Name] = obj.Value.ToObject(PluginClass.Configurations[obj.Name].GetType()); } catch (Exception ex) { PointBlankLogging.LogError("Failed to set the configuration " + obj.Name, ex, false, false); ConfigurationData.Document[obj.Name] = JToken.FromObject(PluginClass.Configurations[obj.Name]); } } }
public bool Start() { if (Enabled) // Don't run if it is already running { return(true); } PointBlankLogging.Log("Starting service: " + ServiceClass.Name); // Call the important functions try { PointBlankServiceEvents.RunServiceStart(ServiceClass); // Run the pre-run event ServiceClass.Load(); // Run the code PointBlankServiceEvents.RunServiceLoaded(ServiceClass); // Run the post-run event } catch (Exception ex) { PointBlankLogging.LogError("Error when starting service: " + ServiceClass.Name, ex); } // Set the variables Enabled = true; PointBlankLogging.Log("Started service: " + ServiceClass.Name); return(true); }
/// <summary> /// Uploads a file to the website using async /// </summary> /// <param name="URL">The URL to the website</param> /// <param name="path">The path to the file to upload</param> /// <param name="method">The method to run once the upload is done</param> /// <param name="useNewClient">Use a new client</param> /// <param name="client">A custom client(leave null to create a new one)</param> /// <returns>If the file was uploaded successfully</returns> public static bool UploadFileAsync(string URL, string path, UploadFileCompletedEventHandler method = null, bool useNewClient = true, WeebClient client = null) { try { if (useNewClient || client == null) { WeebClient wc = new WeebClient(); wc.UploadFileCompleted += new UploadFileCompletedEventHandler(OnUploadFile); if (method != null) { wc.UploadFileCompleted += method; } wc.UploadFileAsync(new Uri(URL), path); return(true); } client.UploadFileAsync(new Uri(URL), path); return(true); } catch (Exception ex) { PointBlankLogging.LogError("Failed to upload file via async to " + URL, ex, false, false); return(false); } }
public static bool RevertDetour(OffsetBackup backup) { try { unsafe { byte *ptrOriginal = (byte *)backup.Method.ToPointer(); *ptrOriginal = backup.A; *(ptrOriginal + 1) = backup.B; *(ptrOriginal + 10) = backup.C; *(ptrOriginal + 11) = backup.D; *(ptrOriginal + 12) = backup.E; if (IntPtr.Size == sizeof(Int32)) { *((uint *)(ptrOriginal + 2)) = backup.F32; } else { *((ulong *)(ptrOriginal + 2)) = backup.F64; } } return(true); } catch (Exception ex) { PointBlankLogging.LogError("Error reverting detour!", ex); return(false); } }
public virtual void UnloadPlugin(PluginState state = PluginState.Unloaded) { PointBlankLogging.Log("Unloading rocket plugin " + Name); OnPluginUnloading?.Invoke(this); Unload(); _State = state; }
private void Notify() { if (!PluginConfiguration.NotifyUpdates) { return; } PointBlankLogging.LogWarning("New update for plugin: " + Name); }
private void StopService(ServiceWrapper wrapper) // Stops the service { try { wrapper.Stop(); // Stop the service } catch (Exception ex) { PointBlankLogging.LogError("Error stopping service: " + wrapper.ServiceClass.Name, ex); } }
private void StopService(ServiceWrapper wrapper) // Stops the service { try { wrapper.Stop(); // Stop the service Environment.runtimeObjects["Services"].RemoveCodeObject(wrapper.ServiceClass.GetType().Name); } catch (Exception ex) { PointBlankLogging.LogError("Error stopping service: " + wrapper.ServiceClass.Name, ex); } }
public ECommandRunError Execute(PointBlankPlayer executor, string[] args) { try { if (CommandClass.AllowedServerState == EAllowedServerState.LOADING && PointBlankServer.IsRunning) { PointBlankPlayer.SendMessage(executor, Translations["CommandWrapper_Running"], ConsoleColor.Red); return(ECommandRunError.SERVER_RUNNING); } if (CommandClass.AllowedServerState == EAllowedServerState.RUNNING && !PointBlankServer.IsRunning) { PointBlankPlayer.SendMessage(executor, Translations["CommandWrapper_NotRunning"], ConsoleColor.Red); return(ECommandRunError.SERVER_LOADING); } if (CommandClass.AllowedCaller == EAllowedCaller.SERVER && executor != null) { executor.SendMessage(Translations["CommandWrapper_NotConsole"], Color.red); return(ECommandRunError.NOT_CONSOLE); } if (CommandClass.AllowedCaller == EAllowedCaller.PLAYER && executor == null) { executor.SendMessage(Translations["CommandWrapper_NotPlayer"], Color.red); return(ECommandRunError.NOT_PLAYER); } if (CommandClass.MinimumParams > args.Length) { PointBlankPlayer.SendMessage(executor, Translations["CommandWrapper_Arguments"], ConsoleColor.Red); return(ECommandRunError.ARGUMENT_COUNT); } if (executor != null && executor.HasCooldown(CommandClass)) { executor.SendMessage(Translations["CommandWrapper_Cooldown"], Color.red); return(ECommandRunError.COOLDOWN); } bool shouldExecute = true; PointBlankCommandEvents.RunCommandExecute(CommandClass, args, executor, ref shouldExecute); if (!shouldExecute) { return(ECommandRunError.NO_EXECUTE); } executor?.SetCooldown(CommandClass, DateTime.Now); CommandClass.Execute(executor, args); return(ECommandRunError.NONE); } catch (Exception ex) { PointBlankLogging.LogError("Error when running command: " + Class.Name, ex); return(ECommandRunError.EXCEPTION); } }
public override void Load() { if (!Directory.Exists(PointBlankServer.LibrariesPath)) { Directory.CreateDirectory(PointBlankServer.LibrariesPath); // Create libraries directory } if (!Directory.Exists(PointBlankServer.PluginsPath)) { Directory.CreateDirectory(PointBlankServer.PluginsPath); // Create plugins directory } if (!Directory.Exists(ConfigurationPath)) { Directory.CreateDirectory(ConfigurationPath); // Create plugins directory } if (!Directory.Exists(TranslationPath)) { Directory.CreateDirectory(TranslationPath); // Create plugins directory } // Setup the config UniConfig = new UniversalData(SM.ConfigurationPath + "\\PluginManager"); JSONConfig = UniConfig.GetData(EDataType.JSON) as JsonData; LoadConfig(); foreach (string library in Directory.GetFiles(PointBlankServer.LibrariesPath, "*.dll")) // Get all the dll files in libraries directory { _libraries.Add(Assembly.Load(File.ReadAllBytes(library))); // Load and add the library } foreach (string plugin in Directory.GetFiles(PointBlankServer.PluginsPath, "*.dll")) // Get all the dll files in plugins directory { try { PluginWrapper wrapper = new PluginWrapper(plugin); // Create the plugin wrapper _plugins.Add(wrapper); // Add the wrapper if (!wrapper.Load() && !PluginConfiguration.ContinueOnError) { break; } } catch (Exception ex) { PointBlankLogging.LogError("Error initializing plugin!", ex); if (!PluginConfiguration.ContinueOnError) { break; } } } PointBlankPluginEvents.RunPluginsLoaded(); }
private void Update() { if (!PluginConfiguration.AutoUpdate) { return; } if (string.IsNullOrEmpty(PluginClass.BuildURL)) { return; } PointBlankLogging.LogImportant("Downloading " + Name + "..."); WebsiteData.DownloadFile(PluginClass.BuildURL, Location); PointBlankLogging.LogImportant(Name + " updated successfully! Please restart the server to finalize the update!"); }
public CommandWrapper(Type _class, JObject config) { // Set the variables this.Class = _class; this.Config = config; // Setup the variables CommandClass = (CMD)Activator.CreateInstance(Class); Translations = Environment.ServiceTranslations[typeof(ServiceTranslations)].Translations; // Run the code Reload(); PointBlankLogging.Log("Loaded command: " + Commands[0]); }
public object CallOriginal(object[] args, object instance = null) { Revert(); object result = null; try { result = Original.Invoke(instance ?? Instance, args); } catch (Exception ex) { PointBlankLogging.LogError("Error when attempting to run original method!", ex); } Detour(); return result; }
public void Initialize() { if (Instance != null && Enabled) // Don't run if already running { return; } Environment.ServerDirectory = $"{Directory.GetCurrentDirectory()}/Servers/{Dedicator.serverID}"; if (!Directory.Exists(Environment.ServerDirectory)) { Directory.CreateDirectory(Environment.ServerDirectory); } Console.WriteLine(); PointBlankLogging.LogImportant("Loading " + PointBlankInfo.Name + " v" + PointBlankInfo.Version + "..."); PointBlankLogging.Log(); // Run required methods ApplyPatches(); // Setup the runtime objects Environment.runtimeObjects.Add("Framework", new RuntimeObject(new GameObject("Framework"))); Environment.runtimeObjects.Add("Extensions", new RuntimeObject(new GameObject("Extensions"))); Environment.runtimeObjects.Add("Services", new RuntimeObject(new GameObject("Services"))); Environment.runtimeObjects.Add("Plugins", new RuntimeObject(new GameObject("Plugins"))); // Add the code objects Environment.runtimeObjects["Framework"].AddCodeObject <InterfaceManager>(); // Both the service manager and interface manager are important without them Environment.runtimeObjects["Framework"].AddCodeObject <ServiceManager>(); // the modloader won't be able to function properly making it as usefull as Rocket // Run the inits Environment.runtimeObjects["Framework"].GetCodeObject <InterfaceManager>().Init(); Environment.runtimeObjects["Framework"].GetCodeObject <ServiceManager>().Init(); // Run required methods RunRequirements(); // Initialize Instance = this; Enabled = true; #if !DEBUG Console.WriteLine("In debug mode!"); #endif PointBlankLogging.Log(); PointBlankLogging.LogImportant("Loaded " + PointBlankInfo.Name + " v" + PointBlankInfo.Version + "!"); }
private void handleChat(SteamPlayer steamPlayer, EChatMode chatMode, ref Color incomingColor, string message, ref bool cancel) { cancel = false; Color color = incomingColor; try { UnturnedPlayer player = UnturnedPlayer.FromSteamPlayer(steamPlayer); color = UnturnedPlayerEvents.firePlayerChatted(player, chatMode, player.Color, message, ref cancel); } catch (Exception ex) { PointBlankLogging.LogError("Error in handling chat!", ex); } cancel = !cancel; incomingColor = color; }
public bool Load() { try { if (Enabled) { return(true); } PointBlankLogging.Log("Starting " + Name + "..."); Type _class = PluginAssembly.GetTypes().First(a => a.IsClass && typeof(PointBlankPlugin).IsAssignableFrom(a)); // Get the first plugin class PluginClass = Enviroment.runtimeObjects["Plugins"].AddCodeObject(_class) as PointBlankPlugin; // Instentate the plugin class Name = PluginClass.GetType().Name; // Change the name Version = PluginClass.Version; if (CheckUpdates()) { if (PluginConfiguration.NotifyUpdates) { Notify(); } if (PluginConfiguration.AutoUpdate) { Update(); } } LoadConfiguration(); // Load the configuration LoadTranslation(); // Load the translation PointBlankPluginEvents.RunPluginStart(PluginClass); // Run the start event PluginClass.Load(); // Run the load function PointBlankPluginEvents.RunPluginLoaded(PluginClass); // Run the loaded event Enabled = true; // Set the enabled to true t.Start(); // Start the thread return(true); } catch (Exception ex) { PointBlankLogging.LogError("Error starting plugin: " + Name, ex); Unload(); return(false); } }
public static void TryInvoke(this System.MulticastDelegate theDelegate, params object[] args) { if (theDelegate == null) { return; } foreach (Delegate handler in theDelegate.GetInvocationList()) { try { handler.DynamicInvoke(args); } catch (Exception ex) { PointBlankLogging.LogError("Error in MulticastDelegate " + handler.GetType().Name + "!", ex); } } }
/// <summary> /// Used to detour a specific function /// </summary> /// <param name="tClass">The class containing the method</param> /// <param name="method">The name of the method to replace</param> /// <param name="flags">The flags of the method to replace</param> public DetourAttribute(Type tClass, string method, BindingFlags flags, int index = 0) { // Set the variables Class = tClass; MethodName = method; Flags = flags; try { Method = Class.GetMethods(flags).Where(a => a.Name == method).ToArray()[index]; MethodFound = true; } catch (Exception ex) { PointBlankLogging.LogError("Method not found! " + MethodName + " in class " + Class.FullName, ex, false, false); MethodFound = false; } }
public static bool DetourFunction(IntPtr ptrOriginal, IntPtr ptrModified) { try { switch (IntPtr.Size) { case sizeof(Int32): unsafe { byte *ptrFrom = (byte *)ptrOriginal.ToPointer(); *(ptrFrom + 1) = 0xBB; *((uint *)(ptrFrom + 2)) = (uint)ptrModified.ToInt32(); *(ptrFrom + 11) = 0xFF; *(ptrFrom + 12) = 0xE3; } break; case sizeof(Int64): unsafe { byte *ptrFrom = (byte *)ptrOriginal.ToPointer(); *ptrFrom = 0x49; *(ptrFrom + 1) = 0xBB; *((ulong *)(ptrFrom + 2)) = (ulong)ptrModified.ToInt64(); *(ptrFrom + 10) = 0x41; *(ptrFrom + 11) = 0xFF; *(ptrFrom + 12) = 0xE3; } break; default: return(false); } return(true); } catch (Exception ex) { PointBlankLogging.LogError("Error adding detour!", ex); return(false); } }
} // Is PointBlank running #endregion #region Loader Functions public void Initialize() { if (!Environment.GetCommandLineArgs().Contains("-pointblank")) // Don't run if this isn't a server or if the -pointblank argument wasn't added { return; } if (Instance != null && Enabled) // Don't run if already running { return; } PointBlankLogging.LogImportant("Loading " + PointBlankInfo.Name + " v" + PointBlankInfo.Version + "..."); // Run required methods ApplyPatches(); // Setup the runtime objects Enviroment.runtimeObjects.Add("Framework", new RuntimeObject(new GameObject("Framework"))); Enviroment.runtimeObjects.Add("Extensions", new RuntimeObject(new GameObject("Extensions"))); Enviroment.runtimeObjects.Add("Services", new RuntimeObject(new GameObject("Services"))); Enviroment.runtimeObjects.Add("Plugins", new RuntimeObject(new GameObject("Plugins"))); // Add the code objects Enviroment.runtimeObjects["Framework"].AddCodeObject <InterfaceManager>(); // Both the service manager and interface manager are important without them Enviroment.runtimeObjects["Framework"].AddCodeObject <ServiceManager>(); // the modloader won't be able to function properly making it as usefull as Rocket // Run the inits Enviroment.runtimeObjects["Framework"].GetCodeObject <InterfaceManager>().Init(); Enviroment.runtimeObjects["Framework"].GetCodeObject <ServiceManager>().Init(); // Run required methods RunRequirements(); // Initialize Instance = this; Enabled = true; #if !DEBUG Console.Clear(); #endif PointBlankLogging.LogImportant("Loaded " + PointBlankInfo.Name + " v" + PointBlankInfo.Version + "!"); }
private void CheckUpdates() { while (Running) { Thread.Sleep(300000); // Check every 5 minutes if (WebsiteData.GetData(URL, out string data)) { JObject info = JObject.Parse(data); if ((string)info["PointBlank_Version"] == "0") // Ignore if no version { continue; } if ((string)info["PointBlank_Version"] != PointBlankInfo.Version) { PointBlankLogging.LogImportant("A new update is available for PointBlank!"); } } } }
/// <summary> /// Disconnects from the server /// </summary> /// <returns>Was the disconnect successful</returns> public bool Disconnect() { if (!Connected) { return(true); } try { Connection.Close(); // Close the connection Connected = false; // Set the connected return(true); } catch (Exception ex) { PointBlankLogging.LogError("Error while disconnecting from the SQL server " + Server, ex, false, false); return(false); } }