public static void StopSPServer(out SqlInt32 res) { res = 0; using (SqlConnection conn = new SqlConnection("context connection=true")) { try { conn.Open(); lock (m_cs) { if (Plugin != null) { if (ServerCoreLoader.IsRunning()) { ServerCoreLoader.SetOnIdle(null); Plugin.StopSocketProServer(); res += 1; } Plugin.Dispose(); Plugin = null; res += 1; } } } catch (Exception err) { UConfig.LogMsg(err.Message, "USqlStream::StopSPServer", 57); //line 57 } finally { conn.Close(); } } }
// Load Json Configuration static UConfig LoadConfig(string fileName) { using (StreamReader r = new StreamReader(fileName)) { string json = r.ReadToEnd(); UConfig uconfig = JsonConvert.DeserializeObject <UConfig>(json); return(uconfig); } }
public static void UpdateConfigFile(UConfig config) { try { string json = config.ToJson(); File.WriteAllText(DEFAULT_WORKING_DIRECTORY + STREAM_DB_CONFIG_FILE, json); } catch (Exception ex) { LogMsg(ex.Message, "UConfig::UpdateConfigFile", 142); //line 142 } }
protected override bool OnIsPermitted(ulong hSocket, string userId, string password, uint nSvsID) { string driver = "DRIVER=" + m_Config.odbc_driver + ";Server=(local)"; if (m_Config.default_db != null && m_Config.default_db.Length > 0) { driver += (";database=" + m_Config.default_db); } int res = DoSPluginAuthentication(hSocket, userId, password, nSvsID, driver); if (res <= 0) { string message = "Authentication failed for user " + userId + ", res: " + res; UConfig.LogMsg(message, "CSqlPlugin::OnIsPermitted", 65); //line 65 } return(res > 0); }
public void CopyFrom(UConfig config) { port = config.port; main_threads = config.main_threads; disable_ipv6 = config.disable_ipv6; cert_root_store = config.cert_root_store; cert_subject_cn = config.cert_subject_cn; services = config.services; services_config = config.services_config; odbc_driver = config.odbc_driver; default_db = config.default_db; version = config.version; odbc_plugin_version = config.odbc_plugin_version; sp_server_core_version = config.sp_server_core_version; service_id = config.service_id; manual_batching = config.manual_batching; }
public override bool Run(uint port, uint maxBacklog, bool v6Supported) { IntPtr p = CSocketProServer.DllManager.AddALibrary("sodbc"); if (p.ToInt64() == 0) { UConfig.LogMsg("Cannot load SocketPro ODBC plugin!", "CSqlPlugin::Run", 38); //line 38 UConfig.UpdateLog(); return(false); } ConfigServices(); PushManager.AddAChatGroup(SocketProAdapter.UDB.DB_CONSTS.STREAMING_SQL_CHAT_GROUP_ID, "Subscribe/publish for MS SQL SERVER Table events, DELETE, INSERT and UPDATE"); bool ok = base.Run(port, maxBacklog, v6Supported); if (!ok) { string errMsg = string.Format("Starting listening socket failed (errCode={0}; errMsg={1})", CSocketProServer.LastSocketError, CSocketProServer.ErrorMessage); UConfig.LogMsg(errMsg, "CSqlPlugin::Run", 48); //line 48 UConfig.UpdateLog(); } return(ok); }
public static void StartSPServer(out SqlInt32 res) { res = 0; using (SqlConnection conn = new SqlConnection("context connection=true")) { try { lock (m_cs) { UConfig config; try { if (!Directory.Exists(UConfig.DEFAULT_WORKING_DIRECTORY)) { Directory.CreateDirectory(UConfig.DEFAULT_WORKING_DIRECTORY); } Directory.SetCurrentDirectory(UConfig.DEFAULT_WORKING_DIRECTORY); } catch (Exception ex) { UConfig.LogMsg(ex.Message, "USqlStream::StartSPServer", 85); //line 85 } finally { } try { string json = System.IO.File.ReadAllText(UConfig.DEFAULT_WORKING_DIRECTORY + UConfig.STREAM_DB_CONFIG_FILE); config = new UConfig(json); } catch (Exception ex) { UConfig.LogMsg(ex.Message, "USqlStream::StartSPServer", 96); //line 96 config = new UConfig(); UConfig.UpdateConfigFile(config); UConfig.UpdateLog(); } if (Plugin == null) { Plugin = new CSqlPlugin(config); } res = 1; if (!ServerCoreLoader.IsRunning()) { if (config.cert_root_store.Length > 0 && config.cert_subject_cn.Length > 0) { Plugin.UseSSL(config.cert_root_store, config.cert_subject_cn, ""); } if (Plugin.Run(config.port, 16, !config.disable_ipv6)) { res += 1; } else { res = 0; } } } } catch (Exception err) { UConfig.LogMsg(err.Message, "USqlStream::StartSPServer", 125); //line 125 Plugin = null; } finally { if (res == 2 && ServerCoreLoader.IsRunning()) { AppDomain.CurrentDomain.DomainUnload += (sender, args) => { ServerCoreLoader.StopSocketProServer(); Plugin = null; }; } conn.Close(); } } }
public static void PublishDMLEvent() { SqlTriggerContext tc = SqlContext.TriggerContext; if (!SqlContext.IsAvailable || tc == null) { return; } string errMsg = ""; using (SqlConnection conn = new SqlConnection("context connection=true")) { try { DataTable dt = null; List <object[]> rows = null; string[] v = null; lock (m_cs) { if (ServerCoreLoader.IsRunning()) { conn.Open(); v = GetUSqlServerKeys(conn); switch (tc.TriggerAction) { case TriggerAction.Update: rows = GetUpdateRows(conn, out dt); if (dt == null) { errMsg = "DELETED schema table not available"; } break; case TriggerAction.Delete: rows = GetRows(conn, true, out dt); if (dt == null) { errMsg = "DELETED schema table not available"; } break; case TriggerAction.Insert: rows = GetRows(conn, false, out dt); if (dt == null) { errMsg = "INSERTED schema table not available"; } break; default: errMsg = "Unknown DML event"; break; } } do { if (dt == null) { break; } if (ServerHost == null || ServerHost.Length == 0) { ServerHost = GetServerName(conn); } if (ServerHost == null || ServerHost.Length == 0) { errMsg = "Server not available"; break; } string tblName = GuessTablePath(conn, dt); if (tblName == null || tblName.Length == 0) { errMsg = "Table name not available"; break; } lock (m_cs) { foreach (object[] msg in rows) { msg[1] = ServerHost; msg[2] = v[0]; msg[3] = v[1]; msg[4] = tblName; if (!Publish(msg, DB_CONSTS.STREAMING_SQL_CHAT_GROUP_ID)) { errMsg = "Message publishing failed"; break; } } } } while (false); } } catch (Exception err) { errMsg = err.Message; } finally { conn.Close(); if (errMsg.Length > 0) { UConfig.LogMsg(errMsg, "USqkStream::PublishDMEvent", 470); //line 470 } } } }
private void ConfigServices() { bool changed = false; string odbc_plugin_version = Marshal.PtrToStringAnsi(GetSPluginVersion()); if (m_Config.odbc_plugin_version != odbc_plugin_version) { m_Config.odbc_plugin_version = odbc_plugin_version; changed = true; } string server_core_version = Version; if (m_Config.sp_server_core_version != server_core_version) { m_Config.sp_server_core_version = server_core_version; changed = true; } ODBCConfig oconfig = new ODBCConfig(); oconfig.manual_batching = m_Config.manual_batching; string json = oconfig.ToJson(); bool ok = SetSPluginGlobalOptions(json); string[] vService = m_Config.services.Split(';'); List <string> vP = new List <string>(); foreach (string s in vService) { string p_name = s.Trim(); if (p_name.Length == 0) { continue; } if (p_name.Equals("sodbc", StringComparison.OrdinalIgnoreCase) || p_name.Equals("sodbc.dll", StringComparison.OrdinalIgnoreCase)) { continue; //cannot load odbc plugin again } do { IntPtr h = DllManager.AddALibrary(p_name); if (h.ToInt64() == 0) { string message = "Not able to load server plugin " + p_name; UConfig.LogMsg(message, "CSqlPlugin::ConfigServices", 117); //line 117 break; } vP.Add(p_name); bool having = m_Config.services_config.ContainsKey(p_name); if (!having) { changed = true; } IntPtr addr = GetProcAddress(h, "GetSPluginGlobalOptions"); if (addr.ToInt64() != 0) { try { DGetSPluginGlobalOptions GetSPluginGlobalOptions = (DGetSPluginGlobalOptions)Marshal.GetDelegateForFunctionPointer(addr, typeof(DGetSPluginGlobalOptions)); byte[] bytes = new byte[65536]; uint res = GetSPluginGlobalOptions(bytes, bytes.Length); string jsonutf8 = System.Text.Encoding.UTF8.GetString(bytes, 0, (int)res); Dictionary <string, object> v = jsonutf8.FromJson <Dictionary <string, object> >(); if (m_Config.services_config.ContainsKey(p_name)) { Dictionary <string, object> old = m_Config.services_config[p_name]; if (old.ContainsKey("version")) { v["version"] = old["version"]; } m_Config.services_config[p_name] = v; } else { m_Config.services_config.Add(p_name, v); } } catch (Exception ex) { UConfig.LogMsg(ex.Message, "CSqlPlugin::ConfigServices/GetSPluginGlobalOptions", 152); //line 152 m_Config.services_config.Add(p_name, new Dictionary <string, object>()); } } else { m_Config.services_config.Add(p_name, new Dictionary <string, object>()); } Dictionary <string, object> jsonDic = m_Config.services_config[p_name]; if (having && jsonDic.Count > 0) { addr = GetProcAddress(h, "SetSPluginGlobalOptions"); if (addr.ToInt64() != 0) { try { DSetSPluginGlobalOptions func = (DSetSPluginGlobalOptions)Marshal.GetDelegateForFunctionPointer(addr, typeof(DSetSPluginGlobalOptions)); if (!func(jsonDic.ToJson(false))) { UConfig.LogMsg("Not able to set global options for plugin " + p_name, "CSqlPlugin::ConfigServices", 171); //line 171 } } catch (Exception ex) { UConfig.LogMsg(ex.Message, "CSqlPlugin::ConfigServices/SetSPluginGlobalOptions", 176); //line 176 } } } //DGetSPluginVersion addr = GetProcAddress(h, "GetSPluginVersion"); if (addr.ToInt64() != 0) { try { DGetSPluginVersion func = (DGetSPluginVersion)Marshal.GetDelegateForFunctionPointer(addr, typeof(DGetSPluginVersion)); string v = Marshal.PtrToStringAnsi(func()); string vOld = null; if (jsonDic.ContainsKey("version") && jsonDic["version"] is string) { vOld = (string)jsonDic["version"]; } if (v != null && (vOld == null || v != vOld)) { jsonDic["version"] = v; changed = true; } } catch (Exception ex) { UConfig.LogMsg(ex.Message, "CSqlPlugin::ConfigServices/GetSPluginVersion", 201); //line 201 } } } while (false); } if (vP.Count != vService.Length) { string str = ""; foreach (string item in vP) { if (str.Length > 0) { str += ";"; } str += item; } m_Config.services = str; changed = true; } List <string> unused = new List <string>(); foreach (var entry in m_Config.services_config) { if (!vP.Contains(entry.Key)) { unused.Add(entry.Key); } } foreach (string key in unused) { m_Config.services_config.Remove(key); changed = true; } if (changed) { UConfig.UpdateConfigFile(m_Config); } }
protected override void OnIdle(ulong milliseconds) { UConfig.UpdateLog(); }
public CSqlPlugin(UConfig config) : base(config.main_threads) { m_Config.CopyFrom(config); }
public void LoadConfig(string filePath) { UConfig.LoadConfigFromFile(filePath); ReParseCode(); }
public UConfig(string json) { bool changed = false; try { UConfig config = json.FromJson <UConfig>(); CopyFrom(config); if (version != MY_VERSION) { version = MY_VERSION; changed = true; } if (service_id != SocketProAdapter.BaseServiceID.sidODBC) { service_id = SocketProAdapter.BaseServiceID.sidODBC; changed = true; } if (main_threads <= 0) { main_threads = DEFAULT_MAIN_THREADS; changed = true; } if (port == 0 || port > 0xffff) { port = UConfig.DEFAULT_PORT; changed = true; } string str = odbc_driver.Trim(); if (odbc_driver != str || str.Length == 0) { odbc_driver = UConfig.DEFAULT_DRIVER; changed = true; } str = default_db.Trim(); if (str != default_db) { default_db = str; changed = true; } str = services.Trim(); if (str != services) { services = str; changed = true; } str = cert_root_store.Trim(); if (str != cert_root_store) { cert_root_store = str; changed = true; } str = cert_subject_cn.Trim(); if (str != cert_subject_cn) { cert_subject_cn = str; changed = true; } } catch (Exception ex) { LogMsg(ex.Message, "UConfig::UConfig(string json)", 103); //line 103 changed = true; } finally { if (changed) { UpdateConfigFile(this); UpdateLog(); } } }
// Entrance static void Main(string[] args) { if (args.Length == 0) { return; } else { // Encoding Registration Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Get Binary Path string binaryPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); // Parse User Configuration UConfig uconfig = LoadConfig(Path.Combine(binaryPath, "config.json")); // Get File URL string URL = args[0]; // Parse Username and Password Match m = Regex.Match(URL, @"^ftp://(?<fore>(?<username>.*?)?(?:\:(?<password>.*?)?)?@)?(?<back>(?<domain>.+?)(?:/|$).*$)"); if (m.Success) { string username = m.Groups["username"].Value; string domain = m.Groups["domain"].Value; string back = m.Groups["back"].Value; foreach (ServerItem server in uconfig.servers) { // Reconstruct URL if (Uri.UnescapeDataString(username) == server.username && Uri.UnescapeDataString(domain) == server.address) { if (server.username == "") { URL = string.Format(@"ftp://{0}", back); } else if (server.password == "") { URL = string.Format(@"ftp://{0}@{1}", username, back); } else { URL = string.Format(@"ftp://{0}:{1}@{2}", username, Uri.EscapeDataString(server.password), back); } break; } } // Get File Name Extension string ext = Regex.Replace(Path.GetExtension(URL), @"^\.([^\?]+)", "$1"); // Filter and Execute foreach (AppItem item in uconfig.apps) { if (item.extList.Any(s => s.Equals(ext, StringComparison.OrdinalIgnoreCase))) { // Decode URL URL = DecodeURL(item, URL); // Append Query String URL += "?" + item.queryString; // Execute ExecuteApplication(item.programPath, string.Join(URL, item.command)); // Return after Execution return; } } } // Fallback Execution URL = DecodeURL(uconfig.fallback, URL); URL = Uri.EscapeUriString(URL); ExecuteApplication(uconfig.fallback.programPath, string.Join(URL, uconfig.fallback.command)); return; } }