using GeoSigma.SigmaDrawerUtil; using System; using System.Collections.Generic; using System.Diagnostics.Eventing.Reader; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace GeoSigmaDrawLib { /// /// 许可信息类 /// public class LicenseInfo { /// /// 产品列表 /// public string Products { get; set; } /// /// 版本号 /// public string Version { get; set; } /// /// 工作单位 /// public string Company { get; set; } /// /// 部门 /// public string Department { get; set; } /// /// 用户名 /// public string UserName { get; set; } /// /// 联系方式 /// public string Contact { get; set; } /// /// 机器序列号 /// public string MachineInfo { get; set; } /// /// 要写出的许可文件 /// public string LicenseFile { get; set; } /// /// 起始日期 /// public DateTime StartDate { get; set; } /// /// 失效日期 /// public DateTime ExpireDate { get; set; } /// /// 是否限制日期 /// public bool LimitDate { get; set; } /// /// 是否不限制设备 /// public bool UnlimitMachine { get; set; } /// /// 是否网络许可 /// public bool IsNetServer { get; set; } = false; /// /// 客户端数量 /// public int ClientCount { get; set; } } public class Security { private LicenseServerConnection serverConnection; private Form parentForm; private bool serverSuccess = false; private static LicenseInfo curentLicenseInfo = null; public LicenseServerConnection.LicenseInvalidateEventHandler LicenseInvalidateEvent; public static LicenseInfo CurentLicenseInfo { get { if (curentLicenseInfo == null) { string strBaseDir = AppDomain.CurrentDomain.BaseDirectory; string strLicFile = System.IO.Path.Combine(strBaseDir, "Constrction.lic"); long pData = 0; int dataLength = 0; bool success = GetLicenseInfo(strLicFile, ref pData, ref dataLength); if (success == false) { return null; } byte[] btData = new byte[dataLength]; Marshal.Copy((IntPtr)pData, btData, 0, dataLength); string strData = System.Text.Encoding.Default.GetString(btData); //GeoSigmaLib.PointerArrayDelete((IntPtr)pData); Marshal.FreeCoTaskMem((IntPtr)pData); curentLicenseInfo = new LicenseInfo(); using (StringReader sr = new StringReader(strData)) { string line = sr.ReadLine(); curentLicenseInfo.Products = line; line = sr.ReadLine(); curentLicenseInfo.Version = line; line = sr.ReadLine(); curentLicenseInfo.Company = line; line = sr.ReadLine(); curentLicenseInfo.Department = line; line = sr.ReadLine(); curentLicenseInfo.UserName = line; line = sr.ReadLine(); curentLicenseInfo.Contact = line; line = sr.ReadLine(); curentLicenseInfo.MachineInfo = line; line = sr.ReadLine(); if (DateTime.TryParse(line, out DateTime dateStart)) { curentLicenseInfo.StartDate = dateStart; } line = sr.ReadLine(); if (DateTime.TryParse(line, out DateTime dateEnd)) { curentLicenseInfo.ExpireDate = dateEnd; } line = sr.ReadLine(); if (int.TryParse(line, out int limitDate)) { if (limitDate == 1) { curentLicenseInfo.LimitDate = true; } else { curentLicenseInfo.LimitDate = false; } } line = sr.ReadLine(); if (int.TryParse(line, out int unLimitMachine)) { if (unLimitMachine == 1) { curentLicenseInfo.UnlimitMachine = true; } else { curentLicenseInfo.UnlimitMachine = false; } } line = sr.ReadLine(); if (line != null) { if (line.Equals("1")) { curentLicenseInfo.IsNetServer = true; } else { curentLicenseInfo.IsNetServer = false; } } } } return curentLicenseInfo; } } public void CheckLicense(Form parent) { this.parentForm = parent; LicenseInfo license = Security.CurentLicenseInfo; if (license.IsNetServer == false) { int err = GeoSigmaDrawLib.Security.MachineValidate(); if (err > 0) { if (err == 1) { MessageBox.Show("运行错误(E001),请联系服务人员!"); } else if (err == 2) { MessageBox.Show("运行错误(E002),系统时间有问题!\r\n检测到系统时间被非正常修改!", "软件保护"); } Application.Exit(); return; } } else { // 网络许可 DrawerConfig config = DrawerConfig.Instance; string strRootUrl = config.FindConfigValue("LicenseServer", "RootUrl", "http://127.0.0.1:9527"); serverConnection = new LicenseServerConnection(); serverConnection.StartOrUpdateTask(strRootUrl, TimeSpan.FromSeconds(20)); serverConnection.LicenseInvalidateEvent += serverConfigSync; } } public void CloseLicense() { if (CurentLicenseInfo.IsNetServer == true) { serverConnection.LicenseInvalidateEvent -= serverConfigSync; serverConnection?.StopTask(); if (serverSuccess) { try { serverConnection?.SendOfflineAsync().GetAwaiter().GetResult(); } catch { } } } } private async void serverConfigSync(int status, string message) { LicenseInvalidateEvent?.Invoke(status, message); if (status != 1) { serverSuccess = false; if (this.parentForm !=null && this.parentForm.InvokeRequired) { this.parentForm.Invoke(new Action(async () => { DrawerConfig config = DrawerConfig.Instance; await resetServerConfig(message, config); })); } else { DrawerConfig config = DrawerConfig.Instance; await resetServerConfig(message, config); } } else { serverSuccess = true; } } // // 摘要: // 显示许可服务器配置 // // 返回结果: // 异步任务 public async Task ShowServerConfig() { if (!CurentLicenseInfo.IsNetServer) { return; } serverConnection.StopTask(); FrmLicenseServerConfig frmLicenseServer = new FrmLicenseServerConfig(); if (parentForm == null) { frmLicenseServer.StartPosition = FormStartPosition.CenterScreen; } else { frmLicenseServer.StartPosition = FormStartPosition.CenterParent; } DrawerConfig config = DrawerConfig.Instance; frmLicenseServer.Url = config.FindConfigValue("LicenseServer", "RootUrl", "http://127.0.0.1:9527"); frmLicenseServer.Message = "当前服务器地址:" + frmLicenseServer.Url; if (frmLicenseServer.ShowDialog(parentForm) == DialogResult.OK) { serverConnection.UrlRootPath = frmLicenseServer.Url; if (!config.SetConfigValue("LicenseServer", "RootUrl", frmLicenseServer.Url)) { ConfigNode node = new ConfigNode("LicenseServer", "许可服务", display: false); node.AddItem(new CustomProperty("RootUrl", null, "服务器地址", frmLicenseServer.Url, typeof(string))); config.AddNode(node); } config.Save(); serverConnection.StartOrUpdateTask(serverConnection.UrlRootPath, TimeSpan.FromSeconds(20.0)); } else { try { await Task.Delay(new TimeSpan(0, 1, 0)); } catch (TaskCanceledException) { } serverConnection.StartOrUpdateTask(serverConnection.UrlRootPath, TimeSpan.FromSeconds(20.0)); } } /// /// 重新设置许可服务器. /// /// The message. /// The config. private async Task resetServerConfig(string message, DrawerConfig config) { serverConnection.StopTask(); FrmLicenseServerConfig frmLicenseServer = new FrmLicenseServerConfig(); if (this.parentForm == null) { frmLicenseServer.StartPosition = FormStartPosition.CenterScreen; } else { frmLicenseServer.StartPosition = FormStartPosition.CenterParent; } frmLicenseServer.Message = message; frmLicenseServer.Url = config.FindConfigValue("LicenseServer", "RootUrl", "http://127.0.0.1:9527"); if (frmLicenseServer.ShowDialog(this.parentForm) == DialogResult.OK) { serverConnection.UrlRootPath = frmLicenseServer.Url; if (config.SetConfigValue("LicenseServer", "RootUrl", frmLicenseServer.Url) == false) { ConfigNode node = new ConfigNode("LicenseServer", "许可服务", false); node.AddItem(new CustomProperty("RootUrl", null, "服务器地址", frmLicenseServer.Url, typeof(string))); config.AddNode(node); } config.Save(); serverConnection.StartOrUpdateTask(serverConnection.UrlRootPath, TimeSpan.FromSeconds(20)); } else { try { // 使用 Task.Delay 代替 Timer 的 period,它能被安全地取消。 await Task.Delay(new TimeSpan(0, 1, 0)); } catch (TaskCanceledException) { // 等待期间任务被取消,正常退出 } serverConnection.StartOrUpdateTask(serverConnection.UrlRootPath, TimeSpan.FromSeconds(20)); } } public static int MachineValidate() { string strBaseDir = AppDomain.CurrentDomain.BaseDirectory; string strLicFile = System.IO.Path.Combine(strBaseDir, "Constrction.lic"); bool bValidate = MachineValidate(strLicFile); if (bValidate == false) { return 1; } // 查询系统日志 try { if (LogValidate() == false) { return 2; } } catch { return 2; } return 0; } private static bool LogValidate() { DateTime dateNow = DateTime.Now; System.Diagnostics.EventLog[] logs = System.Diagnostics.EventLog.GetEventLogs(); foreach (System.Diagnostics.EventLog log in logs) { string strQuery = string.Format("*[System[TimeCreated[@SystemTime > '{0}']]]", dateNow.ToUniversalTime().AddMinutes(1).ToString("o")); //strQuery = "*[System[TimeCreated[@SystemTime > '2022-02-12T06:31:37.6336111Z']]]"; var elQuery = new EventLogQuery(log.Log, PathType.LogName, strQuery); EventLogReader elReader = null; try { elReader = new EventLogReader(elQuery); } catch (Exception ex) { LoggerUtil.Logger.Error(log.Log+":"+ ex.Message); continue; } EventRecord record = elReader.ReadEvent(); if (record != null) { LoggerUtil.Logger.Error(record.ToXml()); return false; } //var entrysCount = log.Entries.Cast() // //.Select(entry => new { entry.TimeGenerated, entry.TimeWritten }) // .Where(entry => entry.TimeGenerated > dateNow || entry.TimeWritten > dateNow) // .Take(300) // .Count(); //if (entrysCount>0) //{ // return false; //} } return true; } #if DEBUG const string SIGMALIB = "MachineInterface.dll"; #else const string SIGMALIB = "MachineInterface.dll"; #endif [DllImport(SIGMALIB, EntryPoint = "MachineValidate", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)] public static extern bool MachineValidate(string licFile); [DllImport(SIGMALIB, EntryPoint = "GetLicenseInfo", ExactSpelling = false, CallingConvention = CallingConvention.Cdecl)] public static extern bool GetLicenseInfo(string licFile, ref Int64 bufferElement, ref int buffLengt); } }