You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

426 lines
16 KiB
C#

1 month ago
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
{
/// <summary>
/// 许可信息类
/// </summary>
public class LicenseInfo
{
/// <summary>
/// 产品列表
/// </summary>
public string Products { get; set; }
/// <summary>
/// 版本号
/// </summary>
public string Version { get; set; }
/// <summary>
/// 工作单位
/// </summary>
public string Company { get; set; }
/// <summary>
/// 部门
/// </summary>
public string Department { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 联系方式
/// </summary>
public string Contact { get; set; }
/// <summary>
/// 机器序列号
/// </summary>
public string MachineInfo { get; set; }
/// <summary>
/// 要写出的许可文件
/// </summary>
public string LicenseFile { get; set; }
/// <summary>
/// 起始日期
/// </summary>
public DateTime StartDate { get; set; }
/// <summary>
/// 失效日期
/// </summary>
public DateTime ExpireDate { get; set; }
/// <summary>
/// 是否限制日期
/// </summary>
public bool LimitDate { get; set; }
/// <summary>
/// 是否不限制设备
/// </summary>
public bool UnlimitMachine { get; set; }
/// <summary>
/// 是否网络许可
/// </summary>
public bool IsNetServer { get; set; } = false;
/// <summary>
/// 客户端数量
/// </summary>
public int ClientCount { get; set; }
}
public class Security
{
private LicenseServerConnection serverConnection;
private Form parentForm;
private bool serverSuccess = false;
1 month ago
private static LicenseInfo curentLicenseInfo = null;
public LicenseServerConnection.LicenseInvalidateEventHandler LicenseInvalidateEvent;
1 month ago
public static LicenseInfo CurentLicenseInfo
{
get
{
1 month ago
if (curentLicenseInfo == null)
1 month ago
{
1 month ago
string strBaseDir = AppDomain.CurrentDomain.BaseDirectory;
string strLicFile = System.IO.Path.Combine(strBaseDir, "Constrction.lic");
1 month ago
1 month ago
long pData = 0;
int dataLength = 0;
bool success = GetLicenseInfo(strLicFile, ref pData, ref dataLength);
if (success == false)
1 month ago
{
1 month ago
return null;
1 month ago
}
1 month ago
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))
1 month ago
{
1 month ago
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))
1 month ago
{
1 month ago
curentLicenseInfo.StartDate = dateStart;
1 month ago
}
1 month ago
line = sr.ReadLine();
if (DateTime.TryParse(line, out DateTime dateEnd))
1 month ago
{
1 month ago
curentLicenseInfo.ExpireDate = dateEnd;
1 month ago
}
1 month ago
line = sr.ReadLine();
if (int.TryParse(line, out int limitDate))
1 month ago
{
1 month ago
if (limitDate == 1)
{
curentLicenseInfo.LimitDate = true;
}
else
{
curentLicenseInfo.LimitDate = false;
}
1 month ago
}
1 month ago
line = sr.ReadLine();
if (int.TryParse(line, out int unLimitMachine))
1 month ago
{
1 month ago
if (unLimitMachine == 1)
{
curentLicenseInfo.UnlimitMachine = true;
}
else
{
curentLicenseInfo.UnlimitMachine = false;
}
1 month ago
}
1 month ago
line = sr.ReadLine();
if (line != null)
1 month ago
{
1 month ago
if (line.Equals("1"))
{
curentLicenseInfo.IsNetServer = true;
}
else
{
curentLicenseInfo.IsNetServer = false;
}
1 month ago
}
}
}
1 month ago
return curentLicenseInfo;
1 month ago
}
}
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<string>("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)
{
1 month ago
LicenseInvalidateEvent?.Invoke(status, message);
1 month ago
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;
1 month ago
await resetServerConfig(message, config);
1 month ago
}
}
else
{
serverSuccess = true;
}
}
1 month ago
//
// 摘要:
// 显示许可服务器配置
//
// 返回结果:
// 异步任务
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));
}
}
1 month ago
/// <summary>
/// 重新设置许可服务器.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="config">The config.</param>
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<string>("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<System.Diagnostics.EventLogEntry>()
// //.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);
}
}