From 0f9c06e52455153ae4ed90bac177be9cf4682cf8 Mon Sep 17 00:00:00 2001 From: snltty <1069410172@qq.com> Date: Sat, 13 Apr 2024 17:06:26 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=99=E6=A1=8C=E9=9D=A2=E5=85=B1=E4=BA=AB?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BB=A3=E7=90=86=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 59 +- cmonitor.install.win/Config.cs | 28 +- cmonitor.install.win/MainForm.Designer.cs | 39 + cmonitor.install.win/MainForm.cs | 12 + cmonitor.install.win/MainForm.resx | 1946 +++++++++-------- cmonitor.install.win/MainForm.zh-Hans.resx | 87 +- cmonitor.viewer.client.win/default.aproj | 2 +- .../dist/cmonitor.viewer.client.win.exe | Bin 1323520 -> 1323520 bytes cmonitor.viewer.client.win/main.aardio | 2 +- cmonitor.viewer.server.win/MainForm.cs | 83 +- cmonitor.viewer.server.win/Program.cs | 31 +- .../views/device/plugins/viewer/Command.vue | 3 + .../views/device/plugins/viewer/Screen.vue | 3 +- .../src/views/device/plugins/viewer/index.js | 4 +- cmonitor/Program.cs | 10 +- cmonitor/api/ApiServer.cs | 8 +- cmonitor/api/ApiStartup.cs | 2 +- cmonitor/client/ClientSignInTransfer.cs | 74 +- cmonitor/client/ClientStartup.cs | 29 +- cmonitor/client/args/ISignInArgs.cs | 7 + cmonitor/client/args/SignInArgsTransfer.cs | 30 + cmonitor/client/config/Config.cs | 48 + .../client/report/ClientReportTransfer.cs | 6 +- cmonitor/client/running/RunningConfig.cs | 104 + .../client/runningConfig/IRunningConfig.cs | 8 - .../runningConfig/RunningConfigLinux.cs | 15 - .../runningConfig/RunningConfigMacOS.cs | 15 - .../runningConfig/RunningConfigWindows.cs | 75 - cmonitor/client/trigger/ITrigger.cs | 9 - cmonitor/config/Config.cs | 136 +- .../active/report/ActiveWindowReport.cs | 41 +- .../active/report/ActiveWindowWindows.cs | 16 +- cmonitor/plugins/hijack/HijackStartup.cs | 1 - .../plugins/hijack/report/HijackConfig.cs | 20 +- .../plugins/hijack/report/HijackReport.cs | 58 +- .../keyboard/report/KeyboardWindows.cs | 2 +- cmonitor/plugins/llock/report/LLockReport.cs | 39 +- cmonitor/plugins/llock/report/LLockWindows.cs | 2 +- cmonitor/plugins/modes/ModesApiController.cs | 2 - .../screen/messenger/ScreenMessenger.cs | 2 +- .../screen/report/ScreenWindowsDxgi.cs | 4 +- .../plugins/screen/report/ScreenWindowsGdi.cs | 2 +- .../plugins/signIn/messenger/SignCaching.cs | 12 +- .../signIn/messenger/SignInMessenger.cs | 2 +- .../plugins/snatch/report/SnatchWindows.cs | 2 +- .../plugins/system/report/SystemWindows.cs | 2 +- .../plugins/viewer/RDP桌面共享流程.drawio | 552 +++++ .../plugins/viewer/ViewerApiController.cs | 24 +- cmonitor/plugins/viewer/ViewerStartup.cs | 12 + .../viewer/messenger/ViewerMessenger.cs | 98 +- .../viewer/messenger/ViewerMessengerIds.cs | 11 +- cmonitor/plugins/viewer/proxy/ViewerProxy.cs | 474 ++++ .../viewer/proxy/ViewerProxyCaching.cs | 56 + .../plugins/viewer/proxy/ViewerProxyClient.cs | 42 + .../plugins/viewer/proxy/ViewerProxyServer.cs | 40 + .../viewer/proxy/ViewerProxySignInArgs.cs | 24 + cmonitor/plugins/viewer/report/IViewer.cs | 82 +- cmonitor/plugins/viewer/report/ViewerLinux.cs | 11 +- cmonitor/plugins/viewer/report/ViewerMacOS.cs | 11 +- .../plugins/viewer/report/ViewerReport.cs | 233 +- .../plugins/viewer/report/ViewerWindows.cs | 34 +- .../plugins/volume/report/VolumeReport.cs | 18 +- .../plugins/wallpaper/report/IWallpaper.cs | 19 +- .../wallpaper/report/WallpaperReport.cs | 21 +- .../wallpaper/report/WallpaperWindows.cs | 2 +- cmonitor/plugins/wlan/WlanStartup.cs | 1 - cmonitor/plugins/wlan/report/WlanWindows.cs | 1 - cmonitor/server/IConnection.cs | 67 +- cmonitor/server/MessengerResolver.cs | 7 +- cmonitor/server/ServerStartup.cs | 6 +- cmonitor/server/TcpServer.cs | 10 +- cmonitor/server/config/Config.cs | 14 + cmonitor/startup/StartupTransfer.cs | 17 +- cmonitor/web/WebServer.cs | 4 +- cmonitor/web/WebStartup.cs | 2 +- common.libs/FireWallHelper.cs | 14 +- common.libs/winapis/Win32Interop.cs | 19 + 77 files changed, 3337 insertions(+), 1671 deletions(-) create mode 100644 cmonitor/client/args/ISignInArgs.cs create mode 100644 cmonitor/client/args/SignInArgsTransfer.cs create mode 100644 cmonitor/client/config/Config.cs create mode 100644 cmonitor/client/running/RunningConfig.cs delete mode 100644 cmonitor/client/runningConfig/IRunningConfig.cs delete mode 100644 cmonitor/client/runningConfig/RunningConfigLinux.cs delete mode 100644 cmonitor/client/runningConfig/RunningConfigMacOS.cs delete mode 100644 cmonitor/client/runningConfig/RunningConfigWindows.cs delete mode 100644 cmonitor/client/trigger/ITrigger.cs create mode 100644 cmonitor/plugins/viewer/RDP桌面共享流程.drawio create mode 100644 cmonitor/plugins/viewer/proxy/ViewerProxy.cs create mode 100644 cmonitor/plugins/viewer/proxy/ViewerProxyCaching.cs create mode 100644 cmonitor/plugins/viewer/proxy/ViewerProxyClient.cs create mode 100644 cmonitor/plugins/viewer/proxy/ViewerProxyServer.cs create mode 100644 cmonitor/plugins/viewer/proxy/ViewerProxySignInArgs.cs create mode 100644 cmonitor/server/config/Config.cs diff --git a/README.md b/README.md index ecc18b21..14936cce 100644 --- a/README.md +++ b/README.md @@ -28,17 +28,17 @@ 1. 这是一个粗略的局域网监控程序(说是局域网,你放外网也不是不行) 2. 使用组件式,非常方便扩展,可由 **内存共享(MemoryMappedFiles)** 提供自己定义数据 3. 内存占用小,(非定时,自动GC),linux无解 -4. 使用 **MemoryPack**、**SharpDX**、**NAudio** -1. +4. 使用 **MemoryPack**、**SharpDX**、**NAudio**、**RdpSession+RdpViewer** +5.

## 功能 ###### 系统 -- [x] 桌面捕获,捕获鼠标,**sharpDX** +- [x] 桌面捕获,捕获鼠标,**screen** - [x] 登录界面捕获和登录页面键盘输入 - [x] 双指画面缩放 - [ ] 区域热更新 -- [x] 功能禁用,禁用各种系统功能 **regedit** **第一次成功连接服务端后自动恢复限制** +- [x] 功能禁用,禁用各种系统功能 **system** - 任务栏锁定,任务栏设置,任务栏菜单 - 任务管理器 - 注册表编辑,组策略编辑 @@ -49,35 +49,36 @@ - 关机按钮,注销按钮,锁定按钮,修改密码,切换用户 - 安全SAS - 禁用U盘 -- [x] 系统信息,展示CPU,内存利用率,硬盘使用率,发呆时间 **win api** -- [x] 音量控制,音量和静音 **NAudio** -- [x] 音频峰值,展示音频峰值,是否在播放音视频,及激昂程度 **NAudio** -- [x] 系统亮度,暂不支持外界显示器 **WMI** -- [x] 模拟键盘,键盘操作,模拟ctrl+alt+delete,模拟win+l,等等 **win api** -- [ ] 模拟鼠标,鼠标操作 **win api** +- [x] 系统信息,展示CPU,内存利用率,硬盘使用率,发呆时间 **system** +- [x] 音量控制,音量和静音 **volume** +- [x] 音频峰值,展示音频峰值,是否在播放音视频,及激昂程度 **volume** +- [x] 系统亮度,暂不支持外界显示器 **light** +- [x] 模拟键盘,键盘操作,模拟ctrl+alt+delete,模拟win+l,等等 **keyboard** +- [ ] 模拟鼠标,鼠标操作 **volume** ###### 程序 -- [x] 程序限制,分为禁止打开程序,和自定检测关闭程序 **regedit** **第一次成功连接服务端后自动恢复限制** -- [x] 前景窗口,当前焦点程序捕获,手动关闭之 **win api** -- [x] 时间统计,查看程序使用时间记录 +- [x] 程序限制,分为禁止打开程序,和自定检测关闭程序 **active** +- [x] 前景窗口,当前焦点程序捕获,手动关闭之 **active** +- [x] 时间统计,查看程序使用时间记录 **active** ###### 网络 -- [x] 网络限制,程序,域名,IP 黑白名单 **第一次成功连接服务端后恢复限制** -- [x] 网速显示,由网络限制组件提供 +- [x] 网络限制,程序,域名,IP 黑白名单 **hijack** +- [x] 网速显示,由网络限制组件提供 **hijack** +- [x] 自动连接wifi **wlan** ###### 消息 -- [x] 消息提醒,向设备发送消息提醒 **winform** -- [x] 全局广播,向所有设备发送广播 **winform** -- [x] 语音消息,向设备发送语音消息 **NAudio** +- [x] 消息提醒,向设备发送消息提醒 **message** +- [x] 全局广播,向所有设备发送广播 **notify** +- [x] 语音消息,向设备发送语音消息 **message** ###### 命令 -- [x] 发送命令,执行cmd命令,等等 +- [x] 发送命令,执行cmd命令,等等 **command** ###### 互动 -- [x] 互动答题 **winform** -- [x] 屏幕共享,以某一设备为主机,向其它设备共享屏幕,用于演示 **RDPSession+RDPViewer** **第一次成功连接服务端后自动恢复** +- [x] 互动答题 **snatch** +- [x] 屏幕共享,以某一设备为主机,向其它设备共享屏幕,用于演示 **viewer**第一次成功连接服务端后自动恢复** ###### 壁纸 -- [x] 壁纸程序,为所有设备设置统一壁纸,以程序的方式 **winform** **第一次成功连接服务端后自动恢复** -- [x] 键盘按键,显示键盘按键(当前键盘按键由壁纸程序提供) **win api** +- [x] 壁纸程序,为所有设备设置统一壁纸,以程序的方式 **wallpaper** +- [x] 键盘按键,显示键盘按键(当前键盘按键由壁纸程序提供) **wallpaper** ###### 锁屏 -- [x] 锁屏程序,打开锁屏程序,禁用键盘 **winform** **第一次成功连接服务端后自动恢复** +- [x] 锁屏程序,打开锁屏程序,禁用键盘 **llock** ###### 其它 -- [x] 设备用户,显示当前使用设备用户姓名 **MemoryMappedFiles** +- [x] 设备用户,显示当前使用设备用户姓名 **devices** @@ -86,8 +87,7 @@ ## 运行参数 ``` -第一次运行【cmonitor.exe】后,在 configs/ 文件夹下,会生成配置文件,可以根据需要进行修改,然后再次运行 - +第一次运行后,在 configs/ 文件夹下,会生成配置文件,可以根据需要进行修改,然后再次运行 ``` ## 安装示例 @@ -129,7 +129,10 @@ systemctl restart cmonitor docker镜像 snltty/cmonitor-alpine-x64 or snltty/cmonitor-alpine-arm64 ``` docker run -it -d --name="cmonitor" \ --p 1800:1800/tcp -p 1801:1801/tcp -p 1802:1802/tcp -p 1802:1802/udp \ +-p 1800:1800/tcp -p 1800:1800/udp \ +-p 1801:1801/tcp -p 1801:1801/udp \ +-p 1802:1802/tcp -p 1802:1802/udp \ +-p 1802:1803/tcp -p 1802:1803/udp \ -v /usr/local/cmonitor/configs:/app/configs \ snltty/cmonitor-alpine-x64 ``` diff --git a/cmonitor.install.win/Config.cs b/cmonitor.install.win/Config.cs index f7c77bcc..e04a259d 100644 --- a/cmonitor.install.win/Config.cs +++ b/cmonitor.install.win/Config.cs @@ -126,12 +126,12 @@ namespace cmonitor.install.win } } - public sealed class ConfigCommonInfo + public sealed partial class ConfigCommonInfo { public string[] Modes { get; set; } = new string[] { "client", "server" }; public bool BlueProtect { get; set; } } - public sealed class ConfigClientInfo + public sealed partial class ConfigClientInfo { private string server = new IPEndPoint(IPAddress.Loopback, 1802).ToString(); public string Server @@ -165,7 +165,7 @@ namespace cmonitor.install.win public int ShareMemorySize { get; set; } = 1024; } - public sealed class ConfigServerInfo + public sealed partial class ConfigServerInfo { public int WebPort { get; set; } = 1800; public string WebRoot { get; set; } = "./web/"; @@ -174,3 +174,25 @@ namespace cmonitor.install.win } } + + +namespace cmonitor.install.win +{ + public sealed class ViewerConfigInfo + { + [JsonIgnore] + public const string userNameKey = "viewer-username"; + + public int ProxyPort { get; set; } = 1803; + } + + public sealed partial class ConfigClientInfo + { + public ViewerConfigInfo Viewer { get; set; } = new ViewerConfigInfo(); + } + + public sealed partial class ConfigServerInfo + { + public ViewerConfigInfo Viewer { get; set; } = new ViewerConfigInfo(); + } +} \ No newline at end of file diff --git a/cmonitor.install.win/MainForm.Designer.cs b/cmonitor.install.win/MainForm.Designer.cs index c19a8e27..777b0bc5 100644 --- a/cmonitor.install.win/MainForm.Designer.cs +++ b/cmonitor.install.win/MainForm.Designer.cs @@ -53,6 +53,10 @@ gbClient = new GroupBox(); gbServer = new GroupBox(); cbBlueProtect = new CheckBox(); + tbViewerPortClient = new TextBox(); + label7 = new Label(); + tbViewerPortServer = new TextBox(); + label8 = new Label(); gbClient.SuspendLayout(); gbServer.SuspendLayout(); SuspendLayout(); @@ -173,6 +177,8 @@ // gbClient // resources.ApplyResources(gbClient, "gbClient"); + gbClient.Controls.Add(tbViewerPortClient); + gbClient.Controls.Add(label7); gbClient.Controls.Add(machineName); gbClient.Controls.Add(label16); gbClient.Controls.Add(serverIP); @@ -189,6 +195,8 @@ // gbServer // resources.ApplyResources(gbServer, "gbServer"); + gbServer.Controls.Add(tbViewerPortServer); + gbServer.Controls.Add(label8); gbServer.Controls.Add(apiPort); gbServer.Controls.Add(serverPort); gbServer.Controls.Add(label2); @@ -204,6 +212,26 @@ cbBlueProtect.Name = "cbBlueProtect"; cbBlueProtect.UseVisualStyleBackColor = true; // + // tbViewerPortClient + // + resources.ApplyResources(tbViewerPortClient, "tbViewerPortClient"); + tbViewerPortClient.Name = "tbViewerPortClient"; + // + // label7 + // + resources.ApplyResources(label7, "label7"); + label7.Name = "label7"; + // + // tbViewerPortServer + // + resources.ApplyResources(tbViewerPortServer, "tbViewerPortServer"); + tbViewerPortServer.Name = "tbViewerPortServer"; + // + // label8 + // + resources.ApplyResources(label8, "label8"); + label8.Name = "label8"; + // // MainForm // resources.ApplyResources(this, "$this"); @@ -253,5 +281,16 @@ private GroupBox gbClient; private GroupBox gbServer; private CheckBox cbBlueProtect; + +/* 项目“cmonitor.install.win (net8.0-windows)”的未合并的更改 +在此之前: + private TextBox textBox1; +在此之后: + private TextBox tbViewerPortCLient; +*/ + private TextBox tbViewerPortClient; + private Label label7; + private TextBox tbViewerPortServer; + private Label label8; } } diff --git a/cmonitor.install.win/MainForm.cs b/cmonitor.install.win/MainForm.cs index 77692a9c..aff29883 100644 --- a/cmonitor.install.win/MainForm.cs +++ b/cmonitor.install.win/MainForm.cs @@ -38,6 +38,7 @@ namespace cmonitor.install.win machineName.Text = config.Client.Name; serverIP.Text = config.Client.Server; + tbViewerPortClient.Text = config.Client.Viewer.ProxyPort.ToString(); shareKey.Text = config.Client.ShareMemoryKey; shareLen.Text = config.Client.ShareMemoryCount.ToString(); @@ -46,6 +47,7 @@ namespace cmonitor.install.win serverPort.Text = config.Server.ServicePort.ToString(); apiPort.Text = config.Server.ApiPort.ToString(); webPort.Text = config.Server.WebPort.ToString(); + tbViewerPortServer.Text = config.Server.Viewer.ProxyPort.ToString(); } private bool loading = false; @@ -162,10 +164,20 @@ namespace cmonitor.install.win MessageBox.Show("web端口必填"); return false; } + if (string.IsNullOrWhiteSpace(tbViewerPortClient.Text) || string.IsNullOrWhiteSpace(tbViewerPortServer.Text)) + { + MessageBox.Show("共享桌面代理端口必填"); + return false; + } config.Client.Server = serverIP.Text; config.Server.WebPort = int.Parse(webPort.Text); config.Server.ApiPort = int.Parse(apiPort.Text); config.Server.ServicePort = int.Parse(serverPort.Text); + + config.Client.Viewer.ProxyPort = int.Parse(tbViewerPortClient.Text); + config.Server.Viewer.ProxyPort = int.Parse(tbViewerPortServer.Text); + + return true; } diff --git a/cmonitor.install.win/MainForm.resx b/cmonitor.install.win/MainForm.resx index f5ac66c4..21b828b3 100644 --- a/cmonitor.install.win/MainForm.resx +++ b/cmonitor.install.win/MainForm.resx @@ -117,433 +117,79 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - 数据数量 - - - 10 - - - 100, 23 + + 106, 76 - - - 11 + + 19 - - 30 + + gbServer - - 7 + + label8 - - label10 - - - label9 - - - screenDelay - - - gbClient - - - 9 - - - True - - - 1 - - - 25 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Windows.Forms.Form, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 418, 420 - - - 100, 23 - - - 7 - - - 68, 17 - - - 服务端端口 - - - 294, 150 - - - shareKey - - - 4 - - - 15 - - - reportDelay - - - $this - - - 294, 102 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - label14 + + shareItemLen label16 - - label3 - - - True - - - cbBlueProtect - - - gbServer - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 106, 177 - - - $this - - - label17 - - - 0 - - - 报告间隔ms - - - 331, 378 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 73, 17 - - - gbClient - - - 37 - - - gbServer - - + 5 - - 211, 253 - - - 7, 17 - - - MainForm - - - gbClient - - - gbServer - - - 66, 17 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - apiPort - - - 21 - - - 100, 23 - - - 截屏缩放比例 - - - gbClient - - - True - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 68, 17 - - - 17 - - - $this - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 27, 280 - - - 0 - - - $this - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Windows.Forms.Button, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - True - - - True - - - 12 - - - label1 - - - 22, 337 - - - 106, 102 - - - 27, 154 - - - 106, 331 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - $this - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 23, 106 - - - MiddleCenter - - - 9 - - - runBtn - - - 36 - - - modeClient - - - 20, 181 - - - 100, 23 - - - 27, 307 - - - label4 - - - 6 - - - 372, 23 - - - 39 - - - 27, 226 - - - label2 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 225, 280 - - - 174, 12 - - - True - - - 106, 49 - - - $this - - - llockIndex - - - 80, 17 - 2 - - 18 - - - 100, 23 - - - 21 - - - 20 - - - 56, 17 - - - 5 - - - 5 - - - 63, 21 - - - 2 - - - 2 - - 3 - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 100, 23 - - - $this - - - $this - - - True - - - 1 - - - $this + 5 $this - - 1 + + System.Windows.Forms.GroupBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - cmonitor安装工具 + + $this - - 每项255长度,0项保留不可用 + + 225, 280 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 100, 23 + + + 100, 23 + + + 114, 372 gbClient - - gbClient + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - True + + machineName - - 客户端 + + + 39 - - modeServer - - + 100, 23 - - $this + + 27, 280 - - 停止运行 - - - True - - - $this - - - $this - - - label11 - - - 80, 17 + + 36 @@ -824,524 +470,131 @@ lbj4VzZ7T6Ce2eKyfeTF92Tj/y+1yov7XH58jUaj0Wg0Gk2v5P8D5M/bzdE8cNIAAAAASUVORK5CYII= - - gbClient - - - 294, 276 - - - 5 - - - 3 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 4 - - - gbServer - - - 100, 23 - - - 13 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 锁屏键下标 - - - 34 - - - 68, 17 - - - 服务端 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 19 - - - 23 - - - 294, 249 - - - 7 - - - label15 - - - gbClient - - - 106, 249 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - questionIndex - - - 227, 306 - - - 2 - - - 0 - - - 31 - - - 32, 80 - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Windows.Forms.CheckBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - True - - - 75, 23 - - + 73, 17 - - 机器名 - - - 201, 372 - - - 20 - - - 29 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - checkStateBtn - - - $this - - - screenScale - - - $this - - - $this - - - 55, 17 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 81, 35 - - - 219, 22 - - - 壁纸键下标 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - serverPort - - - web端口 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - machineName - - - 0 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 28 - - - $this - - - 68, 17 - - - True - - - 8 - - - SAS键下标 - - - wallpaperIndex - - - label6 - - - 106, 303 - - - 1 - - - $this - - - 41, 253 - - - True - - - 22 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 9 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 220, 154 - - - 100, 23 - - - 服务端IP - - - 63, 21 - - - 39 - - - 6 - - - $this - - - 8 - - - installBtn - - - 32 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 223, 80 - - - webPort - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 106, 150 - - - 37 - - - System.Windows.Forms.GroupBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 2 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - label12 - - - $this - - - gbClient - - - 安装自启动 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - serverIP - - - 3 - - - True - - - 40 - - - 81, 35 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 294, 76 - - - System.Windows.Forms.GroupBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 38 - - - 26 - - - label13 - - - 213, 333 - - - 100, 23 - - - 100, 23 - - - 5 - - - True - - - 294, 302 - - - $this - - - gbClient - - - True - - - 156, 21 - - - 106, 276 - - - 100, 23 - - - 33 - - - 100, 23 - - - 4 - - - 12, 48 - - - 截屏间隔ms - - - 219, 49 - - - 25 - - - 每项数据长度 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 检查状态 - - - 16 - - - 键盘键下标 - - - $this - - - System.Windows.Forms.Button, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 38 - - - True - - - shareItemLen - - - 24 - - - $this - - - $this - - - label8 - - - 27 - - - 35 - - - 19 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 44, 17 - - - 114, 372 - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - gbServer - - - 106, 222 - - - keyboardIndex - - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 4 - - - $this - - - 18 - - - gbServer - - - 80, 17 - - - 100, 23 - - - 8 - - - label5 - - - 36, 53 - - - 68, 17 - - - 232, 106 - - - $this - - - System.Windows.Forms.Button, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 共享数据键 - - - 7 - - - System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 6 - 22 - - 100, 23 + + 8 - - 24 + + MiddleCenter + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 106, 303 + + + 20, 181 + + + 32 + + + 22, 337 + + + 1 + + + 68, 17 + + + 93, 80 + + + gbServer + + + 安装自启动 + + + gbClient + + + 2 + + + 219, 49 + + + gbClient + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + modeClient + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 7 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + MainForm + + + $this + + + 25 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + 键盘键下标 + + + screenScale + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + gbClient + + + 56, 17 + + + 41, 253 + + + 服务端IP + + + modeServer + + + 15 + + + 13 + + + 106, 222 label18 @@ -1349,75 +602,864 @@ 100, 23 - + $this - - System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 3 - - - shareLen - - - 3 - - - sasIndex - - - gbClient - - - gbServer - - - 294, 330 - - - 0 - - - 23 - - - 106, 76 - 15, 334 + + 25 + + + 294, 249 + + + gbClient + + + 5 + + + 227, 306 + + + label17 + + + tbViewerPortServer + + + 100, 23 + + + 截屏缩放比例 + + + gbClient + + + 232, 106 + + + 100, 23 + + + 75, 23 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 锁屏键下标 + + + label13 + + + 20 + + + 11 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + label1 + + + label3 + + + $this + + + 1 + + + 106, 102 + + + 100, 23 + + + 18 + + + 8 + + + 7 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + runBtn + + + 9 + + + wallpaperIndex + + + 40 + + + shareLen + + + True + + + serverPort + + + reportDelay + + + 17 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 客户端 + + + gbClient + + + 2 + + + 28 + label7 - - 管理接口端口 + + llockIndex + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + gbClient + + + $this + + + 21 + + + 0 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 37 + + + 6 + + + 81, 35 + + + 6 + + + 壁纸键下标 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 34 + + + $this + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 68, 17 + + + 7 14 - - 1 + + label6 + + + 66, 17 + + + 23, 106 + + + 106, 49 + + + System.Windows.Forms.Button, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 3 + + + 32, 80 + + + cbBlueProtect 6 - - answerIndex + + 37 - - 8 - - + 100, 23 + + gbServer + + + 2 + + + 220, 154 + + + 331, 378 + + + 服务端 + + + 294, 150 + + + 106, 150 + + + 6 + + + $this + + + 服务端端口 + + + 100, 23 + + + gbClient + + + label2 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + label5 + + + True + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + gbServer + + + True + + + label14 + + + True + + + 7, 17 + + + 100, 23 + + + gbServer + + + 5 + + + 100, 23 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 44, 17 + + + 68, 17 + + + 372, 23 + + + 11 + + + 100, 23 + + + 106, 331 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 27, 154 + + + 100, 23 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 201, 372 + + + 37 + + + webPort + + + gbServer + + + 27, 307 + + + 0 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 211, 253 + + + 39 + + + 55, 17 + + + 停止运行 + + + 294, 102 + + + 29 + + + 19 + + + $this + + + 4 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 10 + + + 每项数据长度 + + + 38 + + + 100, 23 + + + 3 + + + 80, 17 + + + $this + + + 223, 80 + + + screenDelay + + + 30 + + + 3 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + gbServer + 56, 17 + + 106, 177 + + + System.Windows.Forms.GroupBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + $this + + + 26 + + + True + + + System.Windows.Forms.Form, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + gbClient + + + 68, 17 + + + 79, 104 + + + 20 + + + 21 + + + 2 + + + installBtn + + + True + + + $this + + + True + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 16 + + + 27 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + 68, 17 + + + 100, 23 + + + 1 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + gbServer + + + 80, 17 + + + True + + + 0 + + + 81, 35 + + + 数据数量 + + + 4 + + + 27, 226 + + + 7 + + + 418, 420 + + + 106, 276 + + + 31 + + + 106, 249 + + + label9 + + + $this + + + 100, 23 + + + web端口 + + + 23 + + + True + + + 63, 21 + + + True + + + System.Windows.Forms.Button, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + sasIndex + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + True + + $this + + + 219, 22 + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 294, 330 + + + gbServer + + + 294, 276 + + + System.Windows.Forms.Button, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 39 + + + 24 + + + $this + + + $this + + + 73, 17 + + + 5 + + + 9 + + + 检查状态 + + + 63, 21 + + + 213, 333 + + + 截屏间隔ms + + + gbClient + + + $this + + + 机器名 + + + 报告间隔ms + + + answerIndex + + + SAS键下标 + + + 294, 302 + + + questionIndex + + + shareKey + + + System.Windows.Forms.CheckBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + cmonitor安装工具 + + + label12 + + + True + + + 100, 23 + + + 6 + + + 8 + + + 100, 23 + + + 12 + + + 23 + + + 100, 23 + + + serverIP + + + $this + + + gbClient + + + 1 + + + 80, 17 + + + True + + + label15 + + + gbClient + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 12, 48 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 35 + + + True + + + 0 + + + tbViewerPortClient + + + keyboardIndex + + + 174, 12 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + label11 + + + System.Windows.Forms.Label, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 共享数据键 + + + 3 + + + $this + + + 10 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 4 + + + $this + + + $this + + + 4 + + + 36, 53 + + + 7 + + + 156, 21 + + + 1 + + + 0 + + + $this + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + checkStateBtn + + + 管理接口端口 + + + 8 + + + 18 + + + System.Windows.Forms.TextBox, System.Windows.Forms, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + apiPort + + + 33 + + + 294, 76 + + + 3 + + + label4 + + + 9 + + + $this + + + 每项255长度,0项保留不可用 + + + 38 + + + label10 + zh-Hans diff --git a/cmonitor.install.win/MainForm.zh-Hans.resx b/cmonitor.install.win/MainForm.zh-Hans.resx index 0408b4f5..5f93e2a4 100644 --- a/cmonitor.install.win/MainForm.zh-Hans.resx +++ b/cmonitor.install.win/MainForm.zh-Hans.resx @@ -131,7 +131,7 @@ 服务端地址 - 17, 85 + 17, 80 56, 17 @@ -140,7 +140,7 @@ 服务端口 - 79, 82 + 79, 77 17, 28 @@ -149,7 +149,7 @@ 79, 24 - 17, 56 + 17, 54 56, 17 @@ -158,7 +158,7 @@ 管理端口 - 79, 53 + 79, 51 105, 45 @@ -167,16 +167,16 @@ 298, 45 - 19, 130 + 19, 150 - 93, 127 + 93, 147 - 14, 104 + 14, 124 - 93, 100 + 93, 120 26, 29 @@ -185,25 +185,25 @@ 93, 25 - 175, 268 + 175, 299 - 88, 268 + 88, 299 - 305, 274 + 305, 305 - 7, 159 + 7, 179 - 93, 156 + 93, 176 12, 72 - 200, 190 + 200, 212 客户端参数 @@ -212,7 +212,7 @@ 219, 73 - 187, 189 + 187, 211 服务端参数 @@ -221,20 +221,63 @@ True - - 174, 12 - 111, 21 - - 39 - 异常关闭则蓝屏 + + 93, 80 + + + 100, 23 + + + 37 + + + + NoControl + + + 11, 83 + + + 80, 17 + + + 38 + + + 共享桌面端口 + + + 79, 104 + + + 100, 23 + + + 39 + + + NoControl + + + -3, 107 + + + 80, 17 + + + 40 + + + 共享桌面端口 + - 418, 315 + 418, 346 diff --git a/cmonitor.viewer.client.win/default.aproj b/cmonitor.viewer.client.win/default.aproj index cbe55881..a865ee59 100644 --- a/cmonitor.viewer.client.win/default.aproj +++ b/cmonitor.viewer.client.win/default.aproj @@ -1,5 +1,5 @@  - + diff --git a/cmonitor.viewer.client.win/dist/cmonitor.viewer.client.win.exe b/cmonitor.viewer.client.win/dist/cmonitor.viewer.client.win.exe index b1a941ceb2326b3e1ccd223604b62058b84dee4e..64a6879b6c7bb2cd202518d0ec20afb94fe61a08 100644 GIT binary patch delta 849 zcmY+DO=uHA6vzLw*_y;=GMmjt8xytBLPf+6EYgDF#uSQ_hTs=P5UuBU2%Z9BwzU$1 z3JFzK#hXx5yyPMQks2|g)LaTudJ%HS$tt8$GzTe80{YT{AH(mx-Pt#9cC1FiY9vat z%uyV6&lQxBxe6<>;+>R|O({&$o*fcZ(j(a>aY|egcR8hOU;C4(d4PtB&L}?Ri2BIC zzvNg5kw5;(kvu}K{^mHfgM5^Gk-td(<+>NG6XdlgUL2~Ex6&emnH~z<$_O~UdZOabT z9~#EH3QqjgwiM|3rD1)F-p8a5>&Mvt4sYaid~#C$O{SpZ`5p>fE9v;!Rk2ys(HExt zWL-zHkG$H_vC{RyXP5oBw@CQ|K?9>M@?^xo6_Y$tn=&vUPygRP(3GxrwR9t!X1x+m zInDU|I1AhT6a3_`saSU_K(2CzJwlAB%)(gIfwR-^m8_g|(=kWUw3L1mo#*nE*vvs# z(CqsYyc&=lz}4uvu}gqF-S%jnX7=(vf52Y5DLnS=I5+L)dEv4b<2=Gbc0JB_vru+3 z&Lv)nkZ2O0L@#f~{Yy*QQ5;5_;~0@E-hjOtG=|)Ro%Mmia$uL?R~#}c?@F|s3>yuy JhkK0+`d_Njwf6u3 delta 842 zcmY+DPiWIn9LK*e>1^xzk~Ga~+f`lB!;m@u4XL1zZXSfOZik5=>@b~&K@mDTu&0Ju zDMOT&AwjRooR~uom4b+?Fi_@I$_^8H=wWCNZm9I&!Dm5#-GdLw=l3P#_kJ(2np0MD zs+?zXG45R{Nf%aXtjvn{(o!KUF~Q%fEN}^W1P26efk)u2rlo`5e&;Gapy@(q6`yh> z{N$fsalGs&w?1&BPLa2Maa;tK@HQC}^K2uRKvO)F5wU)f|?3s4$mP;a12~ z4^_O8$p=d+)(?^Itf@HGwE^F26<<}#+Z!r+1LUqP6{`tyC!Evp=>-+;zSl6)NAA?M zeLHNmG>msO9N*LSHTdJFhTU0ue&?DWyJy({32!g!_~@qmd9I}6*%2ySDeL&s)$!nl zj!=|xv!NpuB6r$4>Rm6)Uk~8HJIb}Nfy*B9>6n2TlRQ?LHE>*<{=aWvOSr3Rq}zoo z>lOH_S;kk#S;QWg;1|!;n03DfEZ0WaV~jBuvtTAe>IjvCXt JT{~@r{s2iEvzh<^ diff --git a/cmonitor.viewer.client.win/main.aardio b/cmonitor.viewer.client.win/main.aardio index db81d2e6..abbcba32 100644 --- a/cmonitor.viewer.client.win/main.aardio +++ b/cmonitor.viewer.client.win/main.aardio @@ -37,7 +37,7 @@ mainForm.connect = function(){ var invitationString = reg.queryValue("viewerConnectStr"); if(string.len(invitationString)>0) { - mainForm.tsc.Connect(invitationString,"snltty","snltty"); + mainForm.tsc.Connect(invitationString,_ARGV[1],_ARGV[1]); }else{ mainForm.connecting = false; } diff --git a/cmonitor.viewer.server.win/MainForm.cs b/cmonitor.viewer.server.win/MainForm.cs index 720ca06d..3da5b8d9 100644 --- a/cmonitor.viewer.server.win/MainForm.cs +++ b/cmonitor.viewer.server.win/MainForm.cs @@ -3,11 +3,8 @@ using cmonitor.viewer.server.win.Properties; using common.libs; using Microsoft.Win32; using RDPCOMAPILib; -using System.Data.SqlTypes; using System.Diagnostics; -using System.Resources; -using System.Text; -using System.Windows.Forms; +using System.Net; using System.Xml; namespace cmonitor.viewer.server.win @@ -29,18 +26,16 @@ namespace cmonitor.viewer.server.win private readonly Hook hook = new Hook(); private readonly ShareMemory shareMemory; - private int shareIndex = 0; - private Mode shareMode = Mode.Client; private const string shareClientExe = "cmonitor.viewer.client.win"; - private byte[] shareKeyBytes = Encoding.UTF8.GetBytes(shareClientExe); - public MainForm(string key, int length, int size, int index, Mode mode) + ParamInfo paramInfo; + + public MainForm(ParamInfo paramInfo) { - InitializeComponent(); + this.paramInfo = paramInfo; - shareMode = mode; - shareIndex = index; - shareMemory = new ShareMemory(key, length, size); + InitializeComponent(); + shareMemory = new ShareMemory(paramInfo.ShareMkey, paramInfo.ShareMLength, paramInfo.ShareItemMLength); shareMemory.InitLocal(); } @@ -51,12 +46,12 @@ namespace cmonitor.viewer.server.win this.ShowInTaskbar = false; this.WindowState = FormWindowState.Minimized; this.Visible = false; + FireWallHelper.Write(Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)); #endif - FireWallHelper.Write(Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)); CheckRunning(); - if (shareMode == Mode.Client) + if (paramInfo.Mode == Mode.Client) { OpenShareClient(); } @@ -68,25 +63,25 @@ namespace cmonitor.viewer.server.win private void CheckRunning() { hook.Close(); - shareMemory.AddAttribute(shareIndex, ShareMemoryAttribute.Running); - shareMemory.RemoveAttribute(shareIndex, ShareMemoryAttribute.Closed); + shareMemory.AddAttribute(paramInfo.ShareIndex, ShareMemoryAttribute.Running); + shareMemory.RemoveAttribute(paramInfo.ShareIndex, ShareMemoryAttribute.Closed); Task.Run(async () => { while (true) { try { - if (shareMemory.ReadAttributeEqual(shareIndex, ShareMemoryAttribute.Closed)) + if (shareMemory.ReadAttributeEqual(paramInfo.ShareIndex, ShareMemoryAttribute.Closed)) { CloseServer(); } else { - shareMemory.IncrementVersion(shareIndex); + shareMemory.IncrementVersion(paramInfo.ShareIndex); } if (Process.GetProcessesByName(shareClientExe).Length == 0) { - shareMemory.AddAttribute(shareIndex, ShareMemoryAttribute.Error); + shareMemory.AddAttribute(paramInfo.ShareIndex, ShareMemoryAttribute.Error); } } catch (Exception) @@ -99,7 +94,7 @@ namespace cmonitor.viewer.server.win } private void CloseServer() { - shareMemory.RemoveAttribute(shareIndex, ShareMemoryAttribute.Running); + shareMemory.RemoveAttribute(paramInfo.ShareIndex, ShareMemoryAttribute.Running); CloseShareClient(); CloseShareDesktop(); Application.ExitThread(); @@ -111,7 +106,7 @@ namespace cmonitor.viewer.server.win { hook.Start((code) => { return true; }); - CommandHelper.Windows(string.Empty, new string[] { $"start {shareClientExe}.exe" }, false); + CommandHelper.Windows(string.Empty, new string[] { $"start {shareClientExe}.exe {paramInfo.GroupName}" }, false); } private void CloseShareClient() { @@ -155,24 +150,43 @@ namespace cmonitor.viewer.server.win { try { - string guid = Guid.NewGuid().ToString(); CloseShareDesktop(); session = new RDPSession(); session.SetDesktopSharedRect(0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); session.OnAttendeeConnected += Session_OnAttendeeConnected; session.Open(); - IRDPSRAPIInvitation invitation = session.Invitations.CreateInvitation(guid, "snltty", "snltty", 1024); + IRDPSRAPIInvitation invitation = session.Invitations.CreateInvitation(null, paramInfo.GroupName, paramInfo.GroupName, 1024); invitationString = invitation.ConnectionString; - /* - XmlDocument xmlDoc = new XmlDocument(); - xmlDoc.LoadXml(invitationString); - XmlElement newLNode = xmlDoc.CreateElement("L"); - newLNode.SetAttribute("P", "12345"); - newLNode.SetAttribute("N", "192.168.1.35"); - xmlDoc.DocumentElement["C"]["T"].AppendChild(newLNode); - Debug.WriteLine(xmlDoc.OuterXml); - */ + if(string.IsNullOrWhiteSpace(paramInfo.ProxyServers) == false) + { + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(invitationString); + + //留给客户端自己替换为自己本地的代理地址 + XmlElement newLNode = xmlDoc.CreateElement("L"); + newLNode.SetAttribute("P", "{port}"); + newLNode.SetAttribute("N", "{ip}"); + xmlDoc.DocumentElement["C"]["T"].AppendChild(newLNode); + + //插入其它代理地址 + foreach (var item in paramInfo.ProxyServers.Split(',')) + { + try + { + IPEndPoint ep = IPEndPoint.Parse(item); + + XmlElement newLNode1 = xmlDoc.CreateElement("L"); + newLNode1.SetAttribute("P", ep.Port.ToString()); + newLNode1.SetAttribute("N", ep.Address.ToString()); + xmlDoc.DocumentElement["C"]["T"].AppendChild(newLNode1); + } + catch (Exception) + { + } + } + invitationString = xmlDoc.OuterXml; + } Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Cmonitor", "viewerConnectStr", invitationString); @@ -182,14 +196,11 @@ namespace cmonitor.viewer.server.win catch (Exception ex) { Debug.WriteLine(ex + ""); - //MessageBox.Show(ex.Message); notifyIcon.Icon = Icon.FromHandle(Resources.logo_share_gray.GetHicon()); notifyIcon.Text = "共享失败"; } }); } - - private void Session_OnAttendeeConnected(object pAttendee) { IRDPSRAPIAttendee attendee = (IRDPSRAPIAttendee)pAttendee; @@ -200,7 +211,7 @@ namespace cmonitor.viewer.server.win try { session?.Close(); - Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Cmonitor", "viewerConnectStr", string.Empty); + //Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Cmonitor", "viewerConnectStr", string.Empty); } catch (Exception) { diff --git a/cmonitor.viewer.server.win/Program.cs b/cmonitor.viewer.server.win/Program.cs index c540f7d3..d09766ad 100644 --- a/cmonitor.viewer.server.win/Program.cs +++ b/cmonitor.viewer.server.win/Program.cs @@ -1,3 +1,6 @@ +using System.Net; +using System.Text.Json; + namespace cmonitor.viewer.server.win { internal static class Program @@ -19,22 +22,26 @@ namespace cmonitor.viewer.server.win MessageBox.Show(b.ExceptionObject.ToString()); }; - string shareMkey = "cmonitor/share"; - int shareMLength = 10; - int shareItemMLength = 1024; - int shareIndex = 5; - Mode mode = Mode.Server; + ParamInfo paramInfo = new ParamInfo(); if (arg.Length > 0) { - shareMkey = arg[0]; - shareMLength = int.Parse(arg[1]); - shareItemMLength = int.Parse(arg[2]); - shareIndex = int.Parse(arg[3]); - mode = (Mode)byte.Parse(arg[4]); + paramInfo = JsonSerializer.Deserialize(arg[0]); } - ApplicationConfiguration.Initialize(); - Application.Run(new MainForm(shareMkey, shareMLength, shareItemMLength, shareIndex, mode)); + Application.Run(new MainForm(paramInfo)); } + + + } + + public sealed class ParamInfo + { + public string ShareMkey { get; set; } = "cmonitor/share"; + public int ShareMLength { get; set; } = 10; + public int ShareItemMLength { get; set; } = 1024; + public int ShareIndex { get; set; } = 5; + public Mode Mode { get; set; } = Mode.Server; + public string GroupName { get; set; } = "snltty"; + public string ProxyServers { get; set; } = "127.0.0.1:1803"; } } \ No newline at end of file diff --git a/cmonitor.web/src/views/device/plugins/viewer/Command.vue b/cmonitor.web/src/views/device/plugins/viewer/Command.vue index 1d57de99..7fc40324 100644 --- a/cmonitor.web/src/views/device/plugins/viewer/Command.vue +++ b/cmonitor.web/src/views/device/plugins/viewer/Command.vue @@ -46,10 +46,13 @@ export default { ElMessage.error('请选择一个共享设备'); return; } + const device = globalState.value.devices.filter(c=>c.MachineName == pluginState.value.viewer.device) + viewerUpdate({ Open: true, Server: pluginState.value.viewer.device, Clients: clients, + ShareId: device.Viewer.id, }).then(() => { pluginState.value.viewer.showShare = false; ElMessage.success('操作成功'); diff --git a/cmonitor.web/src/views/device/plugins/viewer/Screen.vue b/cmonitor.web/src/views/device/plugins/viewer/Screen.vue index 9c93a0f0..35040995 100644 --- a/cmonitor.web/src/views/device/plugins/viewer/Screen.vue +++ b/cmonitor.web/src/views/device/plugins/viewer/Screen.vue @@ -31,7 +31,8 @@ export default { const handleConfirm = () => { viewerUpdate({ open: false, - server: props.data.MachineName + server: props.data.MachineName, + shareid:props.data.Viewer.id }).then(() => { ElMessage.success('已操作!') }).catch(() => { diff --git a/cmonitor.web/src/views/device/plugins/viewer/index.js b/cmonitor.web/src/views/device/plugins/viewer/index.js index b8cc7615..50013610 100644 --- a/cmonitor.web/src/views/device/plugins/viewer/index.js +++ b/cmonitor.web/src/views/device/plugins/viewer/index.js @@ -3,7 +3,8 @@ export default { return { Viewer: { share: false, - mode: 'server' + mode: 'server', + id: '' } }; }, @@ -25,6 +26,7 @@ export default { if (!report.Viewer) return; + item.Viewer.id = report.Viewer.ShareId; item.Viewer.share = report.Viewer.Value; item.Viewer.mode = ['client', 'server'][report.Viewer.Mode]; } diff --git a/cmonitor/Program.cs b/cmonitor/Program.cs index 61a0dc37..fc997cce 100644 --- a/cmonitor/Program.cs +++ b/cmonitor/Program.cs @@ -15,10 +15,10 @@ namespace cmonitor //初始化配置文件 Config config = new Config(); - config.Elevated = args.Any(c => c.Contains("elevated")); + config.Data.Elevated = args.Any(c => c.Contains("elevated")); Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); - StartupTransfer.Init(); + StartupTransfer.Init(config); //依赖注入 ServiceProvider serviceProvider = null; @@ -33,9 +33,6 @@ namespace cmonitor serviceProvider = serviceCollection.BuildServiceProvider(); StartupTransfer.Use(serviceProvider, config, assemblies); - - FireWallHelper.Write(Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)); - GCHelper.FlushMemory(); await Helper.Await(); } @@ -66,6 +63,7 @@ namespace cmonitor { common.libs.winapis.Win32Interop.RelaunchElevated(); } + FireWallHelper.Write(Path.GetFileNameWithoutExtension(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)); #endif } @@ -116,6 +114,6 @@ namespace cmonitor } - + } \ No newline at end of file diff --git a/cmonitor/api/ApiServer.cs b/cmonitor/api/ApiServer.cs index 765f52d6..6ac6bfeb 100644 --- a/cmonitor/api/ApiServer.cs +++ b/cmonitor/api/ApiServer.cs @@ -38,7 +38,11 @@ namespace cmonitor.api Type voidType = typeof(void); IEnumerable types = assemblys.SelectMany(c => c.GetTypes()).Where(c => c.GetInterfaces().Contains(typeof(IApiController))); - + if (config.Data.Common.PluginNames.Length > 0) + { + types = types.Where(c => config.Data.Common.PluginNames.Any(d => c.FullName.Contains(d))); + } + foreach (Type item in types) { object obj = serviceProvider.GetService(item); @@ -76,7 +80,7 @@ namespace cmonitor.api server = new WebSocketServer(); try { - server.Start(System.Net.IPAddress.Any, config.Server.ApiPort); + server.Start(System.Net.IPAddress.Any, config.Data.Server.ApiPort); } catch (Exception ex) { diff --git a/cmonitor/api/ApiStartup.cs b/cmonitor/api/ApiStartup.cs index 47b08dd2..73162dcd 100644 --- a/cmonitor/api/ApiStartup.cs +++ b/cmonitor/api/ApiStartup.cs @@ -27,7 +27,7 @@ namespace cmonitor.api IApiServer clientServer = serviceProvider.GetService(); clientServer.LoadPlugins(assemblies); clientServer.Websocket(); - Logger.Instance.Info($"api listen:{config.Server.ApiPort}"); + Logger.Instance.Info($"api listen:{config.Data.Server.ApiPort}"); } } } diff --git a/cmonitor/client/ClientSignInTransfer.cs b/cmonitor/client/ClientSignInTransfer.cs index 49bb5f5d..3e31a004 100644 --- a/cmonitor/client/ClientSignInTransfer.cs +++ b/cmonitor/client/ClientSignInTransfer.cs @@ -1,4 +1,5 @@ -using cmonitor.config; +using cmonitor.client.args; +using cmonitor.config; using cmonitor.plugins.signIn.messenger; using cmonitor.server; using common.libs; @@ -15,13 +16,15 @@ namespace cmonitor.client private readonly Config config; private readonly TcpServer tcpServer; private readonly MessengerSender messengerSender; + private readonly SignInArgsTransfer signInArgsTransfer; - public ClientSignInTransfer(ClientSignInState clientSignInState, Config config, TcpServer tcpServer, MessengerSender messengerSender) + public ClientSignInTransfer(ClientSignInState clientSignInState, Config config, TcpServer tcpServer, MessengerSender messengerSender, SignInArgsTransfer signInArgsTransfer) { this.clientSignInState = clientSignInState; this.config = config; this.tcpServer = tcpServer; this.messengerSender = messengerSender; + this.signInArgsTransfer = signInArgsTransfer; SignInTask(); tcpServer.OnDisconnected += (hashcode) => @@ -57,45 +60,27 @@ namespace cmonitor.client } private async Task SignIn() { - IPAddress[] ips = new IPAddress[] { config.Client.ServerEP.Address }; + IPEndPoint[] ips = new IPEndPoint[] { config.Data.Client.ServerEP }; if (Logger.Instance.LoggerLevel <= LoggerTypes.DEBUG) Logger.Instance.Info($"get ip:{ips.ToJsonFormat()}"); - if (ips.Length == 0) return; - foreach (IPAddress ip in ips) + foreach (IPEndPoint ip in ips) { try { - IPEndPoint remote = new IPEndPoint(ip, config.Client.ServerEP.Port); - //Logger.Instance.Info($"connect server {remote}"); - Socket socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp); - socket.KeepAlive(); - IAsyncResult result = socket.BeginConnect(remote, null, null); - await Task.Delay(500); - if (result.IsCompleted == false) + if (await ConnectServer(ip) == false) { - socket.SafeClose(); continue; } - clientSignInState.Connection = tcpServer.BindReceive(socket); - MessageResponeInfo resp = await messengerSender.SendReply(new MessageRequestWrap + if (await SignIn2Server() == false) { - Connection = clientSignInState.Connection, - MessengerId = (ushort)SignInMessengerIds.SignIn, - Payload = MemoryPackSerializer.Serialize(new SignInfo - { - MachineName = config.Client.Name, - Version = config.Version - }) - }); - if (resp.Code != MessageResponeCodes.OK || resp.Data.Span.SequenceEqual(Helper.TrueArray) == false) - { - clientSignInState.Connection?.Disponse(); continue; } + GCHelper.FlushMemory(); clientSignInState.PushNetworkEnabled(); + break; } catch (Exception ex) @@ -106,5 +91,42 @@ namespace cmonitor.client } } + private async Task ConnectServer(IPEndPoint remote) + { + Socket socket = new Socket(remote.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + socket.KeepAlive(); + IAsyncResult result = socket.BeginConnect(remote, null, null); + await Task.Delay(500); + if (result.IsCompleted == false) + { + socket.SafeClose(); + return false; + } + clientSignInState.Connection = tcpServer.BindReceive(socket); + return true; + } + private async Task SignIn2Server() + { + Dictionary args = new Dictionary(); + signInArgsTransfer.Invoke(args); + + MessageResponeInfo resp = await messengerSender.SendReply(new MessageRequestWrap + { + Connection = clientSignInState.Connection, + MessengerId = (ushort)SignInMessengerIds.SignIn, + Payload = MemoryPackSerializer.Serialize(new SignInfo + { + MachineName = config.Data.Client.Name, + Version = config.Data.Version, + Args = args, + }) + }); + if (resp.Code != MessageResponeCodes.OK || resp.Data.Span.SequenceEqual(Helper.TrueArray) == false) + { + clientSignInState.Connection?.Disponse(); + return false; + } + return true; + } } } diff --git a/cmonitor/client/ClientStartup.cs b/cmonitor/client/ClientStartup.cs index 3d26ec60..7de3e3b0 100644 --- a/cmonitor/client/ClientStartup.cs +++ b/cmonitor/client/ClientStartup.cs @@ -1,12 +1,12 @@ -using cmonitor.client.runningConfig; -using cmonitor.client.report; +using cmonitor.client.report; using cmonitor.config; using cmonitor.libs; using cmonitor.startup; using common.libs; using Microsoft.Extensions.DependencyInjection; using System.Reflection; -using cmonitor.server.ruleConfig; +using cmonitor.client.args; +using cmonitor.client.running; namespace cmonitor.client { @@ -14,30 +14,24 @@ namespace cmonitor.client { public void AddClient(ServiceCollection serviceCollection, Config config, Assembly[] assemblies) { + serviceCollection.AddSingleton(); + + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); - - if (OperatingSystem.IsWindows()) serviceCollection.AddSingleton(); - else if (OperatingSystem.IsLinux()) serviceCollection.AddSingleton(); - else if (OperatingSystem.IsMacOS()) serviceCollection.AddSingleton(); - //内存共享 - ShareMemory shareMemory = new ShareMemory(config.Client.ShareMemoryKey, config.Client.ShareMemoryCount, config.Client.ShareMemorySize); + ShareMemory shareMemory = new ShareMemory(config.Data.Client.ShareMemoryKey, config.Data.Client.ShareMemoryCount, config.Data.Client.ShareMemorySize); serviceCollection.AddSingleton((a) => shareMemory); } - public void AddServer(ServiceCollection serviceCollection, Config config, Assembly[] assemblies) - { - - } - public void UseClient(ServiceProvider serviceProvider, Config config, Assembly[] assemblies) { Logger.Instance.Info($"start client"); - Logger.Instance.Info($"server ip {config.Client.ServerEP}"); + Logger.Instance.Info($"server ip {config.Data.Client.ServerEP}"); Logger.Instance.Info($"start client report transfer"); ClientReportTransfer report = serviceProvider.GetService(); @@ -53,6 +47,11 @@ namespace cmonitor.client ClientSignInTransfer clientTransfer = serviceProvider.GetService(); } + + public void AddServer(ServiceCollection serviceCollection, Config config, Assembly[] assemblies) + { + + } public void UseServer(ServiceProvider serviceProvider, Config config, Assembly[] assemblies) { } diff --git a/cmonitor/client/args/ISignInArgs.cs b/cmonitor/client/args/ISignInArgs.cs new file mode 100644 index 00000000..975553cb --- /dev/null +++ b/cmonitor/client/args/ISignInArgs.cs @@ -0,0 +1,7 @@ +namespace cmonitor.client.args +{ + public interface ISignInArgs + { + public void Invoke(Dictionary args); + } +} diff --git a/cmonitor/client/args/SignInArgsTransfer.cs b/cmonitor/client/args/SignInArgsTransfer.cs new file mode 100644 index 00000000..83d44a45 --- /dev/null +++ b/cmonitor/client/args/SignInArgsTransfer.cs @@ -0,0 +1,30 @@ +using cmonitor.config; +using common.libs; +using Microsoft.Extensions.DependencyInjection; +using System; + +namespace cmonitor.client.args +{ + public sealed class SignInArgsTransfer + { + private List startups; + + public SignInArgsTransfer(ServiceProvider serviceProvider, Config config) + { + var types = ReflectionHelper.GetInterfaceSchieves(typeof(ISignInArgs)); + if (config.Data.Common.PluginNames.Length > 0) + { + types = types.Where(c => config.Data.Common.PluginNames.Any(d => c.FullName.Contains(d))); + } + startups = types.Select(c => serviceProvider.GetService(c) as ISignInArgs).Where(c=>c != null).ToList(); + } + + public void Invoke(Dictionary args) + { + foreach (var item in startups) + { + item.Invoke(args); + } + } + } +} diff --git a/cmonitor/client/config/Config.cs b/cmonitor/client/config/Config.cs new file mode 100644 index 00000000..2f0bc9a3 --- /dev/null +++ b/cmonitor/client/config/Config.cs @@ -0,0 +1,48 @@ +using common.libs; +using common.libs.extends; +using System.Net; +using System.Text.Json.Serialization; + +namespace cmonitor.config +{ + public sealed partial class ConfigInfo + { + public ConfigClientInfo Client { get; set; } = new ConfigClientInfo(); + } + + public sealed partial class ConfigClientInfo + { + private string server = new IPEndPoint(IPAddress.Loopback, 1802).ToString(); + public string Server + { + get => server; set + { + server = value; + if (string.IsNullOrWhiteSpace(server) == false) + { + string[] arr = server.Split(':'); + int port = arr.Length == 2 ? int.Parse(arr[1]) : 1802; + IPAddress ip = NetworkHelper.GetDomainIp(arr[0]); + ServerEP = new IPEndPoint(ip, port); + } + } + } + [JsonIgnore] + public IPEndPoint ServerEP { get; set; } = new IPEndPoint(IPAddress.Loopback, 1802); + + + private string name = Dns.GetHostName().SubStr(0, 12); + public string Name + { + get => name; set + { + name = value.SubStr(0, 12); + } + } + + public string ShareMemoryKey { get; set; } = "cmonitor/share"; + public int ShareMemoryCount { get; set; } = 100; + public int ShareMemorySize { get; set; } = 1024; + + } +} diff --git a/cmonitor/client/report/ClientReportTransfer.cs b/cmonitor/client/report/ClientReportTransfer.cs index abd937e9..0afc9dc3 100644 --- a/cmonitor/client/report/ClientReportTransfer.cs +++ b/cmonitor/client/report/ClientReportTransfer.cs @@ -34,7 +34,11 @@ namespace cmonitor.client.report public void LoadPlugins(Assembly[] assembs) { IEnumerable types = ReflectionHelper.GetInterfaceSchieves(assembs, typeof(IClientReport)); - reports = types.Select(c => (IClientReport)serviceProvider.GetService(c)).Where(c => string.IsNullOrWhiteSpace(c.Name) == false).ToList(); + if (config.Data.Common.PluginNames.Length > 0) + { + types = types.Where(c => config.Data.Common.PluginNames.Any(d => c.FullName.Contains(d))); + } + reports = types.Select(c => (IClientReport)serviceProvider.GetService(c)).Where(c => c != null).Where(c => string.IsNullOrWhiteSpace(c.Name) == false).ToList(); reportObj = new Dictionary(reports.Count); Logger.Instance.Warning($"load reports:{string.Join(",", reports.Select(c => c.Name))}"); diff --git a/cmonitor/client/running/RunningConfig.cs b/cmonitor/client/running/RunningConfig.cs new file mode 100644 index 00000000..09a4510b --- /dev/null +++ b/cmonitor/client/running/RunningConfig.cs @@ -0,0 +1,104 @@ +using common.libs; +using common.libs.extends; +using System.Net; +using System.Text.Json.Serialization; + +namespace cmonitor.client.running +{ + public sealed class RunningConfig + { + private FileStream fs = null; + private StreamWriter writer = null; + private StreamReader reader = null; + private SemaphoreSlim slim = new SemaphoreSlim(1); + private string configPath { get; } = "./configs/"; + + public RunningConfigInfo Data { get; private set; } = new RunningConfigInfo(); + + + public RunningConfig() + { + if (Directory.Exists(configPath) == false) + { + Directory.CreateDirectory(configPath); + } + string path = Path.Join(configPath, "running.json"); + fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); + reader = new StreamReader(fs, System.Text.Encoding.UTF8); + writer = new StreamWriter(fs, System.Text.Encoding.UTF8); + + Load(); + Save(); + SaveTask(); + } + + private void Load() + { + slim.Wait(); + try + { + fs.Seek(0, SeekOrigin.Begin); + string text = reader.ReadToEnd(); + if (string.IsNullOrWhiteSpace(text)) + { + return; + } + Data = text.DeJson(); + } + catch (Exception ex) + { + Logger.Instance.Error(ex); + } + finally + { + slim.Release(); + } + } + private void SaveTask() + { + Task.Run(async () => + { + while (true) + { + uint updated = Data.Updated; + while (updated > 0) + { + Save(); + updated--; + } + await Task.Delay(1000); + } + }); + } + private void Save() + { + slim.Wait(); + try + { + fs.Seek(0, SeekOrigin.Begin); + fs.SetLength(0); + writer.Write(Data.ToJsonFormat()); + writer.Flush(); + } + catch (Exception ex) + { + Logger.Instance.Error(ex); + } + finally + { + slim.Release(); + } + } + } + + public sealed partial class RunningConfigInfo + { + [JsonIgnore] + public uint Updated { get; set; } = 1; + + public void Update() + { + Updated++; + } + } +} diff --git a/cmonitor/client/runningConfig/IRunningConfig.cs b/cmonitor/client/runningConfig/IRunningConfig.cs deleted file mode 100644 index 65e3b858..00000000 --- a/cmonitor/client/runningConfig/IRunningConfig.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace cmonitor.client.runningConfig -{ - public interface IRunningConfig - { - public T Get(T defaultValue); - public void Set(T data); - } -} diff --git a/cmonitor/client/runningConfig/RunningConfigLinux.cs b/cmonitor/client/runningConfig/RunningConfigLinux.cs deleted file mode 100644 index 6283fa74..00000000 --- a/cmonitor/client/runningConfig/RunningConfigLinux.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace cmonitor.client.runningConfig -{ - public sealed class RunningConfigLinux : IRunningConfig - { - public T Get(T defaultValue) - { - return defaultValue; - } - - public void Set(T data) - { - - } - } -} diff --git a/cmonitor/client/runningConfig/RunningConfigMacOS.cs b/cmonitor/client/runningConfig/RunningConfigMacOS.cs deleted file mode 100644 index f5a51e01..00000000 --- a/cmonitor/client/runningConfig/RunningConfigMacOS.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace cmonitor.client.runningConfig -{ - public sealed class RunningConfigMacOS : IRunningConfig - { - public T Get(T defaultValue) - { - return defaultValue; - } - - public void Set(T data) - { - - } - } -} diff --git a/cmonitor/client/runningConfig/RunningConfigWindows.cs b/cmonitor/client/runningConfig/RunningConfigWindows.cs deleted file mode 100644 index a5beb935..00000000 --- a/cmonitor/client/runningConfig/RunningConfigWindows.cs +++ /dev/null @@ -1,75 +0,0 @@ -using common.libs; -using common.libs.database; -using common.libs.extends; -using System.ComponentModel.DataAnnotations.Schema; -using System.Runtime.Versioning; - -namespace cmonitor.client.runningConfig -{ - [SupportedOSPlatform("windows")] - - public sealed class RunningConfigWindows : IRunningConfig - { - private readonly IConfigDataProvider configDataProvider; - private readonly RunningConfigInfo runningConfigInfo; - - private Dictionary cache = new Dictionary(); - - - public RunningConfigWindows(IConfigDataProvider configDataProvider) - { - this.configDataProvider = configDataProvider; - runningConfigInfo = configDataProvider.Load().Result ?? new RunningConfigInfo(); - } - - public T Get(T defaultValue) - { - try - { - string name = typeof(T).Name; - if (cache.TryGetValue(name, out object cacheValue)) - { - return (T)cacheValue; - } - - if (runningConfigInfo.Running.TryGetValue(name, out string value)) - { - if (string.IsNullOrWhiteSpace(value) == false) - { - T data = value.DeJson(); - cache[name] = data; - return data; - } - } - } - catch (Exception ex) - { - Logger.Instance.Error(ex); - } - return defaultValue; - } - - public void Set(T data) - { - try - { - string name = typeof(T).Name; - string value = data.ToJson(); - runningConfigInfo.Running[name] = value; - cache[name] = data; - - configDataProvider.Save(runningConfigInfo).Wait(); - } - catch (Exception ex) - { - Logger.Instance.Error(ex); - } - } - } - - [Table("running")] - public sealed class RunningConfigInfo - { - public Dictionary Running { get; set; } = new Dictionary(); - } -} diff --git a/cmonitor/client/trigger/ITrigger.cs b/cmonitor/client/trigger/ITrigger.cs deleted file mode 100644 index e0e9306c..00000000 --- a/cmonitor/client/trigger/ITrigger.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace cmonitor.client.trigger -{ - public interface ITrigger - { - public string Name { get; } - public string Desc { get; } - public void Execute(); - } -} diff --git a/cmonitor/config/Config.cs b/cmonitor/config/Config.cs index c60c1b54..9cab672d 100644 --- a/cmonitor/config/Config.cs +++ b/cmonitor/config/Config.cs @@ -7,62 +7,30 @@ namespace cmonitor.config { public sealed class Config { - FileStream fs = null; - StreamWriter writer = null; - StreamReader reader = null; - SemaphoreSlim slim = new SemaphoreSlim(1); + private FileStream fs = null; + private StreamWriter writer = null; + private StreamReader reader = null; + private SemaphoreSlim slim = new SemaphoreSlim(1); + private string configPath = "./configs/"; + + public ConfigInfo Data { get; private set; } = new ConfigInfo(); + public Config() { - if (Directory.Exists(ConfigPath) == false) + if (Directory.Exists(configPath) == false) { - Directory.CreateDirectory(ConfigPath); + Directory.CreateDirectory(configPath); } - string path = Path.Join(ConfigPath, "config.json"); + string path = Path.Join(configPath, "config.json"); fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read); reader = new StreamReader(fs, System.Text.Encoding.UTF8); writer = new StreamWriter(fs, System.Text.Encoding.UTF8); Load(); - } - - public ConfigCommonInfo Common { get; set; } = new ConfigCommonInfo(); - public ConfigClientInfo Client { get; set; } = new ConfigClientInfo(); - public ConfigServerInfo Server { get; set; } = new ConfigServerInfo(); - - public string ConfigPath { get; } = "./configs/"; - - - private Dictionary> JsonDic = new Dictionary>(); - public T Get(T defaultValue) - { - return Get(typeof(T).Name, defaultValue); - } - public T Get(string name, T defaultValue) - { - if (JsonDic.ContainsKey(name)) - { - return JsonDic[name].ToJson().DeJson(); - } - return defaultValue; - } - public void Set(T value) - { - Set(typeof(T).Name, value); - } - public void Set(string name, T value) - { - JsonDic[name] = value.ToJson().DeJson>(); Save(); } private void Load() - { - InitFileConfig(); - ReadJson(); - Logger.Instance.Debug($"config:{JsonDic.ToJson()}"); - Save(); - } - private void InitFileConfig() { slim.Wait(); try @@ -73,7 +41,7 @@ namespace cmonitor.config { return; } - JsonDic = text.DeJson>>(); + Data = text.DeJson(); } catch (Exception ex) { @@ -83,36 +51,17 @@ namespace cmonitor.config { slim.Release(); } - } - private void ReadJson() - { - if (JsonDic.TryGetValue("Client", out Dictionary elClient)) - { - Client = elClient.ToJson().DeJson(); - } - - if (JsonDic.TryGetValue("Server", out Dictionary elServer)) - { - Server = elServer.ToJson().DeJson(); - } - if (JsonDic.TryGetValue("Common", out Dictionary elCommon)) - { - Common = elCommon.ToJson().DeJson(); - } + } - public void Save() + private void Save() { slim.Wait(); try { - JsonDic["Client"] = Client.ToJson().DeJson>(); - JsonDic["Server"] = Server.ToJson().DeJson>(); - JsonDic["Common"] = Common.ToJson().DeJson>(); - fs.Seek(0, SeekOrigin.Begin); fs.SetLength(0); - writer.Write(JsonDic.ToJsonFormat()); + writer.Write(Data.ToJsonFormat()); writer.Flush(); } catch (Exception ex) @@ -125,59 +74,32 @@ namespace cmonitor.config } } + + } + + public sealed partial class ConfigInfo + { + public ConfigCommonInfo Common { get; set; } = new ConfigCommonInfo(); + [JsonIgnore] public string Version { get; set; } = "1.0.0.1"; [JsonIgnore] public bool Elevated { get; set; } } - public sealed class ConfigCommonInfo + public sealed partial class ConfigCommonInfo { public string[] Modes { get; set; } = new string[] { "client", "server" }; - public bool BlueProtect { get; set; } - } - public sealed class ConfigClientInfo - { - private string server = new IPEndPoint(IPAddress.Loopback, 1802).ToString(); - public string Server + + public string[] plugins = Array.Empty(); + public string[] Plugins { - get => server; set + get => plugins; set { - server = value; - if (string.IsNullOrWhiteSpace(server) == false) - { - string[] arr = server.Split(':'); - int port = arr.Length == 2 ? int.Parse(arr[1]) : 1802; - IPAddress ip = NetworkHelper.GetDomainIp(arr[0]); - ServerEP = new IPEndPoint(ip, port); - } + PluginNames = value.Select(c => $"plugins.{c}.").ToArray(); } } - [JsonIgnore] - public IPEndPoint ServerEP { get; set; } = new IPEndPoint(IPAddress.Loopback, 1802); - - private string name = Dns.GetHostName().SubStr(0, 12); - public string Name - { - get => name; set - { - name = value.SubStr(0, 12); - } - } - public string ShareMemoryKey { get; set; } = "cmonitor/share"; - public int ShareMemoryCount { get; set; } = 100; - public int ShareMemorySize { get; set; } = 1024; - + public string[] PluginNames = Array.Empty(); } - public sealed class ConfigServerInfo - { - public int WebPort { get; set; } = 1800; - public string WebRoot { get; set; } = "./web/"; - public int ApiPort { get; set; } = 1801; - public int ServicePort { get; set; } = 1802; - - } - - } diff --git a/cmonitor/plugins/active/report/ActiveWindowReport.cs b/cmonitor/plugins/active/report/ActiveWindowReport.cs index f7b64f24..f58b0fa6 100644 --- a/cmonitor/plugins/active/report/ActiveWindowReport.cs +++ b/cmonitor/plugins/active/report/ActiveWindowReport.cs @@ -1,5 +1,4 @@ using cmonitor.client; -using cmonitor.client.runningConfig; using cmonitor.client.report; using cmonitor.config; using common.libs; @@ -7,6 +6,8 @@ using MemoryPack; using System.Collections.Concurrent; using System.Text.RegularExpressions; using System.Diagnostics; +using cmonitor.client.running; +using cmonitor.plugins.active.report; namespace cmonitor.plugins.active.report { @@ -14,22 +15,20 @@ namespace cmonitor.plugins.active.report { public string Name => "ActiveWindow"; - private readonly IRunningConfig clientConfig; + private readonly RunningConfig runningConfig; private readonly IActiveWindow activeWindow; private readonly ActiveWindowTimeManager activeWindowTimeManager = new ActiveWindowTimeManager(); private ActiveReportInfo report = new ActiveReportInfo(); - private ActiveDisallowInfo activeConfig; - public ActiveWindowReport(Config config, IRunningConfig clientConfig, IActiveWindow activeWindow, ClientSignInState clientSignInState) + public ActiveWindowReport(Config config, RunningConfig runningConfig, IActiveWindow activeWindow, ClientSignInState clientSignInState) { - this.clientConfig = clientConfig; + this.runningConfig = runningConfig; this.activeWindow = activeWindow; DisallowRun(Array.Empty()); - activeConfig = clientConfig.Get(new ActiveDisallowInfo { }); clientSignInState.NetworkFirstEnabledHandle += () => { - DisallowRun(activeConfig.FileNames); + DisallowRun(runningConfig.Data.Active.FileNames); Loop(); }; } @@ -38,8 +37,8 @@ namespace cmonitor.plugins.active.report public object GetReports(ReportType reportType) { ticks = DateTime.UtcNow.Ticks; - report.Ids1 = activeConfig.Ids1; - report.Ids2 = activeConfig.Ids2; + report.Ids1 = runningConfig.Data.Active.Ids1; + report.Ids2 = runningConfig.Data.Active.Ids2; if (reportType == ReportType.Full || report.Updated()) { return report; @@ -50,8 +49,7 @@ namespace cmonitor.plugins.active.report public void DisallowRun(ActiveDisallowInfo activeDisallowInfo) { - activeConfig = activeDisallowInfo; - clientConfig.Set(activeConfig); + runningConfig.Data.Active = activeDisallowInfo; report.DisallowCount = activeDisallowInfo.FileNames.Length; activeWindow.DisallowRun(activeDisallowInfo.FileNames); } @@ -131,13 +129,13 @@ namespace cmonitor.plugins.active.report private bool Disallow(ActiveWindowInfo window) { - if (activeConfig.FileNames.Length > 0) + if (runningConfig.Data.Active.FileNames.Length > 0) { try { ReadOnlySpan filenameSpan = window.FileName.AsSpan(); uint pid = window.Pid; - foreach (string item in activeConfig.FileNames) + foreach (string item in runningConfig.Data.Active.FileNames) { ReadOnlySpan nameSpan = item.AsSpan(); bool result = item == window.Title @@ -257,6 +255,7 @@ namespace cmonitor.plugins.active.report public DateTime StartTime { get; set; } = DateTime.Now; public List List { get; set; } = new List(); } + [MemoryPackable] public sealed partial class ActiveWindowTimeInfo { @@ -267,3 +266,19 @@ namespace cmonitor.plugins.active.report public Dictionary Titles { get; set; } } } + +namespace cmonitor.client.running +{ + public sealed partial class RunningConfigInfo + { + private ActiveDisallowInfo active = new ActiveDisallowInfo(); + public ActiveDisallowInfo Active + { + get => active; set + { + Updated++; + active = value; + } + } + } +} diff --git a/cmonitor/plugins/active/report/ActiveWindowWindows.cs b/cmonitor/plugins/active/report/ActiveWindowWindows.cs index d6f19715..b33a2d7a 100644 --- a/cmonitor/plugins/active/report/ActiveWindowWindows.cs +++ b/cmonitor/plugins/active/report/ActiveWindowWindows.cs @@ -212,10 +212,12 @@ namespace cmonitor.plugins.active.report private void InitDriver() { - AppDomain.CurrentDomain.ProcessExit += (sender, e) => { + AppDomain.CurrentDomain.ProcessExit += (sender, e) => + { CommandHelper.Windows(string.Empty, new string[] { "sc stop cmonitor.killer & sc delete cmonitor.killer" }, true); }; - Console.CancelKeyPress += (sender, e) => { + Console.CancelKeyPress += (sender, e) => + { CommandHelper.Windows(string.Empty, new string[] { "sc stop cmonitor.killer & sc delete cmonitor.killer" }, true); }; Task.Run(() => @@ -228,7 +230,15 @@ namespace cmonitor.plugins.active.report Logger.Instance.Info($"killer starting"); string sourcePath = Path.GetFullPath(Path.Join("./", "killer.sys")); - string distPath = Path.GetFullPath(Path.Join("./", "killer-temp.sys")); + string distPath = $"{Environment.SystemDirectory}\\drivers\\killer.sys"; + + try + { + File.Delete("killer-temp.sys"); + } + catch (Exception) + { + } try { File.Copy(sourcePath, distPath, true); diff --git a/cmonitor/plugins/hijack/HijackStartup.cs b/cmonitor/plugins/hijack/HijackStartup.cs index 1e34e88a..f6c4277b 100644 --- a/cmonitor/plugins/hijack/HijackStartup.cs +++ b/cmonitor/plugins/hijack/HijackStartup.cs @@ -11,7 +11,6 @@ namespace cmonitor.plugins.hijack { public void AddClient(ServiceCollection serviceCollection, Config config, Assembly[] assemblies) { - serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); if (OperatingSystem.IsWindows()) serviceCollection.AddSingleton(); else if (OperatingSystem.IsLinux()) serviceCollection.AddSingleton(); diff --git a/cmonitor/plugins/hijack/report/HijackConfig.cs b/cmonitor/plugins/hijack/report/HijackConfig.cs index 51540c2a..f3b92717 100644 --- a/cmonitor/plugins/hijack/report/HijackConfig.cs +++ b/cmonitor/plugins/hijack/report/HijackConfig.cs @@ -1,4 +1,6 @@ -namespace cmonitor.plugins.hijack.report +using cmonitor.plugins.hijack.report; + +namespace cmonitor.plugins.hijack.report { public sealed class HijackConfig { @@ -42,3 +44,19 @@ } } + +namespace cmonitor.client.running +{ + public sealed partial class RunningConfigInfo + { + private HijackConfig hijack = new HijackConfig(); + public HijackConfig Hijack + { + get => hijack; set + { + Updated++; + hijack = value; + } + } + } +} diff --git a/cmonitor/plugins/hijack/report/HijackReport.cs b/cmonitor/plugins/hijack/report/HijackReport.cs index 07596f99..911a3395 100644 --- a/cmonitor/plugins/hijack/report/HijackReport.cs +++ b/cmonitor/plugins/hijack/report/HijackReport.cs @@ -1,9 +1,9 @@ using cmonitor.client; -using cmonitor.client.runningConfig; using cmonitor.client.report; using cmonitor.config; using common.libs; using MemoryPack; +using cmonitor.client.running; namespace cmonitor.plugins.hijack.report { @@ -11,19 +11,17 @@ namespace cmonitor.plugins.hijack.report { public string Name => "Hijack"; - private readonly HijackConfig hijackConfig; - private readonly IRunningConfig clientConfig; + private readonly RunningConfig runningConfig; private readonly IHijack hijack; private readonly ClientSignInState clientSignInState; private HijackReportInfo hijackReportInfo = new HijackReportInfo(); private long ticks = DateTime.UtcNow.Ticks; - public HijackReport(IHijack hijack, HijackConfig hijackConfig, IRunningConfig clientConfig, Config config, ClientSignInState clientSignInState) + public HijackReport(IHijack hijack, RunningConfig runningConfig, Config config, ClientSignInState clientSignInState) { this.hijack = hijack; - this.hijackConfig = hijackConfig; - this.clientConfig = clientConfig; + this.runningConfig = runningConfig; this.clientSignInState = clientSignInState; Init(); } @@ -33,18 +31,6 @@ namespace cmonitor.plugins.hijack.report try { clientSignInState.NetworkFirstEnabledHandle += hijack.Start; - - HijackConfig config = clientConfig.Get(new HijackConfig { }); - - hijackConfig.DeniedProcesss = config.DeniedProcesss; - hijackConfig.AllowProcesss = config.AllowProcesss; - hijackConfig.DeniedDomains = config.DeniedDomains; - hijackConfig.AllowDomains = config.AllowDomains; - hijackConfig.DeniedIPs = config.DeniedIPs; - hijackConfig.AllowIPs = config.AllowIPs; - hijackConfig.DomainKill = config.DomainKill; - hijackConfig.HijackIds1 = config.HijackIds1; - hijackConfig.HijackIds2 = config.HijackIds2; UpdateRules(); } catch (Exception ex) @@ -55,26 +41,26 @@ namespace cmonitor.plugins.hijack.report public void Update(HijackSetRuleInfo info) { - hijackConfig.AllowDomains = info.Rules.AllowDomains; - hijackConfig.DeniedDomains = info.Rules.DeniedDomains; - hijackConfig.AllowProcesss = info.Rules.AllowProcesss; - hijackConfig.DeniedProcesss = info.Rules.DeniedProcesss; - hijackConfig.AllowIPs = info.Rules.AllowIPs; - hijackConfig.DeniedIPs = info.Rules.DeniedIPs; - hijackConfig.DomainKill = info.Rules.DomainKill; - hijackConfig.HijackIds1 = info.Ids1; - hijackConfig.HijackIds2 = info.Ids2; + runningConfig.Data.Hijack.AllowDomains = info.Rules.AllowDomains; + runningConfig.Data.Hijack.DeniedDomains = info.Rules.DeniedDomains; + runningConfig.Data.Hijack.AllowProcesss = info.Rules.AllowProcesss; + runningConfig.Data.Hijack.DeniedProcesss = info.Rules.DeniedProcesss; + runningConfig.Data.Hijack.AllowIPs = info.Rules.AllowIPs; + runningConfig.Data.Hijack.DeniedIPs = info.Rules.DeniedIPs; + runningConfig.Data.Hijack.DomainKill = info.Rules.DomainKill; + runningConfig.Data.Hijack.HijackIds1 = info.Ids1; + runningConfig.Data.Hijack.HijackIds2 = info.Ids2; - clientConfig.Set(hijackConfig); + runningConfig.Data.Update(); UpdateRules(); } private void UpdateRules() { - hijack.SetProcess(hijackConfig.AllowProcesss, hijackConfig.DeniedProcesss); - hijack.SetDomain(hijackConfig.AllowDomains, hijackConfig.DeniedDomains, hijackConfig.DomainKill); - hijack.SetIP(hijackConfig.AllowIPs, hijackConfig.DeniedIPs); + hijack.SetProcess(runningConfig.Data.Hijack.AllowProcesss, runningConfig.Data.Hijack.DeniedProcesss); + hijack.SetDomain(runningConfig.Data.Hijack.AllowDomains, runningConfig.Data.Hijack.DeniedDomains, runningConfig.Data.Hijack.DomainKill); + hijack.SetIP(runningConfig.Data.Hijack.AllowIPs, runningConfig.Data.Hijack.DeniedIPs); hijack.UpdateRules(); } @@ -82,10 +68,10 @@ namespace cmonitor.plugins.hijack.report { hijackReportInfo.Upload = hijack.UdpSend + hijack.TcpSend; hijackReportInfo.Download = hijack.TcpReceive + hijack.UdpReceive; - hijackReportInfo.Count = (ulong)(hijackConfig.AllowIPs.Length + hijackConfig.DeniedIPs.Length + hijackConfig.AllowDomains.Length + hijackConfig.DeniedDomains.Length + hijackConfig.AllowProcesss.Length + hijackConfig.DeniedProcesss.Length); - hijackReportInfo.Ids1 = hijackConfig.HijackIds1; - hijackReportInfo.Ids2 = hijackConfig.HijackIds2; - hijackReportInfo.DomainKill = hijackConfig.DomainKill; + hijackReportInfo.Count = (ulong)(runningConfig.Data.Hijack.AllowIPs.Length + runningConfig.Data.Hijack.DeniedIPs.Length + runningConfig.Data.Hijack.AllowDomains.Length + runningConfig.Data.Hijack.DeniedDomains.Length + runningConfig.Data.Hijack.AllowProcesss.Length + runningConfig.Data.Hijack.DeniedProcesss.Length); + hijackReportInfo.Ids1 = runningConfig.Data.Hijack.HijackIds1; + hijackReportInfo.Ids2 = runningConfig.Data.Hijack.HijackIds2; + hijackReportInfo.DomainKill = runningConfig.Data.Hijack.DomainKill; long _ticks = DateTime.UtcNow.Ticks; if (((_ticks - ticks) / TimeSpan.TicksPerMillisecond >= 300 && hijackReportInfo.Updated()) || reportType == ReportType.Full) @@ -97,7 +83,7 @@ namespace cmonitor.plugins.hijack.report } } - public sealed class HijackReportInfo:ReportInfo + public sealed class HijackReportInfo : ReportInfo { public ulong Upload { get; set; } public ulong Download { get; set; } diff --git a/cmonitor/plugins/keyboard/report/KeyboardWindows.cs b/cmonitor/plugins/keyboard/report/KeyboardWindows.cs index 110da44d..5ceb6fd7 100644 --- a/cmonitor/plugins/keyboard/report/KeyboardWindows.cs +++ b/cmonitor/plugins/keyboard/report/KeyboardWindows.cs @@ -77,7 +77,7 @@ namespace cmonitor.plugins.keyboard.report if (inputActions.TryDequeue(out var action)) { - if (config.Elevated == true && !Win32Interop.SwitchToInputDesktop()) + if (config.Data.Elevated == true && !Win32Interop.SwitchToInputDesktop()) { uint code = Kernel32.GetLastError(); tks.Cancel(); diff --git a/cmonitor/plugins/llock/report/LLockReport.cs b/cmonitor/plugins/llock/report/LLockReport.cs index 3b32d47b..24c7804f 100644 --- a/cmonitor/plugins/llock/report/LLockReport.cs +++ b/cmonitor/plugins/llock/report/LLockReport.cs @@ -1,9 +1,10 @@ using cmonitor.client; -using cmonitor.client.runningConfig; using cmonitor.client.report; using cmonitor.config; using cmonitor.libs; using common.libs; +using cmonitor.client.running; +using cmonitor.plugins.llock.report; namespace cmonitor.plugins.llock.report { @@ -13,21 +14,19 @@ namespace cmonitor.plugins.llock.report private LLockReportInfo report = new LLockReportInfo(); - private readonly IRunningConfig clientConfig; + private readonly RunningConfig runningConfig; private readonly ILLock lLock; private readonly ShareMemory shareMemory; - private readonly LLockConfigInfo lLockConfigInfo = new LLockConfigInfo(); - public LLockReport(Config config, IRunningConfig clientConfig, ILLock lLock, ShareMemory shareMemory, ClientSignInState clientSignInState) + public LLockReport(Config config, RunningConfig runningConfig, ILLock lLock, ShareMemory shareMemory, ClientSignInState clientSignInState) { - this.clientConfig = clientConfig; + this.runningConfig = runningConfig; this.lLock = lLock; this.shareMemory = shareMemory; - lLockConfigInfo = clientConfig.Get(new LLockConfigInfo { }); clientSignInState.NetworkFirstEnabledHandle += () => { - LockScreen(lLockConfigInfo.Open); + LockScreen(runningConfig.Data.LLock.Open); WallpaperTask(); }; } @@ -44,10 +43,10 @@ namespace cmonitor.plugins.llock.report public void LockScreen(bool open) { - lLockConfigInfo.Open = open; + runningConfig.Data.LLock.Open = open; + runningConfig.Data.Update(); Task.Run(async () => { - clientConfig.Set(lLockConfigInfo); shareMemory.AddAttribute((int)ShareMemoryIndexs.LLock, ShareMemoryAttribute.Closed); await Task.Delay(100); lLock.Set(open); @@ -72,11 +71,11 @@ namespace cmonitor.plugins.llock.report { while (true) { - if (lLockConfigInfo.Open) + if (runningConfig.Data.LLock.Open) { if (Running() == false) { - LockScreen(lLockConfigInfo.Open); + LockScreen(runningConfig.Data.LLock.Open); } } await Task.Delay(5000); @@ -102,3 +101,21 @@ namespace cmonitor.plugins.llock.report } } + +namespace cmonitor.client.running +{ + public sealed partial class RunningConfigInfo + { + private LLockConfigInfo llock = new LLockConfigInfo(); + public LLockConfigInfo LLock + { + get => llock; set + { + Updated++; + llock = value; + } + } + } +} + + diff --git a/cmonitor/plugins/llock/report/LLockWindows.cs b/cmonitor/plugins/llock/report/LLockWindows.cs index 8d9ef9a5..c3493ce6 100644 --- a/cmonitor/plugins/llock/report/LLockWindows.cs +++ b/cmonitor/plugins/llock/report/LLockWindows.cs @@ -17,7 +17,7 @@ namespace cmonitor.plugins.llock.report if (value) { CommandHelper.Windows(string.Empty, new string[] { - $"start cmonitor.llock.win.exe {config.Client.ShareMemoryKey} {config.Client.ShareMemoryCount} {config.Client.ShareMemorySize} {(int)ShareMemoryIndexs.LLock}" + $"start cmonitor.llock.win.exe {config.Data.Client.ShareMemoryKey} {config.Data.Client.ShareMemoryCount} {config.Data.Client.ShareMemorySize} {(int)ShareMemoryIndexs.LLock}" },false); } } diff --git a/cmonitor/plugins/modes/ModesApiController.cs b/cmonitor/plugins/modes/ModesApiController.cs index aedcad06..2e880bb9 100644 --- a/cmonitor/plugins/modes/ModesApiController.cs +++ b/cmonitor/plugins/modes/ModesApiController.cs @@ -1,6 +1,4 @@ using cmonitor.api; -using cmonitor.plugins.signIn.messenger; -using cmonitor.server; using cmonitor.server.ruleConfig; using common.libs.extends; diff --git a/cmonitor/plugins/screen/messenger/ScreenMessenger.cs b/cmonitor/plugins/screen/messenger/ScreenMessenger.cs index 3131ce07..72a26aa3 100644 --- a/cmonitor/plugins/screen/messenger/ScreenMessenger.cs +++ b/cmonitor/plugins/screen/messenger/ScreenMessenger.cs @@ -63,7 +63,7 @@ namespace cmonitor.plugins.screen.messenger { if (signCaching.Get(connection.Name, out SignCacheInfo cache)) { - if (cache.Version == config.Version) + if (cache.Version == config.Data.Version) { clientServer.Notify("/notify/report/screen/full", connection.Name, connection.ReceiveRequestWrap.Payload); } diff --git a/cmonitor/plugins/screen/report/ScreenWindowsDxgi.cs b/cmonitor/plugins/screen/report/ScreenWindowsDxgi.cs index ba986605..425bd7c1 100644 --- a/cmonitor/plugins/screen/report/ScreenWindowsDxgi.cs +++ b/cmonitor/plugins/screen/report/ScreenWindowsDxgi.cs @@ -245,7 +245,7 @@ namespace cmonitor.plugins.screen.report { try { - if (config.Elevated) + if (config.Data.Elevated) { Win32Interop.SwitchToInputDesktop(); } @@ -372,7 +372,7 @@ namespace cmonitor.plugins.screen.report bool result = false; try { - if (config.Elevated == true && !Win32Interop.SwitchToInputDesktop()) + if (config.Data.Elevated == true && !Win32Interop.SwitchToInputDesktop()) { var errCode = Marshal.GetLastWin32Error(); if (Logger.Instance.LoggerLevel <= LoggerTypes.DEBUG) diff --git a/cmonitor/plugins/screen/report/ScreenWindowsGdi.cs b/cmonitor/plugins/screen/report/ScreenWindowsGdi.cs index 611d6272..7b10ba4c 100644 --- a/cmonitor/plugins/screen/report/ScreenWindowsGdi.cs +++ b/cmonitor/plugins/screen/report/ScreenWindowsGdi.cs @@ -38,7 +38,7 @@ namespace cmonitor.plugins.screen.report { try { - if (config.Elevated == true && !Win32Interop.SwitchToInputDesktop()) + if (config.Data.Elevated == true && !Win32Interop.SwitchToInputDesktop()) { var errCode = Marshal.GetLastWin32Error(); if (Logger.Instance.LoggerLevel <= LoggerTypes.DEBUG) diff --git a/cmonitor/plugins/signIn/messenger/SignCaching.cs b/cmonitor/plugins/signIn/messenger/SignCaching.cs index 2be2e34d..5ddc4729 100644 --- a/cmonitor/plugins/signIn/messenger/SignCaching.cs +++ b/cmonitor/plugins/signIn/messenger/SignCaching.cs @@ -31,7 +31,8 @@ namespace cmonitor.plugins.signIn.messenger { Connection = connection, MachineName = signInfo.MachineName, - Version = signInfo.Version + Version = signInfo.Version, + Args = signInfo.Args, }; config.Clients.TryAdd(signInfo.MachineName, cache1); changed = true; @@ -86,6 +87,8 @@ namespace cmonitor.plugins.signIn.messenger public string MachineName { get; set; } public string Version { get; set; } = "1.0.0.0"; + public Dictionary Args { get; set; } = new Dictionary(); + [JsonIgnore] public int ReportFlag = 1; [JsonIgnore] @@ -115,7 +118,6 @@ namespace cmonitor.plugins.signIn.messenger ScreenTime = Environment.TickCount; } - public bool Connected { get @@ -130,7 +132,9 @@ namespace cmonitor.plugins.signIn.messenger [MemoryPackable] public sealed partial class SignInfo { - public string MachineName { get; set; } - public string Version { get; set; } + public string MachineName { get; set; } = string.Empty; + public string Version { get; set; } = string.Empty; + + public Dictionary Args { get; set; } = new Dictionary(); } } diff --git a/cmonitor/plugins/signIn/messenger/SignInMessenger.cs b/cmonitor/plugins/signIn/messenger/SignInMessenger.cs index 0dbdf95c..d7408463 100644 --- a/cmonitor/plugins/signIn/messenger/SignInMessenger.cs +++ b/cmonitor/plugins/signIn/messenger/SignInMessenger.cs @@ -19,7 +19,7 @@ namespace cmonitor.plugins.signIn.messenger public void SignIn(IConnection connection) { SignInfo info = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); - if (info.Version == config.Version) + if (info.Version == config.Data.Version) { signCaching.Sign(connection, info); connection.Write(Helper.TrueArray); diff --git a/cmonitor/plugins/snatch/report/SnatchWindows.cs b/cmonitor/plugins/snatch/report/SnatchWindows.cs index 5b514b40..a072446d 100644 --- a/cmonitor/plugins/snatch/report/SnatchWindows.cs +++ b/cmonitor/plugins/snatch/report/SnatchWindows.cs @@ -15,7 +15,7 @@ namespace cmonitor.plugins.snatch.report public void StartUp(SnatchQuestionInfo snatchQuestionInfo) { CommandHelper.Windows(string.Empty, new string[] { - $"start cmonitor.snatch.win.exe {config.Client.ShareMemoryKey} {config.Client.ShareMemoryCount} {config.Client.ShareMemorySize} {(int)ShareMemoryIndexs.SnatchQuestion} {(int)ShareMemoryIndexs.SnatchAnswer}" + $"start cmonitor.snatch.win.exe {config.Data.Client.ShareMemoryKey} {config.Data.Client.ShareMemoryCount} {config.Data.Client.ShareMemorySize} {(int)ShareMemoryIndexs.SnatchQuestion} {(int)ShareMemoryIndexs.SnatchAnswer}" },false); } } diff --git a/cmonitor/plugins/system/report/SystemWindows.cs b/cmonitor/plugins/system/report/SystemWindows.cs index b54ff53f..979ce993 100644 --- a/cmonitor/plugins/system/report/SystemWindows.cs +++ b/cmonitor/plugins/system/report/SystemWindows.cs @@ -115,7 +115,7 @@ namespace cmonitor.plugins.system.report { while (actions.TryDequeue(out Action action)) { - if (config.Elevated) + if (config.Data.Elevated) { Win32Interop.SwitchToInputDesktop(); } diff --git a/cmonitor/plugins/viewer/RDP桌面共享流程.drawio b/cmonitor/plugins/viewer/RDP桌面共享流程.drawio new file mode 100644 index 00000000..119a699a --- /dev/null +++ b/cmonitor/plugins/viewer/RDP桌面共享流程.drawio @@ -0,0 +1,552 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cmonitor/plugins/viewer/ViewerApiController.cs b/cmonitor/plugins/viewer/ViewerApiController.cs index f03c87d7..259913c5 100644 --- a/cmonitor/plugins/viewer/ViewerApiController.cs +++ b/cmonitor/plugins/viewer/ViewerApiController.cs @@ -1,6 +1,7 @@ using cmonitor.api; using cmonitor.plugins.signIn.messenger; using cmonitor.plugins.viewer.messenger; +using cmonitor.plugins.viewer.proxy; using cmonitor.plugins.viewer.report; using cmonitor.server; using common.libs.extends; @@ -12,28 +13,39 @@ namespace cmonitor.plugins.viewer { private readonly MessengerSender messengerSender; private readonly SignCaching signCaching; - public ViewerApiController(MessengerSender messengerSender, SignCaching signCaching) + private readonly ViewerProxyCaching viewerProxyCaching; + + public ViewerApiController(MessengerSender messengerSender, SignCaching signCaching, ViewerProxyCaching viewerProxyCaching) { this.messengerSender = messengerSender; this.signCaching = signCaching; + this.viewerProxyCaching = viewerProxyCaching; } public bool Update(ApiControllerParamsInfo param) { ViewerUpdateParamInfo viewer = param.Content.DeJson(); - //去掉服务端 + //去掉服务端, var list = viewer.Clients.ToList(); list.Remove(viewer.Server); viewer.Clients = list.ToArray(); + viewerProxyCaching.Remove(viewer.ShareId); if (signCaching.Get(viewer.Server, out SignCacheInfo cache) && cache.Connected) { - byte[] serverBytes = MemoryPackSerializer.Serialize(new ViewerConfigInfo + ViewerRunningConfigInfo info = new ViewerRunningConfigInfo { - Clients = viewer.Clients, + ServerMachine = viewer.Server, + ClientMachines = viewer.Clients, ConnectStr = string.Empty, Mode = ViewerMode.Server, Open = viewer.Open - }); + }; + if (info.Open) + { + info.ShareId = viewerProxyCaching.Set(viewer.Server); + } + + byte[] serverBytes = MemoryPackSerializer.Serialize(info); _ = messengerSender.SendOnly(new MessageRequestWrap { Connection = cache.Connection, @@ -48,6 +60,8 @@ namespace cmonitor.plugins.viewer public bool Open { get; set; } public string Server { get; set; } = string.Empty; public string[] Clients { get; set; } = Array.Empty(); + + public string ShareId { get; set; } = string.Empty; } } diff --git a/cmonitor/plugins/viewer/ViewerStartup.cs b/cmonitor/plugins/viewer/ViewerStartup.cs index 4c538b69..bd253901 100644 --- a/cmonitor/plugins/viewer/ViewerStartup.cs +++ b/cmonitor/plugins/viewer/ViewerStartup.cs @@ -1,7 +1,9 @@ using cmonitor.config; using cmonitor.plugins.viewer.messenger; +using cmonitor.plugins.viewer.proxy; using cmonitor.plugins.viewer.report; using cmonitor.startup; +using common.libs; using Microsoft.Extensions.DependencyInjection; using System.Reflection; @@ -18,20 +20,30 @@ namespace cmonitor.plugins.viewer serviceCollection.AddSingleton(); + + serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); } public void AddServer(ServiceCollection serviceCollection, Config config, Assembly[] assemblies) { + + serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); serviceCollection.AddSingleton(); + serviceCollection.AddSingleton(); } public void UseClient(ServiceProvider serviceProvider, Config config, Assembly[] assemblies) { + Logger.Instance.Info($"use viewer proxy server in client mode"); + ViewerProxyClient viewerProxyServer = serviceProvider.GetService(); } public void UseServer(ServiceProvider serviceProvider, Config config, Assembly[] assemblies) { + Logger.Instance.Info($"use viewer proxy server in server mode"); + ViewerProxyServer viewerProxyServer = serviceProvider.GetService(); } } } diff --git a/cmonitor/plugins/viewer/messenger/ViewerMessenger.cs b/cmonitor/plugins/viewer/messenger/ViewerMessenger.cs index 31fa50aa..9d127a9e 100644 --- a/cmonitor/plugins/viewer/messenger/ViewerMessenger.cs +++ b/cmonitor/plugins/viewer/messenger/ViewerMessenger.cs @@ -1,4 +1,8 @@ -using cmonitor.plugins.signIn.messenger; +using cmonitor.client; +using cmonitor.client.running; +using cmonitor.config; +using cmonitor.plugins.signIn.messenger; +using cmonitor.plugins.viewer.proxy; using cmonitor.plugins.viewer.report; using cmonitor.server; using MemoryPack; @@ -8,36 +12,54 @@ namespace cmonitor.plugins.viewer.messenger public sealed class ViewerClientMessenger : IMessenger { private readonly ViewerReport viewerReport; + private readonly ViewerProxyClient viewerProxyClient; + private readonly Config config; + private readonly ClientSignInState clientSignInState; + private readonly RunningConfig runningConfig; - public ViewerClientMessenger(ViewerReport viewerReport) + public ViewerClientMessenger(ViewerReport viewerReport, ViewerProxyClient viewerProxyClient, Config config, ClientSignInState clientSignInState, RunningConfig runningConfig) { this.viewerReport = viewerReport; + this.viewerProxyClient = viewerProxyClient; + this.config = config; + this.clientSignInState = clientSignInState; + this.runningConfig = runningConfig; } [MessengerId((ushort)ViewerMessengerIds.Server)] public void Server(IConnection connection) { - ViewerConfigInfo viewerConfigInfo = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); + ViewerRunningConfigInfo viewerConfigInfo = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); viewerReport.Server(viewerConfigInfo); } - - [MessengerId((ushort)ViewerMessengerIds.Client)] - public void Client(IConnection connection) - { - ViewerConfigInfo viewerConfigInfo = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); - viewerReport.Client(viewerConfigInfo); - } - - [MessengerId((ushort)ViewerMessengerIds.Heart)] public void Heart(IConnection connection) { - string connectStr = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); - viewerReport.Heart(connectStr); + ViewerRunningConfigInfo viewerConfigInfo = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); + viewerReport.Heart(viewerConfigInfo); + } + + + [MessengerId((ushort)ViewerMessengerIds.ProxyFromClient)] + public async Task ProxyFromClient(IConnection connection) + { + ViewerProxyInfo proxy = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); + proxy.TargetEP = runningConfig.Data.Viewer.ConnectEP; + await viewerProxyClient.Connect(proxy); + } + + [MessengerId((ushort)ViewerMessengerIds.ProxyFromServer)] + public async Task ProxyFromServer(IConnection connection) + { + ViewerProxyInfo proxy = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); + proxy.ProxyEP = $"{clientSignInState.Connection.Address.Address}:{config.Data.Client.Viewer.ProxyPort}"; + proxy.TargetEP = runningConfig.Data.Viewer.ConnectEP; + await viewerProxyClient.Connect(proxy); } } + public sealed class ViewerServerMessenger : IMessenger { private readonly MessengerSender messengerSender; @@ -50,35 +72,12 @@ namespace cmonitor.plugins.viewer.messenger } - [MessengerId((ushort)ViewerMessengerIds.NotifyClient)] - public void NotifyClient(IConnection connection) - { - ViewerConfigInfo viewerConfigInfo = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); - string[] usernames = viewerConfigInfo.Clients; - viewerConfigInfo.Clients = Array.Empty(); - viewerConfigInfo.Mode = ViewerMode.Client; - byte[] bytes = MemoryPackSerializer.Serialize(viewerConfigInfo); - foreach (var item in usernames) - { - if (signCaching.Get(item, out SignCacheInfo cache) && cache.Connected) - { - _ = messengerSender.SendOnly(new MessageRequestWrap - { - Connection = cache.Connection, - MessengerId = (ushort)ViewerMessengerIds.Client, - Payload = bytes - }); - } - } - } - - [MessengerId((ushort)ViewerMessengerIds.NotifyHeart)] - public void NotifyHeart(IConnection connection) + [MessengerId((ushort)ViewerMessengerIds.HeartNotify)] + public void HeartNotify(IConnection connection) { - ViewerConfigInfo viewerConfigInfo = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); - string[] usernames = viewerConfigInfo.Clients; - byte[] bytes = MemoryPackSerializer.Serialize(viewerConfigInfo.ConnectStr); + ViewerRunningConfigInfo viewerConfigInfo = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); + string[] usernames = viewerConfigInfo.ClientMachines; foreach (var item in usernames) { if (signCaching.Get(item, out SignCacheInfo cache) && cache.Connected) @@ -87,10 +86,25 @@ namespace cmonitor.plugins.viewer.messenger { Connection = cache.Connection, MessengerId = (ushort)ViewerMessengerIds.Heart, - Payload = bytes + Payload = connection.ReceiveRequestWrap.Payload }); } } } + + [MessengerId((ushort)ViewerMessengerIds.ProxyNotify)] + public void ProxyNotify(IConnection connection) + { + ViewerProxyInfo proxy = MemoryPackSerializer.Deserialize(connection.ReceiveRequestWrap.Payload.Span); + if (signCaching.Get(proxy.ViewerMachine, out SignCacheInfo cache) && cache.Connected) + { + _ = messengerSender.SendOnly(new MessageRequestWrap + { + Connection = cache.Connection, + MessengerId = (ushort)ViewerMessengerIds.ProxyFromClient, + Payload = connection.ReceiveRequestWrap.Payload + }); + } + } } } diff --git a/cmonitor/plugins/viewer/messenger/ViewerMessengerIds.cs b/cmonitor/plugins/viewer/messenger/ViewerMessengerIds.cs index 9a068a24..138018cf 100644 --- a/cmonitor/plugins/viewer/messenger/ViewerMessengerIds.cs +++ b/cmonitor/plugins/viewer/messenger/ViewerMessengerIds.cs @@ -3,10 +3,13 @@ public enum ViewerMessengerIds : ushort { Server = 1800, - Client = 1801, - NotifyClient = 1802, - Heart = 1803, - NotifyHeart = 1804, + Heart = 1801, + HeartNotify = 1802, + + ProxyFromClient = 1803, + ProxyFromServer = 1804, + ProxyNotify = 1805, + None = 1899 } } diff --git a/cmonitor/plugins/viewer/proxy/ViewerProxy.cs b/cmonitor/plugins/viewer/proxy/ViewerProxy.cs new file mode 100644 index 00000000..2a877bd4 --- /dev/null +++ b/cmonitor/plugins/viewer/proxy/ViewerProxy.cs @@ -0,0 +1,474 @@ +using common.libs; +using common.libs.extends; +using MemoryPack; +using System.Buffers; +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; +using System.Text; + +namespace cmonitor.plugins.viewer.proxy +{ + public class ViewerProxy + { + private readonly WheelTimer wheelTimer = new WheelTimer(); + private readonly ConcurrentDictionary connects = new ConcurrentDictionary(); + private NumberSpaceUInt32 ns = new NumberSpaceUInt32(); + private SocketAsyncEventArgs acceptEventArg; + + Socket socket; + + public IPEndPoint LocalEndpoint => socket?.LocalEndPoint as IPEndPoint ?? new IPEndPoint(IPAddress.Any, 0); + + public ViewerProxy() + { + } + + public void Start(int port) + { + try + { + Stop(); + + IPEndPoint localEndPoint = new IPEndPoint(NetworkHelper.IPv6Support ? IPAddress.IPv6Any : IPAddress.Any, port); + socket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + socket.IPv6Only(localEndPoint.AddressFamily, false); + socket.ReuseBind(localEndPoint); + socket.Listen(int.MaxValue); + + acceptEventArg = new SocketAsyncEventArgs + { + UserToken = new AsyncUserToken + { + SourceSocket = socket + }, + SocketFlags = SocketFlags.None, + }; + + acceptEventArg.Completed += IO_Completed; + StartAccept(acceptEventArg); + + } + catch (Exception ex) + { + Logger.Instance.Error(ex); + } + } + private void StartAccept(SocketAsyncEventArgs acceptEventArg) + { + acceptEventArg.AcceptSocket = null; + AsyncUserToken token = (AsyncUserToken)acceptEventArg.UserToken; + try + { + if (token.SourceSocket.AcceptAsync(acceptEventArg) == false) + { + ProcessAccept(acceptEventArg); + } + } + catch (Exception) + { + token.Clear(); + } + } + private void IO_Completed(object sender, SocketAsyncEventArgs e) + { + switch (e.LastOperation) + { + case SocketAsyncOperation.Accept: + ProcessAccept(e); + break; + case SocketAsyncOperation.Receive: + ProcessReceive(e); + break; + default: + break; + } + } + private void ProcessAccept(SocketAsyncEventArgs e) + { + if (e.AcceptSocket != null) + { + BindReceive(e); + StartAccept(e); + } + } + private void BindReceive(SocketAsyncEventArgs e) + { + try + { + AsyncUserToken token = (AsyncUserToken)e.UserToken; + var socket = e.AcceptSocket; + + if (socket == null || socket.RemoteEndPoint == null) + { + return; + } + + socket.KeepAlive(); + AsyncUserToken userToken = new AsyncUserToken + { + SourceSocket = socket + }; + + SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs + { + UserToken = userToken, + SocketFlags = SocketFlags.None, + }; + readEventArgs.SetBuffer(new byte[8 * 1024], 0, 8 * 1024); + readEventArgs.Completed += IO_Completed; + if (socket.ReceiveAsync(readEventArgs) == false) + { + ProcessReceive(readEventArgs); + } + } + catch (Exception ex) + { + if (Logger.Instance.LoggerLevel <= LoggerTypes.DEBUG) + Logger.Instance.Error(ex); + } + } + private async void ProcessReceive(SocketAsyncEventArgs e) + { + try + { + AsyncUserToken token = (AsyncUserToken)e.UserToken; + + if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) + { + int offset = e.Offset; + int length = e.BytesTransferred; + if (token.Step == ViewerProxyStep.Request) + { + await ReadPacket(e, token, e.Buffer.AsMemory(0, length)); + return; + } + await token.TargetSocket.SendAsync(e.Buffer.AsMemory(0, length), SocketFlags.None); + if (token.SourceSocket.Available > 0) + { + while (token.SourceSocket.Available > 0) + { + length = token.SourceSocket.Receive(e.Buffer); + if (length > 0) + { + await token.TargetSocket.SendAsync(e.Buffer.AsMemory(0, length), SocketFlags.None); + } + else + { + CloseClientSocket(e); + return; + } + } + } + + if (token.SourceSocket.Connected == false) + { + CloseClientSocket(e); + return; + } + + if (token.SourceSocket.ReceiveAsync(e) == false) + { + ProcessReceive(e); + } + } + else + { + CloseClientSocket(e); + } + } + catch (Exception ex) + { + if (Logger.Instance.LoggerLevel <= LoggerTypes.DEBUG) + Logger.Instance.Error(ex); + + CloseClientSocket(e); + } + } + private async Task ReadPacket(SocketAsyncEventArgs e, AsyncUserToken token, Memory data) + { + if (GetMachineName(data, out string machine)) + { + uint id = ns.Increment(); + byte[] tempData = new byte[data.Length]; + data.CopyTo(tempData); + ConnectServerCache cache = new ConnectServerCache { Id = id, Saea = e, Data = tempData }; + connects.TryAdd(id, cache); + + WheelTimerTimeout timeout = wheelTimer.NewTimeout(new WheelTimerTimeoutTask { State = cache, Callback = ConnectTimeout, }, 3000); + cache.Timeout = timeout; + + await Connect(machine, cache.Id); + } + else if (GetConnectId(data, out uint connectId)) + { + if (connects.TryRemove(connectId, out ConnectServerCache cache)) + { + cache.Timeout.Cancel(); + AsyncUserToken sourceToken = cache.Saea.UserToken as AsyncUserToken; + sourceToken.Step = ViewerProxyStep.Forward; + sourceToken.TargetSocket = token.SourceSocket; + sourceToken.TargetSocket.KeepAlive(); + + await sourceToken.TargetSocket.SendAsync(cache.Data, SocketFlags.None); + + cache.Clear(); + + if (sourceToken.SourceSocket.ReceiveAsync(cache.Saea) == false) + { + ProcessReceive(cache.Saea); + } + BindReceiveTarget(sourceToken); + } + } + else + { + CloseClientSocket(e); + } + } + private void ConnectTimeout(WheelTimerTimeout timeout) + { + if (timeout.IsCanceled == false) + { + if (connects.TryRemove(timeout.Task.State.Id, out ConnectServerCache cache)) + { + CloseClientSocket(cache.Saea); + cache.Clear(); + } + } + } + + public virtual async Task Connect(string name, uint connectId) + { + await Task.CompletedTask; + } + public async Task Connect(ViewerProxyInfo viewerProxyInfo) + { + Socket proxySocket = null; + Socket targetSocket = null; + try + { + if (IPEndPoint.TryParse(viewerProxyInfo.ProxyEP, out IPEndPoint proxyEP) == false) + { + return; + } + if (IPEndPoint.TryParse(viewerProxyInfo.TargetEP, out IPEndPoint targetEP) == false) + { + return; + } + + proxySocket = new Socket(proxyEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + proxySocket.KeepAlive(); + await proxySocket.ConnectAsync(proxyEP); + + targetSocket = new Socket(targetEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp); + targetSocket.KeepAlive(); + await targetSocket.ConnectAsync(targetEP); + + int length = responseBytes.Length + 4; + byte[] data = ArrayPool.Shared.Rent(length); + responseBytes.AsMemory().CopyTo(data); + viewerProxyInfo.ConnectId.ToBytes(data.AsMemory(responseBytes.Length)); + await proxySocket.SendAsync(data.AsMemory(0, length)); + ArrayPool.Shared.Return(data); + + BindReceiveTarget(new AsyncUserToken { SourceSocket = proxySocket, TargetSocket = targetSocket }); + BindReceiveTarget(new AsyncUserToken { SourceSocket = targetSocket, TargetSocket = proxySocket }); + } + catch (Exception ex) + { + Logger.Instance.Error(ex); + proxySocket?.SafeClose(); + targetSocket?.SafeClose(); + } + } + + + private void IO_CompletedTarget(object sender, SocketAsyncEventArgs e) + { + switch (e.LastOperation) + { + case SocketAsyncOperation.Receive: + ProcessReceiveTarget(e); + break; + default: + break; + } + } + private void BindReceiveTarget(AsyncUserToken userToken) + { + try + { + SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs + { + UserToken = userToken, + SocketFlags = SocketFlags.None, + }; + readEventArgs.SetBuffer(new byte[8 * 1024], 0, 8 * 1024); + readEventArgs.Completed += IO_CompletedTarget; + if (userToken.TargetSocket.ReceiveAsync(readEventArgs) == false) + { + ProcessReceiveTarget(readEventArgs); + } + } + catch (Exception ex) + { + if (Logger.Instance.LoggerLevel <= LoggerTypes.DEBUG) + Logger.Instance.Error(ex); + } + } + private async void ProcessReceiveTarget(SocketAsyncEventArgs e) + { + try + { + AsyncUserToken token = (AsyncUserToken)e.UserToken; + + if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success) + { + int offset = e.Offset; + int length = e.BytesTransferred; + + await token.SourceSocket.SendAsync(e.Buffer.AsMemory(0, length), SocketFlags.None); + + if (token.TargetSocket.Available > 0) + { + while (token.TargetSocket.Available > 0) + { + length = token.TargetSocket.Receive(e.Buffer); + if (length > 0) + { + await token.SourceSocket.SendAsync(e.Buffer.AsMemory(0, length), SocketFlags.None); + } + else + { + CloseClientSocket(e); + return; + } + } + } + + if (token.TargetSocket.Connected == false) + { + CloseClientSocket(e); + return; + } + + if (token.TargetSocket.ReceiveAsync(e) == false) + { + ProcessReceiveTarget(e); + } + } + else + { + CloseClientSocket(e); + } + } + catch (Exception ex) + { + if (Logger.Instance.LoggerLevel <= LoggerTypes.DEBUG) + Logger.Instance.Error(ex); + + CloseClientSocket(e); + } + } + + + private void CloseClientSocket(SocketAsyncEventArgs e) + { + if (e == null) return; + AsyncUserToken token = e.UserToken as AsyncUserToken; + if (token.SourceSocket != null) + { + token.Clear(); + e.Dispose(); + } + } + public void Stop() + { + CloseClientSocket(acceptEventArg); + } + + private readonly byte[] endBytes = Encoding.UTF8.GetBytes("\r\n"); + private readonly byte[] startBytes = Encoding.UTF8.GetBytes("mstshash="); + private byte[] responseBytes = Encoding.UTF8.GetBytes("snltty="); + private bool GetMachineName(Memory memory, out string machine) + { + machine = string.Empty; + + int start = memory.Span.IndexOf(startBytes); + if (start < 0) return false; + + memory = memory.Slice(start); + int end = memory.Span.IndexOf(endBytes); + if (end < 0) return false; + + machine = Encoding.UTF8.GetString(memory.Span.Slice(startBytes.Length, end - startBytes.Length)); + + return true; + } + private bool GetConnectId(Memory memory, out uint id) + { + var span = memory.Span; + id = 0; + if (span.Length != responseBytes.Length + 4 || span.Slice(0, responseBytes.Length).SequenceEqual(responseBytes) == false) + { + return false; + } + id = span.Slice(responseBytes.Length).ToUInt32(); + return true; + } + + + } + + [MemoryPackable] + public sealed partial class ViewerProxyInfo + { + public uint ConnectId { get; set; } + + public string ViewerMachine { get; set; } + + public string ProxyEP { get; set; } + + public string TargetEP { get; set; } + } + + public sealed class ConnectServerCache + { + public uint Id { get; set; } + public SocketAsyncEventArgs Saea { get; set; } + public WheelTimerTimeout Timeout { get; set; } + + public Memory Data { get; set; } + + public void Clear() + { + } + + + } + + public sealed class AsyncUserToken + { + public Socket SourceSocket { get; set; } + public Socket TargetSocket { get; set; } + public ViewerProxyStep Step { get; set; } = ViewerProxyStep.Request; + + public void Clear() + { + SourceSocket?.SafeClose(); + SourceSocket = null; + + TargetSocket?.SafeClose(); + TargetSocket = null; + + GC.Collect(); + } + } + + public enum ViewerProxyStep : byte + { + Request = 1, + Forward = 2 + } +} diff --git a/cmonitor/plugins/viewer/proxy/ViewerProxyCaching.cs b/cmonitor/plugins/viewer/proxy/ViewerProxyCaching.cs new file mode 100644 index 00000000..22f8677c --- /dev/null +++ b/cmonitor/plugins/viewer/proxy/ViewerProxyCaching.cs @@ -0,0 +1,56 @@ +using cmonitor.plugins.signIn.messenger; +using cmonitor.server; +using common.libs.extends; +using System.Collections.Concurrent; + +namespace cmonitor.plugins.viewer.proxy +{ + public sealed class ViewerProxyCaching + { + private readonly ConcurrentDictionary viewerCache = new ConcurrentDictionary(); + + + private readonly SignCaching signCaching; + public ViewerProxyCaching(SignCaching signCaching) + { + this.signCaching = signCaching; + } + + public string Set(string serverMachineName) + { + while (true) + { + string id = GenerateUniqueId(); + if (viewerCache.TryAdd(id, serverMachineName)) + { + return id; + } + } + } + public bool Remove(string id) + { + return viewerCache.TryRemove(id, out _); + } + + public bool Get(string id, out IConnection connection) + { + connection = null; + if (viewerCache.TryGetValue(id, out string serverMachineName)) + { + if (signCaching.Get(serverMachineName, out SignCacheInfo info)) + { + connection = info.Connection; + return connection != null && connection.Connected; + } + } + return false; + } + + + private string GenerateUniqueId() + { + byte[] bytes = Guid.NewGuid().ToByteArray(); + return Convert.ToBase64String(bytes).SubStr(0, 9); + } + } +} diff --git a/cmonitor/plugins/viewer/proxy/ViewerProxyClient.cs b/cmonitor/plugins/viewer/proxy/ViewerProxyClient.cs new file mode 100644 index 00000000..d6aed7c7 --- /dev/null +++ b/cmonitor/plugins/viewer/proxy/ViewerProxyClient.cs @@ -0,0 +1,42 @@ +using cmonitor.client; +using cmonitor.client.running; +using cmonitor.config; +using cmonitor.plugins.viewer.messenger; +using cmonitor.server; +using MemoryPack; + +namespace cmonitor.plugins.viewer.proxy +{ + public sealed class ViewerProxyClient : ViewerProxy + { + private readonly MessengerSender messengerSender; + private readonly ClientSignInState clientSignInState; + private readonly Config config; + private readonly RunningConfig runningConfig; + + public ViewerProxyClient(MessengerSender messengerSender, ClientSignInState clientSignInState, Config config, RunningConfig runningConfig) + { + this.messengerSender = messengerSender; + this.clientSignInState = clientSignInState; + this.config = config; + this.runningConfig = runningConfig; + + Start(0); + } + + public override async Task Connect(string name, uint connectId) + { + await messengerSender.SendOnly(new MessageRequestWrap + { + Connection = clientSignInState.Connection, + MessengerId = (ushort)ViewerMessengerIds.ProxyNotify, + Payload = MemoryPackSerializer.Serialize(new ViewerProxyInfo + { + ConnectId = connectId, + ProxyEP = $"{clientSignInState.Connection.LocalAddress.Address}:{LocalEndpoint.Port}", + ViewerMachine = runningConfig.Data.Viewer.ServerMachine + }) + }); + } + } +} diff --git a/cmonitor/plugins/viewer/proxy/ViewerProxyServer.cs b/cmonitor/plugins/viewer/proxy/ViewerProxyServer.cs new file mode 100644 index 00000000..b835eeff --- /dev/null +++ b/cmonitor/plugins/viewer/proxy/ViewerProxyServer.cs @@ -0,0 +1,40 @@ +using cmonitor.config; +using cmonitor.plugins.viewer.messenger; +using cmonitor.server; +using MemoryPack; + +namespace cmonitor.plugins.viewer.proxy +{ + public sealed class ViewerProxyServer : ViewerProxy + { + private readonly MessengerSender messengerSender; + private readonly ViewerProxyCaching viewerProxyCaching; + + public ViewerProxyServer(MessengerSender messengerSender, Config config, ViewerProxyCaching viewerProxyCaching) + { + this.messengerSender = messengerSender; + this.viewerProxyCaching = viewerProxyCaching; + + Start(config.Data.Server.Viewer.ProxyPort); + + } + + public override async Task Connect(string name, uint connectId) + { + if (viewerProxyCaching.Get(name, out IConnection connection)) + { + await messengerSender.SendOnly(new MessageRequestWrap + { + Connection = connection, + MessengerId = (ushort)ViewerMessengerIds.ProxyFromServer, + Payload = MemoryPackSerializer.Serialize(new ViewerProxyInfo + { + ConnectId = connectId, + ProxyEP = string.Empty, + ViewerMachine = string.Empty + }) + }); + } + } + } +} diff --git a/cmonitor/plugins/viewer/proxy/ViewerProxySignInArgs.cs b/cmonitor/plugins/viewer/proxy/ViewerProxySignInArgs.cs new file mode 100644 index 00000000..45752fc5 --- /dev/null +++ b/cmonitor/plugins/viewer/proxy/ViewerProxySignInArgs.cs @@ -0,0 +1,24 @@ +using cmonitor.client.args; +using cmonitor.plugins.viewer.report; +using common.libs.winapis; + +namespace cmonitor.plugins.viewer.proxy +{ + public sealed class ViewerProxySignInArgs : ISignInArgs + { + public void Invoke(Dictionary args) + { + string userName = GetUserName(); + args[ViewerConfigInfo.userNameKey] = userName; + } + + private string GetUserName() + { + if (OperatingSystem.IsWindows()) + { + return Win32Interop.GetUserName(); + } + return string.Empty; + } + } +} diff --git a/cmonitor/plugins/viewer/report/IViewer.cs b/cmonitor/plugins/viewer/report/IViewer.cs index e2c5f66a..5ffc39cb 100644 --- a/cmonitor/plugins/viewer/report/IViewer.cs +++ b/cmonitor/plugins/viewer/report/IViewer.cs @@ -1,22 +1,56 @@ -using MemoryPack; +using cmonitor.plugins.viewer.report; +using MemoryPack; +using System.Net; +using System.Text.Json.Serialization; namespace cmonitor.plugins.viewer.report { public interface IViewer { - public void Open(bool value, ViewerMode mode); + public void Open(bool value, ParamInfo info); public string GetConnectString(); public void SetConnectString(string connectStr); + public string GetConnectEP(string connectStr) + { + return string.Empty; + } + } + + public sealed class ViewerConfigInfo + { + [JsonIgnore] + public const string userNameKey = "viewer-username"; + + public int ProxyPort { get; set; } = 1803; } [MemoryPackable] - public sealed partial class ViewerConfigInfo + public sealed partial class ViewerRunningConfigInfo { public ViewerMode Mode { get; set; } public bool Open { get; set; } - public string[] Clients { get; set; } = Array.Empty(); + public string ShareId { get; set; } = string.Empty; + + /// + /// 共享服务端机器名,在通知消息和代理时需要 + /// + public string ServerMachine { get; set; } = string.Empty; + /// + /// 共享客户端机器名列表 + /// + public string[] ClientMachines { get; set; } = Array.Empty(); + + /// + /// 共享连接串,提供给客户端的共享桌面工具,去连接服务 + /// public string ConnectStr { get; set; } = string.Empty; + /// + /// 共享服务的连接地址,在代理时需要 + /// 比如 B 是共享服务端,A是共享客户端 + /// 当连不上时,会需要代理,由B去连接A或者B去连接服务器,形成通道,那B这边还需要手动连接共享服务,就用这个去连 + /// + public string ConnectEP { get; set; } = string.Empty; } public enum ViewerMode : byte @@ -24,4 +58,44 @@ namespace cmonitor.plugins.viewer.report Client = 0, Server = 1, } + + public sealed class ParamInfo + { + public string ShareMkey { get; set; } = "cmonitor/share"; + public int ShareMLength { get; set; } = 10; + public int ShareItemMLength { get; set; } = 1024; + public int ShareIndex { get; set; } = 5; + public ViewerMode Mode { get; set; } = ViewerMode.Server; + public string GroupName { get; set; } = "snltty"; + public string ProxyServers { get; set; } = "127.0.0.1:1803"; + } +} + +namespace cmonitor.config +{ + public sealed partial class ConfigClientInfo + { + public ViewerConfigInfo Viewer { get; set; } = new ViewerConfigInfo(); + } + + public sealed partial class ConfigServerInfo + { + public ViewerConfigInfo Viewer { get; set; } = new ViewerConfigInfo(); + } +} + +namespace cmonitor.client.running +{ + public sealed partial class RunningConfigInfo + { + private ViewerRunningConfigInfo viewer = new ViewerRunningConfigInfo(); + public ViewerRunningConfigInfo Viewer + { + get => viewer; set + { + Updated++; + viewer = value; + } + } + } } diff --git a/cmonitor/plugins/viewer/report/ViewerLinux.cs b/cmonitor/plugins/viewer/report/ViewerLinux.cs index 95aefcde..6cd69320 100644 --- a/cmonitor/plugins/viewer/report/ViewerLinux.cs +++ b/cmonitor/plugins/viewer/report/ViewerLinux.cs @@ -1,8 +1,10 @@ -namespace cmonitor.plugins.viewer.report +using System.Net; + +namespace cmonitor.plugins.viewer.report { public sealed class ViewerLinux : IViewer { - public void Open(bool value, ViewerMode mode) + public void Open(bool value, ParamInfo info) { } public string GetConnectString() @@ -13,5 +15,10 @@ { } + + public string GetConnectEP(string connectStr) + { + return string.Empty; + } } } diff --git a/cmonitor/plugins/viewer/report/ViewerMacOS.cs b/cmonitor/plugins/viewer/report/ViewerMacOS.cs index 37398971..ee7b0cd4 100644 --- a/cmonitor/plugins/viewer/report/ViewerMacOS.cs +++ b/cmonitor/plugins/viewer/report/ViewerMacOS.cs @@ -1,8 +1,10 @@ -namespace cmonitor.plugins.viewer.report +using System.Net; + +namespace cmonitor.plugins.viewer.report { public sealed class ViewerMacOS : IViewer { - public void Open(bool value, ViewerMode mode) + public void Open(bool value, ParamInfo info) { } public string GetConnectString() @@ -13,5 +15,10 @@ { } + + public string GetConnectEP(string connectStr) + { + return string.Empty; + } } } diff --git a/cmonitor/plugins/viewer/report/ViewerReport.cs b/cmonitor/plugins/viewer/report/ViewerReport.cs index 8e7530ff..29a85038 100644 --- a/cmonitor/plugins/viewer/report/ViewerReport.cs +++ b/cmonitor/plugins/viewer/report/ViewerReport.cs @@ -1,5 +1,4 @@ using cmonitor.client; -using cmonitor.client.runningConfig; using cmonitor.client.report; using cmonitor.config; using cmonitor.libs; @@ -7,6 +6,10 @@ using cmonitor.plugins.viewer.messenger; using cmonitor.server; using common.libs; using MemoryPack; +using cmonitor.client.running; +using System.Net; +using System.Text.Json; +using cmonitor.plugins.viewer.proxy; namespace cmonitor.plugins.viewer.report { @@ -20,22 +23,24 @@ namespace cmonitor.plugins.viewer.report public string Name => "Viewer"; private ViewerReportInfo report = new ViewerReportInfo(); - private readonly IRunningConfig clientConfig; + private readonly RunningConfig runningConfig; private readonly IViewer viewer; private readonly ShareMemory shareMemory; - private ViewerConfigInfo viewerConfigInfo; private readonly MessengerSender messengerSender; private readonly ClientSignInState clientSignInState; + private readonly Config config; + private readonly ViewerProxyClient viewerProxyClient; - public ViewerReport(Config config, IRunningConfig clientConfig, IViewer viewer, ShareMemory shareMemory, ClientSignInState clientSignInState, MessengerSender messengerSender) + public ViewerReport(Config config, RunningConfig runningConfig, IViewer viewer, ShareMemory shareMemory, ClientSignInState clientSignInState, MessengerSender messengerSender, ViewerProxyClient viewerProxyClient) { - this.clientConfig = clientConfig; + this.config = config; + this.runningConfig = runningConfig; this.viewer = viewer; this.shareMemory = shareMemory; this.clientSignInState = clientSignInState; this.messengerSender = messengerSender; + this.viewerProxyClient = viewerProxyClient; - viewerConfigInfo = clientConfig.Get(new ViewerConfigInfo { }); clientSignInState.NetworkFirstEnabledHandle += () => { Update(); @@ -46,7 +51,8 @@ namespace cmonitor.plugins.viewer.report public object GetReports(ReportType reportType) { report.Value = Running(); - report.Mode = viewerConfigInfo.Mode; + report.Mode = runningConfig.Data.Viewer.Mode; + report.ShareId = runningConfig.Data.Viewer.ShareId; if (reportType == ReportType.Full || report.Updated() || shareMemory.ReadVersionUpdated((int)ShareMemoryIndexs.Viewer)) { return report; @@ -54,63 +60,68 @@ namespace cmonitor.plugins.viewer.report return null; } - private void Update() - { - if (viewerConfigInfo.Mode == ViewerMode.Server && viewerConfigInfo.Open && Running() == false) - { - Server(viewerConfigInfo); - } - } - public void Server(ViewerConfigInfo info) + public void Server(ViewerRunningConfigInfo info) { if (info.Open) { - viewerConfigInfo = info; + runningConfig.Data.Viewer = info; } else { - viewerConfigInfo.Open = info.Open; + runningConfig.Data.Viewer.Open = info.Open; } + runningConfig.Data.Update(); - clientConfig.Set(viewerConfigInfo); - viewerConfigInfo.ConnectStr = string.Empty; - viewer.SetConnectString(viewerConfigInfo.ConnectStr); Task.Run(async () => { - shareMemory.AddAttribute((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Closed); - shareMemory.RemoveAttribute((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Running); - await Task.Delay(200); + Close(); + await HeartNotify(false); + await Task.Delay(500); + Open(); - viewer.Open(viewerConfigInfo.Open, viewerConfigInfo.Mode); - if (viewerConfigInfo.Open) + if (runningConfig.Data.Viewer.Open) { - try + runningConfig.Data.Viewer.ConnectStr = await GetNewConnectStr(); + if (string.IsNullOrWhiteSpace(runningConfig.Data.Viewer.ConnectStr) == false) { - for (int i = 0; i < 300; i++) - { - var attr = shareMemory.ReadAttribute((int)ShareMemoryIndexs.Viewer); - if (shareMemory.ReadAttributeEqual((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Running)) - { - viewerConfigInfo.ConnectStr = viewer.GetConnectString(); - if (string.IsNullOrWhiteSpace(viewerConfigInfo.ConnectStr) == false) - { - NotifyHeart(); - break; - } - } - await Task.Delay(100); - } - } - catch (Exception ex) - { - Logger.Instance.Error(ex); + UpdateConnectEP(); + await HeartNotify(runningConfig.Data.Viewer.Open); } } - else - { - NotifyClient(); - } + }); + } + public void Heart(ViewerRunningConfigInfo info) + { + if (info.ConnectStr != runningConfig.Data.Viewer.ConnectStr) + { + viewer.SetConnectString(ReplaceProxy(info.ConnectStr)); + } + + //未运行,或者不是client模式,或者状态不对,都需要重启一下 + bool restart = Running() != true + || runningConfig.Data.Viewer.Mode != ViewerMode.Client + || runningConfig.Data.Viewer.Open != info.Open; + + runningConfig.Data.Viewer = info; + runningConfig.Data.Update(); + + if (restart) + { + RestartClient(); + } + } + private async Task HeartNotify(bool open) + { + ViewerRunningConfigInfo info = JsonSerializer.Deserialize(JsonSerializer.Serialize(runningConfig.Data.Viewer)); + info.Mode = ViewerMode.Client; + info.Open = open; + + await messengerSender.SendOnly(new MessageRequestWrap + { + Connection = clientSignInState.Connection, + MessengerId = (ushort)ViewerMessengerIds.HeartNotify, + Payload = MemoryPackSerializer.Serialize(info) }); } @@ -118,58 +129,87 @@ namespace cmonitor.plugins.viewer.report { Task.Run(async () => { - shareMemory.AddAttribute((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Closed); - shareMemory.RemoveAttribute((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Running); + Close(); await Task.Delay(500); - viewer.Open(viewerConfigInfo.Open, viewerConfigInfo.Mode); + Open(); }); } - public void Client(ViewerConfigInfo info) + private void Update() { - viewerConfigInfo = info; - clientConfig.Set(viewerConfigInfo); - viewer.SetConnectString(viewerConfigInfo.ConnectStr); - RestartClient(); - } - private void NotifyClient() - { - _ = messengerSender.SendOnly(new MessageRequestWrap + if (runningConfig.Data.Viewer.Mode == ViewerMode.Server && runningConfig.Data.Viewer.Open && Running() == false) { - Connection = clientSignInState.Connection, - MessengerId = (ushort)ViewerMessengerIds.NotifyClient, - Payload = MemoryPackSerializer.Serialize(viewerConfigInfo) - }); + Server(runningConfig.Data.Viewer); + } } - public void Heart(string connectStr) - { - bool restart = Running() == false || viewerConfigInfo.Mode == ViewerMode.Server; - viewerConfigInfo.ConnectStr = connectStr; - viewerConfigInfo.Mode = ViewerMode.Client; - viewerConfigInfo.Open = true; - clientConfig.Set(viewerConfigInfo); - viewer.SetConnectString(viewerConfigInfo.ConnectStr); - if (restart) - { - RestartClient(); - } - } - private void NotifyHeart() + + private async Task GetNewConnectStr() { - if (string.IsNullOrWhiteSpace(viewerConfigInfo.ConnectStr)) + try { - return; - } - if (viewerConfigInfo.Open && viewerConfigInfo.Mode == ViewerMode.Server && Running()) - { - _ = messengerSender.SendOnly(new MessageRequestWrap + for (int i = 0; i < 300; i++) { - Connection = clientSignInState.Connection, - MessengerId = (ushort)ViewerMessengerIds.NotifyHeart, - Payload = MemoryPackSerializer.Serialize(viewerConfigInfo) + if (shareMemory.ReadAttributeEqual((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Running)) + { + string connectStr = viewer.GetConnectString(); + if (string.IsNullOrWhiteSpace(connectStr) == false) return connectStr; + } + await Task.Delay(100); + } + } + catch (Exception ex) + { + Logger.Instance.Error(ex); + } + return string.Empty; + } + private string ReplaceProxy(string connectStr) + { + if (IPAddress.IsLoopback(clientSignInState.Connection.LocalAddress.Address)) + { + Logger.Instance.Warning($"use Loopback address【{clientSignInState.Connection.LocalAddress.Address}】 as viewer proxy,may fail"); + Logger.Instance.Warning($"connect to the local or external network address of the cmonitor server,to fix this"); + } + + return connectStr + .Replace("{ip}", clientSignInState.Connection.LocalAddress.Address.ToString()) + //.Replace("{port}", "12345"); + .Replace("{port}", viewerProxyClient.LocalEndpoint.Port.ToString()); + + } + private void UpdateConnectEP() + { + string connectEP = viewer.GetConnectEP(runningConfig.Data.Viewer.ConnectStr); + runningConfig.Data.Viewer.ConnectEP = connectEP; + runningConfig.Data.Update(); + } + + private void Open() + { + if (runningConfig.Data.Viewer.Open) + { + viewer.Open(runningConfig.Data.Viewer.Open, new ParamInfo + { + GroupName = runningConfig.Data.Viewer.ShareId, + Mode = runningConfig.Data.Viewer.Mode, + ProxyServers = string.Join(",", new string[] { + $"{clientSignInState.Connection.Address.Address}:{config.Data.Client.Viewer.ProxyPort}" + }), + ShareIndex = (int)ShareMemoryIndexs.Viewer, + ShareMkey = config.Data.Client.ShareMemoryKey, + ShareMLength = config.Data.Client.ShareMemoryCount, + ShareItemMLength = config.Data.Client.ShareMemorySize }); } } + private void Close() + { + shareMemory.AddAttribute((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Closed); + shareMemory.RemoveAttribute((int)ShareMemoryIndexs.Viewer, ShareMemoryAttribute.Running); + runningConfig.Data.Viewer.ConnectStr = string.Empty; + viewer.SetConnectString(runningConfig.Data.Viewer.ConnectStr); + runningConfig.Data.Update(); + } private bool Running() { @@ -183,20 +223,35 @@ namespace cmonitor.plugins.viewer.report { while (true) { - NotifyHeart(); + bool heart = string.IsNullOrWhiteSpace(runningConfig.Data.Viewer.ConnectStr) == false + && runningConfig.Data.Viewer.Open && runningConfig.Data.Viewer.Mode == ViewerMode.Server && Running(); + + if (heart) + { + await HeartNotify(runningConfig.Data.Viewer.Open); + } + await Task.Delay(5000); } }); } } + [MemoryPackable] + public sealed partial class ViewerHeartInfo + { + public string Server { get; set; } + public string ConnectStr { get; set; } + } + public sealed class ViewerReportInfo : ReportInfo { public bool Value { get; set; } public ViewerMode Mode { get; set; } + public string ShareId { get; set; } = string.Empty; public override int HashCode() { - return Value.GetHashCode() ^ Mode.GetHashCode(); + return Value.GetHashCode() ^ Mode.GetHashCode() ^ ShareId.GetHashCode(); } } } diff --git a/cmonitor/plugins/viewer/report/ViewerWindows.cs b/cmonitor/plugins/viewer/report/ViewerWindows.cs index b9b70565..97c67db4 100644 --- a/cmonitor/plugins/viewer/report/ViewerWindows.cs +++ b/cmonitor/plugins/viewer/report/ViewerWindows.cs @@ -1,7 +1,10 @@ using cmonitor.config; using common.libs; using Microsoft.Win32; +using System.Net; using System.Runtime.Versioning; +using System.Text.Json; +using System.Xml; namespace cmonitor.plugins.viewer.report { @@ -13,17 +16,14 @@ namespace cmonitor.plugins.viewer.report { this.config = config; } - public void Open(bool value, ViewerMode mode) + public void Open(bool value, ParamInfo info) { if (value) { - string command = $"start cmonitor.viewer.server.win.exe {config.Client.ShareMemoryKey} {config.Client.ShareMemoryCount} {config.Client.ShareMemorySize} {(int)ShareMemoryIndexs.Viewer} {(byte)mode}"; + string str = JsonSerializer.Serialize(info); + string command = $"start cmonitor.viewer.server.win.exe \"{str.Replace("\"","\\\"")}\""; CommandHelper.Windows(string.Empty, new string[] { command }, false); } - else - { - //CommandHelper.Windows(string.Empty, new string[] { $"taskkill /f /im cmonitor.viewer.server.win.exe" }); - } } public string GetConnectString() @@ -34,5 +34,27 @@ namespace cmonitor.plugins.viewer.report { Registry.SetValue("HKEY_CURRENT_USER\\SOFTWARE\\Cmonitor", "viewerConnectStr", connectStr); } + + public string GetConnectEP(string connectStr) + { + try + { + XmlDocument xmlDoc = new XmlDocument(); + xmlDoc.LoadXml(connectStr); + + var nodes = xmlDoc.DocumentElement["C"]["T"].ChildNodes; + + var node = nodes[nodes.Count - 3]; + var p = node.Attributes["P"].Value; + var n = node.Attributes["N"].Value; + + return $"{n}:{p}"; + } + catch (Exception ex) + { + Logger.Instance.Error(ex); + } + return string.Empty; + } } } diff --git a/cmonitor/plugins/volume/report/VolumeReport.cs b/cmonitor/plugins/volume/report/VolumeReport.cs index dcc21af5..d36950fc 100644 --- a/cmonitor/plugins/volume/report/VolumeReport.cs +++ b/cmonitor/plugins/volume/report/VolumeReport.cs @@ -1,5 +1,6 @@ using cmonitor.client.report; using cmonitor.config; +using cmonitor.plugins.volume.report; namespace cmonitor.plugins.volume.report { @@ -9,13 +10,11 @@ namespace cmonitor.plugins.volume.report private VolumeReportInfo report = new VolumeReportInfo(); private readonly IVolume volume; - private VolumeConfigInfo config; + private Config config; public VolumeReport(Config config, IVolume volume) { - this.config = config.Get(this.Name, new VolumeConfigInfo()); - config.Set(this.Name, this.config); - + this.config = config; this.volume = volume; } @@ -23,7 +22,7 @@ namespace cmonitor.plugins.volume.report { report.Value = volume.GetVolume(); report.Mute = volume.GetMute(); - if (config.MasterPeak) + if (config.Data.Client.Volume.MasterPeak) { report.MasterPeak = volume.GetMasterPeak(); } @@ -66,4 +65,13 @@ namespace cmonitor.plugins.volume.report { public bool MasterPeak { get; set; } } + } + +namespace cmonitor.config +{ + public sealed partial class ConfigClientInfo + { + public VolumeConfigInfo Volume { get; set; } = new VolumeConfigInfo(); + } +} \ No newline at end of file diff --git a/cmonitor/plugins/wallpaper/report/IWallpaper.cs b/cmonitor/plugins/wallpaper/report/IWallpaper.cs index 89eebbf7..c0b9739e 100644 --- a/cmonitor/plugins/wallpaper/report/IWallpaper.cs +++ b/cmonitor/plugins/wallpaper/report/IWallpaper.cs @@ -1,4 +1,5 @@ -using MemoryPack; +using cmonitor.plugins.wallpaper.report; +using MemoryPack; namespace cmonitor.plugins.wallpaper.report { @@ -14,3 +15,19 @@ namespace cmonitor.plugins.wallpaper.report public string ImgUrl { get; set; } } } + +namespace cmonitor.client.running +{ + public sealed partial class RunningConfigInfo + { + private WallpaperConfigInfo wallpaper = new WallpaperConfigInfo(); + public WallpaperConfigInfo Wallpaper + { + get => wallpaper; set + { + Updated++; + wallpaper = value; + } + } + } +} \ No newline at end of file diff --git a/cmonitor/plugins/wallpaper/report/WallpaperReport.cs b/cmonitor/plugins/wallpaper/report/WallpaperReport.cs index c0d6bd61..08597051 100644 --- a/cmonitor/plugins/wallpaper/report/WallpaperReport.cs +++ b/cmonitor/plugins/wallpaper/report/WallpaperReport.cs @@ -1,9 +1,9 @@ using cmonitor.client; -using cmonitor.client.runningConfig; using cmonitor.client.report; using cmonitor.config; using cmonitor.libs; using common.libs; +using cmonitor.client.running; namespace cmonitor.plugins.wallpaper.report { @@ -12,21 +12,19 @@ namespace cmonitor.plugins.wallpaper.report public string Name => "Wallpaper"; private WallpaperReportInfo report = new WallpaperReportInfo(); - private readonly IRunningConfig clientConfig; + private readonly RunningConfig runningConfig; private readonly IWallpaper wallpaper; private readonly ShareMemory shareMemory; - private WallpaperConfigInfo wallpaperConfig; - public WallpaperReport(Config config, IRunningConfig clientConfig, IWallpaper wallpaper, ShareMemory shareMemory, ClientSignInState clientSignInState) + public WallpaperReport(Config config, RunningConfig runningConfig, IWallpaper wallpaper, ShareMemory shareMemory, ClientSignInState clientSignInState) { - this.clientConfig = clientConfig; + this.runningConfig = runningConfig; this.wallpaper = wallpaper; this.shareMemory = shareMemory; - wallpaperConfig = clientConfig.Get(new WallpaperConfigInfo { }); clientSignInState.NetworkFirstEnabledHandle += () => { - Update(wallpaperConfig); + Update(runningConfig.Data.Wallpaper); WallpaperTask(); }; } @@ -43,13 +41,12 @@ namespace cmonitor.plugins.wallpaper.report public void Update(WallpaperConfigInfo info) { - wallpaperConfig = info; + runningConfig.Data.Wallpaper = info; Task.Run(async () => { - clientConfig.Set(wallpaperConfig); shareMemory.AddAttribute((int)ShareMemoryIndexs.Wallpaper, ShareMemoryAttribute.Closed); await Task.Delay(100); - wallpaper.Set(wallpaperConfig); + wallpaper.Set(runningConfig.Data.Wallpaper); }); } @@ -65,11 +62,11 @@ namespace cmonitor.plugins.wallpaper.report { while (true) { - if (wallpaperConfig.Open) + if (runningConfig.Data.Wallpaper.Open) { if (Running() == false) { - Update(wallpaperConfig); + Update(runningConfig.Data.Wallpaper); } } await Task.Delay(5000); diff --git a/cmonitor/plugins/wallpaper/report/WallpaperWindows.cs b/cmonitor/plugins/wallpaper/report/WallpaperWindows.cs index 6c69e669..c64a3f1d 100644 --- a/cmonitor/plugins/wallpaper/report/WallpaperWindows.cs +++ b/cmonitor/plugins/wallpaper/report/WallpaperWindows.cs @@ -15,7 +15,7 @@ namespace cmonitor.plugins.wallpaper.report if (info.Open) { CommandHelper.Windows(string.Empty, new string[] { - $"start cmonitor.wallpaper.win.exe \"{info.ImgUrl}\" {config.Client.ShareMemoryKey} {config.Client.ShareMemoryCount} {config.Client.ShareMemorySize} {(int)ShareMemoryIndexs.Keyboard} {(int)ShareMemoryIndexs.Wallpaper}" + $"start cmonitor.wallpaper.win.exe \"{info.ImgUrl}\" {config.Data.Client.ShareMemoryKey} {config.Data.Client.ShareMemoryCount} {config.Data.Client.ShareMemorySize} {(int)ShareMemoryIndexs.Keyboard} {(int)ShareMemoryIndexs.Wallpaper}" },false); } } diff --git a/cmonitor/plugins/wlan/WlanStartup.cs b/cmonitor/plugins/wlan/WlanStartup.cs index 243cac43..0286f742 100644 --- a/cmonitor/plugins/wlan/WlanStartup.cs +++ b/cmonitor/plugins/wlan/WlanStartup.cs @@ -28,7 +28,6 @@ namespace cmonitor.plugins.wlan public void UseClient(ServiceProvider serviceProvider, Config config, Assembly[] assemblies) { - serviceProvider.GetServices(); } public void UseServer(ServiceProvider serviceProvider, Config config, Assembly[] assemblies) diff --git a/cmonitor/plugins/wlan/report/WlanWindows.cs b/cmonitor/plugins/wlan/report/WlanWindows.cs index 79459909..b1ebca53 100644 --- a/cmonitor/plugins/wlan/report/WlanWindows.cs +++ b/cmonitor/plugins/wlan/report/WlanWindows.cs @@ -1,5 +1,4 @@ using ManagedNativeWifi; -using System.Net.NetworkInformation; namespace cmonitor.plugins.wlan.report { diff --git a/cmonitor/server/IConnection.cs b/cmonitor/server/IConnection.cs index bbd03fdf..9a4bc636 100644 --- a/cmonitor/server/IConnection.cs +++ b/cmonitor/server/IConnection.cs @@ -11,7 +11,7 @@ namespace cmonitor.server /// public interface IConnection { - public string Name{ get; set; } + public string Name { get; set; } /// /// /// 已连接 @@ -19,6 +19,7 @@ namespace cmonitor.server public bool Connected { get; } public IPEndPoint Address { get; } + public IPEndPoint LocalAddress { get; } #region 接收数据 /// @@ -77,10 +78,6 @@ namespace cmonitor.server public void Return(); #endregion - - public Task WaitOne(); - public void Release(); - } public abstract class Connection : IConnection @@ -98,6 +95,7 @@ namespace cmonitor.server /// 地址 /// public IPEndPoint Address { get; protected set; } + public IPEndPoint LocalAddress { get; protected set; } #region 接收数据 @@ -210,61 +208,9 @@ namespace cmonitor.server /// public virtual void Disponse() { - try - { - if (Semaphore != null) - { - if (locked) - { - locked = false; - Semaphore.Release(); - } - Semaphore.Dispose(); - } - Semaphore = null; - } - catch (Exception ex) - { - Logger.Instance.Error(ex); - } - //ReceiveRequestWrap = null; - //ReceiveResponseWrap = null; } - SemaphoreSlim Semaphore = new SemaphoreSlim(1); - bool locked = false; - public virtual async Task WaitOne() - { - try - { - if (Semaphore != null) - { - locked = true; - await Semaphore.WaitAsync(); - } - } - catch (Exception ex) - { - Logger.Instance.Error(ex); - } - - } - public virtual void Release() - { - try - { - if (Semaphore != null) - { - locked = false; - Semaphore.Release(); - } - } - catch (Exception ex) - { - Logger.Instance.Error(ex); - } - } } @@ -280,6 +226,13 @@ namespace cmonitor.server address = new IPEndPoint(new IPAddress(address.Address.GetAddressBytes()[^4..]), address.Port); } Address = address; + + IPEndPoint localaddress = TcpSocket.LocalEndPoint as IPEndPoint ?? new IPEndPoint(IPAddress.Any, 0); + if (localaddress.Address.AddressFamily == AddressFamily.InterNetworkV6 && localaddress.Address.IsIPv4MappedToIPv6) + { + localaddress = new IPEndPoint(new IPAddress(localaddress.Address.GetAddressBytes()[^4..]), localaddress.Port); + } + LocalAddress = localaddress; } /// diff --git a/cmonitor/server/MessengerResolver.cs b/cmonitor/server/MessengerResolver.cs index 814aad94..0fb8294f 100644 --- a/cmonitor/server/MessengerResolver.cs +++ b/cmonitor/server/MessengerResolver.cs @@ -30,11 +30,16 @@ namespace cmonitor.server this.serviceProvider = serviceProvider; } - public void LoadMessenger(Assembly[] assemblys) + public void LoadMessenger(Assembly[] assemblys, string[] pluginNames) { Type voidType = typeof(void); Type midType = typeof(MessengerIdAttribute); var types = ReflectionHelper.GetInterfaceSchieves(assemblys, typeof(IMessenger)).Distinct(); + if (pluginNames.Length > 0) + { + types = types.Where(c => pluginNames.Any(d => c.FullName.Contains(d))); + } + foreach (Type type in types) { object obj = serviceProvider.GetService(type); diff --git a/cmonitor/server/ServerStartup.cs b/cmonitor/server/ServerStartup.cs index a55ed347..e529af18 100644 --- a/cmonitor/server/ServerStartup.cs +++ b/cmonitor/server/ServerStartup.cs @@ -35,7 +35,7 @@ namespace cmonitor.server if (loaded == false) { MessengerResolver messengerResolver = serviceProvider.GetService(); - messengerResolver.LoadMessenger(assemblies); + messengerResolver.LoadMessenger(assemblies, config.Data.Common.PluginNames); loaded = true; } } @@ -45,7 +45,7 @@ namespace cmonitor.server if (loaded == false) { MessengerResolver messengerResolver = serviceProvider.GetService(); - messengerResolver.LoadMessenger(assemblies); + messengerResolver.LoadMessenger(assemblies, config.Data.Common.PluginNames); loaded = true; } @@ -53,7 +53,7 @@ namespace cmonitor.server //服务 TcpServer tcpServer = serviceProvider.GetService(); tcpServer.Start(); - Logger.Instance.Info($"server listen:{config.Server.ServicePort}"); + Logger.Instance.Info($"server listen:{config.Data.Server.ServicePort}"); } } } diff --git a/cmonitor/server/TcpServer.cs b/cmonitor/server/TcpServer.cs index 2e5b1409..046f8b28 100644 --- a/cmonitor/server/TcpServer.cs +++ b/cmonitor/server/TcpServer.cs @@ -31,7 +31,7 @@ namespace cmonitor.server private Socket BindAccept() { - IPEndPoint localEndPoint = new IPEndPoint(NetworkHelper.IPv6Support ? IPAddress.IPv6Any : IPAddress.Any, config.Server.ServicePort); + IPEndPoint localEndPoint = new IPEndPoint(NetworkHelper.IPv6Support ? IPAddress.IPv6Any : IPAddress.Any, config.Data.Server.ServicePort); Socket socket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.IPv6Only(localEndPoint.AddressFamily, false); socket.ReuseBind(localEndPoint); @@ -48,7 +48,7 @@ namespace cmonitor.server acceptEventArg.Completed += IO_Completed; StartAccept(acceptEventArg); - socketUdp = new UdpClient(new IPEndPoint(IPAddress.Any, config.Server.ServicePort)); + socketUdp = new UdpClient(new IPEndPoint(IPAddress.Any, config.Data.Server.ServicePort)); //socketUdp.JoinMulticastGroup(config.BroadcastIP); socketUdp.Client.EnableBroadcast = true; socketUdp.Client.WindowsUdpBug(); @@ -74,9 +74,9 @@ namespace cmonitor.server { dic.Add(item, new BroadcastEndpointInfo { - Web = config.Server.WebPort, - Api = config.Server.ApiPort, - Service = config.Server.ServicePort + Web = config.Data.Server.WebPort, + Api = config.Data.Server.ApiPort, + Service = config.Data.Server.ServicePort }); } diff --git a/cmonitor/server/config/Config.cs b/cmonitor/server/config/Config.cs new file mode 100644 index 00000000..1b427774 --- /dev/null +++ b/cmonitor/server/config/Config.cs @@ -0,0 +1,14 @@ +namespace cmonitor.config +{ + public sealed partial class ConfigInfo + { + public ConfigServerInfo Server { get; set; } = new ConfigServerInfo(); + } + public sealed partial class ConfigServerInfo + { + public int WebPort { get; set; } = 1800; + public string WebRoot { get; set; } = "./web/"; + public int ApiPort { get; set; } = 1801; + public int ServicePort { get; set; } = 1802; + } +} diff --git a/cmonitor/startup/StartupTransfer.cs b/cmonitor/startup/StartupTransfer.cs index dfaae74b..7449d31b 100644 --- a/cmonitor/startup/StartupTransfer.cs +++ b/cmonitor/startup/StartupTransfer.cs @@ -8,18 +8,23 @@ namespace cmonitor.startup public static class StartupTransfer { static List startups; - public static void Init() + public static void Init(Config config) { - startups = ReflectionHelper.GetInterfaceSchieves(typeof(IStartup)).Select(c => Activator.CreateInstance(c) as IStartup).ToList(); + var types = ReflectionHelper.GetInterfaceSchieves(typeof(IStartup)); + if (config.Data.Common.PluginNames.Length > 0) + { + types = types.Where(c => config.Data.Common.PluginNames.Any(d => c.FullName.Contains(d))); + } + startups = types.Select(c => Activator.CreateInstance(c) as IStartup).ToList(); } public static void Add(ServiceCollection serviceCollection, Config config, Assembly[] assemblies) { foreach (var startup in startups) { - if (config.Common.Modes.Contains("client")) + if (config.Data.Common.Modes.Contains("client")) startup.AddClient(serviceCollection, config, assemblies); - if (config.Common.Modes.Contains("server")) + if (config.Data.Common.Modes.Contains("server")) startup.AddServer(serviceCollection, config, assemblies); } } @@ -27,9 +32,9 @@ namespace cmonitor.startup { foreach (var startup in startups) { - if (config.Common.Modes.Contains("client")) + if (config.Data.Common.Modes.Contains("client")) startup.UseClient(serviceProvider, config, assemblies); - if (config.Common.Modes.Contains("server")) + if (config.Data.Common.Modes.Contains("server")) startup.UseServer(serviceProvider, config, assemblies); } } diff --git a/cmonitor/web/WebServer.cs b/cmonitor/web/WebServer.cs index 6c844e67..4f829f03 100644 --- a/cmonitor/web/WebServer.cs +++ b/cmonitor/web/WebServer.cs @@ -26,7 +26,7 @@ namespace cmonitor.web { HttpListener http = new HttpListener(); http.IgnoreWriteExceptions = true; - http.Prefixes.Add($"http://+:{config.Server.WebPort}/"); + http.Prefixes.Add($"http://+:{config.Data.Server.WebPort}/"); http.Start(); http.BeginGetContext(Callback, http); @@ -53,7 +53,7 @@ namespace cmonitor.web if (path == "/") path = "index.html"; - path = Path.Join(config.Server.WebRoot, path); + path = Path.Join(config.Data.Server.WebRoot, path); if (File.Exists(path)) { byte[] bytes = File.ReadAllBytes(path); diff --git a/cmonitor/web/WebStartup.cs b/cmonitor/web/WebStartup.cs index 2eafe188..1510cfcf 100644 --- a/cmonitor/web/WebStartup.cs +++ b/cmonitor/web/WebStartup.cs @@ -25,7 +25,7 @@ namespace cmonitor.web { IWebServer webServer = serviceProvider.GetService(); webServer.Start(); - Logger.Instance.Info($"web listen:{config.Server.WebPort}"); + Logger.Instance.Info($"web listen:{config.Data.Server.WebPort}"); } } } diff --git a/common.libs/FireWallHelper.cs b/common.libs/FireWallHelper.cs index 5fa94610..3610f65f 100644 --- a/common.libs/FireWallHelper.cs +++ b/common.libs/FireWallHelper.cs @@ -31,7 +31,9 @@ namespace common.libs private static void Windows(string fileName) { - string content = $@"@echo off + try + { + string content = $@"@echo off cd ""%CD%"" for /f ""tokens=4,5 delims=. "" %%a in ('ver') do if %%a%%b geq 60 goto new @@ -49,9 +51,13 @@ cmd /c netsh advfirewall firewall add rule name=""{fileName}"" dir=in action=all cmd /c netsh advfirewall firewall add rule name=""{fileName}"" dir=in action=allow program=""%CD%\{fileName}.exe"" protocol=tcp enable=yes profile=private cmd /c netsh advfirewall firewall add rule name=""{fileName}"" dir=in action=allow program=""%CD%\{fileName}.exe"" protocol=udp enable=yes profile=private :end"; - System.IO.File.WriteAllText("firewall.bat", content); - CommandHelper.Execute("firewall.bat", string.Empty, new string[0]); - System.IO.File.Delete("firewall.bat"); + System.IO.File.WriteAllText("firewall.bat", content); + CommandHelper.Execute("firewall.bat", string.Empty, new string[0]); + System.IO.File.Delete("firewall.bat"); + } + catch (Exception) + { + } } } } diff --git a/common.libs/winapis/Win32Interop.cs b/common.libs/winapis/Win32Interop.cs index 02d3ce44..ef33729a 100644 --- a/common.libs/winapis/Win32Interop.cs +++ b/common.libs/winapis/Win32Interop.cs @@ -10,6 +10,7 @@ using System.Runtime.Serialization; using System.Security.Principal; using System.Text; using System.Threading.Tasks; +using static cmonitor.libs.winapis.WTSAPI32; using static common.libs.winapis.ADVAPI32; using static common.libs.winapis.Kernel32; using static common.libs.winapis.NetApi32; @@ -397,6 +398,24 @@ namespace common.libs.winapis return currentUsername == "NT AUTHORITY\\SYSTEM"; } + public static string GetUserName() + { + // 获取活动的控制台会话 ID + uint sessionId = WTSGetActiveConsoleSessionId(); + + IntPtr buffer; + uint bytesReturned; + string userName = ""; + + // 获取用户名 + if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WTS_INFO_CLASS.WTSUserName, out buffer, out bytesReturned)) + { + userName = Marshal.PtrToStringAnsi(buffer); + WTSFreeMemory(buffer); + } + + return userName; + } public static void SetHandleBlockKill(IntPtr handle) {