Compare commits
10
Commits
13fcedcae5
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8aa295779c | ||
|
|
c3f574d5cf | ||
|
|
9c767ec551 | ||
|
|
c6676266af | ||
|
|
92f9e76536 | ||
|
|
fc50d39309 | ||
|
|
b37e5d7a14 | ||
|
|
776a42f510 | ||
|
|
372080590c | ||
|
|
34b7771efb |
No files matched your search
@@ -0,0 +1,79 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.IO.Compression;
|
||||||
|
using System.Runtime.Intrinsics.X86;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace ForwardingServerUI.Class
|
||||||
|
{
|
||||||
|
public class AES
|
||||||
|
{
|
||||||
|
public static string AesEncipher(string Key, string dat) //加密
|
||||||
|
{
|
||||||
|
//压缩
|
||||||
|
byte[] plainBytes = Compress( Encoding.UTF8.GetBytes(dat));
|
||||||
|
|
||||||
|
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||||||
|
using var aes = System.Security.Cryptography.Aes.Create();
|
||||||
|
|
||||||
|
aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Key));
|
||||||
|
aes.Mode = CipherMode.CBC;
|
||||||
|
aes.Padding = PaddingMode.PKCS7;
|
||||||
|
aes.GenerateIV(); // 生成随机 IV
|
||||||
|
|
||||||
|
using var enc = aes.CreateEncryptor();
|
||||||
|
byte[] cipherBytes = enc.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
|
||||||
|
|
||||||
|
//将 IV (16字节) 和 密文 拼接成一个完整的字节数组
|
||||||
|
byte[] combinedBytes = new byte[aes.IV.Length + cipherBytes.Length];
|
||||||
|
Buffer.BlockCopy(aes.IV, 0, combinedBytes, 0, aes.IV.Length);
|
||||||
|
Buffer.BlockCopy(cipherBytes, 0, combinedBytes, aes.IV.Length, cipherBytes.Length);
|
||||||
|
|
||||||
|
return Convert.ToBase64String(combinedBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string AesDecrypt(string Key, string dat)//解密
|
||||||
|
{
|
||||||
|
// 解码Base64
|
||||||
|
byte[] cipherBytes = Convert.FromBase64String(dat);
|
||||||
|
|
||||||
|
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||||||
|
using var aes = System.Security.Cryptography.Aes.Create();
|
||||||
|
|
||||||
|
aes.Key = sha256.ComputeHash(Encoding.UTF8.GetBytes(Key));
|
||||||
|
aes.Mode = CipherMode.CBC;
|
||||||
|
aes.Padding = PaddingMode.PKCS7;
|
||||||
|
// 从字节数组中提取前 16 字节作为 IV
|
||||||
|
aes.IV = cipherBytes.AsSpan(0, 16).ToArray();
|
||||||
|
using var dec = aes.CreateDecryptor();
|
||||||
|
|
||||||
|
// 解密
|
||||||
|
byte[] bytes = dec.TransformFinalBlock(cipherBytes, 16, cipherBytes.Length - 16);
|
||||||
|
//解压缩并返回
|
||||||
|
return Encoding.UTF8.GetString(Decompress(bytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Brotli 压缩辅助方法
|
||||||
|
private static byte[] Compress(byte[] data)
|
||||||
|
{
|
||||||
|
using var output = new MemoryStream();
|
||||||
|
using (var brotli = new BrotliStream(output, CompressionLevel.Optimal))
|
||||||
|
{
|
||||||
|
brotli.Write(data, 0, data.Length);
|
||||||
|
}
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Brotli 解压辅助方法
|
||||||
|
private static byte[] Decompress(byte[] data)
|
||||||
|
{
|
||||||
|
using var input = new MemoryStream(data);
|
||||||
|
using var brotli = new BrotliStream(input, CompressionMode.Decompress);
|
||||||
|
using var output = new MemoryStream();
|
||||||
|
brotli.CopyTo(output);
|
||||||
|
return output.ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -76,8 +76,27 @@ namespace ForwardingServerUI.Class
|
|||||||
|
|
||||||
Application.Current.Dispatcher.Invoke(() => {
|
Application.Current.Dispatcher.Invoke(() => {
|
||||||
MainWindowViewModel._userTable.Rows.Add(client.Id, client.IP, deserializedPerson.User,
|
MainWindowViewModel._userTable.Rows.Add(client.Id, client.IP, deserializedPerson.User,
|
||||||
"", deserializedPerson.Terminal, "", "");
|
URL, deserializedPerson.Terminal, "", "");
|
||||||
});
|
});
|
||||||
|
//记录请求指令
|
||||||
|
string AESDATA = Regex.Replace(
|
||||||
|
AES.AesDecrypt(deserializedPerson.Terminal, deserializedPerson.Dat)
|
||||||
|
, @"\\u[0-9A-Fa-f]{4}", match =>
|
||||||
|
{
|
||||||
|
return Regex.Unescape(match.Value);
|
||||||
|
});
|
||||||
|
//记录
|
||||||
|
Dictionary<string, object> userlog = new Dictionary<string, object>();
|
||||||
|
userlog.Add("User", deserializedPerson.User);
|
||||||
|
userlog.Add("LastLoginIP", deserializedPerson.IP);
|
||||||
|
userlog.Add("IP", client.IP);
|
||||||
|
userlog.Add("LastLoginTerminal", deserializedPerson.Terminal);
|
||||||
|
userlog.Add("Note", AESDATA);
|
||||||
|
userlog.Add("Enterprise", URL);
|
||||||
|
userlog.Add("Time", DateTime.Now.ToString("yyyy-MM-dd dd:HH:mm:ss:fff"));
|
||||||
|
MainWindowViewModel.SQLiteHelpers.InsertData("ActionLog", userlog);
|
||||||
|
LogGing.LINKDATA(URL, "[COMMAND]" + deserializedPerson.User, AESDATA);
|
||||||
|
|
||||||
// 创建一个 秒的延时任务
|
// 创建一个 秒的延时任务
|
||||||
Task delayTask = Task.Delay(15000);
|
Task delayTask = Task.Delay(15000);
|
||||||
// 创建一个监测任务,不断检查变量
|
// 创建一个监测任务,不断检查变量
|
||||||
|
|||||||
+89
-50
@@ -4,11 +4,14 @@ using System.Data;
|
|||||||
using System.Security.Cryptography.Pkcs;
|
using System.Security.Cryptography.Pkcs;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Threading.Channels;
|
||||||
using System.Windows;
|
using System.Windows;
|
||||||
using System.Windows.Markup;
|
using System.Windows.Markup;
|
||||||
using System.Xml.Linq;
|
using System.Xml.Linq;
|
||||||
using TouchSocket.Core;
|
using TouchSocket.Core;
|
||||||
using TouchSocket.Sockets;
|
using TouchSocket.Sockets;
|
||||||
|
using static ForwardingServerUI.MainWindowViewModel;
|
||||||
using static System.Runtime.InteropServices.JavaScript.JSType;
|
using static System.Runtime.InteropServices.JavaScript.JSType;
|
||||||
|
|
||||||
namespace ForwardingServerUI.Class
|
namespace ForwardingServerUI.Class
|
||||||
@@ -24,6 +27,14 @@ namespace ForwardingServerUI.Class
|
|||||||
public required string SERRVERPASWORD { get; set; }
|
public required string SERRVERPASWORD { get; set; }
|
||||||
public required string MachineVer { get; set; }
|
public required string MachineVer { get; set; }
|
||||||
}
|
}
|
||||||
|
public class PersonUser
|
||||||
|
{
|
||||||
|
public required string User { get; set; }
|
||||||
|
public required string Password { get; set; }
|
||||||
|
public required string IP { get; set; }
|
||||||
|
public required string Terminal { get; set; }
|
||||||
|
public required string Dat { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
private static Timer? _timer;
|
private static Timer? _timer;
|
||||||
public static TcpService service = new TcpService();
|
public static TcpService service = new TcpService();
|
||||||
@@ -38,17 +49,17 @@ namespace ForwardingServerUI.Class
|
|||||||
//离线记录
|
//离线记录
|
||||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "] NOT ID " +
|
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "] NOT ID " +
|
||||||
client.Id + " IP " + client.IP);
|
client.Id + " IP " + client.IP);
|
||||||
|
|
||||||
DataRow row = MainWindowViewModel._machineTable.Select("ID='" + client.Id + "'").First();
|
|
||||||
|
|
||||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "] BREAK LINK ID = " +
|
|
||||||
row["ID"] + " IP = " + row["IP"] + " Enterprise = " + row["Enterprise"] +
|
|
||||||
" MachineName = " + row["MachineName"]);
|
|
||||||
|
|
||||||
Application.Current.Dispatcher.Invoke(() =>
|
Application.Current.Dispatcher.Invoke(() =>
|
||||||
{
|
{
|
||||||
|
DataRow row = MainWindowViewModel._machineTable.Select("ID='" + client.Id + "'").First();
|
||||||
|
|
||||||
|
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "] BREAK LINK ID = " +
|
||||||
|
row["ID"] + " IP = " + row["IP"] + " Enterprise = " + row["Enterprise"] +
|
||||||
|
" MachineName = " + row["MachineName"]);
|
||||||
|
|
||||||
MainWindowViewModel._machineTable.Rows.Remove(row);
|
MainWindowViewModel._machineTable.Rows.Remove(row);
|
||||||
});
|
});
|
||||||
|
|
||||||
return EasyTask.CompletedTask;
|
return EasyTask.CompletedTask;
|
||||||
};//有客户端断开连接
|
};//有客户端断开连接
|
||||||
service.Received = (client, e) =>{
|
service.Received = (client, e) =>{
|
||||||
@@ -79,9 +90,26 @@ namespace ForwardingServerUI.Class
|
|||||||
drEmployee["RDAT"] = trimmedDat;
|
drEmployee["RDAT"] = trimmedDat;
|
||||||
drEmployee.EndEdit();
|
drEmployee.EndEdit();
|
||||||
drEmployee.AcceptChanges();
|
drEmployee.AcceptChanges();
|
||||||
|
|
||||||
|
PersonUser deserializedPersonuser = JsonSerializer.Deserialize<PersonUser>(trimmedDat)!;
|
||||||
|
string data = AES.AesDecrypt(deserializedPersonuser.Terminal, deserializedPersonuser.Dat);
|
||||||
|
string decodedData = Regex.Replace(data, @"\\u[0-9A-Fa-f]{4}", match =>
|
||||||
|
{
|
||||||
|
return Regex.Unescape(match.Value);
|
||||||
|
});
|
||||||
|
|
||||||
|
Dictionary<string, object> userlog = new Dictionary<string, object>();
|
||||||
|
userlog.Add("User", drEmployee["User"]);
|
||||||
|
userlog.Add("LastLoginIP", drEmployee["IP"]);
|
||||||
|
userlog.Add("LastLoginTerminal", drEmployee["Terminal"]);
|
||||||
|
userlog.Add("Note", decodedData);
|
||||||
|
userlog.Add("Enterprise", drEmployee["Enterprise"]);
|
||||||
|
userlog.Add("Time", DateTime.Now.ToString("yyyy-MM-dd dd:HH:mm:ss:fff"));
|
||||||
|
SQLiteHelpers.InsertData("ActionLog", userlog);
|
||||||
|
|
||||||
|
LogGing.LINKDATA(drEmployee["Enterprise"].ToString()!,"[REPLY]"+ drEmployee["User"].ToString()!, decodedData);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
else if (s_ == 90)
|
else if (s_ == 90)
|
||||||
{ }
|
{ }
|
||||||
@@ -96,32 +124,37 @@ namespace ForwardingServerUI.Class
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
Personm deserializedPerson = JsonSerializer.Deserialize<Personm>(DAT)!;
|
string trimmedDat = DAT.Trim();
|
||||||
Application.Current.Dispatcher.Invoke(() =>
|
if (!string.IsNullOrEmpty(trimmedDat) &&
|
||||||
|
(trimmedDat[0] == '{' || trimmedDat[0] == '['))
|
||||||
{
|
{
|
||||||
var mach = MainWindowViewModel._machineTable.Select("Enterprise='" + deserializedPerson.SERVEREnterprise +
|
Personm deserializedPerson = JsonSerializer.Deserialize<Personm>(trimmedDat)!;
|
||||||
"'and MachineName='" + deserializedPerson.SERVERMachineName + "'");
|
Application.Current.Dispatcher.Invoke(() =>
|
||||||
if (mach.Length > 0)
|
|
||||||
{
|
{
|
||||||
//刷新设备信息表
|
var mach = MainWindowViewModel._machineTable.Select("Enterprise='" + deserializedPerson.SERVEREnterprise +
|
||||||
DataRow dataRow = mach.First();
|
"'and MachineName='" + deserializedPerson.SERVERMachineName + "'");
|
||||||
dataRow.BeginEdit();
|
if (mach.Length > 0)
|
||||||
dataRow["ID"] = client.Id;
|
{
|
||||||
dataRow["IP"] = client.IP;
|
//刷新设备信息表
|
||||||
dataRow["Start"] = 30;
|
DataRow dataRow = mach.First();
|
||||||
dataRow["Enterprise"] = "/" + deserializedPerson.SERVEREnterprise;
|
dataRow.BeginEdit();
|
||||||
dataRow["MachineName"] = deserializedPerson.SERVERMachineName;
|
dataRow["ID"] = client.Id;
|
||||||
dataRow["MachineVer"] = deserializedPerson.MachineVer;
|
dataRow["IP"] = client.IP;
|
||||||
dataRow.EndEdit();
|
dataRow["Start"] = 30;
|
||||||
dataRow.AcceptChanges();
|
dataRow["Enterprise"] = "/" + deserializedPerson.SERVEREnterprise;
|
||||||
}
|
dataRow["MachineName"] = deserializedPerson.SERVERMachineName;
|
||||||
else
|
dataRow["MachineVer"] = deserializedPerson.MachineVer;
|
||||||
{
|
dataRow.EndEdit();
|
||||||
//添加设备信息表
|
dataRow.AcceptChanges();
|
||||||
MainWindowViewModel._machineTable.Rows.Add(client.Id, client.IP, 30, "/" + deserializedPerson.SERVEREnterprise,
|
}
|
||||||
deserializedPerson.SERVERMachineName, DateTime.Now.ToString(), deserializedPerson.MachineVer);
|
else
|
||||||
}
|
{
|
||||||
});
|
//添加设备信息表
|
||||||
|
MainWindowViewModel._machineTable.Rows.Add(client.Id, client.IP, 30, "/" + deserializedPerson.SERVEREnterprise,
|
||||||
|
deserializedPerson.SERVERMachineName, DateTime.Now.ToString(), deserializedPerson.MachineVer);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " LINK ID " + client.Id + " IP " + client.IP + "]\nDATA =" + DAT);
|
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " LINK ID " + client.Id + " IP " + client.IP + "]\nDATA =" + DAT);
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -162,43 +195,49 @@ namespace ForwardingServerUI.Class
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
int rows = MainWindowViewModel._machineTable.Rows.Count;
|
DataRow[] row = MainWindowViewModel._machineTable.Select("HeartbeatTime<'" + DateTime.Now.AddSeconds(-30).ToString() + "'");
|
||||||
for (int i = rows; i > 0; i--)
|
|
||||||
{
|
|
||||||
DataRow dataRow = MainWindowViewModel._machineTable.Rows[i-1];
|
|
||||||
DateTime dateTime = DateTime.Parse(dataRow["HeartbeatTime"].ToString()!);
|
|
||||||
|
|
||||||
if (DateTime.Now > dateTime.AddSeconds(30) && (int)dataRow["Start"] == 30)
|
Application.Current.Dispatcher.Invoke(() =>
|
||||||
|
{
|
||||||
|
foreach (var dataRow in row)
|
||||||
{
|
{
|
||||||
Application.Current.Dispatcher.Invoke(() =>
|
if ((int)dataRow["Start"] == 30)
|
||||||
{
|
{
|
||||||
dataRow.BeginEdit();
|
dataRow.BeginEdit();
|
||||||
dataRow["Start"] = 999;
|
dataRow["Start"] = 999;
|
||||||
dataRow.EndEdit();
|
dataRow.EndEdit();
|
||||||
dataRow.AcceptChanges();
|
dataRow.AcceptChanges();
|
||||||
});
|
|
||||||
|
|
||||||
Console.WriteLine("[" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "] NOT LINK ID = " +
|
Console.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] NOT LINK ID = {dataRow["ID"]} " +
|
||||||
dataRow["ID"] + " IP = " + dataRow["IP"] + " Enterprise = " + dataRow["Enterprise"] +
|
$"IP = {dataRow["IP"]} Enterprise = {dataRow["Enterprise"]} " +
|
||||||
" MachineName = " + dataRow["MachineName"]);
|
$"MachineName = {dataRow["MachineName"]}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
if (DateTime.Now > dateTime.AddSeconds(180))
|
DataRow[] rowout = MainWindowViewModel._machineTable.Select("HeartbeatTime<'" + DateTime.Now.AddSeconds(-120).ToString() + "'");
|
||||||
|
|
||||||
|
Application.Current.Dispatcher.Invoke(() =>
|
||||||
|
{
|
||||||
|
foreach (var dataRow in rowout)
|
||||||
{
|
{
|
||||||
//关闭无回应连接
|
dataRow.BeginEdit();
|
||||||
|
dataRow["Start"] = 999;
|
||||||
|
dataRow.EndEdit();
|
||||||
|
dataRow.AcceptChanges();
|
||||||
|
|
||||||
foreach (var item in service.Clients)
|
foreach (var item in service.Clients)
|
||||||
{
|
{
|
||||||
if (item.Id == dataRow["ID"].ToString())
|
if (item.Id == dataRow["ID"].ToString())
|
||||||
{
|
{
|
||||||
await item.CloseAsync();
|
item.CloseAsync(); // 关闭完成
|
||||||
|
item.Dispose(); // 释放资源
|
||||||
//在断开连接后,释放对象。
|
break;
|
||||||
item.Dispose();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,6 +7,25 @@ namespace ForwardingServerUI.Class
|
|||||||
{
|
{
|
||||||
public class LogGing
|
public class LogGing
|
||||||
{
|
{
|
||||||
|
public static void LINKDATA(string path,string User, string dat)
|
||||||
|
{
|
||||||
|
string logpath = System.Environment.CurrentDirectory + "\\DB\\"+path;//日志文件目录
|
||||||
|
string logPath = logpath +"\\" + DateTime.Now.ToString(" yyyy-MM-dd HH-mm-ss-ffff") + User + ".txt";//日志文件
|
||||||
|
|
||||||
|
if (Directory.Exists(logpath))//检查日志路径
|
||||||
|
{
|
||||||
|
FileStream fs = new FileStream(logPath, FileMode.CreateNew, FileAccess.Write);//创建写入文件
|
||||||
|
StreamWriter wr = new StreamWriter(fs);//创建文件
|
||||||
|
wr.WriteLine(dat);
|
||||||
|
wr.Close();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
DirectoryInfo directoryInfo = new DirectoryInfo(logpath);
|
||||||
|
directoryInfo.Create();//创建日志路径
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public static void LogGingDATA(string dat)
|
public static void LogGingDATA(string dat)
|
||||||
{
|
{
|
||||||
string logpath = System.Environment.CurrentDirectory + "\\Log";//日志文件目录
|
string logpath = System.Environment.CurrentDirectory + "\\Log";//日志文件目录
|
||||||
|
|||||||
@@ -0,0 +1,504 @@
|
|||||||
|
using Microsoft.Data.Sqlite;
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Data;
|
||||||
|
using System.Data.Common;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
|
||||||
|
namespace ForwardingServerUI.Class
|
||||||
|
{
|
||||||
|
public class ClsLock : IDisposable
|
||||||
|
{
|
||||||
|
private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
|
||||||
|
|
||||||
|
public IDisposable Read()
|
||||||
|
{
|
||||||
|
_lock.EnterReadLock();
|
||||||
|
return new DisposableAction(() => _lock.ExitReadLock());
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose() => _lock?.Dispose();
|
||||||
|
|
||||||
|
private class DisposableAction : IDisposable
|
||||||
|
{
|
||||||
|
private readonly Action _action;
|
||||||
|
public DisposableAction(Action action) => _action = action;
|
||||||
|
public void Dispose() => _action?.Invoke();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class SqliteHelper
|
||||||
|
{
|
||||||
|
#region 字段
|
||||||
|
private SqliteTransaction? dbTrans = null!;
|
||||||
|
private static readonly Dictionary<string, ClsLock> RWL = new Dictionary<string, ClsLock>();
|
||||||
|
private readonly string mDataFile;
|
||||||
|
private readonly string mPassWord = "";
|
||||||
|
private readonly string lockName = "";
|
||||||
|
private SqliteConnection mConn = null!;
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 构造函数
|
||||||
|
public SqliteHelper(string dataFile)
|
||||||
|
{
|
||||||
|
this.mDataFile = dataFile ?? throw new ArgumentNullException(nameof(dataFile));
|
||||||
|
this.mDataFile = dataFile; // 注意:原代码有两次赋值,保留逻辑
|
||||||
|
if (!RWL.ContainsKey(dataFile))
|
||||||
|
{
|
||||||
|
lockName = dataFile;
|
||||||
|
RWL.Add(dataFile, new ClsLock());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public SqliteHelper(string dataFile, string PassWord)
|
||||||
|
{
|
||||||
|
this.mDataFile = dataFile ?? throw new ArgumentNullException(nameof(dataFile));
|
||||||
|
this.mPassWord = PassWord ?? throw new ArgumentNullException(nameof(PassWord));
|
||||||
|
this.mDataFile = dataFile;
|
||||||
|
if (!RWL.ContainsKey(dataFile))
|
||||||
|
{
|
||||||
|
lockName = dataFile;
|
||||||
|
RWL.Add(dataFile, new ClsLock());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 打开/关闭 数据库
|
||||||
|
// 注意:Microsoft.Data.Sqlite.Core 不支持连接字符串构建器,需手动拼接
|
||||||
|
// 加密支持通常需要 Microsoft.Data.Sqlite.Core + SQLitePCLRaw.bundle_green (且加密功能可能受限)
|
||||||
|
|
||||||
|
public void Open()
|
||||||
|
{
|
||||||
|
// 构建连接字符串
|
||||||
|
var connectionString = $"Data Source={mDataFile}";
|
||||||
|
if (!string.IsNullOrWhiteSpace(mPassWord))
|
||||||
|
{
|
||||||
|
connectionString += $";Password={mPassWord}"; // 注意:原生 Microsoft.Data.Sqlite 不支持加密
|
||||||
|
// 如果需要加密,通常需要使用 SQLitePCLRaw 的特定提供程序或第三方库
|
||||||
|
}
|
||||||
|
|
||||||
|
mConn = new SqliteConnection(connectionString);
|
||||||
|
|
||||||
|
// 如果文件不存在,Open() 会自动创建数据库文件
|
||||||
|
// 但表结构需要你自己执行 CREATE TABLE
|
||||||
|
mConn.Open();
|
||||||
|
|
||||||
|
Console.WriteLine("The database was opened successfully");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Close()
|
||||||
|
{
|
||||||
|
if (this.mConn != null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
this.mConn.Close();
|
||||||
|
// 注意:不要在这里移除 RWL,因为这是静态的,可能影响其他实例
|
||||||
|
// if (RWL.ContainsKey(LockName)) { RWL.Remove(LockName); }
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
Console.WriteLine("Shutdown failed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Console.WriteLine("The database was shut down successfully");
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 事务
|
||||||
|
public void BeginTrain()
|
||||||
|
{
|
||||||
|
EnsureConnection();
|
||||||
|
dbTrans = mConn.BeginTransaction();
|
||||||
|
}
|
||||||
|
|
||||||
|
public void DBCommit()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
dbTrans?.Commit();
|
||||||
|
dbTrans?.Dispose();
|
||||||
|
dbTrans = null; // 提交后置空
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
dbTrans?.Rollback();
|
||||||
|
dbTrans?.Dispose();
|
||||||
|
dbTrans = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 工具
|
||||||
|
// OpenConnection 逻辑已合并到 Open() 方法中,因为 SqliteConnection 构造函数只接受字符串
|
||||||
|
|
||||||
|
public SqliteConnection Connection
|
||||||
|
{
|
||||||
|
get { return mConn; }
|
||||||
|
private set { mConn = value ?? throw new ArgumentNullException(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
protected void EnsureConnection()
|
||||||
|
{
|
||||||
|
if (this.mConn == null)
|
||||||
|
{
|
||||||
|
throw new Exception("SQLiteManager.Connection=null");
|
||||||
|
}
|
||||||
|
if (mConn.State != ConnectionState.Open)
|
||||||
|
{
|
||||||
|
mConn.Open();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public string GetDataFile() => this.mDataFile;
|
||||||
|
|
||||||
|
public bool TableExists(string table)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(table)) return false;
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
// 注意:参数化查询在表名/列名上无效,这里使用字符串拼接(需确保table变量安全)
|
||||||
|
// 或者使用 PRAGMA table_info(table_name)
|
||||||
|
var sql = $"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='{table}'";
|
||||||
|
|
||||||
|
using (var cmd = new SqliteCommand(sql, Connection))
|
||||||
|
{
|
||||||
|
var result = cmd.ExecuteScalar();
|
||||||
|
return Convert.ToInt32(result) > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool Vacuum()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (var Command = new SqliteCommand("VACUUM", Connection))
|
||||||
|
{
|
||||||
|
Command.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception) // SqliteException
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// 将 IDataReader 转换为 DataSet
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="reader">已经执行了查询的 DataReader</param>
|
||||||
|
/// <returns>包含数据的 DataSet</returns>
|
||||||
|
public DataSet ReaderToDataSet(IDataReader reader)
|
||||||
|
{
|
||||||
|
DataSet ds = new DataSet();
|
||||||
|
|
||||||
|
do
|
||||||
|
{
|
||||||
|
DataTable schemaTable = reader.GetSchemaTable()!;
|
||||||
|
DataTable dataTable = new DataTable();
|
||||||
|
|
||||||
|
if (schemaTable != null)
|
||||||
|
{
|
||||||
|
// 创建列
|
||||||
|
foreach (DataRow schemaRow in schemaTable.Rows)
|
||||||
|
{
|
||||||
|
string colName = schemaRow["ColumnName"].ToString()!;
|
||||||
|
Type dataType = (Type)schemaRow["DataType"];
|
||||||
|
|
||||||
|
// 防止列名重复
|
||||||
|
string uniqueColName = colName;
|
||||||
|
int i = 1;
|
||||||
|
while (dataTable.Columns.Contains(uniqueColName))
|
||||||
|
{
|
||||||
|
uniqueColName = colName + i++;
|
||||||
|
}
|
||||||
|
|
||||||
|
DataColumn column = new DataColumn(uniqueColName, dataType);
|
||||||
|
dataTable.Columns.Add(column);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 读取行
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
object[] values = new object[dataTable.Columns.Count];
|
||||||
|
for (int i = 0; i < dataTable.Columns.Count; i++)
|
||||||
|
{
|
||||||
|
values[i] = reader.IsDBNull(i) ? DBNull.Value : reader.GetValue(i);
|
||||||
|
}
|
||||||
|
dataTable.Rows.Add(values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// 如果没有 Schema (例如 "SELECT 1" 这种标量查询)
|
||||||
|
// 需要手动创建列
|
||||||
|
for (int i = 0; i < reader.FieldCount; i++)
|
||||||
|
{
|
||||||
|
dataTable.Columns.Add("Column" + i);
|
||||||
|
}
|
||||||
|
while (reader.Read())
|
||||||
|
{
|
||||||
|
object[] values = new object[reader.FieldCount];
|
||||||
|
reader.GetValues(values);
|
||||||
|
dataTable.Rows.Add(values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ds.Tables.Add(dataTable);
|
||||||
|
} while (reader.NextResult()); // 处理多个结果集
|
||||||
|
|
||||||
|
return ds;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
|
||||||
|
#region 执行SQL (Reader & Scalar)
|
||||||
|
|
||||||
|
public SqliteDataReader? ExecuteReader(string sql, SqliteParameter[]? paramArr)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
// 注意:using 语句会立即释放 Reader,导致无法读取
|
||||||
|
// 这里的 RWL 锁在 using 外部处理,或者调用方自己处理锁
|
||||||
|
// 这里简化逻辑,直接返回 Reader,调用方需自行管理连接状态
|
||||||
|
var cmd = new SqliteCommand(sql, Connection);
|
||||||
|
|
||||||
|
if (paramArr != null)
|
||||||
|
{
|
||||||
|
cmd.Parameters.AddRange(paramArr);
|
||||||
|
}
|
||||||
|
|
||||||
|
// CommandBehavior.CloseConnection 确保 Reader 关闭时连接也关闭
|
||||||
|
// 但这里我们管理连接,所以不加
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// 注意:不要在这里 Dispose Command,否则 Reader 会失效
|
||||||
|
// 返回 Reader,由调用方在读取完毕后关闭
|
||||||
|
return cmd.ExecuteReader();
|
||||||
|
}
|
||||||
|
catch(Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine("[SQLITE_ExecuteReader:err]" + ex.ToString());
|
||||||
|
cmd?.Dispose();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public DataSet? ExecuteDataSet(string sql, SqliteParameter[]? paramArr)
|
||||||
|
{
|
||||||
|
var dat = ExecuteReader(sql, paramArr);
|
||||||
|
if (dat == null)
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return ReaderToDataSet(dat);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecuteScalar
|
||||||
|
public object? ExecuteScalar(string sql, SqliteParameter[]? paramArr)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
using (RWL[lockName].Read())
|
||||||
|
{
|
||||||
|
using (var cmd = new SqliteCommand(sql, Connection))
|
||||||
|
{
|
||||||
|
if (paramArr != null)
|
||||||
|
{
|
||||||
|
cmd.Parameters.AddRange(paramArr);
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return cmd.ExecuteScalar();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine("[SQLITE_ExecuteScalar:err]" + ex.ToString());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// QueryOne (返回字典或对象)
|
||||||
|
public Dictionary<string, object?>? QueryOne(string table, string conditionCol, object conditionVal)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(table)) return null;
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
string sql = $"SELECT * FROM [{table}]"; // 使用 [] 防止关键字冲突
|
||||||
|
var parameters = new List<SqliteParameter>();
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(conditionCol))
|
||||||
|
{
|
||||||
|
sql += $" WHERE [{conditionCol}] = @{conditionCol}";
|
||||||
|
parameters.Add(new SqliteParameter($"@{conditionCol}", conditionVal));
|
||||||
|
}
|
||||||
|
|
||||||
|
using (var cmd = new SqliteCommand(sql, Connection))
|
||||||
|
{
|
||||||
|
cmd.Parameters.AddRange(parameters.ToArray());
|
||||||
|
using (var reader = cmd.ExecuteReader())
|
||||||
|
{
|
||||||
|
if (reader.Read())
|
||||||
|
{
|
||||||
|
var dict = new Dictionary<string, object?>();
|
||||||
|
for (int i = 0; i < reader.FieldCount; i++)
|
||||||
|
{
|
||||||
|
var value = reader.GetValue(i);
|
||||||
|
if (value == DBNull.Value) value = null;
|
||||||
|
dict[reader.GetName(i)] = value;
|
||||||
|
}
|
||||||
|
return dict;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region 增 删 改
|
||||||
|
// 注意:参数前缀统一为 @
|
||||||
|
|
||||||
|
public int InsertData(string table, Dictionary<string, object> entity)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(table)) throw new ArgumentNullException(nameof(table));
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
string sql = BuildInsert(table, entity);
|
||||||
|
var parameters = BuildParamArray(entity);
|
||||||
|
return ExecuteNonQuery(sql, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Update(string table, Dictionary<string, object> entity, string where, SqliteParameter[]? whereParams)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(table)) throw new ArgumentNullException(nameof(table));
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
string sql = BuildUpdate(table, entity);
|
||||||
|
var parameters = BuildParamArray(entity);
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(where))
|
||||||
|
{
|
||||||
|
sql += " WHERE " + where;
|
||||||
|
if (whereParams != null)
|
||||||
|
{
|
||||||
|
var combined = new SqliteParameter[parameters.Length + whereParams.Length];
|
||||||
|
parameters.CopyTo(combined, 0);
|
||||||
|
whereParams.CopyTo(combined, parameters.Length);
|
||||||
|
parameters = combined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ExecuteNonQuery(sql, parameters);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Delete(string table, string where, SqliteParameter[]? whereParams)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(table)) return 0;
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
string sql = $"DELETE FROM [{table}]";
|
||||||
|
if (!string.IsNullOrEmpty(where))
|
||||||
|
{
|
||||||
|
sql += " WHERE " + where;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ExecuteNonQuery(sql, whereParams);
|
||||||
|
}
|
||||||
|
|
||||||
|
public int ExecuteNonQuery(string sql, SqliteParameter[]? paramArr)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(sql)) throw new ArgumentNullException(nameof(sql));
|
||||||
|
EnsureConnection();
|
||||||
|
|
||||||
|
using (RWL[lockName].Read()) // 注意:写操作通常建议用 Write 锁
|
||||||
|
{
|
||||||
|
using (var cmd = new SqliteCommand(sql, Connection))
|
||||||
|
{
|
||||||
|
if (paramArr != null)
|
||||||
|
{
|
||||||
|
cmd.Parameters.AddRange(paramArr);
|
||||||
|
}
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return cmd.ExecuteNonQuery();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Console.WriteLine("[SQLITE_ExecuteScalar:err]" + ex.ToString());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建 SQL 和 参数的方法保持不变,仅泛型类型变更
|
||||||
|
private SqliteParameter[] BuildParamArray(Dictionary<string, object> entity)
|
||||||
|
{
|
||||||
|
var list = new List<SqliteParameter>();
|
||||||
|
foreach (string key in entity.Keys)
|
||||||
|
{
|
||||||
|
// 注意:参数名必须包含 @ 前缀
|
||||||
|
list.Add(new SqliteParameter($"@{key}", entity[key]));
|
||||||
|
}
|
||||||
|
return list.ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string BuildInsert(string table, Dictionary<string, object> entity)
|
||||||
|
{
|
||||||
|
var buf = new StringBuilder();
|
||||||
|
buf.Append("INSERT INTO ").Append(table).Append(" (");
|
||||||
|
var cols = new List<string>();
|
||||||
|
var vals = new List<string>();
|
||||||
|
foreach (string key in entity.Keys)
|
||||||
|
{
|
||||||
|
cols.Add(key);
|
||||||
|
vals.Add($"@{key}");
|
||||||
|
}
|
||||||
|
buf.Append(string.Join(",", cols)).Append(") VALUES (");
|
||||||
|
buf.Append(string.Join(",", vals)).Append(")");
|
||||||
|
return buf.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private string BuildUpdate(string table, Dictionary<string, object> entity)
|
||||||
|
{
|
||||||
|
var buf = new StringBuilder();
|
||||||
|
buf.Append("UPDATE ").Append(table).Append(" SET ");
|
||||||
|
var sets = new List<string>();
|
||||||
|
foreach (string key in entity.Keys)
|
||||||
|
{
|
||||||
|
sets.Add($"{key} = @{key}");
|
||||||
|
}
|
||||||
|
buf.Append(string.Join(",", sets));
|
||||||
|
return buf.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 辅助方法:DataRow 转 Dictionary (由于没有 DataTable,通常直接从 Reader 转)
|
||||||
|
// 这里保留原方法签名,但实际使用中可能需要调整
|
||||||
|
public Dictionary<string, object?> DataTableToDictionary(DataTable dataTable)
|
||||||
|
{
|
||||||
|
var result = new Dictionary<string, object?>();
|
||||||
|
if (dataTable.Rows.Count > 0)
|
||||||
|
{
|
||||||
|
var row = dataTable.Rows[0];
|
||||||
|
foreach (DataColumn column in dataTable.Columns)
|
||||||
|
{
|
||||||
|
var value = row[column];
|
||||||
|
if (value == DBNull.Value) value = null;
|
||||||
|
result[column.ColumnName] = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -10,6 +10,8 @@
|
|||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
||||||
|
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.10" />
|
||||||
|
<PackageReference Include="Microsoft.Data.Sqlite.Core" Version="10.0.10" />
|
||||||
<PackageReference Include="TouchSocket" Version="4.2.16" />
|
<PackageReference Include="TouchSocket" Version="4.2.16" />
|
||||||
<PackageReference Include="TouchSocket.Http" Version="4.2.16" />
|
<PackageReference Include="TouchSocket.Http" Version="4.2.16" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ using ForwardingServerUI.Class;
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
|
using System.Reflection.PortableExecutable;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
using TouchSocket.Sockets;
|
using TouchSocket.Sockets;
|
||||||
|
|
||||||
@@ -26,8 +27,16 @@ namespace ForwardingServerUI
|
|||||||
[ObservableProperty]
|
[ObservableProperty]
|
||||||
public static DataTable _userTable = new();
|
public static DataTable _userTable = new();
|
||||||
|
|
||||||
|
public static SqliteHelper SQLiteHelpers = null!; //定义数据库
|
||||||
|
private readonly string DBAddress = Environment.CurrentDirectory + "\\DB\\DB.db"; //数据库路径
|
||||||
|
public static DataTable ActionLog = new DataTable();
|
||||||
|
public static readonly object TableLock = new object();
|
||||||
|
|
||||||
public async void Data()
|
public async void Data()
|
||||||
{
|
{
|
||||||
|
SQLiteHelpers = new SqliteHelper(DBAddress); //数据库连接路径
|
||||||
|
SQLiteHelpers.Open(); //打开数据库
|
||||||
|
|
||||||
_machineTable.Columns.Add("ID", typeof(string));
|
_machineTable.Columns.Add("ID", typeof(string));
|
||||||
_machineTable.Columns.Add("IP", typeof(string));
|
_machineTable.Columns.Add("IP", typeof(string));
|
||||||
_machineTable.Columns.Add("Start", typeof(int));
|
_machineTable.Columns.Add("Start", typeof(int));
|
||||||
@@ -36,7 +45,6 @@ namespace ForwardingServerUI
|
|||||||
_machineTable.Columns.Add("HeartbeatTime", typeof(string));
|
_machineTable.Columns.Add("HeartbeatTime", typeof(string));
|
||||||
_machineTable.Columns.Add("MachineVer", typeof(string));
|
_machineTable.Columns.Add("MachineVer", typeof(string));
|
||||||
|
|
||||||
|
|
||||||
_userTable.Columns.Add("ID", typeof(string));
|
_userTable.Columns.Add("ID", typeof(string));
|
||||||
_userTable.Columns.Add("IP", typeof(string));
|
_userTable.Columns.Add("IP", typeof(string));
|
||||||
_userTable.Columns.Add("User", typeof(string));
|
_userTable.Columns.Add("User", typeof(string));
|
||||||
|
|||||||
Reference in new issue
Block a user