public WMIBMySQL() { string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml"; Core.RecoverFile(file); if (File.Exists(file)) { Syslog.WarningLog("There is a mysql dump file from previous run containing mysql rows that were never successfuly inserted, trying to recover them"); XmlDocument document = new XmlDocument(); using (TextReader sr = new StreamReader(file)) { document.Load(sr); using (XmlNodeReader reader = new XmlNodeReader(document.DocumentElement)) { XmlSerializer xs = new XmlSerializer(typeof(Unwritten)); Unwritten un = (Unwritten)xs.Deserialize(reader); lock (unwritten.PendingRows) { unwritten.PendingRows.AddRange(un.PendingRows); } } } } Thread reco = new Thread(Exec) { Name = "MySQL/Recovery" }; Core.ThreadManager.RegisterThread(reco); reco.Start(); }
public void InsertUser(XmlNode node) { string regex = null; string role = null; foreach (XmlAttribute info in node.Attributes) { switch (info.Name) { case "regex": regex = info.Value; break; case "role": role = info.Value; break; } } if (regex == null || role == null) { Syslog.WarningLog("Skipping invalid user record for " + this._Channel.Name); } lock (Users) { Users.Add(new SystemUser(role, regex)); } }
private void Exec() { while (this.IsActive && Core.IsRunning) { try { this.Disconnect(); this.Connect(); while (!this.IsWorking && !this.Protocol.IsDisconnected) { // we need to wait for the irc handler to connect to irc Thread.Sleep(100); } // now we can finally join all channels Join(); // then we just sleep while (this.Network.IsConnected) { Thread.Sleep(2000); } // in case we got disconnected, we log it and restart the procedure Syslog.WarningLog("Disconnected from irc network on " + Nick); Thread.Sleep(20000); } catch (ThreadAbortException) { Syslog.DebugLog("Terminated primary thread for instance " + Nick); return; } catch (IOException fail) { if (this.IsActive) { Syslog.ErrorLog("Failure of primary thread of instance " + Nick + " attempting to recover"); Core.HandleException(fail); } else { return; } } catch (Exception fail) { Core.HandleException(fail); if (this.IsActive) { Syslog.ErrorLog("Failure of primary thread of instance " + Nick + " attempting to recover"); } else { return; } Thread.Sleep(20000); } } Core.ThreadManager.UnregisterThread(Thread.CurrentThread); }
private void Exec() { try { Thread.Sleep(8000); if (unwritten.PendingRows.Count == 0 && File.Exists(Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml")) { File.Delete(Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml"); } while (Core.IsRunning) { if (unwritten.PendingRows.Count > 0) { int count; Syslog.WarningLog("Performing recovery of " + unwritten.PendingRows.Count + " MySQL rows"); Recovering = true; List <SerializedRow> rows = new List <SerializedRow>(); lock (unwritten.PendingRows) { count = unwritten.PendingRows.Count; rows.AddRange(unwritten.PendingRows); unwritten.PendingRows.Clear(); } int recovered = 0; foreach (SerializedRow row in rows) { if (InsertRow(row.table, row.row)) { recovered++; } else { Syslog.DebugLog("Failed to recover 1 row", 2); } } Syslog.WarningLog("Recovery finished, recovered " + recovered + " of total " + count); Recovering = false; FlushRows(); Thread.Sleep(200000); if (unwritten.PendingRows.Count == 0 && File.Exists(Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml")) { File.Delete(Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml"); } } Thread.Sleep(200); } } catch (Exception fail) { Core.HandleException(fail); Syslog.ErrorLog("Recovery thread for Mysql is down"); } }
/// <summary> /// Initializes a new instance of the <see cref="wmib.Channel"/> class. /// </summary> /// <param name='name'> /// Name. /// </param> public Channel(string name) { Name = name; Suppress = false; SystemUsers = new Security(this); LoadConfig(); if (DefaultInstance == "any") { PrimaryInstance = Instance.GetInstance(); // we need to save the instance so that next time bot reconnect to bouncer it uses the same instance DefaultInstance = PrimaryInstance.Nick; SaveConfig(); } else { if (!Instance.Instances.ContainsKey(DefaultInstance)) { Syslog.WarningLog("There is no instance " + DefaultInstance + " reassigning channel " + this.Name + " to a different instance"); this.PrimaryInstance = Instance.GetInstance(); Syslog.Log("Reassigned to " + this.PrimaryInstance.Nick); } else { PrimaryInstance = Instance.Instances[DefaultInstance]; } } if (!Directory.Exists(Configuration.WebPages.HtmlPath)) { Directory.CreateDirectory(Configuration.WebPages.HtmlPath); } foreach (Module module in ExtensionHandler.ExtensionList) { try { if (module.IsWorking) { Channel self = this; module.Hook_Channel(self); } } catch (Exception fail) { Syslog.Log("MODULE: exception at Hook_Channel in " + module.Name, true); Core.HandleException(fail); } } }
/// <summary> /// Load a binary module /// </summary> /// <param name="path"></param> /// <returns></returns> public static bool LoadAllModulesInLibrary(string path) { try { if (File.Exists(path)) { Assembly library = Assembly.LoadFrom(path); if (library == null) { Syslog.WarningLog("Unable to load " + path + " because the file can't be read"); return(false); } Type[] types = library.GetTypes(); foreach (Type type in types) { if (type.IsSubclassOf(typeof(Module))) { // For recall later _moduleTypes.Add(type); if (ShouldCreateModuleOnStartup(type)) { CreateModule(type); } else { Syslog.DebugLog("Not registering module (type " + type.Name + ") because it's not in a module list"); } } } return(true); } Syslog.Log("Unable to load " + path + " because the file can't be read", true); } catch (Exception fail) { Core.HandleException(fail); } return(false); }
private void HandleError(string statement, List <Database.Bind> bind_var = null) { if (Configuration.Postgres.Unwritten == null) { return; } string text = "/* Recovery backup of query that has failed at " + DateTime.Now.ToString() + " */\n"; text += statement; if (!statement.EndsWith(";")) { statement += ";"; } statement += "\n"; if (bind_var != null) { } Syslog.WarningLog("POSTGRESQL: Storing failed query into recovery file"); System.IO.File.AppendAllText(Configuration.Postgres.Unwritten, text); }
private void FlushRows() { if (Recovering) { return; } // prevent multiple threads calling this function at same time lock (this) { string file = Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "unwrittensql.xml"; if (File.Exists(file)) { Core.BackupData(file); if (!File.Exists(Configuration.TempName(file))) { Syslog.WarningLog("Unable to create backup file for " + file); return; } } try { File.Delete(file); XmlSerializer xs = new XmlSerializer(typeof(Unwritten)); StreamWriter writer = File.AppendText(file); lock (unwritten) { xs.Serialize(writer, unwritten); } writer.Close(); if (File.Exists(Configuration.TempName(file))) { File.Delete(Configuration.TempName(file)); } } catch (Exception fail) { Core.HandleException(fail); Syslog.WarningLog("Recovering the mysql unwritten dump because of exception to: " + file); Core.RecoverFile(file); } } }
private bool connectBnc() { this.Send("CONTROL: CREATE " + this.Server); this.ChannelsJoined = false; int retries = 0; bool Connected_ = false; while (!Connected_) { Thread.Sleep(2000); this.Send("CONTROL: STATUS"); string response = streamReader.ReadLine(); this.TrafficLog(response, true); if (response.StartsWith(":")) { // we received network data here lock (Backlog) Backlog.Add(response); continue; } if (response == "CONTROL: TRUE") { Syslog.Log("Bouncer connected to " + Server + " on: " + this.IRCNetwork.Nickname); return(true); } else { retries++; if (retries > 6) { Syslog.WarningLog("Bouncer failed to connect to the network within 10 seconds, disconnecting it: " + this.IRCNetwork.Nickname); this.Send("CONTROL: DISCONNECT"); return(false); } Syslog.Log("Still waiting for bouncer (trying " + retries.ToString() + "/6) on " + this.IRCNetwork.Nickname + " " + response); } } return(true); }
public static bool DumpAllModulesInLibrary(string path) { try { if (File.Exists(path)) { Assembly library = Assembly.LoadFrom(path); if (library == null) { Syslog.WarningLog("Unable to load " + path + " because the file can't be read"); return(false); } Type[] types = library.GetTypes(); string list = ""; foreach (Type type in types) { if (type.IsSubclassOf(typeof(Module))) { list += type.Name + ","; } } list = list.TrimEnd(','); if (list == "") { list = "No modules found in this file"; } Console.WriteLine("In " + path + ": " + list); return(true); } Syslog.Log("Unable to load " + path + " because the file can't be read", true); } catch (Exception fail) { Core.HandleException(fail); } return(false); }
public static void RegisterAlias(string name, string target, string module = null) { lock (aliases) { if (aliases.ContainsKey(name)) { throw new WmibException("This alias is already registered: " + name); } if (module != null) { Syslog.DebugLog("Module " + module + " registered alias " + name + " for command " + target); } else { Syslog.DebugLog("Registered alias " + name + " for command " + target); } if (!commands.ContainsKey(target)) { Syslog.WarningLog("Alias " + name + " points to command " + target + " which doesn't exist"); } aliases.Add(name, target); } }
/// <summary> /// Load all roles /// </summary> public static void Init() { Core.RecoverFile(Configuration.Paths.Security); if (File.Exists(Configuration.Paths.Security)) { DumpableDict dict = new DumpableDict(); XmlSerializer xmlSerializer = new XmlSerializer(dict.GetType()); using (StreamReader reader = new StreamReader(Variables.ConfigurationDirectory + Path.DirectorySeparatorChar + "security.xml")) { dict = (DumpableDict)xmlSerializer.Deserialize(reader); } // first we need to create all roles in the file, that is important foreach (DumpableDict.RoleInfo ri in dict.Roles) { Roles.Add(ri.Name, new Role(ri.Level)); } foreach (DumpableDict.RoleInfo ri in dict.Roles) { // now give this role all permissions and roles it had foreach (string permission in ri.Permissions) { Roles[ri.Name].Grant(permission); } foreach (string role in ri.Roles) { if (!Roles.ContainsKey(role)) { Syslog.WarningLog("There is no role " + role + " that could be granted to " + ri.Name + " skipping it"); } Roles[ri.Name].Grant(Roles[role]); } } return; } // let's assume there is no role definition file, so we create some initial, built-in roles Roles.Add("null", new Role(0)); Roles.Add("trusted", new Role(100)); Roles.Add("operator", new Role(1000)); Roles.Add("admin", new Role(20000)); Roles.Add("root", new Role(65535)); Roles["trusted"].Grant("trust"); // trusted users can add users to trust list Roles["trusted"].Grant("trustadd"); Roles["trusted"].Grant("trustdel"); Roles["operator"].Grant(Roles["trusted"]); Roles["operator"].Grant("join"); Roles["admin"].Grant("admin"); Roles["admin"].Grant("drop"); Roles["admin"].Grant("suppress"); Roles["admin"].Grant("unsuppress"); Roles["admin"].Grant("part"); Roles["admin"].Grant(Roles["operator"]); // admins have all privileges as trusted users Roles["admin"].Grant(Roles["trusted"]); Roles["root"].Grant("root"); foreach (Module module in ExtensionHandler.ExtensionList) { try { module.RegisterPermissions(); } catch (Exception fail) { Core.HandleException(fail, module.Name); } } }
/// <summary> /// Save config /// </summary> public void SaveConfig() { string fn = GetConfigFilePath(); try { XmlDocument data = new XmlDocument(); XmlNode xmlnode = data.CreateElement("channel"); InsertData("talkmode", Suppress.ToString(), ref data, ref xmlnode); InsertData("langcode", Language, ref data, ref xmlnode); InsertData("respond_message", RespondMessage.ToString(), ref data, ref xmlnode); InsertData("ignore-unknown", IgnoreUnknown.ToString(), ref data, ref xmlnode); InsertData("suppress-warnings", SuppressWarnings.ToString(), ref data, ref xmlnode); InsertData("respond_wait", RespondWait.ToString(), ref data, ref xmlnode); InsertData("sharedinfo", SharedDB, ref data, ref xmlnode); if (!String.IsNullOrEmpty(this.Password)) { InsertData("password", Password, ref data, ref xmlnode); } InsertData("defaultbot", DefaultInstance, ref data, ref xmlnode); if (!(SharedLinkedChan.Count < 1)) { foreach (Channel current in SharedLinkedChan) { InsertData("name", current.Name, ref data, ref xmlnode, "sharedch"); } } if (!(Infobot_IgnoredNames.Count < 1)) { foreach (string curr in Infobot_IgnoredNames) { InsertData("name", curr, ref data, ref xmlnode, "ignored"); } } if (ExtensionData.Count > 0) { foreach (KeyValuePair <string, string> item in ExtensionData) { InsertData(item.Key, item.Value, ref data, ref xmlnode, "extension"); } } lock (this.SystemUsers.Users) { foreach (SystemUser user in this.SystemUsers.Users) { XmlAttribute name = data.CreateAttribute("regex"); name.Value = user.Name; XmlAttribute kk = data.CreateAttribute("role"); kk.Value = user.Role; XmlNode db = data.CreateElement("user"); db.Attributes.Append(name); db.Attributes.Append(kk); xmlnode.AppendChild(db); } } if (File.Exists(fn)) { Core.BackupData(fn); if (!File.Exists(Configuration.TempName(fn))) { Syslog.WarningLog("Unable to create backup file for " + Name); } } data.AppendChild(xmlnode); data.Save(fn); if (File.Exists(Configuration.TempName(fn))) { File.Delete(Configuration.TempName(fn)); } } catch (Exception) { Core.RecoverFile(fn, Name); } }