Compare commits
24
Commits
1c832ff7f2
..
v1.4.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e99092ca70 | ||
|
|
ebc2d03290 | ||
|
|
0a6cbbbf06 | ||
|
|
36ae4b3057 | ||
|
|
cbb84809d8 | ||
|
|
96f1bacd43 | ||
|
|
6a3d536d38 | ||
|
|
389de9d456 | ||
|
|
bc75e1ae99 | ||
|
|
46f4bf2dfb | ||
|
|
50a489e316 | ||
|
|
99db28e2e2 | ||
|
|
cc891e3670 | ||
|
|
d4f312c9d8 | ||
|
|
de621aa555 | ||
|
|
82f59b2469 | ||
|
|
1d875ddbd1 | ||
|
|
dcb5ae25c6 | ||
|
|
56a937fabb | ||
|
|
dc4fd792f6 | ||
|
|
5bff9df3fc | ||
|
|
45e1dd9f6c | ||
|
|
13c02fe50b | ||
|
|
cd10d0cc1b |
No files matched your search
+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,41 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日志
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP 运维套件 & WebSocket 传输 & 抓屏健壮性**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 工具集 27 → 60**:新增主机 / 连接 / 服务 / 计划任务管理(16 个,写操作执行前后复核,受 McpMachine / McpMachineDangerous 双开关)、远程交谈(4 个,McpChat)、文件系统写操作 delete_path / move_path / create_folder(McpFileWrite)、remote_block_input(带截止时间与看门狗)、copy_files_c2c(客户端间直传,服务端只中继)、search_file、get_server_status、get_keylog 扩展、mcp_list_sessions / mcp_cancel_session;离线主机查询、批量只读调用(ids ≤ 50)、列表过滤器与分页
|
||||
- **MCP 协议**:initialize instructions、能力上报(platform / remoteControl / fileTransferV2 / c2cPaths / registry 等)、工具注解(readOnly / destructive / idempotent / openWorld)、结构化结果二次文本块、通知取消(-32800)与 progress 进度、dry-run 预演、客户端结构化失败令牌(170–173:失败与空结果可区分)、错误码收敛(参数错误 -32012、写入失败 -32011)、超时经 `McpToolTimeoutMs` 可调
|
||||
- **MCP 端点**:内置 HTTPS(Schannel 同端口按首字节嗅探,RSA / ECDSA、支持 fullchain、不可用时 fail-closed)、请求体 2 MB 上限、Bearer 失败按源 IP 限流(1 分钟 10 次封 15 分钟)、`logs\mcp_audit.log` 审计
|
||||
- **WebSocket 传输**:新增 PROTO_WS(5) / PROTO_WSS(6),升级路径 `/api/ws`,仅放行 80/443 的网络也能接入;MFC 与 Go 服务端同一设备端口三路嗅探(明文 / TLS / WS);在线列表右键「协议切换」把已在线客户端在 直连 TCP / WS / WSS 之间远程切换(COMMAND_SET_PROTO 177,WSS 下发反代信任锚,5 分钟未登录自动回退)
|
||||
- **Windows 抓屏健壮性**:旋转显示器按真实纹理描述分配并直立图像(原首屏与每帧全黑)、DXGI 无帧自动切 GDI(无头 / Session 0)、工作站锁定与断开会话直接选 GDI(避免初始化卡死)、探测帧保留以便静态桌面首帧即出图、发送尺寸改为长边 ≤1920 / 短边 ≤1080 等比缩放
|
||||
- **Web 控制台**:非控制模式显示真实远端光标(形状变化即时、位置 ≤50 ms/次);iOS 幽灵竖线(画布固定 + `ctx.setTransform` 绘制);竖屏输入法下指针与画面错位(覆盖层与画布同包含块、坐标用画布局部像素);输入条固定在画面下沿不再随键盘跳动;Go 端滚轮小数 delta 导致彻底失灵
|
||||
- **Linux / macOS 客户端能力补齐**:MCP 一级工具(kill_process / exec_command / 终端 / 远控 / 剪贴板)支持 Linux、文件上传下载与 C2C 目标支持 POSIX、Linux 远程升级(COMMAND_UPDATE 校验 + 原子替换 + execv 回滚)、TLS 切换立即生效、屏幕预览(服务端统一转 JPEG)、桌面 / 下载 / 主目录快捷方式按 `user-dirs.dirs` 展开、运行时长按北京时间换算
|
||||
- **客户端与主控**:在线列表右键「复制名称」、高级菜单与免责声明补 16×16 图标、SOCKS5 代理映射移除 HP-Socket 依赖并重写(阻塞 socket + select、仅绑回环、SOCKS5 握手按字节流解析、按主连接队列背压、30 秒握手看门狗)
|
||||
|
||||
**改进:**
|
||||
- 依赖清单扩充至 23 项 / LICENSE-THIRD-PARTY 至 657 行(10 类许可证、33 项组件),并更正 x264(GPL-2.0 静态链接)、FFmpeg(静态链接、仅解码)、FRP(本地修改)三处
|
||||
- `DISABLE_X264_FOR_TEST` 真正生效(此前既没前置 config.h 也仍引用 x264 类型),libyuv 从该开关解绑
|
||||
- `build.ps1` 按 `atlmfc` 库存在与否挑选 MSBuild 实例(修复挑到无 ATL 的 BuildTools 时 `LNK1104 atls.lib`)
|
||||
- 协议切换、SOCKS5 会话日志、复制名称、MCP 新开关等字符串补齐 en_US / zh_TW / de_DE
|
||||
|
||||
**Bug 修复:**
|
||||
- 主控重启后客户端重连空转(一秒 919 行重复日志刷爆环形缓冲)
|
||||
- 右键菜单作用于错误主机(虚拟列表行号在菜单模态循环期间被排序 / 下线挪动)
|
||||
- 构建对话框默认协议错位(`CBS_SORT` + `AddString` 致 `SetCurSel(0)` 落在 HTTP)
|
||||
- 在线列表表头偶发闪烁(缺 `WS_CLIPCHILDREN`,改为只擦最后一列右侧空带)
|
||||
- 加壳客户端收不到即时消息 / 远程交谈对话框创建失败(资源段为空,改内嵌模板)、非 936 系统标题与正文乱码、多显示器居中偏移、窗口与线程泄漏
|
||||
- 键盘记录饿死快捷键转发(钩子线程不泵消息被系统摘除)
|
||||
- 锁定聊天时 Win 键不转发(未 `CallNextHookEx` 挡住后续钩子)
|
||||
- 聊天消息以 e 开头被丢弃(首个字节 101 被心跳守卫吞掉)
|
||||
- 文件搜索栈溢出(`wsprintf` 无界拼 MAX_PATH,深目录必崩)
|
||||
- 空目录下载超时;文件传输会话子连接悬空指针(超时后 `CancelIO` 到已回收连接)
|
||||
- 连接列表地址反序(`192.168.0.55` → `55.0.168.192`)与宽窄字符格式化塌缩
|
||||
- macOS 合盖外接屏鼠标偏移(取被抓显示器的 `CGDisplayBounds`,另加按主机保存的校准)
|
||||
- 任务与机器管理一批缺陷(计划任务命令组装、解冻只恢复一个线程、窗口列表空指针、服务枚举句柄泄漏、删除进程 PID 判断与句柄、IE 历史时间戳翻转等)
|
||||
|
||||
### v1.4.1 (2026.10.20)
|
||||
|
||||
**Web 运维控制台 & 安全加固 & 单向 TLS**
|
||||
|
||||
@@ -378,6 +378,41 @@ Valid : 2026-02-01 to 2028-02-01
|
||||
|
||||
## Changelog
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP operations suite & WebSocket transport & capture robustness**
|
||||
|
||||
**New features:**
|
||||
- **MCP tool count grew from 27 to 60**: host / connection / service / scheduled-task management (16 tools, writes re-read state before and re-verify after, gated by both McpMachine and McpMachineDangerous), remote chat (4 tools, McpChat), filesystem writes delete_path / move_path / create_folder (McpFileWrite), remote_block_input (with a deadline and a watchdog), copy_files_c2c (client-to-client delivery relayed without touching server disk), search_file, an extended get_keylog, get_server_status, mcp_list_sessions / mcp_cancel_session; offline-host queries, batched read-only calls (ids up to 50), list filters and paging
|
||||
- **MCP protocol**: initialize instructions, capability reporting (platform / remoteControl / fileTransferV2 / c2cPaths / registry and more), tool annotations (readOnly / destructive / idempotent / openWorld), a second text block carrying the structured result, notification-based cancellation (-32800) and progress, dry-run previews, structured client failure tokens (170-173, so failure is distinguishable from an empty result), consolidated error codes (parameter errors -32012, write failures -32011), and a tunable timeout via `McpToolTimeoutMs`
|
||||
- **MCP endpoint**: built-in HTTPS (Schannel sniffing on the same port, RSA / ECDSA, fullchain support, fail-closed when the certificate is unusable), a 2 MB request-body cap, per-source-IP rate limiting of Bearer failures (10 in a minute blocks for 15 minutes), and an audit trail in `logs\mcp_audit.log`
|
||||
- **WebSocket transport**: new PROTO_WS(5) / PROTO_WSS(6) with upgrade path `/api/ws`, so clients on networks that only allow 80/443 can connect; both MFC and Go servers sniff plaintext / TLS / WS on the same device port; a new "Protocol switch" context-menu action moves an already-online client between direct TCP / WS / WSS (COMMAND_SET_PROTO 177, WSS carries the reverse-proxy trust anchor, automatic rollback if login does not succeed within 5 minutes)
|
||||
- **Windows capture robustness**: rotated displays allocate by the real texture description and orient the image (previously fully black first and every frame), DXGI falls back to GDI when no frame arrives (headless / Session 0), locked workstations and disconnected sessions select GDI up front (avoiding a stuck initialisation), the probe frame is kept so a static desktop paints on first connect, and the send size is scaled proportionally to long edge <= 1920 / short edge <= 1080
|
||||
- **Web console**: the real remote cursor is shown outside control mode (shape changes immediately, position at most every 50 ms); iOS ghost vertical lines (canvas pinned, drawn with `ctx.setTransform`); pointer misalignment with the IME open in portrait (overlay shares the canvas containing block and uses canvas-local pixels); the input bar sits at the bottom of the picture instead of following the keyboard; fractional wheel deltas on the Go server no longer break scrolling entirely
|
||||
- **Linux / macOS client parity**: MCP tier-one tools (kill_process / exec_command / terminal / remote control / clipboard) now accept Linux hosts; upload, download and C2C targets support POSIX paths; Linux remote upgrade (COMMAND_UPDATE with verification, atomic replace and execv rollback); TLS switches take effect immediately; screen preview (the server converts to JPEG in one place); Desktop / Downloads / Home shortcuts expand through `user-dirs.dirs`; uptime is converted from Beijing time
|
||||
- **Client and master**: "Copy name" in the online-list context menu; 16x16 icons for the advanced menu and the disclaimer item; the SOCKS5 proxy mapping drops the HP-Socket dependency and is rewritten (blocking socket + select, byte-level SOCKS5 parsing, back-pressure against the master send queue, 30-second handshake watchdog)
|
||||
|
||||
**Improvements:**
|
||||
- The dependency inventory grew to 23 items and LICENSE-THIRD-PARTY to 657 lines (10 license classes, 33 components), with corrections for x264 (GPL-2.0, statically linked), FFmpeg (static, decoders only) and FRP (locally modified)
|
||||
- `DISABLE_X264_FOR_TEST` now actually works (config.h was not included first and the class still referenced x264 types), and libyuv is no longer tied to that switch
|
||||
- `build.ps1` picks the MSBuild instance that has the `atlmfc` libraries, fixing `LNK1104 atls.lib` when a BuildTools install without ATL was chosen first
|
||||
- Strings added by protocol switching, SOCKS5 session logging, "Copy name" and the new MCP switches are translated in en_US / zh_TW / de_DE
|
||||
|
||||
**Bug fixes:**
|
||||
- Clients spun in a reconnect loop after a master restart (919 identical log lines per second flushed the 1000-line ring buffer)
|
||||
- The context menu could act on the wrong host (virtual-list row indices shift while the menu's modal loop keeps dispatching timers)
|
||||
- The build dialog defaulted to the wrong protocol (`CBS_SORT` plus `AddString` made `SetCurSel(0)` land on HTTP)
|
||||
- Occasional header flicker in the online list (missing `WS_CLIPCHILDREN`; erasure now limited to the empty band right of the last column)
|
||||
- Packed clients never showed instant messages / could not create the chat dialog (empty resource section, now an embedded template), with garbled titles and text on non-936 systems, off-centre placement on multi-monitor hosts, and window and thread leaks
|
||||
- The keylogger hook starved hotkey forwarding (its thread never pumped messages and Windows removed the hook)
|
||||
- Win-key forwarding stopped while chat was locked (`CallNextHookEx` was skipped, shadowing later hooks)
|
||||
- Chat messages starting with "e" were dropped (byte 101 was swallowed by the heartbeat guard)
|
||||
- Stack overflow in recursive file search (`wsprintf` into a `MAX_PATH` buffer with no bound)
|
||||
- Downloading an empty directory timed out; file-transfer sessions kept dangling sub-connection pointers (`CancelIO` against a recycled connection after a timeout)
|
||||
- Connection-list addresses were byte-reversed (`192.168.0.55` shown as `55.0.168.192`) and collapsed by a mixed wide/narrow format string
|
||||
- macOS mouse offset in clamshell mode (now uses the captured display's `CGDisplayBounds`, plus a per-host calibration)
|
||||
- A batch of machine and task-management defects (scheduled-task command assembly, thawing only one thread, a null dereference on an empty window list, leaked service-enumeration handles, PID truncation and handle leaks when deleting processes, flipped IE history timestamps)
|
||||
|
||||
### v1.4.1 (2026.10.20)
|
||||
|
||||
**Web operations console & security hardening & one-way TLS**
|
||||
|
||||
@@ -378,6 +378,41 @@ nohup ./server_linux_amd64 --port 6543 --http-port 9001 > yama.log 2>&1 &
|
||||
|
||||
## 更新日誌
|
||||
|
||||
### v1.4.2 (2026.10.31)
|
||||
|
||||
**MCP 維運套件 & WebSocket 傳輸 & 擷取畫面健壯性**
|
||||
|
||||
**新功能:**
|
||||
- **MCP 工具集 27 → 60**:新增主機 / 連線 / 服務 / 排程工作管理(16 個,寫入操作執行前後複核,受 McpMachine / McpMachineDangerous 雙開關)、遠端交談(4 個,McpChat)、檔案系統寫入 delete_path / move_path / create_folder(McpFileWrite)、remote_block_input(帶截止時間與看門狗)、copy_files_c2c(用戶端間直傳,伺服端只中繼不落地)、search_file、get_keylog 擴充、get_server_status、mcp_list_sessions / mcp_cancel_session;離線主機查詢、批次唯讀呼叫(ids ≤ 50)、列表過濾與分頁
|
||||
- **MCP 協定**:initialize instructions、能力上報(platform / remoteControl / fileTransferV2 / c2cPaths / registry 等)、工具註解(readOnly / destructive / idempotent / openWorld)、結構化結果二次文字區塊、通知取消(-32800)與 progress 進度、dry-run 預演、用戶端結構化失敗權杖(170–173,失敗與空結果可區分)、錯誤碼收斂(參數錯誤 -32012、寫入失敗 -32011)、逾時可經 `McpToolTimeoutMs` 調整
|
||||
- **MCP 端點**:內建 HTTPS(Schannel 同連接埠依首位元組嗅探,RSA / ECDSA、支援 fullchain、不可用時 fail-closed)、請求本文 2 MB 上限、Bearer 失敗依來源 IP 限流(1 分鐘 10 次封 15 分鐘)、`logs\mcp_audit.log` 稽核
|
||||
- **WebSocket 傳輸**:新增 PROTO_WS(5) / PROTO_WSS(6),升級路徑 `/api/ws`,只放行 80/443 的網路也能接入;MFC 與 Go 伺服端同一裝置連接埠三路嗅探(明文 / TLS / WS);線上列表右鍵「協定切換」把已線上用戶端在 直連 TCP / WS / WSS 之間遠端切換(COMMAND_SET_PROTO 177,WSS 下發反代信任錨,5 分鐘未登入自動回退)
|
||||
- **Windows 擷取畫面健壯性**:旋轉顯示器依真實紋理描述配置並直立影像(原首屏與每幀全黑)、DXGI 無幀自動切 GDI(無頭 / Session 0)、工作站鎖定與中斷工作階段直接選 GDI(避免初始化卡死)、保留探測幀讓靜態桌面首幀即出圖、傳送尺寸改為長邊 ≤1920 / 短邊 ≤1080 等比縮放
|
||||
- **Web 控制台**:非控制模式顯示真實遠端游標(形狀變化即時、位置 ≤50 ms/次);iOS 幽靈豎線(畫布固定 + `ctx.setTransform` 繪製);豎屏輸入法下指標與畫面錯位(覆蓋層與畫布同包含區塊、座標用畫布局部像素);輸入列固定在畫面下緣不再隨鍵盤跳動;Go 端滾輪小數 delta 導致徹底失靈
|
||||
- **Linux / macOS 用戶端能力補齊**:MCP 一級工具(kill_process / exec_command / 終端 / 遠控 / 剪貼簿)支援 Linux、檔案上傳下載與 C2C 目標支援 POSIX、Linux 遠端升級(COMMAND_UPDATE 校驗 + 原子替換 + execv 回退)、TLS 切換立即生效、螢幕預覽(伺服端統一轉 JPEG)、桌面 / 下載 / 主目錄捷徑依 `user-dirs.dirs` 展開、執行時間依北京時間換算
|
||||
- **用戶端與主控**:線上列表右鍵「複製名稱」、進階選單與免責聲明補 16×16 圖示、SOCKS5 代理映射移除 HP-Socket 依賴並重寫(阻塞 socket + select、位元組級 SOCKS5 解析、依主連線佇列背壓、30 秒握手看門狗)
|
||||
|
||||
**改進:**
|
||||
- 依賴清單擴充至 23 項 / LICENSE-THIRD-PARTY 至 657 行(10 類授權、33 項元件),並更正 x264(GPL-2.0 靜態連結)、FFmpeg(靜態連結、僅解碼)、FRP(本機修改)三處
|
||||
- `DISABLE_X264_FOR_TEST` 真正生效(先前既未前置 config.h 也仍引用 x264 型別),libyuv 從該開關解綁
|
||||
- `build.ps1` 依 `atlmfc` 函式庫存在與否挑選 MSBuild 實例(修復挑到無 ATL 的 BuildTools 時 `LNK1104 atls.lib`)
|
||||
- 協定切換、SOCKS5 工作階段日誌、複製名稱、MCP 新開關等字串補齊 en_US / zh_TW / de_DE
|
||||
|
||||
**Bug 修復:**
|
||||
- 主控重啟後用戶端重連空轉(一秒 919 行重複日誌刷爆環形緩衝)
|
||||
- 右鍵選單作用於錯誤主機(虛擬列表列號在選單模態迴圈期間被排序 / 離線挪動)
|
||||
- 建置對話框預設協定錯位(`CBS_SORT` + `AddString` 致 `SetCurSel(0)` 落在 HTTP)
|
||||
- 線上列表表頭偶發閃爍(缺 `WS_CLIPCHILDREN`,改為只擦最後一欄右側空帶)
|
||||
- 加殼用戶端收不到即時訊息 / 遠端交談對話框建立失敗(資源區段為空,改內嵌模板)、非 936 系統標題與本文亂碼、多螢幕居中偏移、視窗與執行緒洩漏
|
||||
- 鍵盤記錄餓死快速鍵轉發(掛鉤執行緒不泵訊息被系統摘除)
|
||||
- 鎖定聊天時 Win 鍵不轉發(未 `CallNextHookEx` 擋住後續掛鉤)
|
||||
- 聊天訊息以 e 開頭被丟棄(首位元組 101 被心跳守衛吞掉)
|
||||
- 檔案搜尋堆疊溢位(`wsprintf` 無界拼 MAX_PATH,深目錄必崩)
|
||||
- 空目錄下載逾時;檔案傳輸工作階段子連線懸空指標(逾時後 `CancelIO` 到已回收連線)
|
||||
- 連線列表位址反序(`192.168.0.55` → `55.0.168.192`)與寬窄字元格式化塌縮
|
||||
- macOS 合蓋外接螢幕滑鼠偏移(取被抓螢幕的 `CGDisplayBounds`,另加依主機儲存的校準)
|
||||
- 工作與機器管理一批缺陷(排程工作命令組裝、解凍只恢復一個執行緒、視窗列表空指標、服務列舉控制代碼洩漏、刪除處理程序 PID 判斷與控制代碼、IE 歷程時間戳翻轉等)
|
||||
|
||||
### v1.4.1 (2026.10.20)
|
||||
|
||||
**Web 維運控制台 & 安全加固 & 單向 TLS**
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -11,4 +11,6 @@ public:
|
||||
virtual bool Start() = 0;
|
||||
virtual bool Stop() = 0;
|
||||
virtual bool IsMainInstance() = 0;
|
||||
// 分享实例(被别人挂在主控上)的连接入口由分享方控制,不跟随本机主控的协议切换。
|
||||
virtual bool IsShared() { return false; }
|
||||
};
|
||||
+148
-2
@@ -373,6 +373,11 @@ DWORD WINAPI AutoRun(LPVOID param)
|
||||
{
|
||||
do {
|
||||
TestRun(NULL, 0);
|
||||
// 旧工作线程还没退完时 TestRun 会立刻返回(此时连日志都不打,见其内部的
|
||||
// SetServer 返回值判断),不睡就会满速空转、白占一个核且毫无提示。
|
||||
// 只在真会空转的条件下睡,正常重启路径零延迟。
|
||||
if (S_SERVER_EXIT == g_MyApp.g_bExit && g_MyApp.IsThreadRun())
|
||||
Sleep(20);
|
||||
} while (S_SERVER_EXIT == g_MyApp.g_bExit);
|
||||
|
||||
if (g_MyApp.g_Connection->ClientType() == CLIENT_TYPE_SHELLCODE) {
|
||||
@@ -415,8 +420,11 @@ extern "C" __declspec(dllexport) void TestRun(char* szServerIP,int uPort)
|
||||
ClientApp& app(g_MyApp);
|
||||
CONNECT_ADDRESS& settings(*(app.g_Connection));
|
||||
if (app.IsThreadRun()) {
|
||||
settings.SetServer(szServerIP, uPort);
|
||||
Mprintf("TestRun SetServer[%s:%d]\n", szServerIP ? szServerIP : "", uPort);
|
||||
// 只在地址真的变了才记日志。主控端重启后,加载器和 AutoRun 会反复调用本函数
|
||||
// 直到旧工作线程退完,每次都打一行会把客户端 1000 行环形日志冲光。
|
||||
// SetServer 返回 false 表示地址没变,同时也涵盖 TestRun(NULL, 0)(空地址直接返回)。
|
||||
if (settings.SetServer(szServerIP, uPort))
|
||||
Mprintf("TestRun SetServer[%s:%d]\n", szServerIP ? szServerIP : "", uPort);
|
||||
return;
|
||||
}
|
||||
app.SetThreadRun(TRUE);
|
||||
@@ -584,6 +592,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);
|
||||
@@ -665,6 +799,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));
|
||||
@@ -689,6 +827,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);
|
||||
|
||||
@@ -61,6 +61,10 @@ public:
|
||||
{
|
||||
SAFE_DELETE(g_Connection);
|
||||
}
|
||||
bool IsShared() override
|
||||
{
|
||||
return m_bShared != FALSE;
|
||||
}
|
||||
ClientApp* SetID(unsigned id)
|
||||
{
|
||||
m_ID = id;
|
||||
|
||||
+112
-2
@@ -391,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);
|
||||
}
|
||||
@@ -467,6 +470,58 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
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())同样拒绝
|
||||
@@ -480,16 +535,69 @@ BOOL IOCPClient::ConnectServer(const char* szServerIP, unsigned short uPort)
|
||||
m_sClientSocket = INVALID_SOCKET;
|
||||
return FALSE;
|
||||
}
|
||||
if (TlsEnabled()) {
|
||||
if (!m_tls.Handshake(m_sClientSocket)) {
|
||||
// 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;
|
||||
Mprintf("连接服务端成功: %s:%d.\n", m_sCurIP.c_str(), (int)port);
|
||||
|
||||
@@ -908,6 +1016,8 @@ VOID IOCPClient::Disconnect()
|
||||
#ifdef YAMA_TLS_CHANNEL
|
||||
m_useTls = false; // 连接已断,Send/Recv 回到明文路径(下次 ConnectServer 重新锁定)
|
||||
#endif
|
||||
m_useWs = false; // WebSocket 帧状态同样按连接锁定,重连时重新握手
|
||||
m_ws.Reset();
|
||||
m_bConnected = FALSE;
|
||||
}
|
||||
|
||||
|
||||
+36
-1
@@ -15,6 +15,9 @@
|
||||
// 且不定义 YAMA_TLS_CHANNEL,下方代码自动退回明文。
|
||||
#include "TlsChannel.h"
|
||||
|
||||
// WebSocket 传输(经反代 443 等受限端口接入)。头文件实现,各平台编译目标无需改动。
|
||||
#include "WsChannel.h"
|
||||
|
||||
#include "Buffer.h"
|
||||
#include "zstd/zstd.h"
|
||||
#include "domain_pool.h"
|
||||
@@ -36,6 +39,7 @@
|
||||
#endif
|
||||
#include "IOCPBase.h"
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <chrono>
|
||||
|
||||
@@ -204,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;
|
||||
@@ -286,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
|
||||
@@ -293,6 +311,9 @@ 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);
|
||||
@@ -304,6 +325,8 @@ protected:
|
||||
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);
|
||||
@@ -312,8 +335,11 @@ protected:
|
||||
}
|
||||
// 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
|
||||
@@ -328,13 +354,22 @@ 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 会话(或反过来),白白制造协议错误。
|
||||
bool m_useTls = false;
|
||||
std::atomic<bool> m_useTls{false};
|
||||
#endif
|
||||
BOOL m_bWorkThread;
|
||||
HANDLE m_hWorkThread;
|
||||
|
||||
+126
-2
@@ -45,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);
|
||||
}
|
||||
@@ -800,6 +804,28 @@ void ResponseDisable(IOCPClient *client, const char* type, LPBYTE data, int size
|
||||
|
||||
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;
|
||||
@@ -853,15 +879,20 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
|
||||
case COMMAND_TLS_ENABLE: {
|
||||
// 服务端下发信任锚证书:payload = PEM 正文(szBuffer+1 .. ulLength-1)。
|
||||
// 写入注册表 settings\tls_cert,客户端下次启动读到证书即启用 TLS(非实时)。
|
||||
// 写入注册表 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,
|
||||
@@ -869,6 +900,94 @@ VOID CKernelManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1123,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()) {
|
||||
|
||||
+1
-11
@@ -125,17 +125,7 @@ private:
|
||||
|
||||
bool IsWorkstationLocked()
|
||||
{
|
||||
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ);
|
||||
// 如果无法打开桌面,可能是因为桌面已经切换到 Winlogon
|
||||
if (!hInput) return true;
|
||||
char name[256] = {0};
|
||||
DWORD needed;
|
||||
bool isLocked = false;
|
||||
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
|
||||
isLocked = (_stricmp(name, "Winlogon") == 0);
|
||||
}
|
||||
CloseDesktop(hInput);
|
||||
return isLocked;
|
||||
return ::IsWorkstationLocked();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -156,6 +156,22 @@ HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess)
|
||||
return hInputDesktop;
|
||||
}
|
||||
|
||||
bool IsWorkstationLocked()
|
||||
{
|
||||
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ);
|
||||
// 打不开输入桌面,通常就是已经切到 Winlogon(锁屏)
|
||||
if (!hInput) return true;
|
||||
|
||||
char name[256] = { 0 };
|
||||
DWORD needed = 0;
|
||||
bool isLocked = false;
|
||||
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
|
||||
isLocked = (_stricmp(name, "Winlogon") == 0);
|
||||
}
|
||||
CloseDesktop(hInput);
|
||||
return isLocked;
|
||||
}
|
||||
|
||||
// 返回新桌面句柄,如果没有变化返回NULL
|
||||
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights)
|
||||
{
|
||||
|
||||
@@ -15,6 +15,10 @@
|
||||
|
||||
HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess = 0);
|
||||
|
||||
// 工作站是否已锁屏(输入桌面切到 Winlogon)。锁屏时 DXGI 桌面复制在部分环境会卡在
|
||||
// 初始化里不返回,抓屏初始化需要据此提前走 GDI。
|
||||
bool IsWorkstationLocked();
|
||||
|
||||
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights);
|
||||
|
||||
bool SwitchToDesktopIfChanged(HDESK& currentDesk, DWORD accessRights);
|
||||
|
||||
@@ -866,6 +866,24 @@ public:
|
||||
return bmpInfo;
|
||||
}
|
||||
|
||||
// 默认发送尺寸上限:等比缩放,保证长边 ≤1920、短边 ≤1080(横竖屏都成立)。
|
||||
// 原实现是 min(1920,w) 与 min(1080,h) 各自独立截断,宽高比会被破坏:
|
||||
// 竖屏 1440×2560 会被压成 1440×1080(高度只剩 42%)。
|
||||
static void FitDefaultSendSize(LONG& w, LONG& h)
|
||||
{
|
||||
const LONG longEdge = (w > h) ? w : h;
|
||||
const LONG shortEdge = (w > h) ? h : w;
|
||||
float s = 1.0f;
|
||||
if (longEdge > 1920)
|
||||
s = 1920.0f / (float)longEdge;
|
||||
if ((float)shortEdge * s > 1080.0f)
|
||||
s = 1080.0f / (float)shortEdge;
|
||||
if (s < 1.0f) {
|
||||
w = (LONG)((float)w * s);
|
||||
h = (LONG)((float)h * s);
|
||||
}
|
||||
}
|
||||
|
||||
// 编码器 lazy 创建。委托 EncoderFactory 完成"硬编探测 + 软编 fallback"。
|
||||
void ensureEncoder(int width, int height)
|
||||
{
|
||||
|
||||
+382
-32
@@ -24,6 +24,39 @@ private:
|
||||
ID3D11Texture2D* cpuTexture = nullptr;
|
||||
BYTE* m_NextBuffer = nullptr;
|
||||
|
||||
// 各缓冲是否已成功抓到过至少一帧。
|
||||
// DXGI 的语义是「只在桌面有变化时才返回新帧」,静止桌面下 AcquireNextFrame
|
||||
// 必然超时(DXGI_ERROR_WAIT_TIMEOUT)。超时必须复用上一帧而不是当作失败,
|
||||
// 否则 ScanNextScreen 恒返回 nullptr → 只发光标帧 → H.264 编码器永远拿不到
|
||||
// 首帧 IDR → 服务端 Decode() 不执行 → m_bIsFirst 无法解除 → 永久黑屏。
|
||||
bool m_bFirstValid = false;
|
||||
bool m_bNextValid = false;
|
||||
static constexpr int kNoNewFrame = -100; // 无新帧,非错误
|
||||
|
||||
// 旋转输出(竖屏)下 DXGI 给的表面是「未旋转」的横向位图,
|
||||
// 与桌面逻辑尺寸互为宽高交换,需要自行旋转。这里记录表面真实尺寸与旋转角。
|
||||
int m_surfW = 0;
|
||||
int m_surfH = 0;
|
||||
DXGI_MODE_ROTATION m_rotation = DXGI_MODE_ROTATION_IDENTITY;
|
||||
|
||||
// InitDXGI 探测阶段抓到的帧。DuplicateOutput 之后 DXGI 会推送一帧当前桌面,
|
||||
// 静止桌面下这往往就是唯一能拿到的一帧,丢弃它会导致首屏只能等桌面变化。
|
||||
// 因此探测完先留在手上(不 ReleaseFrame),由 ConsumeProbeFrame() 消费。
|
||||
IDXGIResource* m_probeRes = nullptr;
|
||||
|
||||
// DXGI 在部分环境下完全拿不到帧(无头/虚拟显示、Session 0 桌面、驱动不推送
|
||||
// duplication 通知等),连首屏都要靠 GDI 兜底。这种情况下本会话直接降级为
|
||||
// GDI 抓屏,否则 ScanNextScreen 永远返回 nullptr,表现为「首屏有画面,
|
||||
// 但之后切换窗口画面不再更新」。
|
||||
bool m_bGDIFallback = false;
|
||||
|
||||
// GDI 兜底用的离屏缓冲。降级后是每帧都要走的持续路径,必须复用,
|
||||
// 否则每帧 CreateDIBSection/DeleteObject 会反复分配十几 MB 造成抖动。
|
||||
HDC m_hGdiMemDC = nullptr;
|
||||
HBITMAP m_hGdiBmp = nullptr;
|
||||
HGDIOBJ m_hGdiOldBmp = nullptr;
|
||||
void* m_pGdiBits = nullptr;
|
||||
|
||||
public:
|
||||
ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP, BOOL all = FALSE, int level = LEVEL_H264_SOFT,
|
||||
RECT rc = {0}, BOOL switchScreen = TRUE)
|
||||
@@ -73,7 +106,8 @@ public:
|
||||
|
||||
// 4. 获取 DXGI 输出(屏幕)
|
||||
static UINT screen = 0;
|
||||
HRESULT r = dxgiAdapter->EnumOutputs(switchScreen ? screen++ : screen, &dxgiOutput);
|
||||
UINT outIndex = switchScreen ? screen++ : screen;
|
||||
HRESULT r = dxgiAdapter->EnumOutputs(outIndex, &dxgiOutput);
|
||||
if (r == DXGI_ERROR_NOT_FOUND && all) {
|
||||
screen = 0;
|
||||
idx ++;
|
||||
@@ -101,16 +135,67 @@ public:
|
||||
// 7. 获取屏幕大小
|
||||
DXGI_OUTDUPL_DESC duplDesc;
|
||||
deskDupl->GetDesc(&duplDesc);
|
||||
m_ulFullWidth = duplDesc.ModeDesc.Width;
|
||||
m_ulFullHeight = duplDesc.ModeDesc.Height;
|
||||
|
||||
// 8. 创建 CPU 访问纹理
|
||||
// 旋转输出(竖屏)下 ModeDesc 报告的是逻辑桌面尺寸,而实际捕获表面是
|
||||
// 「未旋转」的横向位图,两者宽高互换。若按 ModeDesc 建 CPU 纹理,
|
||||
// CopyResource 会静默不复制(返回 void)→ cpuTexture 全零 → 黑屏。
|
||||
// 先取一帧读真实纹理描述;取不到时按旋转关系推导,避免退回错误尺寸。
|
||||
m_rotation = duplDesc.Rotation;
|
||||
const bool swapWH = (m_rotation == DXGI_MODE_ROTATION_ROTATE90 ||
|
||||
m_rotation == DXGI_MODE_ROTATION_ROTATE270);
|
||||
|
||||
UINT realW = swapWH ? duplDesc.ModeDesc.Height : duplDesc.ModeDesc.Width;
|
||||
UINT realH = swapWH ? duplDesc.ModeDesc.Width : duplDesc.ModeDesc.Height;
|
||||
DXGI_FORMAT realFmt = DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
{
|
||||
IDXGIResource* probeRes = nullptr;
|
||||
DXGI_OUTDUPL_FRAME_INFO probeInfo = {};
|
||||
HRESULT phr = deskDupl->AcquireNextFrame(200, &probeInfo, &probeRes);
|
||||
if (SUCCEEDED(phr)) {
|
||||
if (probeRes) {
|
||||
ID3D11Texture2D* probeTex = nullptr;
|
||||
if (SUCCEEDED(probeRes->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&probeTex)) && probeTex) {
|
||||
D3D11_TEXTURE2D_DESC td = {};
|
||||
probeTex->GetDesc(&td);
|
||||
realW = td.Width;
|
||||
realH = td.Height;
|
||||
realFmt = td.Format;
|
||||
probeTex->Release();
|
||||
}
|
||||
// 不要丢弃这一帧:暂存起来,等缓冲分配完由 ConsumeProbeFrame()
|
||||
// 直接填充首屏。否则静止桌面下首屏 AcquireNextFrame 必然超时。
|
||||
m_probeRes = probeRes;
|
||||
} else {
|
||||
deskDupl->ReleaseFrame();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 内存布局按 4 字节/像素计算,非 4 字节格式回退 BGRA
|
||||
switch (realFmt) {
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM:
|
||||
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM:
|
||||
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
|
||||
case DXGI_FORMAT_R10G10B10A2_UNORM:
|
||||
break;
|
||||
default:
|
||||
Mprintf("[DXGI] unsupported fmt=%d, fallback BGRA\n", (int)realFmt);
|
||||
realFmt = DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
break;
|
||||
}
|
||||
// 后续所有缓冲/位图信息/缩放都按「正立」的逻辑尺寸计算
|
||||
m_surfW = (int)realW;
|
||||
m_surfH = (int)realH;
|
||||
m_ulFullWidth = swapWH ? realH : realW;
|
||||
m_ulFullHeight = swapWH ? realW : realH;
|
||||
|
||||
// 8. 创建 CPU 访问纹理(按表面原始尺寸/格式,保证 CopyResource 成功)
|
||||
D3D11_TEXTURE2D_DESC desc = {};
|
||||
desc.Width = m_ulFullWidth;
|
||||
desc.Height = m_ulFullHeight;
|
||||
desc.Width = realW;
|
||||
desc.Height = realH;
|
||||
desc.MipLevels = 1;
|
||||
desc.ArraySize = 1;
|
||||
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
|
||||
desc.Format = realFmt;
|
||||
desc.SampleDesc.Count = 1;
|
||||
desc.Usage = D3D11_USAGE_STAGING;
|
||||
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
|
||||
@@ -135,9 +220,8 @@ public:
|
||||
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
|
||||
4 * m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
} else {
|
||||
// strategy=0 或 maxWidth=0: 默认 1080p 限制
|
||||
m_BitmapInfor_Send->bmiHeader.biWidth = min(1920, m_BitmapInfor_Send->bmiHeader.biWidth);
|
||||
m_BitmapInfor_Send->bmiHeader.biHeight = min(1080, m_BitmapInfor_Send->bmiHeader.biHeight);
|
||||
// strategy=0 或 maxWidth=0: 默认 1080p 限制(等比,避免竖屏被压扁)
|
||||
FitDefaultSendSize(m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
|
||||
m_BitmapInfor_Send->bmiHeader.biSizeImage =
|
||||
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
|
||||
4 * m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
@@ -149,6 +233,12 @@ public:
|
||||
m_BmpZoomBuffer = new BYTE[m_BitmapInfor_Send->bmiHeader.biSizeImage * 2 + 12];
|
||||
m_BmpZoomFirst = nullptr;
|
||||
|
||||
// 缓冲就绪,把探测阶段暂存的那一帧直接填成首屏内容。
|
||||
// 这一步让首屏不再依赖「桌面发生变化」,连接后立即可出画面。
|
||||
if (m_probeRes) {
|
||||
ConsumeProbeFrame();
|
||||
}
|
||||
|
||||
// ROI
|
||||
int w = m_ROI.right - m_ROI.left, h = m_ROI.bottom - m_ROI.top;
|
||||
if (w > 0 && h > 0) {
|
||||
@@ -158,6 +248,11 @@ public:
|
||||
m_BitmapInfor_Send->bmiHeader.biHeight = h;
|
||||
m_BitmapInfor_Send->bmiHeader.biSizeImage = w * h * 4;
|
||||
}
|
||||
Mprintf("[DXGI] out=%u mode=%ux%u surf=%ux%u fmt=%d rot=%d -> send=%dx%d\n",
|
||||
outIndex, duplDesc.ModeDesc.Width, duplDesc.ModeDesc.Height,
|
||||
m_surfW, m_surfH, (int)realFmt, (int)m_rotation,
|
||||
(int)m_BitmapInfor_Send->bmiHeader.biWidth,
|
||||
(int)m_BitmapInfor_Send->bmiHeader.biHeight);
|
||||
break;
|
||||
} while (true);
|
||||
|
||||
@@ -175,6 +270,27 @@ public:
|
||||
|
||||
void CleanupDXGI()
|
||||
{
|
||||
// GDI 兜底缓冲:先把旧位图选回 DC,再删 DC,最后删位图
|
||||
if (m_hGdiMemDC) {
|
||||
// SelectObject 失败会返回 HGDI_ERROR,不能拿它去恢复,否则位图仍被
|
||||
// DC 选入,后面的 DeleteObject 会失败
|
||||
if (m_hGdiOldBmp && m_hGdiOldBmp != HGDI_ERROR)
|
||||
SelectObject(m_hGdiMemDC, m_hGdiOldBmp);
|
||||
DeleteDC(m_hGdiMemDC);
|
||||
m_hGdiMemDC = nullptr;
|
||||
m_hGdiOldBmp = nullptr;
|
||||
}
|
||||
if (m_hGdiBmp) {
|
||||
DeleteObject(m_hGdiBmp);
|
||||
m_hGdiBmp = nullptr;
|
||||
m_pGdiBits = nullptr;
|
||||
}
|
||||
// 探测帧若还挂着(例如 InitDXGI 中途失败),必须归还,否则 duplication 无法释放
|
||||
if (m_probeRes) {
|
||||
if (deskDupl) deskDupl->ReleaseFrame();
|
||||
m_probeRes->Release();
|
||||
m_probeRes = nullptr;
|
||||
}
|
||||
if (cpuTexture) cpuTexture->Release();
|
||||
if (deskDupl) deskDupl->Release();
|
||||
if (d3dContext) d3dContext->Release();
|
||||
@@ -196,14 +312,59 @@ public:
|
||||
|
||||
LPBYTE GetFirstScreenData(ULONG* ulFirstScreenLength) override
|
||||
{
|
||||
int ret = CaptureFrame(m_FirstBuffer, ulFirstScreenLength, 1);
|
||||
scaleBitmap(m_BmpZoomBuffer, m_FirstBuffer);
|
||||
memcpy(m_FirstBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
if (ret)
|
||||
return nullptr;
|
||||
// 首屏是一次性同步操作:ScreenManager 在调用前已把 m_SendFirst 置 TRUE,
|
||||
// 一旦返回 nullptr 就不会再重试。所以这里尽量拿到内容——探测阶段暂存的
|
||||
// 帧通常已填充好,静止桌面下偶尔无新帧时再用短超时补抓几次。
|
||||
const DWORD startTick = GetTickCount();
|
||||
int ret = 0;
|
||||
int attempts = 0;
|
||||
if (!m_bFirstValid) { // 探测帧已填充时直接用,不再白等一次 AcquireNextFrame
|
||||
ret = kNoNewFrame;
|
||||
while (attempts < 3) {
|
||||
++attempts;
|
||||
ret = CaptureFrame(m_FirstBuffer, ulFirstScreenLength, 1, &m_bFirstValid);
|
||||
if (ret != kNoNewFrame) break;
|
||||
if (m_bFirstValid) { ret = 0; break; }
|
||||
Sleep(20);
|
||||
}
|
||||
}
|
||||
const DWORD elapsed = GetTickCount() - startTick;
|
||||
if (elapsed > 300) {
|
||||
// 只在明显偏慢时记录,正常连接不会产生这行
|
||||
Mprintf("[DXGI] first screen slow: %ums attempts=%d ok=%d\n",
|
||||
elapsed, attempts, ret == 0);
|
||||
}
|
||||
if (ret != 0) {
|
||||
// DXGI 抓帧失败(无新帧 / 尺寸异常 / Map 失败等)。首屏不能放弃:一旦
|
||||
// 返回 nullptr,服务端 m_bIsFirst 就再无机会解锁(ScreenManager 的
|
||||
// m_SendFirst 已置 TRUE 不会重试),只能等桌面变化,表现为一直"请等待"。
|
||||
if (CaptureByGDI(m_FirstBuffer, 1)) {
|
||||
// duplication 连首帧都产不出来,本会话后续帧也必然是空的。
|
||||
// 直接降级为 GDI 抓屏,保证画面能持续更新(否则只有首屏是活的)。
|
||||
m_bGDIFallback = true;
|
||||
if (deskDupl) {
|
||||
deskDupl->Release();
|
||||
deskDupl = nullptr;
|
||||
}
|
||||
Mprintf("[DXGI] no frame from duplication (ret=%d), session falls back to GDI\n", ret);
|
||||
ret = 0;
|
||||
} else {
|
||||
*ulFirstScreenLength = 0;
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
// reservedBytes=1,实际位图从 m_FirstBuffer+1 开始;
|
||||
// 服务端也是从偏移 1 开始拷贝,写回时必须保持同样的偏移
|
||||
scaleBitmap(m_BmpZoomBuffer, m_FirstBuffer + 1);
|
||||
memcpy(m_FirstBuffer + 1, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
// 缓冲已被缩放图覆盖,+1 处不再是完整帧,后续无新帧时不可再复用
|
||||
m_bFirstValid = false;
|
||||
if (m_bAlgorithm == ALGORITHM_GRAY) {
|
||||
ToGray(1 + m_RectBuffer, 1 + m_RectBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
}
|
||||
// 长度必须是缩放后的发送尺寸,不能沿用 CaptureFrame 写入的全尺寸,
|
||||
// 否则会把整帧原始数据(数倍于图像)一并发给服务端
|
||||
*ulFirstScreenLength = m_BitmapInfor_Send->bmiHeader.biSizeImage;
|
||||
m_FirstBuffer[0] = TOKEN_FIRSTSCREEN;
|
||||
return m_FirstBuffer;
|
||||
}
|
||||
@@ -211,11 +372,16 @@ public:
|
||||
LPBYTE ScanNextScreen() override
|
||||
{
|
||||
ULONG ulNextScreenLength = 0;
|
||||
int ret = CaptureFrame(m_NextBuffer, &ulNextScreenLength, 0);
|
||||
scaleBitmap(m_BmpZoomBuffer, m_NextBuffer);
|
||||
memcpy(m_NextBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
int ret = CaptureFrame(m_NextBuffer, &ulNextScreenLength, 0, &m_bNextValid);
|
||||
if (ret == kNoNewFrame) {
|
||||
// 无新帧:m_NextBuffer 里已是上次缩放后的结果,必须原样返回,
|
||||
// 不能再走一遍 scaleBitmap(源已是缩放图,重复缩放会损坏画面)
|
||||
return m_bNextValid ? m_NextBuffer : nullptr;
|
||||
}
|
||||
if (ret)
|
||||
return nullptr;
|
||||
scaleBitmap(m_BmpZoomBuffer, m_NextBuffer);
|
||||
memcpy(m_NextBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
|
||||
|
||||
return m_NextBuffer;
|
||||
}
|
||||
@@ -229,6 +395,12 @@ private:
|
||||
// 重新初始化 Desktop Duplication
|
||||
BOOL ReinitDuplication()
|
||||
{
|
||||
// 重建前必须把暂存帧归还,否则旧的 duplication 无法释放
|
||||
if (m_probeRes) {
|
||||
if (deskDupl) deskDupl->ReleaseFrame();
|
||||
m_probeRes->Release();
|
||||
m_probeRes = nullptr;
|
||||
}
|
||||
if (deskDupl) {
|
||||
deskDupl->Release();
|
||||
deskDupl = nullptr;
|
||||
@@ -263,23 +435,178 @@ private:
|
||||
|
||||
return SUCCEEDED(hr) && deskDupl;
|
||||
}
|
||||
int CaptureFrame(LPBYTE buffer, ULONG* frameSize, int reservedBytes)
|
||||
// 惰性创建 GDI 离屏 DIB(尺寸与 DXGI 表面一致,32bpp bottom-up,与发送格式相同)
|
||||
bool EnsureGDIBuffer()
|
||||
{
|
||||
if (m_hGdiMemDC && m_hGdiBmp && m_pGdiBits) return true;
|
||||
// m_BitmapInfor_Full 已是 32bpp BI_RGB、biHeight 为正(bottom-up)、
|
||||
// 尺寸等于 m_ulFullWidth/Height,直接复用,不必另建一份 BITMAPINFO
|
||||
if (!m_BitmapInfor_Full || m_ulFullWidth == 0 || m_ulFullHeight == 0) return false;
|
||||
|
||||
HDC hScreen = GetDC(NULL);
|
||||
if (!hScreen) return false;
|
||||
|
||||
if (!m_hGdiMemDC) m_hGdiMemDC = CreateCompatibleDC(hScreen);
|
||||
if (!m_hGdiBmp) {
|
||||
m_hGdiBmp = CreateDIBSection(hScreen, m_BitmapInfor_Full, DIB_RGB_COLORS,
|
||||
&m_pGdiBits, NULL, 0);
|
||||
}
|
||||
ReleaseDC(NULL, hScreen);
|
||||
|
||||
if (!m_hGdiMemDC || !m_hGdiBmp || !m_pGdiBits) return false;
|
||||
|
||||
HGDIOBJ old = SelectObject(m_hGdiMemDC, m_hGdiBmp);
|
||||
if (!old || old == HGDI_ERROR) {
|
||||
// 选入失败:销毁位图,否则下次会被上面的「已就绪」判断误认为可用,
|
||||
// 而实际 BitBlt 写不到 m_pGdiBits,抓出来是未初始化的内存
|
||||
DeleteObject(m_hGdiBmp);
|
||||
m_hGdiBmp = nullptr;
|
||||
m_pGdiBits = nullptr;
|
||||
return false;
|
||||
}
|
||||
m_hGdiOldBmp = old;
|
||||
return true;
|
||||
}
|
||||
|
||||
// DXGI 的 AcquireNextFrame 只在桌面有新内容呈现时才返回。在无头/虚拟显示环境,
|
||||
// 或驱动在 DuplicateOutput 后不推送初始帧时,它可能永远超时。此时首屏发不出去,
|
||||
// 服务端 m_bIsFirst 永不解锁,表现为远程桌面一直停在"请等待......"。
|
||||
// GDI BitBlt 不依赖桌面变化,这里用它兜底抓一帧。
|
||||
bool CaptureByGDI(LPBYTE buffer, int reservedBytes)
|
||||
{
|
||||
if (!EnsureGDIBuffer()) return false;
|
||||
|
||||
HDC hScreen = GetDC(NULL);
|
||||
if (!hScreen) return false;
|
||||
BOOL blt = BitBlt(m_hGdiMemDC, 0, 0, (int)m_ulFullWidth, (int)m_ulFullHeight,
|
||||
hScreen, m_iScreenX, m_iScreenY, SRCCOPY);
|
||||
ReleaseDC(NULL, hScreen);
|
||||
if (!blt) return false;
|
||||
|
||||
memcpy(buffer + reservedBytes, m_pGdiBits,
|
||||
(size_t)m_ulFullWidth * m_ulFullHeight * 4);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 把 DXGI 表面(top-down,srcW×srcH,BGRA)按 rotation 摆正后写入目标
|
||||
// (bottom-up DIB,m_ulFullWidth×m_ulFullHeight)。分块处理保证缓存友好。
|
||||
void BlitRotated(BYTE* dst, const BYTE* src, int srcPitch,
|
||||
int srcW, int srcH, DXGI_MODE_ROTATION rot)
|
||||
{
|
||||
const int dstW = (int)m_ulFullWidth;
|
||||
const int dstH = (int)m_ulFullHeight;
|
||||
const int dstPitch = dstW * 4;
|
||||
|
||||
auto put = [&](int x, int y, int sx, int sy) {
|
||||
memcpy(dst + (size_t)(dstH - 1 - y) * dstPitch + (size_t)x * 4,
|
||||
src + (size_t)sy * srcPitch + (size_t)sx * 4, 4);
|
||||
};
|
||||
|
||||
if (rot == DXGI_MODE_ROTATION_ROTATE90 || rot == DXGI_MODE_ROTATION_ROTATE270) {
|
||||
const bool cw = (rot == DXGI_MODE_ROTATION_ROTATE90);
|
||||
const int T = 32;
|
||||
for (int y0 = 0; y0 < dstH; y0 += T) {
|
||||
const int yEnd = (y0 + T < dstH) ? y0 + T : dstH;
|
||||
for (int x0 = 0; x0 < dstW; x0 += T) {
|
||||
const int xEnd = (x0 + T < dstW) ? x0 + T : dstW;
|
||||
for (int y = y0; y < yEnd; y++) {
|
||||
for (int x = x0; x < xEnd; x++) {
|
||||
const int sx = cw ? y : (srcW - 1 - y);
|
||||
const int sy = cw ? (srcH - 1 - x) : x;
|
||||
put(x, y, sx, sy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (rot == DXGI_MODE_ROTATION_ROTATE180) {
|
||||
for (int y = 0; y < dstH; y++)
|
||||
for (int x = 0; x < dstW; x++)
|
||||
put(x, y, srcW - 1 - x, srcH - 1 - y);
|
||||
} else {
|
||||
// IDENTITY:整行拷贝(快路径)
|
||||
for (int y = 0; y < dstH; y++)
|
||||
memcpy(dst + (size_t)(dstH - 1 - y) * dstPitch,
|
||||
src + (size_t)y * srcPitch, (size_t)dstPitch);
|
||||
}
|
||||
}
|
||||
|
||||
// 消费 InitDXGI 探测阶段暂存的那一帧,直接填充 m_FirstBuffer(偏移 1 起)。
|
||||
// 无论成败都会释放暂存资源与 DXGI 帧,避免泄漏。
|
||||
bool ConsumeProbeFrame()
|
||||
{
|
||||
if (!m_probeRes) return false;
|
||||
|
||||
bool ok = false;
|
||||
ID3D11Texture2D* tex = nullptr;
|
||||
if (cpuTexture && m_FirstBuffer &&
|
||||
SUCCEEDED(m_probeRes->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&tex)) && tex) {
|
||||
// 尺寸与格式都必须与建 cpuTexture 时一致,否则 CopyResource 静默不复制
|
||||
// (读出来是全零)。探测阶段 QI 失败会退回推导尺寸、格式白名单也可能把
|
||||
// 非常见格式回退成 BGRA,这里再核对一次,不符就放弃消费,让
|
||||
// GetFirstScreenData 走正常抓帧路径,避免把全黑画面当成首屏发出去。
|
||||
D3D11_TEXTURE2D_DESC sd = {}, dd = {};
|
||||
tex->GetDesc(&sd);
|
||||
cpuTexture->GetDesc(&dd);
|
||||
if (sd.Width == dd.Width && sd.Height == dd.Height && sd.Format == dd.Format) {
|
||||
d3dContext->CopyResource(cpuTexture, tex);
|
||||
|
||||
D3D11_MAPPED_SUBRESOURCE mapped = {};
|
||||
if (SUCCEEDED(d3dContext->Map(cpuTexture, 0, D3D11_MAP_READ, 0, &mapped))) {
|
||||
BlitRotated(m_FirstBuffer + 1, (const BYTE*)mapped.pData,
|
||||
(int)mapped.RowPitch, m_surfW, m_surfH, m_rotation);
|
||||
d3dContext->Unmap(cpuTexture, 0);
|
||||
m_bFirstValid = true;
|
||||
ok = true;
|
||||
}
|
||||
} else {
|
||||
Mprintf("[DXGI] probe %ux%u fmt=%d != cpu %ux%u fmt=%d, skip probe frame\n",
|
||||
sd.Width, sd.Height, (int)sd.Format, dd.Width, dd.Height, (int)dd.Format);
|
||||
}
|
||||
tex->Release();
|
||||
}
|
||||
if (deskDupl) deskDupl->ReleaseFrame();
|
||||
m_probeRes->Release();
|
||||
m_probeRes = nullptr;
|
||||
return ok;
|
||||
}
|
||||
|
||||
int CaptureFrame(LPBYTE buffer, ULONG* frameSize, int reservedBytes, bool* valid)
|
||||
{
|
||||
// 本会话已降级为 GDI(首屏就是靠 GDI 兜底才成功的,说明 duplication 在这个
|
||||
// 环境产不出帧)。继续轮询 DXGI 只会一直返回「无新帧」,画面就停住不动。
|
||||
if (m_bGDIFallback) {
|
||||
if (!CaptureByGDI(buffer, reservedBytes)) return -1;
|
||||
*frameSize = m_ulFullWidth * m_ulFullHeight * 4;
|
||||
if (valid) *valid = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (!deskDupl) {
|
||||
if (!ReinitDuplication()) return -10;
|
||||
}
|
||||
|
||||
// 超时保持 100ms(与修复前一致)。AcquireNextFrame 的 timeout 是「最多等
|
||||
// 多久」而不是「一定等这么久」,有帧会立即返回;静止桌面下白等只会拖慢
|
||||
// 抓屏线程的轮询节奏(曾用 1000ms,导致首屏和之后每一帧都阻塞 1 秒)。
|
||||
const UINT timeout = 100;
|
||||
|
||||
// 1. 获取下一帧
|
||||
IDXGIResource* desktopResource = nullptr;
|
||||
DXGI_OUTDUPL_FRAME_INFO frameInfo;
|
||||
HRESULT hr = deskDupl->AcquireNextFrame(100, &frameInfo, &desktopResource);
|
||||
HRESULT hr = deskDupl->AcquireNextFrame(timeout, &frameInfo, &desktopResource);
|
||||
// 处理全屏切换导致的访问丢失
|
||||
if (hr == DXGI_ERROR_ACCESS_LOST) {
|
||||
if (ReinitDuplication()) {
|
||||
hr = deskDupl->AcquireNextFrame(100, &frameInfo, &desktopResource);
|
||||
hr = deskDupl->AcquireNextFrame(timeout, &frameInfo, &desktopResource);
|
||||
}
|
||||
}
|
||||
|
||||
// 桌面静止时没有新帧,这是 DXGI 的正常语义,不能当成错误。
|
||||
// 调用方据此复用上一帧内容,保证编码器持续有输入。
|
||||
if (hr == DXGI_ERROR_WAIT_TIMEOUT) {
|
||||
return kNoNewFrame;
|
||||
}
|
||||
|
||||
if (FAILED(hr)) {
|
||||
return -1;
|
||||
}
|
||||
@@ -289,10 +616,40 @@ private:
|
||||
hr = desktopResource->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&texture);
|
||||
if (FAILED(hr)) {
|
||||
deskDupl->ReleaseFrame();
|
||||
desktopResource->Release(); // 原来漏了,每次失败都会泄漏一个 DXGI 资源
|
||||
return -2;
|
||||
}
|
||||
|
||||
// 3. 复制到 CPU 纹理
|
||||
// ID3D11DeviceContext::CopyResource 返回 void:尺寸/格式不匹配时不会报错,
|
||||
// 只会静默不复制(目标保持原值 = 全零)。这里显式比对描述。
|
||||
// 尺寸不一致时必须放弃这一帧:BlitRotated 按 m_surfW/H 计算源偏移,
|
||||
// 表面变小会越界读取(崩溃或花屏),宁可跳过等 ReinitDuplication。
|
||||
{
|
||||
D3D11_TEXTURE2D_DESC sd = {};
|
||||
texture->GetDesc(&sd);
|
||||
if ((int)sd.Width != m_surfW || (int)sd.Height != m_surfH) {
|
||||
static LONG s_sizeLog = 0;
|
||||
if (s_sizeLog++ < 3) {
|
||||
Mprintf("[DXGI] surface changed %dx%d -> %ux%u, drop frame\n",
|
||||
m_surfW, m_surfH, sd.Width, sd.Height);
|
||||
}
|
||||
deskDupl->ReleaseFrame();
|
||||
texture->Release();
|
||||
desktopResource->Release();
|
||||
return -4;
|
||||
}
|
||||
static LONG s_fmtLog = 0;
|
||||
if (s_fmtLog < 3) {
|
||||
D3D11_TEXTURE2D_DESC dd = {};
|
||||
cpuTexture->GetDesc(&dd);
|
||||
if (sd.Format != dd.Format) {
|
||||
Mprintf("[DXGI] DESC MISMATCH fmt src=%d dst=%d\n",
|
||||
(int)sd.Format, (int)dd.Format);
|
||||
}
|
||||
s_fmtLog++;
|
||||
}
|
||||
}
|
||||
d3dContext->CopyResource(cpuTexture, texture);
|
||||
|
||||
// 4. 释放 DXGI 资源
|
||||
@@ -307,22 +664,15 @@ private:
|
||||
return -3;
|
||||
}
|
||||
|
||||
// 6. 复制数据到缓冲区(垂直翻转)
|
||||
BYTE* pData = (BYTE*)mapped.pData;
|
||||
int rowSize = m_ulFullWidth * 4; // 每行的字节数(RGBA)
|
||||
|
||||
BYTE* dest = buffer + reservedBytes + (m_ulFullHeight - 1) * rowSize;
|
||||
BYTE* src = pData;
|
||||
for (int y = 0; y < m_ulFullHeight; y++) {
|
||||
memcpy(dest, src, rowSize);
|
||||
dest -= rowSize;
|
||||
src += mapped.RowPitch;
|
||||
}
|
||||
// 6. 复制数据到缓冲区(按旋转角摆正 + 垂直翻转到 bottom-up DIB)
|
||||
BlitRotated(buffer + reservedBytes, (const BYTE*)mapped.pData,
|
||||
(int)mapped.RowPitch, m_surfW, m_surfH, m_rotation);
|
||||
|
||||
// 7. 清理
|
||||
d3dContext->Unmap(cpuTexture, 0);
|
||||
|
||||
*frameSize = m_ulFullWidth * m_ulFullHeight * 4;
|
||||
if (valid) *valid = true;
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
@@ -467,6 +467,26 @@ static BOOL RestoreConsoleSession()
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
// 进程所在会话是否已断开(RDP 断开后没有显示输出)。
|
||||
// 这种会话里 DXGI 桌面复制拿不到帧,部分驱动上连初始化都不返回,必须走 GDI。
|
||||
// Session 0 是服务会话,没有「断开」这个概念,直接返回 FALSE。
|
||||
static BOOL IsCurrentSessionDisconnected()
|
||||
{
|
||||
DWORD sessionId = 0;
|
||||
if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId) || sessionId == 0)
|
||||
return FALSE;
|
||||
|
||||
WTS_CONNECTSTATE_CLASS* pState = NULL;
|
||||
DWORD bytes = 0;
|
||||
if (!WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSConnectState,
|
||||
(LPSTR*)&pState, &bytes) || !pState) {
|
||||
return FALSE;
|
||||
}
|
||||
const BOOL disconnected = (*pState == WTSDisconnected);
|
||||
WTSFreeMemory(pState);
|
||||
return disconnected;
|
||||
}
|
||||
|
||||
void CScreenManager::InitScreenSpy()
|
||||
{
|
||||
int DXGI = USING_GDI;
|
||||
@@ -551,7 +571,20 @@ void CScreenManager::InitScreenSpy()
|
||||
}
|
||||
}
|
||||
SAFE_DELETE(m_ScreenSpyObject);
|
||||
if ((USING_DXGI == DXGI && IsWindows8orHigher())) {
|
||||
// 锁屏(输入桌面切到 Winlogon)或会话已断开时,当前会话没有可用的交互桌面:
|
||||
// DXGI 桌面复制拿不到帧,部分环境(无 GPU 的 Server、断开/锁定的 RDP 会话)
|
||||
// 甚至会在初始化里卡死不返回 —— 那样 InitScreenSpy 走不完,WorkThreadProc 里
|
||||
// 紧随其后的 SendBitMapInfo() 永远发不出去,主控端一直等不到 TOKEN_BITMAPINFO,
|
||||
// 连远程桌面窗口都不会弹。GDI 的 BitBlt 不依赖桌面变化,这些情况下照样能抓,
|
||||
// 所以直接走 GDI。
|
||||
const BOOL locked = IsWorkstationLocked();
|
||||
const BOOL disconnected = IsCurrentSessionDisconnected();
|
||||
const bool noDesktop = (USING_DXGI == DXGI && (locked || disconnected));
|
||||
if (noDesktop) {
|
||||
Mprintf("CScreenManager: no interactive desktop (locked=%d, disconnected=%d), use GDI instead of DXGI\n",
|
||||
(int)locked, (int)disconnected);
|
||||
}
|
||||
if ((USING_DXGI == DXGI && IsWindows8orHigher() && !noDesktop)) {
|
||||
m_isGDI = FALSE;
|
||||
auto s = new ScreenCapturerDXGI(algo, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen);
|
||||
if (s->IsInitSucceed()) {
|
||||
|
||||
@@ -66,9 +66,8 @@ CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL
|
||||
Mprintf("CScreenSpy: 自定义分辨率 %dx%d\n",
|
||||
m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
|
||||
} else {
|
||||
// strategy=0 或 maxWidth=0: 默认 1080p 限制
|
||||
m_BitmapInfor_Send->bmiHeader.biWidth = min(1920, m_BitmapInfor_Send->bmiHeader.biWidth);
|
||||
m_BitmapInfor_Send->bmiHeader.biHeight = min(1080, m_BitmapInfor_Send->bmiHeader.biHeight);
|
||||
// strategy=0 或 maxWidth=0: 默认 1080p 限制(等比,避免竖屏被压扁)
|
||||
FitDefaultSendSize(m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
|
||||
m_BitmapInfor_Send->bmiHeader.biSizeImage =
|
||||
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
|
||||
4 * m_BitmapInfor_Send->bmiHeader.biHeight;
|
||||
|
||||
+2
-2
@@ -103,7 +103,7 @@ IDR_WAVE WAVE "Res\\msg.wav"
|
||||
//
|
||||
|
||||
VS_VERSION_INFO VERSIONINFO
|
||||
FILEVERSION 1,0,4,1
|
||||
FILEVERSION 1,0,4,2
|
||||
PRODUCTVERSION 1,0,0,1
|
||||
FILEFLAGSMASK 0x3fL
|
||||
#ifdef _DEBUG
|
||||
@@ -121,7 +121,7 @@ BEGIN
|
||||
BEGIN
|
||||
VALUE "CompanyName", "FUCK THE UNIVERSE"
|
||||
VALUE "FileDescription", "A GHOST"
|
||||
VALUE "FileVersion", "1.0.4.1"
|
||||
VALUE "FileVersion", "1.0.4.2"
|
||||
VALUE "InternalName", "ServerDll.dll"
|
||||
VALUE "LegalCopyright", "Copyright (C) 2019-2026"
|
||||
VALUE "OriginalFilename", "ServerDll.dll"
|
||||
|
||||
Binary file not shown.
+89
-28
@@ -12,14 +12,18 @@
|
||||
#include <fstream> // std::ifstream
|
||||
#include <iterator> // std::istreambuf_iterator
|
||||
#include <string>
|
||||
#include <mutex> // std::call_once
|
||||
#include <mutex> // std::mutex
|
||||
|
||||
#pragma comment(lib, "secur32.lib")
|
||||
#pragma comment(lib, "crypt32.lib")
|
||||
|
||||
namespace {
|
||||
|
||||
std::once_flag g_tlsOnce;
|
||||
// 进程级 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;
|
||||
@@ -160,26 +164,23 @@ bool LoadTrustAnchor(const std::string& pem, const std::string& source, HCERTSTO
|
||||
return true;
|
||||
}
|
||||
|
||||
void InitTls()
|
||||
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, source;
|
||||
std::string pem;
|
||||
if (!ReadTrustAnchor(pem, source)) {
|
||||
// 无证书 → 明文(默认,与老客户端一致)
|
||||
g_tlsEnabled = false;
|
||||
g_tlsError = false;
|
||||
Mprintf("[TLS] disabled: no trust anchor configured, plaintext mode\n");
|
||||
return;
|
||||
err = "no trust anchor configured";
|
||||
return TLS_ANCHOR_NONE;
|
||||
}
|
||||
|
||||
// 证书已配置:管理员已「颁发」,必须走 TLS;加载失败即拒绝连接(fail-closed),
|
||||
// 不能静默回退明文。
|
||||
HCERTSTORE store = NULL;
|
||||
if (!LoadTrustAnchor(pem, source, &store)) {
|
||||
g_tlsEnabled = false;
|
||||
g_tlsError = true;
|
||||
Mprintf("[TLS] FATAL: trust anchor (%s) present but failed to load; refusing connections (fail-closed)\n",
|
||||
source.c_str());
|
||||
return;
|
||||
err = "trust anchor (" + source + ") present but failed to load";
|
||||
return TLS_ANCHOR_INVALID;
|
||||
}
|
||||
|
||||
// 严格钉扎:链引擎只信任该 store 里的根证书,排除系统根库。否则攻击者拿一张任意
|
||||
@@ -190,33 +191,87 @@ void InitTls()
|
||||
HCERTCHAINENGINE engine = NULL;
|
||||
if (!CertCreateCertificateChainEngine(&ec, &engine)) {
|
||||
CertCloseStore(store, 0);
|
||||
g_tlsEnabled = false;
|
||||
g_tlsError = true;
|
||||
Mprintf("[TLS] FATAL: CertCreateCertificateChainEngine failed; refusing connections (fail-closed)\n");
|
||||
return;
|
||||
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 = true;
|
||||
g_tlsEnabled = (anchor == TLS_ANCHOR_OK);
|
||||
g_tlsError = false;
|
||||
Mprintf("[TLS] enabled: trust anchor loaded (%s), all connections use TLS\n", source.c_str());
|
||||
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::call_once(g_tlsOnce, InitTls);
|
||||
std::lock_guard<std::mutex> lk(g_tlsMtx);
|
||||
EnsureTlsLoadedLocked();
|
||||
return g_tlsEnabled;
|
||||
}
|
||||
|
||||
bool TlsLoadError()
|
||||
{
|
||||
std::call_once(g_tlsOnce, InitTls);
|
||||
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()
|
||||
@@ -249,6 +304,10 @@ bool TlsChannel::VerifyServerCert()
|
||||
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;
|
||||
@@ -273,7 +332,7 @@ bool TlsChannel::VerifyServerCert()
|
||||
return trusted;
|
||||
}
|
||||
|
||||
bool TlsChannel::Handshake(SOCKET sock)
|
||||
bool TlsChannel::Handshake(SOCKET sock, const char* sni)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||||
@@ -300,8 +359,10 @@ bool TlsChannel::Handshake(SOCKET sock)
|
||||
SecBufferDesc outDesc = { SECBUFFER_VERSION, 1, &outBuf };
|
||||
ULONG attrs = 0;
|
||||
|
||||
// 首次调用产生 ClientHello
|
||||
sc = InitializeSecurityContextA(&m_cred, NULL, NULL, flags, 0, SECURITY_NATIVE_DREP,
|
||||
// 首次调用产生 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) {
|
||||
@@ -340,7 +401,7 @@ bool TlsChannel::Handshake(SOCKET sock)
|
||||
outBuf = { 0, SECBUFFER_TOKEN, NULL };
|
||||
outDesc = { SECBUFFER_VERSION, 1, &outBuf };
|
||||
|
||||
sc = InitializeSecurityContextA(&m_cred, &m_ctx, NULL, flags, 0, SECURITY_NATIVE_DREP,
|
||||
sc = InitializeSecurityContextA(&m_cred, &m_ctx, (SEC_CHAR*)sni, flags, 0, SECURITY_NATIVE_DREP,
|
||||
&inDesc, 0, NULL, &outDesc, &attrs, &tsExpiry);
|
||||
|
||||
// 裁剪已消费的输入,仅保留 SECBUFFER_EXTRA 指向的未消费尾部
|
||||
|
||||
+17
-4
@@ -34,15 +34,24 @@
|
||||
#include <schannel.h>
|
||||
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
// 进程级 TLS 开关:首次调用时加载信任锚(注册表或文件),返回是否启用。线程安全、幂等。
|
||||
// 进程级 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:
|
||||
@@ -55,7 +64,9 @@ public:
|
||||
|
||||
// 在已连通的 socket 上完成 TLS 客户端握手并校验服务端证书链。失败返回 false,
|
||||
// 调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
|
||||
bool Handshake(SOCKET sock);
|
||||
// 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);
|
||||
@@ -115,7 +126,8 @@ bool TlsLoadError();
|
||||
// 服务端下发信任锚(COMMAND_TLS_ENABLE):把 PEM 正文写入
|
||||
// $XDG_CONFIG_HOME/ghost/yama-ca.pem(默认 ~/.config/ghost/yama-ca.pem,无 HOME 时退回
|
||||
// 程序目录),原子替换、权限 0600。写入前先解析验证,不是合法证书就整包拒绝。
|
||||
// 落盘后用 TlsReload() 立即生效(Windows 客户端仍要重启进程)。
|
||||
// 落盘后用 TlsReload() 立即生效(Windows 客户端在 COMMAND_TLS_ENABLE 里调用同一个
|
||||
// TlsReload(),两平台行为一致)。
|
||||
bool TlsTrustAnchorSave(const std::string& pem, std::string& err);
|
||||
|
||||
// 服务端撤销信任锚(COMMAND_TLS_DISABLE):删除上述配置文件(含程序目录同名文件)。
|
||||
@@ -140,7 +152,8 @@ public:
|
||||
|
||||
// 在已连通的 socket 上完成 TLS 1.2 客户端握手并按信任锚校验服务端证书链。失败返回
|
||||
// false,调用方必须关闭 socket(fail-closed)。可重复调用(重连时复用同一对象)。
|
||||
bool Handshake(int sock);
|
||||
// sni 非空且为域名时作为 SNI 发送(反代按域名分流);证书校验仍只钉信任锚。
|
||||
bool Handshake(int sock, const char* sni = NULL);
|
||||
|
||||
// 解密读取:返回 >0 的明文字节数;0 表示对端正常关闭;SOCKET_ERROR(-1) 出错。
|
||||
int Recv(int sock, char* buf, int len);
|
||||
|
||||
@@ -40,7 +40,7 @@ namespace {
|
||||
|
||||
const char* const kAnchorName = "yama-ca.pem";
|
||||
|
||||
// 进程级 TLS 状态。与 Windows 版的 call_once 不同,这里可由 TlsReload() 热切换
|
||||
// 进程级 TLS 状态。两平台都可由 TlsReload() 热切换(Windows 版改造前是 call_once)
|
||||
// (服务端 COMMAND_TLS_ENABLE/DISABLE 落盘后立即重建),因此用互斥量而不是 once_flag。
|
||||
std::mutex g_stateMtx; // 保护下面四项
|
||||
bool g_inited = false; // 首次加载已完成(含 fail-closed 基态)
|
||||
@@ -415,7 +415,7 @@ void TlsChannel::CloseHandles()
|
||||
m_ready = false;
|
||||
}
|
||||
|
||||
bool TlsChannel::Handshake(int sock)
|
||||
bool TlsChannel::Handshake(int sock, const char* sni)
|
||||
{
|
||||
std::lock_guard<std::recursive_mutex> lk(m_ctxMtx);
|
||||
CloseHandles(); // 重连时清理上一次会话(recursive 锁,此处可重入)
|
||||
@@ -438,6 +438,10 @@ bool TlsChannel::Handshake(int sock)
|
||||
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 只在记录分片等极端情形出现,重试即可。
|
||||
|
||||
@@ -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
|
||||
@@ -501,6 +501,13 @@ BOOL Run(const char* argv1, int argv2, const std::string &runCmd)
|
||||
// 卸载 DLL 时残留分享实例线程。主控端重启(S_SERVER_EXIT)则立即重连,不等仍存活的分享实例。
|
||||
while (bStop && !bStop() && 0 == status)
|
||||
Sleep(20);
|
||||
} else {
|
||||
// 主控端重启:不等分享实例,但上一个工作线程未必已经退完,TestRun 这时
|
||||
// 会立刻返回。不睡就成了每秒上千次的空转——实测 1 秒刷了近千行,把客户端
|
||||
// 1000 行环形日志冲光,其它日志全看不到。
|
||||
// 注意不能用 bStop() 挡:IsStoped() 在 S_SERVER_EXIT 下恒返回 true,挡不住。
|
||||
// 20ms 与线程收尾是并行的,重连延迟净增不超过 20ms。
|
||||
Sleep(20);
|
||||
}
|
||||
} while (bExit && !bExit() && 0 == status);
|
||||
|
||||
|
||||
@@ -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;
|
||||
};
|
||||
+56
-6
@@ -138,6 +138,7 @@ inline int isValid_10s()
|
||||
#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 // 最大输入字符长度
|
||||
|
||||
@@ -346,6 +347,10 @@ enum {
|
||||
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, // 注册表
|
||||
COMMAND_REG_FIND, // 注册表 管理标识
|
||||
@@ -390,6 +395,22 @@ enum {
|
||||
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 的地址/端口均为网络序)。
|
||||
@@ -465,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 字节
|
||||
|
||||
@@ -486,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 {
|
||||
@@ -818,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 {
|
||||
@@ -1107,18 +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)
|
||||
|
||||
@@ -481,6 +481,9 @@ void CMcpSettingsDlg::OnBnClickedBtnSave()
|
||||
- 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。
|
||||
- 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。
|
||||
- `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。
|
||||
- **outputSchema 必须声明批量形状**:只声明单机形状会让客户端把批量结果判为不合规
|
||||
(`-32602: data must have required property 'host'`)。现在由 `ApplyBatchOutputSchema`
|
||||
统一补成 `anyOf:[单机, 批量]`,见 §18.1。
|
||||
|
||||
### 9.3 N3 `get_keylog`
|
||||
|
||||
@@ -886,3 +889,116 @@ Linux 客户端(`LNX`)早已实现下面这些工具的**线上协议**,
|
||||
- **`remote_keyboard` 的 `type` 仍是 ASCII-only**:Linux 侧 `VKtoKeySym` 把 VK 映射为 keysym 后走 XTest,IME 组合输入做不到;非 ASCII 走 `remote_clipboard` + `Ctrl+V`(Linux 客户端把服务端下发的 GBK 转回 UTF-8 再调 `xclip`/`xsel`,需要 X11 桌面)。
|
||||
- **限制**:纯 Wayland 会话无法抓屏/注入(要 X11 或 XWayland);多显示器仍按 §7.2 拒绝(Linux 客户端心跳里 `RES_RESOLUTION` 依赖 `xrandr`,没有 `xrandr` 的系统上报 `0:0*0`,按「无法判定」放行);`remote_*` 需要安装 `libX11` + `libXtst`,剪贴板需要 `xclip`/`xsel`。
|
||||
- **验收**(Debug 实例 + WSL Ubuntu 24.04 客户端,WSLg `DISPLAY=:0`):`exec_command` 真实退出码(`ls` 不存在路径 → 2)、`-32007`/`-32008` 负例、`grep -v ^#` 放行、输出无提示符噪声;持久终端 `cd`/环境变量保持、`false` → 1、`;` 串联取末条、`close` 幂等;`kill_process` 杀死自己起的 `sleep` 且 `remaining` 为空、`pid 1` 被跳过;`remote_open` 返回 3840x1140、`remote_mouse` 归一化 (0.5,0.5) 落在 (1920,570)、`xev` 观测到按键/按钮成对、剪贴板中文往返 UTF-8 一致。Windows 客户端同批工具回归无变化。
|
||||
|
||||
## 18. 增补(2026-10-29:修掉实测报告的三个 P0)
|
||||
|
||||
`docs/Mcp_Test_Report_2026-10-29.md` 的 P0-1/P0-2/P0-3 有三个共同点:**inputSchema 与
|
||||
outputSchema 不是同一份契约**,或者**输出体积没有上限**。三者都只改服务端(P0-3 的
|
||||
Linux 半边另需客户端补一段)。
|
||||
|
||||
### 18.1 批量只读的 outputSchema(P0-1)
|
||||
|
||||
`tools/call` 带 `ids[]` 时走 `BuildBatchCall`,返回的是
|
||||
`{tool, total, succeeded, failed, skipped, results[]}`;而每个工具声明的 `outputSchema`
|
||||
只有单机形状。客户端按声明校验 `structuredContent`,于是**任何** `ids` 调用都以
|
||||
`-32602: data must have required property 'host'` 失败——inputSchema 明写「支持 ids」,
|
||||
outputSchema 却把它判死,十余个只读工具的批量能力整条不可用。
|
||||
|
||||
修法:`McpInternal::ApplyBatchOutputSchema(tools)` 在 `tools/list` 的最后一步(与
|
||||
`ApplyToolAnnotations` 并列)给 `IsBatchReadOnlyTool` 命中的工具把 `outputSchema`
|
||||
改写成 `{type:object, anyOf:[单机形状, 批量形状]}`。放最后一步是为了让三个注册点
|
||||
(本文件内联 / `McpMachine` / `McpChat`)一视同仁,新增工具只要进批量清单就自动生效。
|
||||
`IsBatchReadOnlyTool` 也随之从 `McpServer.cpp` 移到 `McpInternal.cpp`——清单现在同时被
|
||||
`tools/call`(入口判定)和 `tools/list`(补 schema)使用,两处必须共用一份。
|
||||
|
||||
批量形状里的 `results[].data` 只能声明成 `object`:它就是该工具单机的
|
||||
`structuredContent`,字段随工具而定。
|
||||
|
||||
### 18.2 `list_registry` 的根键分支(P0-2)
|
||||
|
||||
`path` 为空时 `BuildRegistryRoots` 只回 `keys`,而 outputSchema 把 `values` 也列进了
|
||||
`required`——于是文档写的**第一种用法**(省略 path 列根键)必然 `-32602`,AI 必须先猜一个
|
||||
真实键路径才能进注册表。现在 `required` 只保留 `keys`,`values` 在根键分支不返回,并在
|
||||
schema 里写明这一点;同时根键分支补上 `path: ""`,让两个分支返回同一组字段(`path` /
|
||||
`keys`),调用方不必按分支判断。
|
||||
|
||||
### 18.3 `get_client_log` 的体积与平台(P0-3)
|
||||
|
||||
两个症状、两个原因:
|
||||
|
||||
| 平台 | 症状 | 原因 |
|
||||
|---|---|---|
|
||||
| Windows | 返回 90,473 字符,超出客户端工具结果上限 | 快照是客户端 ring buffer 全量(最多 1000 行),工具没有 limit |
|
||||
| Linux/macOS | `-32001` 稳定超时 | 客户端**根本没有处理** `COMMAND_QUERY_LOG`(只有 Windows 的 `ClientLogManager` 有),服务端永远等不到 `TOKEN_REPORT_LOG` |
|
||||
|
||||
服务端:`get_client_log` 新增 `limit`(默认 200,上限 2000)与 `filter`(子串,ASCII
|
||||
不区分大小写),**从末尾往前取**——排障看的是最后发生了什么,不是开机第一行。返回补
|
||||
`lines_total` / `lines_matched` / `lines_returned` / `truncated`。除行数外还有 64 KB
|
||||
字节预算:单行可能是超长的堆栈或报文转储,只按行数截断仍会撑爆结果;末尾一行自己就超
|
||||
预算时回它的尾部并置 `truncated=true`。超时文案也改成可诊断的(点明「客户端版本可能
|
||||
不支持日志上报」并给出两条替代路径),而不是一句 `Timeout waiting for client log`。
|
||||
|
||||
客户端:新增 `common/ClientLogHandler.h`(POSIX 版,与 Windows 的 `CClientLogManager`
|
||||
对应),`linux/main.cpp` 与 `macos/main.mm` 在 `COMMAND_QUERY_LOG` 分支开子连接、首包发
|
||||
`TOKEN_REPORT_LOG` + `Logger::DumpMemoryLogFrom(0)`。**必须走子连接**:服务端
|
||||
`MessageHandle` 的 `TOKEN_REPORT_LOG` 分支取走首包后会 `CancelIO` 关掉这条连接,回在
|
||||
主连接上就是把主连接关掉(客户端当场掉线)。
|
||||
|
||||
### 18.4 验证与未覆盖
|
||||
|
||||
- 服务端 21:17:21 构建 + 两端客户端重编后实测:`ids` 批量(`get_host_detail` /
|
||||
`host_list_processes` / `get_client_log`)全部 `succeeded=全数`;`list_registry` 省略
|
||||
`path` 返回 5 个根键;`get_client_log` 在 Windows 上 `1000→200` 行(`truncated=true`)、
|
||||
在 Linux 上正常返回 8 行,且客户端日志里 `Enter/Leave ClientLogThread` 成对、无泄漏。
|
||||
明细见测试报告 §7。
|
||||
- `get_activity_history` 仍是全量返回(实测 501 条),与 P0-3 同一类问题,但不在本次
|
||||
三个 P0 内,留待下一轮。
|
||||
- 连接器会缓存 `tools/list`,`limit`/`filter` 在重连前对模型不可见(默认参数已覆盖
|
||||
P0-3 的场景),与既有的 `overwrite` 缓存问题同源。
|
||||
|
||||
## 19. 增补(2026-10-29:`get_activity_history` 分页,P2-1)
|
||||
|
||||
### 19.1 问题
|
||||
|
||||
`get_activity_history` 是全仓库唯一没有分页的列表类工具。客户端 `ACTIVITY_HISTORY_MAX`
|
||||
= 500,`Dump()` 还会把进行中的当前窗口作为第 1 条,所以一次返回上限约 501 条——实测
|
||||
正是 501 条。每行含窗口标题(可能很长),501 行直接把上下文冲爆;而报告里那份数据还
|
||||
混着大量个人浏览、求职、签证页面,属于「不该被整包塞进模型上下文」的典型。
|
||||
|
||||
### 19.2 顺序:为什么可以直接用 `limit`/`offset`
|
||||
|
||||
`ActivityHistory::Loop()` 用 `m_records.push_front(...)` 维护,`Dump()` 又把当前进行中
|
||||
的窗口拼在最前面——**返回顺序天然是「新在前」**。于是 `offset=0` 就是最近 `limit` 条,
|
||||
不必像「新在后」的日志那样先取一次 `total` 再倒算 `offset=total-limit`。这条顺序不是
|
||||
本次新增的约定,是客户端本来就这样,写进描述是为了让模型敢直接用 `offset=0`。
|
||||
|
||||
### 19.3 实现
|
||||
|
||||
- `inputSchema` 从 `BuildGetHostDetailInputSchema()` 换成 `BuildPagedHostListInputSchema()`
|
||||
(`{ id | ids }` + `limit`/`offset`,与 `list_processes` / `list_windows` 同一套);
|
||||
- `outputSchema` 追加 `AppendPageOutputProps()` 与 `truncated`;
|
||||
- 实现里把原来的 `records` 改名 `all`(全量拆行结果),再 `ResolvePageWindow` +
|
||||
`ApplyPageWindow` 切出 `records`,`WritePageFields` 写回 `total`/`totalAll`/`offset`/
|
||||
`limit`/`hasMore`;
|
||||
- **`activityHistory` 必须按窗口重建**:它原来是 `Dump()` 的整包原文,如果原样返回,
|
||||
501 行的正文照样进上下文,等于没分页。现在它是窗口内 `records` 的按行拼接,语义仍是
|
||||
「同一份数据的纯文本形态」;
|
||||
- 再加 64 KB 字节预算(与 `get_client_log` 同口径),从窗口**末尾**裁——保留最新的那些。
|
||||
裁断时 `truncated=true`;`hasMore` 按 `offset + returned < total` 算,而不是一律置 true
|
||||
(末尾单条自己超预算时不该再报还有下一页)。调用方用 `offset + returned` 继续取;
|
||||
- 至少保留 1 条:单条超预算时若不保底,`returned=0` 会让调用方在同一个 `offset` 上原地
|
||||
打转。窗口标题达到 64 KB 几乎不可能,这是纯兜底。
|
||||
|
||||
### 19.4 批量
|
||||
|
||||
`get_activity_history` 在 `IsBatchReadOnlyTool` 名单里,`BuildBatchCall` 会把 `ids` 摘掉、
|
||||
其余参数原样透传给单机调用,所以 `ids` + `limit` 等于「每台各取最近 N 条」,不需要额外
|
||||
处理。P0-1 的 `anyOf:[单机, 批量]` 包装也自动覆盖新增字段。
|
||||
|
||||
### 19.5 未做
|
||||
|
||||
- 没有 `filter`(按窗口标题子串)。报告没提,且客户端标题是 UTF-8、过滤要按字节子串做,
|
||||
与 `get_client_log` 的 `filter` 不同源,等有实际需求再加。
|
||||
- 没有 `since`(按时间起点取)。记录里的时间是 `[YYYY-MM-DD HH:MM:SS]` 文本前缀,做时间
|
||||
过滤得先解析每行;当前 `limit/offset` 已够用。
|
||||
|
||||
@@ -451,8 +451,8 @@ TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端
|
||||
|
||||
### 14.5 工具契约
|
||||
|
||||
入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N,源端 Windows 绝对路径)、`dst_dir`(必填,绝对路径;Windows 目标用 `C:\x`,Linux/macOS 目标用 `/x`)、`timeout_ms`(默认 600000,上限 3600000)。
|
||||
出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`。
|
||||
入参:`src_id`、`dst_id`(必填,且不得相同)、`paths`(必填,文件或目录,1..N,源端 Windows 绝对路径)、`dst_dir`(必填,绝对路径;Windows 目标用 `C:\x`,Linux/macOS 目标用 `/x`)、`timeout_ms`(默认 600000,上限 3600000)、`overwrite`(默认 `false`,见 §14.9)。
|
||||
出参(`structuredContent`):`transfer_id`、`src_id`、`dst_id`、`dst_dir`、`file_count`、`total_bytes`、`receiver_ack`、`skipped`、`skip_check_failed`。
|
||||
|
||||
`receiver_ack` 三种取值:
|
||||
- `true` 且 `status==0`:目标端已确认全部条目落盘(`file_count`/`total_bytes` 是**目标端实收**值,与源端统计一致)。
|
||||
@@ -597,3 +597,105 @@ TOKEN_C2C_RECV_RESULT = 176, // 目标客户端 → 服务端(目标端
|
||||
| Windows 目标端 `upload_file` / `download_file` / `copy_files_c2c` 回归 | 与改动前一致(Windows 目标的空文件仍不落地,`receiver_ack` 仍为 `false`) |
|
||||
|
||||
注:WSL 重启后 Linux 客户端的 machine-id 会变,`id` 随之改变,测试脚本以运行时 `list_online_hosts` 为准。
|
||||
|
||||
### 14.9 增补(2026-10-29):`overwrite` 与 `skipped`
|
||||
|
||||
#### 14.9.1 问题(实测)
|
||||
|
||||
同一份文件连续 C2C 两次,目标端 mtime 从 `1793276750` 变为 `1793276909`(重写),大小不变、
|
||||
条目数不变 —— 即**每次都全量重发**。更麻烦的是两次返回值完全相同:
|
||||
|
||||
```
|
||||
第一次: file_count=1, total_bytes=11595168, receiver_ack=true
|
||||
第二次: file_count=1, total_bytes=11595168, receiver_ack=true
|
||||
```
|
||||
|
||||
调用方无法分辨「这次真的传了」还是「跳过了」。`upload_file` / `download_file` 有 `overwrite` +
|
||||
`skipped`,只有 C2C 缺这一对。
|
||||
|
||||
#### 14.9.2 做法(纯服务端,协议零改动)
|
||||
|
||||
目标端收包是**无条件覆盖写**(`RecvFileChunkV2` 不判断是否存在),所以跳过只能在服务端做:
|
||||
发起传输前先列一次目标目录,把重名的顶层项从 `paths` 里剔掉。协议、客户端一律不动。
|
||||
|
||||
- `overwrite=false`(默认)时,调用 `ListRemoteTopLevelNames`(`upload_file` 已在用的同一个
|
||||
helper,`McpServer.cpp`)列 `dst_dir` 一层;
|
||||
- 逐个 `paths` 取 basename,与目标端已有名字比对:**Windows 目标不区分大小写,POSIX 目标区分**
|
||||
(为此给 helper 加了 `foldCase` 参数,默认 `true` 保持 `upload_file` 行为不变);
|
||||
- 命中的路径剔除并计入 `skipped`;全被剔除则直接返回成功,**不发起传输、不建 transferID**;
|
||||
- 目标目录不存在时 helper 返回空集(`ERROR_FILE_NOT_FOUND`/`ERROR_PATH_NOT_FOUND` 视为空),
|
||||
正好等价于「无同名项」,不会挡住「传到新目录」;
|
||||
- **预检失败不报错**:预检本身失败时退回「全量发送」,并置 `skip_check_failed=true`。
|
||||
不能让一次检查失败把本该成功的传输挡掉——这是与 `upload_file` 不同的取舍
|
||||
(`upload_file` 在预检失败时直接 `-32001` 失败)。
|
||||
注意这个 fallback 的**实际可达范围很窄**:目标主机被在飞传输或别的工具占用时,预检确实
|
||||
失败,但紧接着的 `BeginC2CTransfer` 也查同一套 `m_Pending` / `m_FileXferSessions` 互斥,
|
||||
会直接返回 `-32003`,根本走不到「全量发送」那一步(见 §14.9.5)。真正能置位的只有
|
||||
「列举超时或异常,而设备此刻空闲」。
|
||||
|
||||
`dst_dir` 传给 helper 时用**不带尾分隔符**的形态(`dstDirListAnsi`):客户端拼 `"%s\*.*"`,
|
||||
带尾分隔符会拼成 `C://*.*` 让 `FindFirstFile` 失败,与 `search_file` 踩过的是同一个坑。
|
||||
|
||||
#### 14.9.3 契约
|
||||
|
||||
| 字段 | 语义 |
|
||||
|---|---|
|
||||
| `overwrite`(入参,bool,默认 false) | `false`:目标目录已有同名顶层项则跳过;`true`:维持旧行为,无条件重发 |
|
||||
| `skipped`(出参,int) | 本次因已存在而跳过的顶层项数;`overwrite=true` 时恒为 0 |
|
||||
| `skip_check_failed`(出参,bool) | `true` 表示没能预检目标目录(主机忙/超时/拒绝访问),本次按全量发送,`skipped` 不可信 |
|
||||
|
||||
#### 14.9.4 验证
|
||||
|
||||
服务端重建并重启后(`exe_build_time=2026-10-29 14:34:33`,PID 12160)实测:
|
||||
|
||||
| 用例 | 结果 |
|
||||
|---|---|
|
||||
| 1. 同一文件连传两次,第二次 `overwrite=false` | **通过**:`file_count=0`、`skipped=1`、`transfer_id=""`、`skip_check_failed=false`,目标端 mtime 不变 |
|
||||
| 2. `overwrite=true` 重传 | **通过**:`file_count=1`、`skipped=0`,目标端 mtime `1793276909` → `1793281657`(推进 4748 s),条目数不变 |
|
||||
| 3. 传到不存在的新目录 | **通过**:目录自动创建,单文件落成 `<dst_dir>/<basename>`(如 `/home/shaun/c2c_probe3/settings.ini`) |
|
||||
| 4. 目标主机被别的工具占住(在飞) | **不可按原描述构造**:返回 `-32003` 而不是「全量发送 + `skip_check_failed=true`」,详见 §14.9.5 |
|
||||
| 5. Windows 目标 + 大小写不同的同名文件 | **通过**:目标 `C:\Temp\c2c_case5` 预置 `SETTINGS.INI`(23 B),传 `settings.ini` → `skipped=1`、`file_count=0`、`transfer_id=""`,目录内仍只有 `SETTINGS.INI` |
|
||||
| 6. Linux 目标 + `SETTINGS.INI` vs `settings.ini` | **通过**:目标 `/home/shaun/c2c_case6` 预置 `SETTINGS.INI`(23 B),传 `settings.ini` → `skipped=0`、`file_count=1`,两个文件并存(23 B 与 1528 B) |
|
||||
|
||||
用例 1、2、3 的目标端是 Ubuntu 24.04(`ubuntu-24` / `Ubuntu24`),源端是 Windows 11(`IOU-Station`);
|
||||
用例 5 的目标端是 Windows 11(`MS084`)。
|
||||
|
||||
#### 14.9.5 用例 4 的期望不成立(实测)
|
||||
|
||||
原用例假设「目标主机被别的工具占住 → 预检失败 → 仍能传完,`skip_check_failed=true`」。实测两条
|
||||
路径都走不到那个结果:
|
||||
|
||||
- **占住目标**(后台 `download_file` 一份 17 MB 日志,随即发起 C2C):返回
|
||||
`-32003 Device busy: source or destination host already has a transfer in flight`。
|
||||
原因是 `BeginC2CTransfer`(`McpServer.cpp`)除了查自己的 `m_FileXferSessions`,还查
|
||||
`src_id`/`dst_id` 的 `m_Pending`——与预检 `BeginPending` 的互斥条件是同一套。预检失败后
|
||||
落到它这里仍然被拒,`skip_check_failed` 因此不可观测。
|
||||
- **让列举失败但写入成功**(`chmod 333`,可写不可读):预检**没有**失败。Linux 客户端把
|
||||
`EACCES` 当成「目录里没有条目」上报(不是 `TOKEN_FILE_LIST_ERROR`),服务端于是
|
||||
`skip_check_failed=false`、`skipped=0`,随后照常覆盖写,文件确实写进了 1528 字节。
|
||||
即这一路是 **fail-open**:列不出来的目录,`overwrite=false` 不会保护其中已有的同名文件。
|
||||
|
||||
因此 `skip_check_failed` 现在只作为「列举超时/异常且设备空闲」的兜底存在,难以稳定构造,
|
||||
字段保留。若要真正验证它,需要让 `WaitPending` 超时(例如临时挂起客户端进程),代价是可能
|
||||
把主机判成离线,本轮没有做。
|
||||
|
||||
#### 14.9.6 一次误报的复盘(重要,避免重犯)
|
||||
|
||||
本轮曾判定「单文件 C2C 落盘会多出 `C:/…` 目录树,只有目录/多文件正常」,并据此在
|
||||
`common/FileTransferV2.h` 里加了一段接收端路径加固。**该结论是错的,加固已还原。**
|
||||
|
||||
根因是自制的 JSON-RPC 直连测试脚本:为了绕过连接器缓存的 `tools/list`(它还没有
|
||||
`overwrite` 字段),脚本用命令行参数传 JSON,而**命令行传递层会把 `\\` 折成 `\/`**,
|
||||
于是 Python 解析出来的路径已经是 `C://ProgramData//HTS//…`(双正斜杠)。源端拿到一条
|
||||
没有任何反斜杠的路径后,`GetRelativePath` 的 basename 兜底用 `find_last_of('\\')` 找分隔符,
|
||||
找不到就把整条绝对路径当相对路径返回 —— 于是落盘成 `<dst_dir>/C:/ProgramData/…`。
|
||||
|
||||
也就是说:**缺陷在测试工具里,不在产品里。** 同一个文件、同一个 `dst_dir`,用连接器
|
||||
(标准 JSON 转义)调用时源端发出的名字是干净的 `/home/shaun/c2c_probe3/settings.ini`。
|
||||
|
||||
教训:
|
||||
|
||||
- 传含反斜杠的路径给自测脚本时,**必须走文件或 stdin,不要走命令行参数**;
|
||||
- 判定「产品有 bug」之前,先用**真实 MCP 客户端**复现一次,别只信自建 harness;
|
||||
- 中继侧/接收侧的日志只能证明「收到的字节是什么」,不能证明「上游是谁写坏的」。
|
||||
|
||||
+59
-41
@@ -17,10 +17,11 @@
|
||||
|
||||
## 0. 结论摘要
|
||||
|
||||
1. **工具面已经覆盖「看 + 管 + 连」三层**(54 个工具,8 个功能族),但仍有三处结构性缺口:
|
||||
**文件系统只有读没有写**(能列、能搜、能传,不能删/改名/建目录)、
|
||||
**远程控制缺「防人工干扰」与「能力自述」**(无法锁定对端键鼠、模型不知道主机支持什么)、
|
||||
**同一能力存在两套重叠工具**(`list_processes` vs `host_list_processes` 等 4 组,模型不知该选哪个)。
|
||||
1. **工具面已经覆盖「看 + 管 + 连」三层**(本方案写作时 54 个工具、8 个功能族;P10-A/B/C 与 P11 之后为
|
||||
**60 个工具、9 个功能族**,见 §1.1)。写作时的三处结构性缺口都已关闭:
|
||||
**文件系统只有读没有写**(P10-B 补了 `delete_path` / `move_path` / `create_folder`)、
|
||||
**远程控制缺「防人工干扰」与「能力自述」**(P10-C 补 `remote_block_input`,P10-A 补
|
||||
`get_host_detail.capabilities`)、**同一能力存在两套重叠工具**(P10-A 用描述互指解决,未合并工具)。
|
||||
2. **最高性价比的一批新工具是文件系统写操作**(`delete_path` / `move_path` / `create_folder`):
|
||||
客户端四个命令 + 三个完成 token **全部已实现**(`client/file/FileManager.cpp:97-121`;
|
||||
`TOKEN_DELETE_FINISH` 被删文件与删目录复用)。MCP 侧复用 P7 的 `followUp` 范式即可,
|
||||
@@ -35,6 +36,8 @@
|
||||
`capabilities` 只描述「这台主机本身能做什么」,两者分工明确。
|
||||
4. **协议层有四个空白**:`initialize.instructions`、`notifications/progress`、`notifications/cancelled`、
|
||||
`logging`。其中前两个直接影响「长任务(下载/上传/搜索/chat_wait)时模型以为卡死」的体验。
|
||||
**现状**(2026-10-28):前三项已落地——`instructions`(P10-A)、progress/cancelled(P11,附录 D.4);
|
||||
`logging` 仍未做(服务端不声明 `capabilities.logging`,也不发 `notifications/message`)。
|
||||
5. **不建议现在做**的:注册表写、Windows 事件日志、进程模块/启动项、剪贴板读——都需要客户端改,
|
||||
且安全边界要单独评审;代理隧道(`COMMAND_PROXY`)价值最高但工程量大,建议单独立项。
|
||||
|
||||
@@ -46,22 +49,29 @@
|
||||
|
||||
## 1. 现状盘点
|
||||
|
||||
### 1.1 工具族(54 个)
|
||||
### 1.1 工具族(60 个)
|
||||
|
||||
登记表在 `server/2015Remote/McpInternal.cpp:368` 的 `kToolHints[]`。
|
||||
注意:**表头注释写「53 个工具」,实际数组是 54 项**(注释已过期,属一处文档瑕疵,见 §5.13)。
|
||||
登记表在 `server/2015Remote/McpInternal.cpp:375` 的 `kToolHints[]`(60 项,与下表的工具逐条对应)。
|
||||
下表是 P11 之后的口径;写作时是 54 个、8 个族,P10-B 加 3 个(文件系统写)、P10-C 加 1 个
|
||||
(`remote_block_input`)、P11 加 2 个(`mcp_list_sessions` / `mcp_cancel_session`)。
|
||||
|
||||
| 族 | 数 | 工具 | 门控条件 |
|
||||
|---|---|---|---|
|
||||
| 服务端本机只读 | 7 | `list_online_hosts` `search_hosts` `list_all_hosts` `get_host_detail` `get_activity_history` `get_audit_log` `get_server_status` | `McpReadonly`(默认 1 = 只读) |
|
||||
| 主机只读 | 21 | `list_processes` `list_windows` `list_files` `list_services` `get_client_log` `get_keylog` `get_screenshot` `list_registry` `download_file` `search_file` `list_network_connections` + `host_list_*`(10 个标签页) | `McpReadonly`;`get_keylog` 另需 `McpKeylog=1`;`host_list_*` 另需 `McpMachine=1` |
|
||||
| 终端 | 4 | `terminal_open` `terminal_exec` `terminal_close` `exec_command` | `McpTerminal=1` **且** `McpReadonly=0` |
|
||||
| 远程控制 | 5 | `remote_open` `remote_close` `remote_mouse` `remote_keyboard` `remote_clipboard` | `McpRemoteControl=1` **且** `McpReadonly=0` |
|
||||
| 文件传输 | 2 | `upload_file` `copy_files_c2c` | `McpFileTransfer=1`(`download_file` 只要求此开关,不要求 `McpReadonly=0`) |
|
||||
| 服务端本机只读 | 9 | `list_online_hosts` `search_hosts` `list_all_hosts` `get_host_detail` `get_activity_history` `get_audit_log` `get_server_status` `mcp_list_sessions` `mcp_cancel_session` | 全部始终在列表里、只读模式下照常可用;`mcp_list_sessions` / `mcp_cancel_session` 还**不受任何开关或只读限制**(卡住请求的唯一出路,见附录 D.5) |
|
||||
| 主机只读 | 21 | `list_processes` `list_windows` `list_files` `list_services` `get_client_log` `get_keylog` `get_screenshot` `list_registry` `download_file` `search_file` `list_network_connections` + `host_list_*`(10 个标签页) | 除下列四类外始终在列表里:`get_keylog` 需 `McpKeylog=1`(其 `clear` / `set_offline` 还需 `McpReadonly=0`)、`download_file` 需 `McpFileTransfer=1`、`list_network_connections` 与 `host_list_*` 需 `McpMachine=1` |
|
||||
| 终端 | 4 | `terminal_open` `terminal_exec` `terminal_close` `exec_command` | `terminal_*`:`McpTerminal=1` **且** `McpReadonly=0`;`exec_command` 只要求 `McpReadonly=0` |
|
||||
| 远程控制 | 6 | `remote_open` `remote_close` `remote_mouse` `remote_keyboard` `remote_clipboard` `remote_block_input` | `McpRemoteControl=1` **且** `McpReadonly=0` |
|
||||
| 文件传输 | 2 | `upload_file` `copy_files_c2c` | `McpFileTransfer=1` **且** `McpReadonly=0`(`download_file` 只要求此开关) |
|
||||
| 文件系统写 | 3 | `delete_path` `move_path` `create_folder` | `McpFileWrite=1` **且** `McpReadonly=0` |
|
||||
| 设备管理 | 4 | `kill_process` `operate_window` `control_service` `power_action` | `McpManage=1` **且** `McpReadonly=0` |
|
||||
| 主机/连接管理 | 7 | `kill_network_connection` `host_control_process` `host_control_window` `host_control_service` `host_control_task` `host_set_remark` `host_set_watch_level` | 前 5 个:`McpMachine=1` + `McpMachineDangerous=1` + `McpReadonly=0`;后 2 个只要求 `McpReadonly=0` |
|
||||
| 主机/连接管理 | 7 | `kill_network_connection` `host_control_process` `host_control_window` `host_control_service` `host_control_task` `host_set_remark` `host_set_watch_level` | 前 5 个:`McpMachine=1` + `McpMachineDangerous=1` + `McpReadonly=0`;`host_set_remark` / `host_set_watch_level` 始终在列表里,调用要求 `McpReadonly=0` |
|
||||
| 远程交谈 | 4 | `chat_open` `chat_send` `chat_wait` `chat_close` | `McpChat=1`(与 `McpReadonly` 无关) |
|
||||
|
||||
合计 9+21+4+6+2+3+4+7+4 = 60。默认配置(`McpReadonly=1`、其余开关 0)下 `tools/list` **19 个**
|
||||
= 服务端本机只读 9 + 主机只读 8(去掉 `get_keylog` / `download_file` / `list_network_connections` /
|
||||
`host_list_*`)+ 主机/连接管理 2(`host_set_remark` / `host_set_watch_level`);其余各族依赖开关,全部不可见。
|
||||
开关全开且关闭只读时为 **60 个**。
|
||||
|
||||
**已有的工程范式**(新工具直接复用,不必重新设计):
|
||||
|
||||
- **一次性子连接 + 首包即数据**:`list_processes` / `list_windows` / `list_services` / `list_registry` / `get_client_log`。
|
||||
@@ -311,7 +321,7 @@ proxy_close(session_id)
|
||||
|
||||
> 另有一项「两套工具族重叠」的优化放在 §3.2(因为要顺带说明它为什么不合并),同样是 P0。
|
||||
|
||||
### 5.1 【P0】`get_host_detail` 增加 `capabilities`
|
||||
### 5.1 【P0,已完成 `bb55f52`】`get_host_detail` 增加 `capabilities`
|
||||
|
||||
**问题**:模型拿到 `clientType=WIN` 就以为所有工具都能用,于是反复撞 `-32005`:
|
||||
|
||||
@@ -342,7 +352,7 @@ host["capabilities"] = caps;
|
||||
**收益**:模型在规划阶段就能排除不可用工具,把「试错 → 报错 → 换工具」的三轮往返压缩成一次。
|
||||
**成本**:约 30 行,零客户端改动,`outputSchema` 加一个对象。
|
||||
|
||||
### 5.2 【P0】`get_keylog`:补离线开关与真实状态(**已重写,初稿前提有误**)
|
||||
### 5.2 【P0,已完成 `bb55f52`】`get_keylog`:补离线开关与真实状态(**已重写,初稿前提有误**)
|
||||
|
||||
> **初稿的错误**:原文断言「现在只能采 1–15 秒窗口,对『昨天谁敲了什么』完全无用,需要新增 `mode=offline`」。
|
||||
> 这是错的。`CKeyboardManager1` 构造时就 `new CircularBuffer(m_strRecordFile)`,而 `CircularBuffer`
|
||||
@@ -371,7 +381,7 @@ host["capabilities"] = caps;
|
||||
|
||||
两个写动作都必须**先于采集窗口下发**,且失败要如实返回(`Send2Client` 的返回值要检查)。
|
||||
|
||||
### 5.3 【P0】`list_processes` / `list_windows` 增加服务端过滤
|
||||
### 5.3 【P0,已完成 `bb55f52`】`list_processes` / `list_windows` 增加服务端过滤
|
||||
|
||||
**问题**:`BuildPagedHostListInputSchema` 只有 `{id, limit, offset}`(`McpServer.cpp:776`,调用点在 `:1477` 等)。一台正常 Windows 有 200–400 个进程、几十个窗口,模型要翻 3–4 页才能找到目标;每页都是完整字段,上下文开销很大。
|
||||
|
||||
@@ -384,7 +394,7 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
|
||||
**收益**:`list_processes(name="chrome")` 从 3 页变 1 条;两套工具族的能力也对齐了(`host_list_*` 本来就有这两个参数)。
|
||||
|
||||
### 5.4 【P1】`power_action` 增加结果验证
|
||||
### 5.4 【P1,已完成 `1c832ff`】`power_action` 增加结果验证
|
||||
|
||||
**问题**:`power_action` 是「发完即走、无响应」(`McpServer.cpp:5812` 附近注释),返回 `ok:true` 只代表**命令写进了 socket**。模型会误以为「已重启」,紧接着调 `list_processes` 却拿到旧进程列表。
|
||||
|
||||
@@ -393,13 +403,13 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
- `wait=true`:轮询主连接是否断开 → 再轮询是否重新上线,返回 `{sent:true, went_offline:true, came_back:true, elapsed_ms}`;
|
||||
- 超时不算失败,返回 `came_back:false` 让模型自己决定。
|
||||
|
||||
### 5.5 【P1】破坏性工具统一 `dry_run`
|
||||
### 5.5 【P1,已完成 `1c832ff`】破坏性工具统一 `dry_run`
|
||||
|
||||
`kill_network_connection` 有 `dry_run`(实测报告「观察项」明确肯定了这个设计),但 `kill_process`、`operate_window(close)`、`host_control_*` 都没有。建议统一:`dry_run=true` 时只做「目标存在性校验 + 返回将被影响的对象」,不执行。
|
||||
|
||||
对 AI 尤其重要:模型可以在执行前把「我要杀这 3 个进程」摆给用户看。
|
||||
|
||||
### 5.6 【P2,收益被初稿高估】错误码:`-32008` 其实只有两种语义
|
||||
### 5.6 【P2,已完成 `1c832ff`(`-32012`,`-32008` 留作别名)】错误码:`-32008` 其实只有两种语义
|
||||
|
||||
> **初稿的错误**:原文说 `-32008` 一码四义(含「老客户端格式」「多显示器不支持」)。核对后全文件只有两处
|
||||
> `-32008`:`exec_command` 的 shell 元字符(`McpServer.cpp:2901`)与 `terminal_exec` 的 `&`/`|`/换行
|
||||
@@ -415,7 +425,7 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
`-32008` 保留为历史别名(不破坏既有客户端与已发布的文档)。这是一次纯常量替换,收益是让模型
|
||||
不必读英文 message 就能区分「改参数」与「换主机」,但**优先级低于 P0 各项**。
|
||||
|
||||
### 5.7 【P1】写工具的 ack 语义显式化
|
||||
### 5.7 【P1,部分完成 `27b5431`:`verified` 三态已落地,`verify_hint` 字段未加】写工具的 ack 语义显式化
|
||||
|
||||
现状:`delete_path` / `move_path` / `create_folder` / `kill_process` / `operate_window` / `control_service` 的 ack 都是**客户端无条件回包**,不代表操作成功。
|
||||
|
||||
@@ -426,7 +436,7 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
|
||||
彻底的做法是客户端补 `TOKEN_FILE_OP_ERROR`(带 win32 码),归入 §4.1 的 P12 批次。
|
||||
|
||||
### 5.8 【P1】`initialize` 返回 `instructions`
|
||||
### 5.8 【P1,已完成 `bb55f52`】`initialize` 返回 `instructions`
|
||||
|
||||
**问题**:模型对这套服务端的「隐性知识」全靠工具描述拼凑:主机 id 是 64 位雪花值(不能猜)、要先 `list_online_hosts` 再操作、`-32003` 是单设备单飞行、`-32006` 不要重试、远程控制要先 `remote_open` 拿 `session_id`。`Mcp_Design.md` 把这些写在文档里,但**模型看不到文档**。
|
||||
|
||||
@@ -440,7 +450,7 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
|
||||
**收益**:这是**单点投入、全局收益**的改动——所有客户端的每一次会话都受益,且零风险。优先级应当排在所有新工具之前。
|
||||
|
||||
### 5.9 【P2】`notifications/progress` 与 `notifications/cancelled`
|
||||
### 5.9 【P2,已完成 `1c832ff`】`notifications/progress` 与 `notifications/cancelled`
|
||||
|
||||
**问题**:
|
||||
|
||||
@@ -454,20 +464,25 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
|
||||
这两项都在 `McpServer.cpp` 的 HTTP 处理器层,**不动任何工具实现**。
|
||||
|
||||
### 5.10 【P2】会话可观测与自救
|
||||
### 5.10 【P2,已完成 `1c832ff`】会话可观测与自救
|
||||
|
||||
`-32003 Device busy` 现在是死路:模型不知道是谁占着这台主机、也不知道等多久。建议加两个纯服务端工具:
|
||||
|
||||
| 工具 | 作用 |
|
||||
|---|---|
|
||||
| `mcp_list_sessions` | 列出所有在飞会话:`{host_id, tool, session_id, started_at, idle_ms, kind}` |
|
||||
| `mcp_cancel_session` | 按 `session_id` 强制中止(等价于 `notifications/cancelled` 的内部路径) |
|
||||
| `mcp_list_sessions` | 列出所有在飞会话,每项 `{host_id, kind, tool, session_id, request_id, busy, elapsed_ms, idle_ms}` |
|
||||
| `mcp_cancel_session` | 按 `request_id`(精确)或 `id`/`session_id`(条件)取消,返回 `{cancelled, released, waited_ms, matched}`;与 `notifications/cancelled` 走同一个取消位 |
|
||||
|
||||
实装口径以附录 D.5 为准。写作时设想的字段是 `{host_id, tool, session_id, started_at, idle_ms, kind}`,
|
||||
落地时去掉了 `started_at`,补了 `request_id`(供 `mcp_cancel_session` 精确回传)、`busy`、`elapsed_ms`。
|
||||
|
||||
`-32003` 的 message 里带上「当前占用者与已持续时间」,模型就能自己决定「等」还是「取消」。
|
||||
|
||||
### 5.11 【P2】`tools/list` 体积
|
||||
|
||||
54 个工具、每个都带完整中文描述 + 双 schema。实测**工具描述与属性说明文本合计约 23 KB**(54 条 `description` + 158 条 schema 属性说明),叠加 JSON 结构与 schema 骨架后,`tools/list` 响应实际在 **45–60 KB** 量级。
|
||||
**60** 个工具(P11 之后的口径,见 §1.1)、每个都带完整中文描述 + 双 schema。按 54 个工具时(P10-A)实测,
|
||||
**工具描述与属性说明文本合计约 23 KB**(54 条 `description` + 158 条 schema 属性说明),叠加 JSON
|
||||
结构与 schema 骨架后,`tools/list` 响应在 **45–60 KB** 量级;多出的 6 个工具只会让它更大。
|
||||
|
||||
对 200K 上下文的模型不算致命,但对小上下文客户端(8K–32K)会挤占绝大部分预算,且**每轮对话都要重传**(多数客户端不缓存)。
|
||||
|
||||
@@ -481,17 +496,19 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
|
||||
`client/ServicesManager.cpp:213` 的 `ServicesConfig` 对每一项 `Sleep(500)` 后再回列表。批量控制 10 个服务 = 至少 5 秒。服务端可以在 `action` 里支持 `items[]` 批量下发(一次子连接、一个 payload),把 N 次往返压成 1 次。**前提是确认客户端能解析多条目 payload**——按现有实现它只处理单条,需要客户端改动,因此列为 P2。
|
||||
|
||||
### 5.13 【P0,顺手修】`kToolHints` 表头注释过期
|
||||
### 5.13 【P0,已修】`kToolHints` 表头注释过期
|
||||
|
||||
`McpInternal.cpp:367` 注释写「53 个工具的语义登记表」,实际数组 **54 项**。一行修复。
|
||||
原注释写「53 个工具的语义登记表」,与数组实际长度不符。P10-A(`bb55f52`)先改成 54,
|
||||
P10-C(`3d388f8`)加工具时索性去掉数字——避免每加一个工具就要改一次注释;
|
||||
核对方式见 §1.1,60 个工具与 60 项注解逐条对应。
|
||||
|
||||
### 5.14 其他小项
|
||||
|
||||
| 项 | 位置 | 说明 |
|
||||
|---|---|---|
|
||||
| `list_windows` 无 `pid` 过滤 | `McpServer.cpp:2201` | 见 §5.3 |
|
||||
| `search_file` 无深度/大小上限参数 | `McpServer.cpp:8050` | 客户端固定深度 32 / 10000 条,服务端可加 `max_depth` 但需客户端支持;暂不做 |
|
||||
| `search_file` 的描述仍写着「会栈溢出」 | `McpServer.cpp:1850` | 客户端侧已于 8f718d9 修复,描述与 `tools/mcp_smoke.ps1` 的注释都过期,应一并更正 |
|
||||
| ~~`list_windows` 无 `pid` 过滤~~ | — | **已完成**(P10-A,`bb55f52`):`list_processes` / `list_windows` 都加了 `name` + `pid` |
|
||||
| `search_file` 无深度/大小上限参数 | `McpServer.cpp:8050` | 客户端固定深度 32 / 10000 条,服务端可加 `max_depth` 但需客户端支持;暂不做(P12) |
|
||||
| ~~`search_file` 的描述仍写着「会栈溢出」~~ | — | **已完成**(P10-A,`bb55f52`):描述改为「超过 260 字节的路径会被静默跳过(既不记录也不继续向下递归)」,`tools/mcp_smoke.ps1` 的两处注释改为「MAX_PATH 的条目会被客户端静默跳过(8f718d9 起不再栈溢出)」 |
|
||||
| `get_screenshot` 无区域裁剪 | `McpServer.cpp:2085` | 有 `max_width`;ROI 需客户端改动,收益有限,不做 |
|
||||
| 审计不含调用参数 | `Mcp_Design.md §10.8` | 有意设计(防泄漏),维持 |
|
||||
| `chat_wait` 会取走 inbox | `McpInternal.cpp:431` | 已正确标注非幂等,无需改 |
|
||||
@@ -500,16 +517,17 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
|
||||
|
||||
## 6. 批次与验收建议
|
||||
|
||||
| 批次 | 内容 | 客户端改动 | 预估规模 | 验收方式 |
|
||||
|---|---|---|---|---|
|
||||
| **P10-A(优化,先做)** | `instructions`、`capabilities`、`list_*` 过滤、`get_keylog` 离线开关与状态、工具族互指、`kToolHints` 注释、`search_file` 过期描述 | 无 | 服务端 ~450 行 | 冒烟断言 `instructions` 非空;`capabilities` 与平台一致;`list_processes(name=...)` 命中数 < 全量且 `totalAll` 正确;`get_keylog.offlineRecord` 与实际 `kbrecord` 一致 |
|
||||
| **P10-B** | `delete_path` / `move_path` / `create_folder` + `McpFileWrite` 开关 + 系统目录保护 + §2.3 的三处接线 + `verified` 复核 | 无 | ~700 行 | 冒烟新增:建目录→传文件→改名→删除→删目录→越界拒绝;中文路径 + 超长路径各一条;超时后确认**不弹**文件管理器窗口 |
|
||||
| **P10-C** | `remote_block_input`(含强制解锁与超时自动解锁) | 无 | ~200 行 | 会话内 block→截图对比→unblock;`remote_close` 后确认已解锁 |
|
||||
| **P11(已完成 2026-10-28,见附录 D)** | `power_action` 验证、`dry_run` 统一、`-32012`、progress/cancelled、`mcp_list_sessions` | 无 | ~700 行 | 长任务 progress 回调计数 > 0;取消后主机 1s 内释放(`get_server_status` 可查) |
|
||||
| **P12** | 注册表写、事件日志、进程模块/启动项、`TOKEN_FILE_OP_ERROR`、`DeleteDirectory` 的路径长度防御 | **需要** | 客户端 + 服务端 | 单独设计文档 |
|
||||
| **独立立项** | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
|
||||
| 批次 | 状态 | 内容 | 客户端改动 | 规模 | 验收方式 |
|
||||
|---|---|---|---|---|---|
|
||||
| **P10-A** | 已完成 `bb55f52` | `instructions`、`capabilities`、`list_*` 过滤、`get_keylog` 离线开关与状态、工具族互指、`kToolHints` 注释(去数字这一步实际随 P10-C 落地,见 §5.13)、`search_file` 过期描述 | 无 | 服务端 ~450 行 | 冒烟断言 `instructions` 非空;`capabilities` 与平台一致;`list_processes(name=...)` 命中数 < 全量且 `totalAll` 正确;`get_keylog.offlineRecord` 与实际 `kbrecord` 一致 |
|
||||
| **P10-B** | 已完成 `27b5431` | `delete_path` / `move_path` / `create_folder` + `McpFileWrite` 开关 + 系统目录保护 + §2.3 的三处接线 + `verified` 复核 | 无 | ~700 行 | 冒烟新增:建目录→传文件→改名→删除→删目录→越界拒绝;中文路径 + 超长路径各一条;超时后确认**不弹**文件管理器窗口 |
|
||||
| **P10-C** | 已完成 `3d388f8` | `remote_block_input`(含强制解锁与超时自动解锁) | 无 | ~200 行 | 会话内 block→截图对比→unblock;`remote_close` 后确认已解锁 |
|
||||
| **P11** | 已完成 `1c832ff`,见附录 D | `power_action` 验证、`dry_run` 统一、`-32012`、progress/cancelled、`mcp_list_sessions` | 无 | ~700 行 | 长任务 progress 回调计数 > 0;取消后主机 1s 内释放(`get_server_status` 可查) |
|
||||
| **P12** | **待做** | 注册表写、事件日志、进程模块/启动项、`TOKEN_FILE_OP_ERROR`、`DeleteDirectory` 的路径长度防御、`control_service` 批量 payload、`search_file.max_depth` | **需要** | 客户端 + 服务端 | 单独设计文档 |
|
||||
| **独立立项** | 未立项 | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
|
||||
|
||||
**建议顺序**:P10-A → P10-B → P10-C → P11,**每批独立提交**。
|
||||
**建议顺序**:P10-A → P10-B → P10-C → P11,**每批独立提交**(已于 2026-10-28 按序完成;
|
||||
未推送前按批次合并了零碎提交,故每批各一个提交,见上表)。
|
||||
|
||||
理由:P10-A 全是**几十行代码换全局体验**的改动(能力自述 + 使用说明 + 描述互指),先落地能立刻降低后续所有工具的试错率,且几乎不引入回归风险;P10-B 是最大的功能缺口,但涉及删除语义,需要更充分的测试与开关灰度;P10-C 小而独立,可随时插入。
|
||||
|
||||
@@ -561,7 +579,7 @@ COMMAND_WEBCAM / COMMAND_AUDIO→ 流式音视频 client/K
|
||||
|
||||
| 主题 | 位置 |
|
||||
|---|---|
|
||||
| 工具注解登记表(54 项) | `server/2015Remote/McpInternal.cpp:368` |
|
||||
| 工具注解登记表(60 项) | `server/2015Remote/McpInternal.cpp:375` |
|
||||
| `tools/list` 构造 | `server/2015Remote/McpServer.cpp:1408` |
|
||||
| `initialize` 结果构造 / HTTP 方法分派 | `McpServer.cpp:46` `BuildInitializeResult` / `:7622` 起 |
|
||||
| 主机技术字段补全 | `server/2015Remote/McpServer.cpp:2018` `AppendHostTechnicalDetail` |
|
||||
|
||||
@@ -275,7 +275,7 @@ Web 是长连接,子链接可长驻;MCP 是**一次性 request/response**。
|
||||
- 复用 MFC 预览的 RTT/FRP 自适应参数挑选 `ChooseScreenPreviewParams` + `SendScreenPreviewRequest`,不重复实现 `GetTargetQualityLevel`。
|
||||
- **可选 `max_width` 参数**:缺省/0 沿用缩略图档位(最大 1024,4K 源屏高档 1280);`max_width`>0 覆盖宽度并钳制到客户端上限 `[64,1920]`(客户端 `CaptureAndEncodePreview` 硬钳制),供 AI 视觉/OCR 场景请求接近原分辨率(1080p 源屏传 1920 即原分辨率,4K 源屏最多 1920)。`jpegQuality` 仍沿用档位自适应值。
|
||||
- **请求关联**:`ScreenPreviewReq.reqId` 提供关联;MCP 用独立 16 位 reqId 发生器(`NextPreviewReqId`,跳过 0)+ `SetPendingReqId` 登记期望值,`TakePreviewResponse` 只接受「挂起命中 + reqId 一致」的响应,过期/他途(MFC 预览并发)响应原样回落到 MFC 路径。
|
||||
- 客户端能力位 `CLIENT_CAP_SCREEN_PREVIEW`(0x0004,仅 Windows 客户端声明):非 Windows 主机返回 `-32005`「不支持」。
|
||||
- 客户端能力位 `CLIENT_CAP_SCREEN_PREVIEW`(0x0004):Windows 客户端恒声明;Linux 客户端在登录时探测到可用 X11 桌面才声明(无 `DISPLAY` 的服务器不声明)。未声明的主机返回 `-32005`「不支持」。
|
||||
- 返回结构:`content[0] = {type:"image", data: base64(JPEG), mimeType:"image/jpeg"}` + `structuredContent.image = {mimeType,width,height,bytes}`(元数据,不含 base64,避免二次膨胀)。
|
||||
|
||||
**`list_files`(文件链路,一次性子链接,模式 A′)**:
|
||||
@@ -303,7 +303,7 @@ Web 是长连接,子链接可长驻;MCP 是**一次性 request/response**。
|
||||
|
||||
**验收 / 实机验证点(待构建后执行)**:
|
||||
- MFC 双击文件管理弹框仍正常(回归点);MFC 双击预览缩略图仍正常(回归点)。
|
||||
- MCP `get_screenshot` 返回 JPEG(base64 + 元数据),Windows 主机正常;非 Windows 主机(或未声明 `CLIENT_CAP_SCREEN_PREVIEW`)返回 `-32005`。
|
||||
- MCP `get_screenshot` 返回 JPEG(base64 + 元数据),Windows 主机正常;带 X11 桌面的 Linux 主机同样正常(客户端回 BGRA,服务端转 JPEG);未声明 `CLIENT_CAP_SCREEN_PREVIEW` 的主机返回 `-32005`。
|
||||
- MCP `list_files`(无 `path`)返回 `drives[]`;`list_files(path="C:\\")` 返回 `files[]`(含目录/文件/大小/mtime),中文文件名无乱码;条目 >500 时截断为 500。
|
||||
- 错误路径:缺 `id`/非数字 `id` → `-32602`;未知/离线主机 → `-32002`;同 host 并发 → `-32003`;发送失败 → `-32004`;超时 → `-32001`。
|
||||
|
||||
|
||||
@@ -0,0 +1,389 @@
|
||||
# YAMA MCP 工具集实测报告
|
||||
|
||||
- **测试日期**:2026-10-29
|
||||
- **服务端**:Yama v1.4.1,构建时间 `2026-10-29 18:26:56`,监听 `0.0.0.0:6544`,10 项开关全开(readonly=false)
|
||||
- **规模**:在线 34 台、离线 3165 台,`tools/list` 共 **60 个工具**
|
||||
- **测试目的**:考察 AI 使用这套 MCP 工具是否顺畅,以及能否对设备完成有效监管与处置
|
||||
- **修复状态**:三个 P0 已于同日修复并实测通过,见 §7(实现说明在 `docs/Mcp_Design.md` §18);P2-1(`get_activity_history` 无分页)已于同日修复,见 §8(实现说明在 `docs/Mcp_Design.md` §19)
|
||||
|
||||
## 1. 测试范围与约定
|
||||
|
||||
按约定划分操作边界:
|
||||
|
||||
| 用途 | 主机 | 说明 |
|
||||
|---|---|---|
|
||||
| 写操作 | `DESKTOP-A55C0OI`(`3441387693643366974`,Win10 VM,MDLL)<br>`Ubuntu24`(`15731161054501180314`,Ubuntu 24.04,Stuttgart,带 UI,LNX) | 仅这两台 |
|
||||
| 读操作 | 以本机 `A6`(`11261158607827860566`)为主,另抽样其他主机 | 不做写操作 |
|
||||
|
||||
**实际覆盖 55 / 60 个工具。** 未覆盖及原因:
|
||||
|
||||
- `control_service`:无 `dry_run`,执行即重启/停止 YAMA 自身服务,会切断 AI 自己的 MCP 通道,**无法安全自测**
|
||||
- `operate_window`、`kill_network_connection`:仅 Windows;唯一可写的 Windows VM 在重启测试窗口内未回线,这两个工具来不及执行(该 VM 未配自动登录,人工登录后才回线,见 P1-9)
|
||||
- `list_windows`:降级路径,已由首选 `host_list_windows` 覆盖
|
||||
- 其余全部实测
|
||||
|
||||
## 2. 结论摘要
|
||||
|
||||
**整体可用,但"监管/处置"链路上有 3 个硬伤会直接卡住 AI,另有 1 个动作可能把设备弄丢。**
|
||||
|
||||
- **读得准**:所有只读工具在 A6 上返回结构正确、过滤与分页语义一致(`total` / `totalAll` / `hasMore` 三者自洽),截屏返回的是 AI 真能看的图像,不是 base64 字符串。
|
||||
- **写得住**:文件上传/下载/C2C 全部正确,下载带 SHA-256 且与本地逐字节吻合,目录结构保留,`overwrite` / `skipped` / `skip_check_failed` 行为与设计一致。
|
||||
- **控得了**:窗口/服务/进程/计划任务的 `dry_run` + 执行后复核闭环质量很高;远程鼠标键盘在 Windows 与 Linux 上都验证成功;远程交谈可视确认。
|
||||
- **审计扎实**:每个 MCP 动作都落审计日志,含主机 id、工具名、关键参数,连鼠标归一化坐标与像素坐标都在。
|
||||
- **但有 3 个硬伤**:批量读取主机详情**必定失败**、客户端日志**拿不到**、**新参数对已连接客户端不可见**。
|
||||
- **重启是唯一会"弄丢设备"的动作**:目标 VM 未配自动登录,重启后停在登录界面,客户端(HKCU 启动项)要等人工输密码才起。`power_action` 既不预检自动登录状态,默认也只等 60 秒,`came_back=false` 既可能是"再等等"也可能是"必须喊人"——AI 无法分辨。
|
||||
|
||||
严重度分布:**P0 × 3**、**P1 × 9**、**P2 × 15**。
|
||||
|
||||
## 3. 发现清单
|
||||
|
||||
### 3.1 P0:阻断性缺陷
|
||||
|
||||
#### P0-1 `get_host_detail` 的批量模式必定失败 `已修复,见 §7`
|
||||
|
||||
```json
|
||||
{"ids": ["17221709513794608622", "11261158607827860566"]}
|
||||
→ -32602 Structured content does not match the tool's output schema:
|
||||
data must have required property 'host'
|
||||
```
|
||||
|
||||
input schema 明确声明支持 `ids`(最多 50 个)、"结果按台汇总在 `results` 里",但 **output schema 只认单台的 `host`**。实现返回 `results` 就必然校验失败。单台 `id` 形式正常。
|
||||
|
||||
影响:**所有只读工具的 `ids` 批量能力全部不可用**(`list_processes`、`list_files`、`list_registry`、`host_list_*` 等十余个工具共用同一套输出 schema)。AI 只能逐台串行调用,34 台机群的横向盘点要 34 次往返。
|
||||
|
||||
#### P0-2 `list_registry` 的根键分支必定失败 `已修复,见 §7`
|
||||
|
||||
```json
|
||||
{"id": "...", "path": ""} # 省略 path,按文档应返回 5 个根键
|
||||
→ -32602 ... data must have required property 'values'
|
||||
```
|
||||
|
||||
带 `path` 时正常(返回 `keys` + `values`);省略 `path` 时只返回 `keys`,而 output schema 要求 `values` 必填。**文档描述的第一种用法("省略或空 path 返回 5 个根键")是死路**,AI 必须先猜一个真实路径才能进注册表。
|
||||
|
||||
#### P0-3 `get_client_log` 两种平台都不可用 `已修复,见 §7`
|
||||
|
||||
| 平台 | 实测结果 |
|
||||
|---|---|
|
||||
| Windows(A6,pid 8668) | 返回 **90,473 字符**(单行 JSON 塞 1000 行日志),直接超出客户端工具结果上限 |
|
||||
| Linux(Ubuntu24) | `-32001 Timeout waiting for client log`,连续两次稳定复现 |
|
||||
|
||||
工具没有任何 `limit` / `offset` / `tail` / `since` 参数,只能全量取。Windows 上"取到了但塞不下",Linux 上"根本取不到"。
|
||||
|
||||
影响:**故障排查最需要的一手证据(客户端日志)AI 拿不到。** 本次测试中我只能改用 `download_file` 把日志文件从主机上拉回本地再读——多绕两跳,且要求 AI 自己想到这条路。
|
||||
|
||||
### 3.2 P1:破坏工作流
|
||||
|
||||
#### P1-1 服务端已发布的新参数,对已连接客户端不可见
|
||||
|
||||
直连 `tools/list` 确认服务端**已声明** `copy_files_c2c.overwrite`:
|
||||
|
||||
```
|
||||
upload_file: ['id', 'local_path', 'overwrite', 'remote_dir', 'timeout_ms']
|
||||
copy_files_c2c: ['dst_dir', 'dst_id', 'overwrite', 'paths', 'src_id', 'timeout_ms']
|
||||
```
|
||||
|
||||
但连接器缓存的 schema 仍是旧版,带 `overwrite` 调用被本地拦下:
|
||||
|
||||
```
|
||||
Parameter validation failed: root: must NOT have additional properties
|
||||
```
|
||||
|
||||
**报错完全不提示"服务端已支持、是你的客户端缓存过期"。** AI 只会以为参数名写错了,反复尝试无效写法。
|
||||
|
||||
功能本身经直连验证是**正确**的:
|
||||
|
||||
| 调用 | 结果 |
|
||||
|---|---|
|
||||
| `overwrite=true` | `file_count=1, skipped=0, transfer_id=7364150632606842580` |
|
||||
| 默认(不带 overwrite) | `file_count=0, skipped=1, transfer_id="", skip_check_failed=false` |
|
||||
|
||||
#### P1-2 本地化枚举值与英文文档冲突,且无枚举可查
|
||||
|
||||
```json
|
||||
{"status": "Ready"} → total: 0 (schema 文档建议 "如 Ready / Disabled")
|
||||
{"status": "已准备"} → total: 222
|
||||
```
|
||||
|
||||
实际值是本地化中文。同类问题存在于 `host_list_win32_services.start_type`(`"Auto Start"` 带空格)与降级版 `list_services.start_type`(`"Auto-Start"` 带连字符)——**两套拼法**。
|
||||
|
||||
影响:AI 按文档写过滤条件会静默得到空结果,误判为"没有匹配项"。schema 里也没有 `enum` 可枚举合法值。
|
||||
|
||||
#### P1-3 Linux 主机完全没有文件变更能力
|
||||
|
||||
`create_folder` / `move_path` / `delete_path` 三个工具均为 Windows-only:
|
||||
|
||||
```
|
||||
create_folder on Ubuntu24 → -32005 create_folder is only supported on Windows hosts
|
||||
```
|
||||
|
||||
Linux 上唯一的替代是 `terminal_exec` 跑 `mkdir` / `mv` / `rm`。而这正是最危险的一类操作,恰恰**没有 `dry_run`、没有执行后复核、没有受保护路径拦截**——与 Windows 侧形成鲜明反差(Windows 的 `delete_path` 会拒绝 `C:\ProgramData` 等系统目录)。
|
||||
|
||||
#### P1-4 C2C 只支持 Windows 作源
|
||||
|
||||
```
|
||||
Ubuntu24 → DESKTOP-A55C0OI → -32005 copy_files_c2c requires a Windows source host
|
||||
DESKTOP-A55C0OI → Ubuntu24 → 正常,receiver_ack=true
|
||||
```
|
||||
|
||||
混合机群里,**从 Linux 取文件到另一台主机**只能 `download_file` → `upload_file` 两跳,且文件要经过主控落盘。这与 C2C"不经主控"的设计初衷相悖,但工具描述里没有提示这一限制。
|
||||
|
||||
#### P1-5 `terminal_exec` 禁管道,`exec_command` 受白名单,两者都不是通用 shell
|
||||
|
||||
```
|
||||
ls -1 /home/yuan/upload | wc -l
|
||||
→ -32012 Command contains & or | or a newline (breaks output capture)
|
||||
```
|
||||
|
||||
`exec_command` 则被白名单挡住常用工具:
|
||||
|
||||
```
|
||||
powershell -NoProfile -Command Get-Date → -32007 Command not allowed by whitelist
|
||||
```
|
||||
|
||||
代价是实打实的:想看"某个目录有几个文件",AI 只能把整个 `ls` 输出拉回上下文自己数;想看进程占用只能先 `host_list_processes` 再本地算。**上下文消耗与往返次数都翻倍**,且两个工具的限制互不覆盖,AI 需要记住"哪件事该用哪个"。
|
||||
|
||||
#### P1-6 删除保护是"建议"而非"强制"
|
||||
|
||||
`delete_path` 的拦截很到位:
|
||||
|
||||
```
|
||||
delete_path C:\ProgramData → -32602 refusing to modify a protected system location
|
||||
```
|
||||
|
||||
但提示语自己给出了绕过方式:
|
||||
|
||||
> use exec_command if you really need to touch them
|
||||
|
||||
而 `terminal_exec` 本身不受白名单约束,`rm -rf` 畅通无阻。**保护只在"守规矩的路径"上生效**,对有意或无意的越界没有约束力。
|
||||
|
||||
#### P1-7 持久终端会话静默过期,AI 无法预判
|
||||
|
||||
Linux 终端会话(`fb4903…`)在空闲约 35 分钟后消失,期间没有任何通知:
|
||||
|
||||
```
|
||||
terminal_exec → -32002 Terminal session not found: fb4903... (call terminal_open first)
|
||||
```
|
||||
|
||||
`mcp_list_sessions` 里也**看不到它曾经存在**,因此 AI 无法在调用前判断会话是否还活着。重新 `terminal_open` 后立刻查询,会话正常出现在列表里(`idle_ms: 3000`)——说明登记机制本身没问题,纯粹是**过期无提示、TTL 未文档化**。
|
||||
|
||||
(`-32002` 的文案本身写得很好,明确让人重新 `terminal_open`。)
|
||||
|
||||
#### P1-8 `mcp_cancel_session` 按主机取消会连带销毁持久终端
|
||||
|
||||
```
|
||||
{"id": "15731161054501180314"} → cancelled: 2, released: false
|
||||
matched 中包含 {"kind": "terminal", "session_id": "21afe3..."}
|
||||
→ 后续 terminal_exec: -32002 Terminal session was destroyed because the request was cancelled
|
||||
```
|
||||
|
||||
取消在飞请求本身**效果很好**——阻塞 40 秒的调用在 4 秒内以 `-32800` 终止。但 schema 描述的是"取消该主机上所有在飞请求",没提会连带销毁持久会话。副作用超出文档承诺范围。
|
||||
|
||||
#### P1-9 重启后能否自行回线,取决于目标机的自动登录配置——而工具不会告诉你
|
||||
|
||||
实测在 `DESKTOP-A55C0OI`(2 GB 内存的 Win10 VM)上执行,按审计日志对齐时间轴:
|
||||
|
||||
| 时刻 | 事件 |
|
||||
|---|---|
|
||||
| 18:45:47 | 下发 `{"action":"reboot","wait":true,"wait_ms":120000}` |
|
||||
| 18:47:47 | 返回 `went_offline=true`、**`came_back=false`** |
|
||||
| 18:52:15 | 主机重新上线(`myself` 组,即被控的那条记录) |
|
||||
| 18:52:23 | 同一台机的**第二个**客户端也上线(`default` 组,见 P2-10) |
|
||||
|
||||
**根因已由环境方确认:该 VM 没有配置自动登录,重启后停在登录界面,必须人工输入密码。** 客户端的自启动在 `HKEY_CURRENT_USER\...\Run`(`test.exe`、`ClientDemo.exe`),HKCU 启动项只在**交互式登录之后**才执行,所以"重启 → 客户端回线"这一步完全取决于有没有人把密码输进去。本次那 4 分 28 秒不是机器自己恢复的,是登录之后才起的。
|
||||
|
||||
这带来三个问题:
|
||||
|
||||
1. **等待窗口本身也不够**:工具默认 `wait_ms=60000`,我设了 120 秒仍不够。即使配了自动登录,60 秒对真实 Windows 开机也偏短,`came_back=false` 会成为重启的常态返回值;
|
||||
2. **`power_action` 没有任何自动登录预检**:AI 在按下重启前无法知道"这台会不会回来",只能盲下;
|
||||
3. **`came_back=false` 之后没有下一步**,文案还把重启归到"关机后需人工开机"那一类,既不准确也没给出可执行动作。
|
||||
|
||||
> **两处自我更正**(都发生在本次测试中):
|
||||
> 1. 初稿判断"重启把设备弄丢了、需人工介入",据此列为 P0——**已撤回**,设备确实回线了;
|
||||
> 2. 第二稿改判"设备 4 分半后自行回线、只是等待窗口太短"——**也不准确**,回线是人工登录的结果。真实结论是:**能不能自愈取决于目标机配置,工具既不检查也不告知**。
|
||||
|
||||
### 3.3 P2:一致性与体验
|
||||
|
||||
| # | 问题 | 证据 |
|
||||
|---|---|---|
|
||||
| 1 | ~~`get_activity_history` 无分页,一次返回 **501 条**~~ **已修复,见 §8** | 直接冲爆上下文,且内容含大量个人浏览/求职/签证页面 |
|
||||
| 2 | `authStatus` 只在 `search_hosts`/`list_all_hosts` 出现,`list_online_hosts` 没有;`myself` 组 6 台全为 `unauthorized` 却可正常写入 | MCP 侧未按授权状态做门禁 |
|
||||
| 3 | 时间口径三套并存 | `list_files.mtime` 是 epoch 整数;`host_list_scheduled_tasks.lastRun` 是 `"2026-10-25 03:38:42"`;`list_network_connections.state` 是 `5` + `"ESTABLISHED"`。主机 `last_seen` 显示 `2026-10-30 01:27`,审计日志同一时刻显示 `18:47`,**差 6 小时以上** |
|
||||
| 4 | 降级工具与首选工具字段命名不一致 | `list_services`: `binary_path` / `start_type: "Demand-Start"`;`host_list_win32_services`: `binaryPath` / `startType: "Demand Start"`。进程总数 354 vs 351(枚举口径不同) |
|
||||
| 5 | `get_keylog` 名为键盘记录,实际返回**剪贴板快照** | 内容是 `[Title:] / [Time:] / [Clipboard:]`,无击键;文档提到的 `offlineRecord` 字段未出现 |
|
||||
| 6 | `host_control_process` 的 `state` 返回进程名 | `{"action":"freeze", "state":"notepad.exe"}`;且此处 `verified: true` 含义是"进程还在",与其它工具"动作已确认"不一致 |
|
||||
| 7 | `remote_block_input` 报 `blocked: true`,但输入仍可用 | 60 秒窗口内 ESC 与右键均生效;工具自己已声明"只代表命令已送达",**无法确认是否真的锁住** |
|
||||
| 8 | 能力位不可信 | `ubuntu-24` 的 `remoteControl: true`,但 `screen` 为 `0:0*0`,`remote_open` 15 秒超时 |
|
||||
| 9 | `host_list_windows` 返回 1×1 / 0×0 的空标题窗口 | `canSee: true` 但 `width:1, height:1, title:""`,属噪声 |
|
||||
| 10 | 同一台机多条记录、无法区分 | `A6` 有 2 条在线记录(`ClientDemo.exe` pid 26064 / `test.exe` pid 8668),进程列表里还有第 3 个客户端进程 pid 35052 **没有对应主机记录**;`DESKTOP-A55C0OI` 重启后**同时回线两条**(`3441…` 是 MDLL `test.exe` / `myself` 组,`4665…` 是桌面上的 `YAMA1234567a.exe` / `default` 组);按名搜该机名命中 **28 条**历史记录 |
|
||||
| 11 | `remote_keyboard.type` 无回执,可能丢字符 | Linux 首次注入(焦点刚切换)得到 `echo LINUX_GUI_O`,输出 `LINUX_GU`;第二次完整。只能靠截图自行复核 |
|
||||
| 12 | 截屏成本偏高 | 960px 宽 ≈ **67 KB / 张**,持续监管会迅速吃掉上下文,且没有区域裁剪或更省格式 |
|
||||
| 13 | `mcp_cancel_session` 把自己的请求也列进 `matched` | `request_id: "373" tool: "mcp_cancel_session"` |
|
||||
| 14 | **已过期客户端仍可正常上线并被操作** | `4665792391648319550` 的 `expiredDate: 20261008`(已过期 3 周),但 `online: true`、`authStatus: authorized_by_super`,`get_host_detail` 正常返回、文件操作可用 |
|
||||
| 15 | 客户端时钟偏差,服务端只打日志不管 | 审计日志中反复出现 `[92.208.227.255]Please check the client's time`;这正是第 3 条里 `last_seen` 与审计日志差 6 小时的来源 |
|
||||
|
||||
## 4. 监管与处置能力评估
|
||||
|
||||
### 4.1 能做到的(已验证)
|
||||
|
||||
| 能力 | 实测证据 |
|
||||
|---|---|
|
||||
| **资产盘点** | 34 台在线 + 3165 台离线,`os` / `client_type` / `group` / `name` / `ip` 组合过滤准确,`total` 与 `totalAll` 自洽(3199 = 34 + 3165) |
|
||||
| **单机取证** | 进程 351 / 服务 278(运行中 110)/ 驱动 402 / 窗口 24 / 软件 112 / 计划任务 272 / 网络连接 486,字段完整 |
|
||||
| **可视化确认** | 截屏是真图像,能直接读出桌面文字(本报告中所有 GUI 结论均靠它闭环) |
|
||||
| **文件处置** | 上传(含目录递归)、下载(SHA-256 逐字节吻合)、C2C(结构保留)、移动、删除,均带 `verified` 复核 |
|
||||
| **受控处置** | 停/启服务(`Spooler` stop→start,状态复核通过)、运行计划任务(状态转"运行中")、终止进程(`notepad.exe` 已消失)、最小化/还原窗口(截图确证) |
|
||||
| **GUI 自动化** | Windows:点击地址栏 → 输入 → 回车;Linux:右键菜单 → 点击终端 → 输入 → 执行,均截图确证 |
|
||||
| **与人沟通** | `chat_open/send/wait/close` 全流程,消息在目标机弹窗显示,截图确证 |
|
||||
| **占用治理** | `mcp_cancel_session` 把阻塞 40 秒的调用在 4 秒内以 `-32800` 中止 |
|
||||
| **事后追溯** | 审计日志完整记录每个 MCP 动作,含 `remote-mouse ... norm=(0.300,0.850) px=(515,782)` 这一级细节 |
|
||||
|
||||
### 4.2 做不到的
|
||||
|
||||
- **横向批量取证**:`ids` 批量全部失效(P0-1),34 台要 34 次往返
|
||||
- **日志取证**:客户端日志取不到(P0-3)
|
||||
- **Linux 文件处置**:只能靠裸 shell(P1-3),且裸 shell 无任何护栏
|
||||
- **管道与过滤**:无法让远端先过滤再回传(P1-5)
|
||||
- **重启后能否回线**:取决于目标机是否配了自动登录;未配置时必须人工登录,而 `power_action` 既不预检也不告知(P1-9)
|
||||
- **会话生命周期预判**:终端会静默过期(P1-7)
|
||||
- **精确锁定目标**:同名主机 28 条、同机 3 个客户端进程,列表视图没有 `clientPath` / `pid` 可供区分(P2-10)
|
||||
|
||||
### 4.3 一次具体的处置失手
|
||||
|
||||
本次测试中,`power_action reboot` 返回 `came_back=false`。我先后做出两个判断,**两个都是错的**:
|
||||
|
||||
| 我的判断 | 实际情况 |
|
||||
|---|---|
|
||||
| "设备失联了,需要人工介入"(据此列为 P0) | 设备在 4 分 28 秒后回线 |
|
||||
| "只是等待窗口太短,设备会自愈" | 回线是**人工登录**的结果——该 VM 未配自动登录,客户端靠 HKCU 启动项、登录后才执行 |
|
||||
|
||||
复盘这条链路,暴露的是**工具没把判断依据交出来**:
|
||||
|
||||
- 返回里只有 `went_offline` / `came_back` / `elapsed_ms`,**没有"这台会不会自己回来"的任何线索**(自动登录状态、是否有 SYSTEM 级自启动),AI 无法区分"再等等"与"必须喊人";
|
||||
- 文案把重启归到"关机后需人工开机"那一类,直接把人引向错误结论;
|
||||
- 没有 `next_step`。
|
||||
|
||||
同一个信息缺口下,**AI 和人都只能靠猜**。这不是 AI 的失手,是返回值的信息量不足——而这类"缺口"恰恰是自动化处置最危险的地方:一次重启就能把一台远程设备变成必须到现场(或控制台)才能救回的状态。
|
||||
|
||||
## 5. 改进建议
|
||||
|
||||
### P0(下一轮必须修)
|
||||
|
||||
1. **让每个输出分支都通过自己的 schema**
|
||||
`get_host_detail` 的 `host` 改为可选、或批量时也返回 `host` 数组;`list_registry` 的 `values` 改为可选。更根本的做法:加一个**契约测试**,对每个工具、每个分支各调一次并用它自己的 output schema 校验。目前 60 个工具里至少 2 个的某个分支是必然失败的,这类问题靠人工回归必然漏。
|
||||
|
||||
2. **给日志类工具加分页与裁剪**
|
||||
`get_client_log` / `get_activity_history` / `get_keylog` 增加 `limit` / `offset`(或 `tail_n` / `since`),默认只回 200 行并在响应里给 `total`。`get_client_log` 尤其应默认 `tail_n=200`——AI 要的是"最近发生了什么",不是 1000 行全量。
|
||||
|
||||
3. **修 Linux `get_client_log` 超时**
|
||||
超时时至少返回已取到的部分快照并置 `truncated=true`,而不是整条失败。
|
||||
|
||||
### P1(本轮内应修)
|
||||
|
||||
4. **重启前查自动登录,重启后给判断依据**
|
||||
`power_action` 增加 `check_autologon=true`:读 `HKLM\...\Winlogon` 的 `AutoAdminLogon`,并结合客户端自启动位置(HKLM/HKCU `Run`、启动文件夹、"计算机启动时"触发的计划任务)判断**这台会不会自己回来**;若判定"不会",在结果里明确写"重启后需人工登录,客户端才会回线",让 AI 能先问过用户再动手。
|
||||
同时:默认 `wait_ms` 提到 300000;返回补 `offline_elapsed_ms` 与 `recommended_wait_ms`;`came_back=false` 时给 `next_step`(如"建议 2 分钟后再查一次 `search_hosts`");文案按 `logout` / `shutdown` / `reboot` 分别措辞。
|
||||
|
||||
5. **给 schema 加版本,让"参数不可见"可自解释**
|
||||
在 `tools/list` 结果里带 `schemaVersion`;当客户端因 `additionalProperties` 拒绝时,服务端无法感知——那就退一步:在工具描述里显式写"若客户端报 unknown property,请重连"。更好的做法是服务端**接受并忽略**未知参数,而不是硬拒。
|
||||
|
||||
6. **枚举值统一为 ASCII,或双向兼容**
|
||||
过滤时同时接受 `"Ready"` 与 `"已准备"`(做一次映射即可),并在 schema 里补 `enum`。`start_type` 的 `"Auto Start"` / `"Auto-Start"` 两套拼法必须统一。
|
||||
|
||||
7. **给 POSIX 补文件变更工具,或给裸 shell 加护栏**
|
||||
首选补 `create_folder` / `move_path` / `delete_path` 的 POSIX 实现(`mkdir -p` / `rename` / `unlink`),复用 Windows 侧的受保护路径策略与 `verified` 复核。若短期不做,至少给 `terminal_exec` 加 `dry_run` 与危险命令二次确认。
|
||||
|
||||
8. **放开 `terminal_exec` 的管道限制**
|
||||
输出哨兵可以改成基于退出码 + 长度前缀的帧协议,不必依赖"命令里不能有 `|`"。这是当前**性价比最高的单点改进**——它同时降低上下文消耗和往返次数。
|
||||
|
||||
9. **让删除保护名副其实,或明确标注为建议**
|
||||
若 `exec_command` / `terminal_exec` 仍可触达系统目录,就应在 `delete_path` 的描述里写"仅为防误触,不是安全边界",避免 AI 误以为已被保护。
|
||||
|
||||
10. **会话 TTL 可见**
|
||||
`mcp_list_sessions` 增加 `expires_in_ms`;`terminal_exec` 在接近过期时返回警告而不是直接 `-32002`。
|
||||
|
||||
### P2(体验优化)
|
||||
|
||||
11. 时间字段统一附加 ISO 字符串(保留 epoch 以兼容),并修掉 `last_seen` 与审计日志的 6 小时时差。
|
||||
12. 统一 `list_*` 与 `host_list_*` 的字段命名;长期看应废弃降级版,或让降级版直接复用首选版的 schema。
|
||||
13. 修 `host_control_process.state`(应返回状态而非进程名);统一 `verified` 语义——"动作已确认"与"目标仍存在"必须分开表达(建议后者改名 `target_present`)。
|
||||
14. `host_list_windows` 默认过滤 0×0 / 1×1 空标题窗口,加 `include_aux=false`。
|
||||
15. `search_hosts` 增加 `include_history=false` 默认值或 `dedupe_by_name`,并在列表视图补 `clientPath` / `pid`,让同机多客户端、同名多记录可区分。
|
||||
16. `authStatus` 补进所有主机列表工具,并明确它是"信息性"还是"门禁性"。
|
||||
17. 截屏默认给更小缩略图,或支持 `crop` 区域与 `webp`,降低持续监管成本。
|
||||
18. `remote_keyboard.type` 增加回执(回显被接受的文本)或 `settle_ms` 参数。
|
||||
19. 主机列表与详情补 `expiredDate`(目前只有 `get_host_detail` 给,且只在 SC 客户端上有),让 AI 能一眼看出"这台已过期";对 `expiredDate` 已过仍在线的情况,至少在 `authStatus` 或独立字段上标注。
|
||||
20. 客户端时钟偏差(`Please check the client's time`)应从"只记日志"升级为可查询的状态字段,否则 `last_seen` 这类时间戳无法用于判案。
|
||||
|
||||
## 6. 给下一轮的一句话
|
||||
|
||||
**这套工具"单点很能打,横向很吃力"**——单台机器上的取证、处置、GUI 操作、审计都做得相当扎实,`dry_run` + 复核 + 诚实免责说明的设计水平明显高于同类产品;但一旦要**横向铺开**(批量读、日志取证、Linux 文件操作、重启判定)就立刻撞墙。下一轮优化应把资源集中在这四处,而不是继续加新工具。
|
||||
|
||||
## 7. 三个 P0 的修复
|
||||
|
||||
三个 P0 都是**声明与实现不一致**,改动集中在服务端;只有 P0-3 的 Linux/macOS 半边需要
|
||||
客户端补一段。实现细节见 `docs/Mcp_Design.md` §18。
|
||||
|
||||
| 编号 | 修法 | 改动位置 |
|
||||
|---|---|---|
|
||||
| P0-1 批量调用必失败 | `tools/list` 收尾时给批量只读工具的 `outputSchema` 补 `anyOf:[单机形状, 批量形状]` | `McpInternal.cpp` 新增 `ApplyBatchOutputSchema`;`IsBatchReadOnlyTool` 从 `McpServer.cpp` 移入 `McpInternal.cpp` |
|
||||
| P0-2 根键分支必失败 | `required` 去掉 `values`,只留 `keys`;根键分支补 `path:""` 使两分支字段一致 | `BuildListRegistryOutputSchema` / `BuildRegistryRoots` |
|
||||
| P0-3 日志取不到 | 新增 `limit`(默认 200、上限 2000)与 `filter`,从末尾往前取,另有 64 KB 字节预算;返回 `lines_total`/`lines_matched`/`lines_returned`/`truncated`;Linux/macOS 客户端补 `COMMAND_QUERY_LOG` 处理 | `BuildClientLogInputSchema`(新)、`BuildGetClientLog`、`common/ClientLogHandler.h`(新)、`linux/main.cpp`、`macos/main.mm` |
|
||||
|
||||
**为什么 P0-1 改在收尾阶段**:三个注册点(`McpServer.cpp` 内联 / `McpMachine` / `McpChat`)
|
||||
各自 `tools.append`,在收尾统一打补丁才能保证以后新增的批量工具不漏。这与既有的
|
||||
`ApplyToolAnnotations` 同一位置、同一思路。
|
||||
|
||||
**P0-3 的两个症状是两个原因**:Windows 是"取到了但塞不下"(无 limit),Linux 是"根本
|
||||
取不到"(客户端没有 `COMMAND_QUERY_LOG` 分支,服务端只能等到超时)。只加 limit 不修
|
||||
客户端,Linux 上的 `get_client_log` 依旧超时;只修客户端不加 limit,Windows 上依旧超上限。
|
||||
|
||||
**验证结果(服务端 21:17:21 构建 / 客户端已重编,2026-10-29 21:19–21:21)**:
|
||||
|
||||
| 用例 | 结果 |
|
||||
|---|---|
|
||||
| `get_host_detail` + `ids`(A6 两条记录) | **通过** `total=2, succeeded=2`,`results[].data.host` 逐台返回 |
|
||||
| `host_list_processes` + `ids` + `limit=2` | **通过** `succeeded=2`,两台各回 2 条、`total=348` |
|
||||
| `get_client_log` + `ids`(Win + Linux 混合) | **通过** `succeeded=2`;Windows 1000 行、Linux 14 行,各自独立裁剪 |
|
||||
| `list_registry` 省略 `path` | **通过** 返回 5 个根键 + `path:""`,不再 `-32602` |
|
||||
| `list_registry` 带 `path`(HKLM\...\Run) | **通过** 3 个值,无回归 |
|
||||
| `get_client_log`(Windows,默认参数) | **通过** `lines_total=1000, lines_returned=200, truncated=true`,不再超上限 |
|
||||
| `get_client_log`(Windows,`limit=3` + `filter=ConnAuth`) | **通过** `lines_matched=28, lines_returned=3` |
|
||||
| `get_client_log`(Linux Ubuntu24) | **通过** 返回 8 行;客户端日志里可见 `Received 'QUERY_LOG' command` → `Enter ClientLogThread` → `Leave ClientLogThread`,子连接进出成对、无泄漏 |
|
||||
| `list_files`(单机,验证 anyOf 包装未影响单机路径) | **通过** 正常分页 |
|
||||
|
||||
**遗留**:连接器仍缓存着旧的 `get_client_log` inputSchema(不含 `limit`/`filter`),模型侧
|
||||
直接传这两个参数会被本地校验拦下(`must NOT have additional properties`)。默认参数已经把
|
||||
P0-3 解决掉,要显式用 `limit`/`filter` 需重连一次连接器——与 §3.2 P1-1 是同一个缓存问题。
|
||||
|
||||
## 8. 附带修复:`get_activity_history` 分页(P2-1)
|
||||
|
||||
P2-1 与 P0-3 是同一类病——**列表类工具没有裁剪,把上下文当垃圾桶**。既然 `get_client_log`
|
||||
的分页/预算机制已经就位,这里直接复用同一套。实现细节见 `docs/Mcp_Design.md` §19。
|
||||
|
||||
| 改动 | 内容 |
|
||||
|---|---|
|
||||
| `inputSchema` | 由 `BuildGetHostDetailInputSchema()`(只有 `{id\|ids}`)换成 `BuildPagedHostListInputSchema()`,补 `limit`(默认 100、上限 1000)与 `offset` |
|
||||
| `outputSchema` | 追加 `AppendPageOutputProps()`(`total`/`totalAll`/`offset`/`limit`/`hasMore`)与 `truncated` |
|
||||
| 实现 | 全量拆行结果改名 `all`,再 `ResolvePageWindow` + `ApplyPageWindow` 切出 `records`,`WritePageFields` 回填 |
|
||||
| `activityHistory` | **按窗口重建**(窗口内 `records` 按行拼接)。原来是 `Dump()` 整包原文,原样返回等于没分页 |
|
||||
| 字节预算 | 64 KB(与 `get_client_log` 同口径),从窗口末尾裁,保留最新的;裁断时 `truncated=true`,`hasMore` 按 `offset+returned < total` 算 |
|
||||
| 保底 | 至少留 1 条,避免 `returned=0` 让调用方在同一个 `offset` 上原地打转 |
|
||||
|
||||
**顺序语义**:客户端 `ActivityHistory::Loop()` 用 `m_records.push_front(...)`,`Dump()` 又把
|
||||
进行中的当前窗口拼在最前——返回顺序**天然是「新在前」**。所以 `offset=0` 就是最近 `limit` 条,
|
||||
不需要先取 `total` 再倒算 offset。这条不是新约定,写进工具描述是为了让模型敢直接用 `offset=0`。
|
||||
|
||||
**批量**:本工具在 `IsBatchReadOnlyTool` 名单里,`BuildBatchCall` 摘掉 `ids` 后把其余参数原样
|
||||
透传,所以 `ids` + `limit` 就是「每台各取最近 N 条」,P0-1 的 `anyOf` 包装自动覆盖新字段。
|
||||
|
||||
**验证(服务端 21:34 构建,待重启后实测)**:
|
||||
|
||||
| 用例 | 期望 |
|
||||
|---|---|
|
||||
| 默认参数(不带 `limit`) | `records` 100 条、`total≈501`、`hasMore=true`,结果体积从约 90 KB 降到约 12 KB |
|
||||
| `limit=5` | 5 条,且是最新的 5 条(第 1 条时间最晚) |
|
||||
| `offset=500` | 1 条(尾部最老的那条),`hasMore=false` |
|
||||
| `ids` + `limit=3` | `succeeded=全数`,每台各 3 条,`results[].data.total` 各自独立 |
|
||||
| `activityHistory` 与 `records` | 行数与内容一致(不再是整包原文) |
|
||||
| `offset` 超过 `total` | `records=[]`、`returned=0`、`hasMore=false`,不报错 |
|
||||
|
||||
@@ -69,6 +69,7 @@ YAMA 主界面由以下部分组成:
|
||||
| 执行程序 | 下载执行、上传执行 |
|
||||
| 修改备注 | 编辑主机备注 |
|
||||
| 修改分组 | 更改所属分组 |
|
||||
| 复制名称 | 复制选中主机的名称(有备注取备注),多选时用分号分隔 |
|
||||
|
||||
> **注意**:文件管理、远程终端、进程管理等功能通过**工具栏图标**打开
|
||||
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
# WebSocket 传输设计(受限出站端口下经反代接入)
|
||||
|
||||
> 版本:v1.0(已实现并本地验证) · 日期:2026-10-30
|
||||
> 目标:客户端的出站被限制在 80 / 443 / 8080 等少数端口,且这些端口都不归主控所有时,
|
||||
> 仍能让客户端连上服务端;同时把 nginx 侧改动压到最小(只加一个 server 块或一个 location)。
|
||||
>
|
||||
> 需求原文:
|
||||
> 1. 「我的客户端连接服务端时端口被限制……只能借助于已有端口分流,比如 nginx 的端口。
|
||||
> 但是我的客户端目前是 TCP 流量。调研一下怎么解决」
|
||||
> 2. 「我的客户端连接到 xxx.com:6543, 但是 6543 不允许出站」
|
||||
> 3. 「6543 我可以修改,但是只能改为 80,443,8080,但是这些端口都已经在使用」
|
||||
> 4. 「B 方案更适合目前场景。xxx.com 的 nginx 配置尽量少改,不要大改」
|
||||
>
|
||||
> 已核实前提:客户端当前**都已启用 TLS**。服务端两套实现均可接入:Go 版(`server/go`)
|
||||
> 与 MFC 版(`server/2015Remote`,见 §4.2)。
|
||||
|
||||
## 1. 方案选型
|
||||
|
||||
| 方案 | 做法 | 结论 |
|
||||
|---|---|---|
|
||||
| A. 占用 8080 | 把主控端口改到 8080 直连 | 否决:8080 已被别的应用占用 |
|
||||
| **B. WebSocket over nginx 443** | 客户端把应用字节流套进 WS 帧,经 nginx `server_name` + `location /api/ws` 转发到 127.0.0.1:6543 | **采用** |
|
||||
| C. 租新端口 | 换一台能出站的机器/端口 | 否决:出站白名单是客户端侧策略,换端口仍被拦 |
|
||||
|
||||
B 方案的关键点:WS 升级只是一次普通 HTTP 请求,nginx 现有的 443 已经能承载;
|
||||
真正的应用协议完全不变,只是「字节流外面多了一层帧」。
|
||||
|
||||
## 2. 协议号与形态
|
||||
|
||||
`common/commands.h`:
|
||||
|
||||
| 值 | 枚举 | 形态 |
|
||||
|---|---|---|
|
||||
| 5 | `PROTO_WS` | 裸 WebSocket(明文;反代把明文 upgrade 转发到主控端口) |
|
||||
| 6 | `PROTO_WSS` | WebSocket over TLS(**客户端经反代 443 接入,推荐**) |
|
||||
| 7 | `PROTO_HTTPS` | 从未在生成界面出现过,故 5 让给 WS(原值 5,见下方风险) |
|
||||
|
||||
`WS_UPGRADE_PATH` = `/api/ws`:客户端请求的 Upgrade 路径,反代的 `location` 必须与之对齐;
|
||||
服务端默认接受任意路径,`YAMA_WS_PATH` 只用于把路径收窄。
|
||||
|
||||
传输层位置(自下而上):TCP → TLS(可选)→ **WebSocket 帧** → 既有应用协议(Shine/HELL 头、
|
||||
XOR、zstd、HTTP 伪装层)。WS 与 HTTP 伪装的 `MaskType` 互斥:选 WS 时用 `MaskTypeNone`。
|
||||
|
||||
> 兼容性:`PROTO_HTTPS` 从 5 移到 7。它在 `NewNetClient` 里本来就被直接拒绝、生成界面也从未
|
||||
> 提供,因此不存在已发布客户端带 5 号协议的情况。
|
||||
>
|
||||
> 但这是**协议号复用**:从此任何历史落盘 / 历史配置里的 `proto=5` 一律按 `PROTO_WS` 解释。
|
||||
> 老客户端与老服务端之间若曾有 `5` 的任何含义,都会在这次升级后变成 WS。
|
||||
|
||||
## 3. 客户端实现
|
||||
|
||||
新增 `client/WsChannel.h`(**头文件实现**,各平台工程文件不必改动):
|
||||
|
||||
- `Handshake(sock, host, port, path, &err)`:发 `GET <path> HTTP/1.1` + `Upgrade: websocket`,
|
||||
期望 `HTTP/1.1 101`;`Sec-WebSocket-Key` 用固定值(它只用于让中间设备识别这是 WS 握手,
|
||||
安全由隧道内登录与 TLS 承担)。
|
||||
- `Send`:一次 `SendTo` 写一帧(FIN + binary,**客户端帧必须掩码**,RFC 6455 §5.3),
|
||||
与 Go 端 `wsConn.Write` 的「一次 Write 一帧」对齐,包边界与发出时一致。
|
||||
- `Recv`:在帧载荷上做流式读取(`m_remaining` 记录剩余、`m_maskPos` 记录掩码位置),
|
||||
ping 自动回 pong,close 回 close 并按正常关闭返回 0,跨帧边界的应用层包不会丢。
|
||||
- `HasPending()`:帧载荷只解析了一半、或 WSS 下 TLS 会话里还压着已解密明文时返回 true,
|
||||
让接收线程在 `select` 之前优先消费(否则只能等 2 秒超时)。
|
||||
- 并发写:`Recv` 里要为 ping/close 回写控制帧,与发送线程的数据帧是两条并发的写路径。
|
||||
`WriteFrame` 用 `m_sendMtx` 串行化,并把整帧(帧头 + 掩码载荷)放进一个复用缓冲区、
|
||||
一次 `SendAll` 写出——若头体分两次写,两帧会互相穿插,对端从此解帧错位。
|
||||
|
||||
接线(`IOCPClient.h` / `.cpp`):`ReceiveData` / `SendTo` / `HasPendingData` 三处在
|
||||
`m_useTls` 之前判 `m_useWs`;`ConnectServer` 在 socket 选项之后、`m_bConnected = TRUE` 之前
|
||||
完成 `TLS 握手 → WS 握手`,`Disconnect` 清 `m_useWs` 并 `m_ws.Reset()`。
|
||||
|
||||
- 握手超时:`connect()` 之后、TLS/WS 握手之前给 socket 设 **15 s** `SO_RCVTIMEO`/`SO_SNDTIMEO`,
|
||||
握手结束(成功路径)立刻清零。`WsChannel::Handshake` 是同步逐字节读 101 响应的;没有这道
|
||||
保护时,对端接受 TCP 却不回数据(反代上游黑洞)会让 `StartClient` 的重连循环永久停摆。
|
||||
服务端两个握手线程用的是同一个 15 s。
|
||||
- `m_useWs` / `m_useTls` / `WsChannel::m_ready` 均为 `std::atomic<bool>`:写的一方是连接线程,
|
||||
读的一方是接收/发送线程(`Disconnect` 也可能从接收线程侧清)。
|
||||
- 帧掩码由 `WsChannel` 私有的 xorshift64 在 `m_sendMtx` **内**生成:不能用全局 `rand()`
|
||||
——`HttpMask` 的构造函数里有 `srand(time(nullptr))`,会在同进程内重置全局序列,而收、发两个
|
||||
线程都会写帧。
|
||||
- 不校验 `Sec-WebSocket-Accept`(设计上由 TLS + 隧道内登录承担)。明文 `PROTO_WS` 下这意味着
|
||||
中间人可以伪造 101 接管字节流——这正是「裸 WS 只适合内网」的另一半理由。
|
||||
- 没有 `conn` 的构造路径(Linux / macOS / Android 的 `main` 都是 `new IOCPClient(exit, false)`)
|
||||
拿不到外壳注入的 `CONNECT_ADDRESS`,协议由 `IOCPClient::SetDefaultProto()` 显式给出;
|
||||
三个平台的 `main` 都在进入重连循环前调一次。不调则保持 `-1`、按明文直连——那正是
|
||||
「配置成 WS 却毫无反应」的来源,所以这里留了一行日志便于排查。
|
||||
|
||||
### 3.1 信任模型:不换锚,靠 SNI 分流
|
||||
|
||||
客户端证书校验仍是**钉死信任锚**(Windows:`CertCreateCertificateChainEngine` + `hExclusiveRoot`
|
||||
手动建链;Linux:`SSL_VERIFY_PEER` + 自定义 `X509_STORE`;均**不校主机名**)。因此
|
||||
「经 nginx 接入」不能随便换成网站自己的证书——那会校验失败。
|
||||
|
||||
于是给 nginx 一个**独立 `server_name`**(如 `ws.xxx.com`)并挂主控自己的证书,客户端靠
|
||||
**SNI** 让 nginx 选中这个 server 块:
|
||||
|
||||
- Windows Schannel:`InitializeSecurityContextA(..., pszTargetName = sni, ...)`(TlsChannel.cpp)
|
||||
- Linux OpenSSL:`SSL_set_tlsext_host_name(ssl, sni)`(TlsChannelLinux.cpp)
|
||||
- 只在 `PROTO_WSS` 且地址是域名时传;直连主控端口时保持原样(不发明 SNI),行为与改造前一致。
|
||||
|
||||
Host 头同理:用**配置里的地址(域名)**,而不是解析后的 IP——子连接只拿到 IP,必须回到
|
||||
`CONNECT_ADDRESS::GetFirstServerIP()` 取。地址里填分号分隔的多个地址时取第一个,因此经反代
|
||||
接入只应填一个域名。
|
||||
|
||||
### 3.2 回退与 fail-closed
|
||||
|
||||
传输方式只由信任锚决定(进程内缓存,服务端下发后可热重载,见 §3.3):
|
||||
|
||||
| 情形 | 行为 |
|
||||
|---|---|
|
||||
| 有锚 + `PROTO_WSS` / 直连主控端口 | TLS 握手;**握手或证书校验失败即断开**(fail-closed) |
|
||||
| **无锚 + `PROTO_WSS`** | **回退为明文 WebSocket**:客户端还没被「颁发」证书,先打通隧道;服务端下发锚后自动升级(见下) |
|
||||
| 有锚但加载失败(损坏/为空) | 拒绝连接(fail-closed)——管理员已「颁发」证书,不能静默回退明文 |
|
||||
| 无锚 + `PROTO_WS` | 明文(本来如此) |
|
||||
| 有锚 + `PROTO_WS` | **仍是明文**(显式选择的形态,见下) |
|
||||
| 平台无 TLS(macOS / Android 未定义 `YAMA_TLS_CHANNEL`)+ `PROTO_WSS` | 直接断开并打日志:没有热切换路径,回退只会让人误以为在加密 |
|
||||
| WS 握手失败 | 断开,`Mprintf` 里带上服务端返回的状态行 |
|
||||
|
||||
回退的判据是「本机**根本没有**信任锚」这一可观测状态,而不是握手中途失败——TLS 握手
|
||||
失败、证书链校验失败、WS 握手失败一律断开。因此中间人最多能让「尚未下发锚」的客户端
|
||||
留在明文(此时本来也没有可校验的锚),无法把已经持锚的客户端拉回明文。
|
||||
|
||||
升级路径(服务端菜单「TLS 传输 → 启用」,`COMMAND_TLS_ENABLE` + PEM 正文):客户端把锚
|
||||
落盘(Windows 注册表 `settings\tls_cert`;Linux `~/.config/ghost/yama-ca.pem`),调用
|
||||
`TlsReload()` 重建 TLS 上下文,**只在传输方式真正变化(明文 ↔ TLS)时**断开重连,之后
|
||||
的新连接自动走 WSS;仅换一张证书(仍是 TLS)不打断现有会话。两平台都是立即生效,
|
||||
不再需要重启进程。撤销(`COMMAND_TLS_DISABLE`)同理反向切换。
|
||||
|
||||
> 部署含义:「先明文、之后升级为 WSS」要求同一个 `地址:端口` 既能吃明文 WS 也能吃 TLS
|
||||
> ——Go 服务端的设备端口正是这样(`wrapTLS` → `wrapWebSocket` 两级嗅探,见 §4)。由
|
||||
> nginx 终止 TLS 的部署做不到:443 只收 TLS,明文回退会直接失败,这种拓扑必须先把证书
|
||||
> 配到 nginx 上再出包。(对应的两个 nginx 监听端口也无法互替,地址是出包时写死的。)
|
||||
|
||||
`PROTO_WS` 的定位不变:它是**显式选择的明文形态**(§5.2 的 80 端口明文反代、内网直连),
|
||||
即便客户端配了信任锚也不叠加 TLS,否则该路径永远不可达——选择 WS 是出包时的决定,
|
||||
不存在远端可触发的降级。
|
||||
|
||||
### 3.3 信任锚热重载
|
||||
|
||||
`TlsEnabled()` / `TlsLoadError()` 首次调用时加载锚,之后读写的是受 `TlsReload` 保护的
|
||||
进程级状态(Windows 原来用 `std::call_once` 缓存到进程结束,无法热切换;现改为互斥量,
|
||||
与 Linux 版语义一致):
|
||||
|
||||
- 重建失败(锚存在但无效)→ **保持现有状态不变**,只记一行日志:一次坏下发不该打死正在
|
||||
工作的客户端;下次启动仍会 fail-closed。
|
||||
- 重建成功 → 互换 store / 链引擎并释放旧的。Windows 的证书校验(`VerifyServerCert`)
|
||||
在整个校验过程中持同一把锁,因此旧句柄不会在别的线程手里被释放。
|
||||
- 回环验证:Linux 由 `linux/main.cpp::ApplyTlsAnchorChange`、Windows 由
|
||||
`client/KernelManager.cpp::ApplyTlsAnchorChange` 调用,两者都只在 `TlsEnabled()`
|
||||
前后值发生变化时 `Disconnect()`,让重连循环用新传输方式重新登录。
|
||||
|
||||
## 4. 服务端实现
|
||||
|
||||
### 4.1 Go 服务端(`server/go`)
|
||||
|
||||
`server/go/server/ws.go`,在 `handleConnection` 里分层嗅探:
|
||||
|
||||
```
|
||||
raw conn --wrapTLS(嗅 0x16 0x03)--> [TLS] --wrapWebSocket(嗅 "GET ")--> [WS 帧]
|
||||
```
|
||||
|
||||
- 非 WS 连接:`bufferedConn` 原样返回,既有客户端零影响;嗅探用 `Peek`,不消耗字节。
|
||||
- WS 连接:解析请求头、校验 `Upgrade`/`Connection`/`Sec-WebSocket-Key`,`YAMA_WS_PATH`
|
||||
非空时再校验路径;通过后回 101 并返回 `wsConn`。
|
||||
- `wsConn`:`Read` 在帧载荷上流式返回,`Write` 一次一帧(`net.Buffers` writev 拼头与体),
|
||||
处理客户端掩码、控制帧(ping/pong/close),`Close` 发 close 帧并设 1 秒写超时。
|
||||
- 反代信任:仅当对端 IP 落在 `TrustedProxies`(默认回环)内才采信 `X-Forwarded-For` /
|
||||
`X-Real-IP`,取到的真实 IP 用于 `Context.GetPeerIP()`、`hub.Device.PeerIP` 与 ConnAuth
|
||||
子连接的源 IP 绑定。
|
||||
- 真实 IP 取 `X-Forwarded-For` 的**最后一段**(nginx 的 `$proxy_add_x_forwarded_for` 把
|
||||
它实际看到的地址追加在末尾,客户端自己塞在开头的段一律无视;与 `web/ws.go` 的 `clientIP`
|
||||
同一规则),没有 XFF 时才退回 `X-Real-IP`。
|
||||
- 每 IP 限流分两段:**直连对端**在 `acceptLoop` 里、起 goroutine 和任何嗅探读之前就计数
|
||||
(否则一个只建连接不发字节的对端能白占 goroutine 和缓冲直到 `ReadTimeout`);**反代后面
|
||||
的设备**在 `handleConnection` 里按上报的真实 IP 计数(否则所有设备共用一个回环额度)。
|
||||
|
||||
环境变量:
|
||||
|
||||
| 变量 | 说明 |
|
||||
|---|---|
|
||||
| `YAMA_WS_PATH` | 只接受该路径的 upgrade(空 = 任意路径) |
|
||||
| `YAMA_TRUSTED_PROXIES` | 允许上报真实 IP 的代理地址,逗号分隔的 IP/CIDR,默认 `127.0.0.0/8,::1/128` |
|
||||
|
||||
### 4.2 MFC 服务端(`server/2015Remote`)
|
||||
|
||||
MFC 服务端此前就在设备端口上嗅探 TLS(首字节 `0x16 0x03` → `ServerTlsSession`),
|
||||
WS 叠在同一层状态机之上,**与 TLS 是分层而不是并列**(`wss` = TLS 里的 WebSocket):
|
||||
|
||||
```
|
||||
子套接字 -- TLS 嗅探 --+-- 明文 --+-- "GET " 嗅探 --+-- WS 帧 --+--> ParseReceivedData
|
||||
| | |
|
||||
+-- TLS ---+----------------+(WSS 时帧在解密的明文里判)
|
||||
```
|
||||
|
||||
新增两个文件,其余改动都在既有握手/收发路径上:
|
||||
|
||||
| 文件 | 职责 |
|
||||
|---|---|
|
||||
| `ServerWsSession.h/.cpp` | 每连接 WS 会话:升级握手(逐行解析、8 KiB 上限、`Sec-WebSocket-Accept`)、流式解帧(不整帧缓冲,大帧按片交付)、控制帧(ping→pong、close 回显后断开)、转发真实 IP |
|
||||
| `IOCPServer.cpp` | `WsHandshakeThreadProc` / `StartWsHandshake`(专用阻塞线程,与 TLS 握手线程同一模式)、`DispatchPlain`(明文/WSS 共用入口)、`OnClientPreSending` 里的「先封帧、再 TLS 加密」 |
|
||||
|
||||
- 状态机:`ServerWsState { WS_Undecided → WS_Handshaking → WS_Ready | WS_None }` 与既有的
|
||||
`ServerTlsState` 并存;`CONTEXT_OBJECT` 复用(`InitMember`)时一并复位并释放会话。
|
||||
- 判定点:**明文的第一段有 ≥6 字节**才开始分类(与 ClientHello 嗅探同一下限),
|
||||
避免把「请求头还没到齐」误判掉;阈值内的字节攒在 `wsPreClassify` 里(与 TLS 嗅探的
|
||||
`tlsPreClassify` 分开,两者服务不同状态机,串行使用但字段不共用)。
|
||||
- 升级线程与 TLS 握手线程同构:`FIONBIO=0`(该套接字常是非阻塞的,`ioctlsocket` 会以
|
||||
`WSAEINVAL` 失败),15 s 收发超时,遇 `WSAEWOULDBLOCK` 用 `select` 等可读/可写再试;
|
||||
线程持有一枚 `IoRefCount`,结束后把 socket 交还 IOCP(`PostRecv`)。升级响应之后同批
|
||||
字节里若已带客户端首帧(WSS 分批解密时常见),先在交还前喂给解帧路径。
|
||||
- 发送方向:`OnClientPreSending` 里把本次新追加的尾部封成一帧(`TruncateBuffer` +
|
||||
`WriteBuffer`,与既有的「只加密新尾部」同一手法规避在途数据),然后才走 TLS 加密;
|
||||
控制帧应答(pong / close 回显)走同一条发送路径(`SendWsReplies`,持 `SendLock`)。
|
||||
- 反代真实 IP:**仅当直接对端是回环地址**时才采信 `X-Forwarded-For` 的**最后一段**
|
||||
(`X-Real-IP` 兜底),且必须是 IP 字面量;结果写回 `PeerName`,在线列表、封禁与
|
||||
白名单看到的就是设备本身。非回环对端的转发头一律忽略(防伪造)。
|
||||
- 两段式限流(与 Go 端 `limitDirectPeer` / `handleConnection` 同构):accept 阶段按
|
||||
`getpeername` 计数——那一次对经反代的连接**没有意义**(反代同机时对端是回环地址,
|
||||
`IPWhitelist` 对回环恒为 true,黑名单/封禁/计数全部不生效)。升级完成后在
|
||||
`WsHandshakeThreadProc` 里按**真实设备 IP** 重做一次黑名单 / 封禁检查与计数,超阈值
|
||||
直接 fail-closed。直连连接(无转发头)只在 accept 阶段计一次,不重复计。
|
||||
反代**异机**部署时转发头不被采信(见 §8),此时需把反代地址加进白名单,否则所有设备
|
||||
共用反代 IP 那一个计数桶。
|
||||
- fail-closed 的两处:握手期间(`wsState == WS_Handshaking`)收到 IORead 直接断开(判断
|
||||
放在 `OnClientReceiving` 最开头,WSS 下 `tlsState` 已是 `TLS_Ready`,放在 TLS 分支之后
|
||||
就不生效);`wsState == WS_Ready` 但会话已关时,应用字节**丢弃而不是裸发**,否则对端
|
||||
解帧错位;同时对该 socket 做一次 `shutdown(SD_BOTH)`,让挂起的 recv 立刻返回 0 字节,
|
||||
由接收路径走正常的 `-2` 收尾(不在这里直接 `RemoveStaleContext`——调用方往往本身就
|
||||
持有 `IoRefCount`,自己等自己会超时,且可能把已回收复用的上下文交回给调用者)。
|
||||
- 既有客户端零影响:非 `GET ` 首包在攒够 6 字节后原样进入 `ParseReceivedData`。
|
||||
- 收尾一致:`dwTrans == 0`(对端 FIN)在 `TLS_Unclassified` / `TLS_Ready` / `TLS_Plain`
|
||||
三条分支上都必须 `RemoveStaleContext`。WS 改造把 `TLS_Plain` 的 `ParseReceivedData`
|
||||
换成 `DispatchPlain` 后,`DispatchPlain` 对空数据返回「已处理」,这个判断一度丢了,
|
||||
连接会停在 CLOSE_WAIT 直到 keepalive(3 分钟),期间占着 IOCP 上下文、一枚挂起的
|
||||
`WSARecv` 和限流槽。现已补回。
|
||||
|
||||
## 5. nginx 最小改动
|
||||
|
||||
前提:客户端地址填 `ws.xxx.com`、端口 **443**、协议选 **WebSocket+TLS**。
|
||||
DNS 加一条 `ws.xxx.com` → 同一台机器即可(共用 443,靠 SNI + Host 分流,**不动**现有站点块)。
|
||||
|
||||
```nginx
|
||||
# 新增一个 server 块;证书用主控自己的那份(就是客户端钉的锚,与 6543 的 YAMA_TLS_CERT 同一文件)
|
||||
server {
|
||||
listen 443 ssl; # nginx ≥1.25.1 可另加一行 http2 on;
|
||||
server_name ws.xxx.com;
|
||||
|
||||
ssl_certificate /etc/nginx/certs/yama.crt;
|
||||
ssl_certificate_key /etc/nginx/certs/yama.key;
|
||||
|
||||
location /api/ws {
|
||||
proxy_pass http://127.0.0.1:6543; # 主控设备端口
|
||||
proxy_http_version 1.1;
|
||||
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr; # 让服务端拿到设备真实 IP
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
|
||||
proxy_buffering off; # 长连接必须关缓冲
|
||||
proxy_read_timeout 86400s; # 空闲心跳间隔远小于此,防止被掐
|
||||
proxy_send_timeout 86400s;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
若该域名现有的 443 证书**正好就是客户端钉的那份**,可以连 server 块都不加,
|
||||
只把上面 `location /api/ws { ... }` 贴进现有 443 块里。
|
||||
|
||||
### 5.1 站点与主控用两张不同证书时
|
||||
|
||||
实际部署里 `xxx.com` 的 443 证书(网站那张)和 6543 用的证书(客户端钉的锚)**是两张**。
|
||||
同一端口放两张证书没问题,nginx 按 **SNI** 选 server 块:
|
||||
|
||||
| 客户端填的地址 | 客户端发的 SNI | nginx 选中 | 出示的证书 | 结果 |
|
||||
|---|---|---|---|---|
|
||||
| `xxx.com` | `xxx.com` | 网站块 | 网站的证书 | **握手失败**(不是钉的锚) |
|
||||
| `ws.xxx.com` | `ws.xxx.com` | 主控块 | 6543 那张 | 通过 |
|
||||
|
||||
所以设备端必须用**另一个名字**(`ws.xxx.com`,或任何解析到同机、nginx 里能单独成块的名字):
|
||||
|
||||
- DNS:加一条 `ws.xxx.com` A 记录;若已有泛解析 `*.xxx.com` 则无需改动。
|
||||
- `ssl_certificate` 指向**与 Go 服务端 `YAMA_TLS_CERT` 完全相同的那个文件**(Go 端若配的是
|
||||
fullchain,这里也用 fullchain)。证书内容稍有不同(换过一张、少了中间证书)就会校验失败。
|
||||
- 这张证书**不需要覆盖 `ws.xxx.com`**——客户端只验链到钉死的锚,不校主机名(见 §3.1)。
|
||||
- 不要给主控块加 `default_server`,让网站块继续当默认块,其它访客行为不变。
|
||||
|
||||
自查(在服务器上执行,输出应是 6543 那张证书):
|
||||
|
||||
```bash
|
||||
openssl s_client -connect 127.0.0.1:443 -servername ws.xxx.com </dev/null 2>/dev/null \
|
||||
| openssl x509 -noout -subject -fingerprint -sha256
|
||||
```
|
||||
|
||||
若看到的是网站的证书,说明 SNI 没落到主控块(名字拼错、块没 reload、或客户端地址填的是 `xxx.com`)。
|
||||
|
||||
### 5.2 拿不到 `ws.xxx.com` 这种名字时:地址填 IP,用 443 的默认块
|
||||
|
||||
结论:**DNS 不是必需的**。SNI 只是 ClientHello 里的一个字符串,nginx 拿它跟 `server_name`
|
||||
比,不做解析;真正需要 DNS 的只有客户端解析地址这一步。所以换一条路走:
|
||||
|
||||
**客户端地址填 IP**(`1.2.3.4`,就是 `xxx.com` 解析出的那个),协议 `WebSocket+TLS`,端口 443。
|
||||
地址是 IP 字面量时,客户端按 RFC 6066 **不发 SNI**(见 §3.1 的条件),nginx 于是落到 443 的
|
||||
`default_server` 块——把主控块设成默认块即可。
|
||||
|
||||
```nginx
|
||||
# 主控块:无 SNI(或 SNI 不匹配)时命中,出示客户端钉的那张证书
|
||||
server {
|
||||
listen 443 ssl default_server;
|
||||
server_name _; # 兜底块,不占任何真实域名
|
||||
|
||||
ssl_certificate /root/cert/yama.crt; # 与 6543 的 YAMA_TLS_CERT 同一文件
|
||||
ssl_certificate_key /root/cert/yama.key;
|
||||
|
||||
location /api/ws {
|
||||
proxy_pass http://127.0.0.1:6543;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 86400s;
|
||||
proxy_send_timeout 86400s;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
现有网站块**一个字都不用改**:浏览器访问 `https://xxx.com` 时会发 SNI `xxx.com`,
|
||||
按名字命中网站块,照旧拿网站的证书。
|
||||
|
||||
四个注意点:
|
||||
|
||||
- **同一 `地址:端口` 只能有一个 `default_server`**。若网站块原本写了
|
||||
`listen 443 ssl default_server;`,把那里的 `default_server` 去掉(`nginx -t` 会直接报
|
||||
duplicate default server)。
|
||||
- 若默认块上设了 `ssl_reject_handshake on;`(有的加固模板会这么写),把它删掉,否则无 SNI 的连接被直接拒。
|
||||
- IPv6 的默认块是独立的:若还有 `listen [::]:443`,默认块要么同样加 `[::]:443 default_server`,
|
||||
要么保持 IPv4 即可(本客户端只连 AF_INET)。
|
||||
- 代价是地址里写死 IP:换机器/换 IP 要重出客户端。站点域名不变、只是 `xxx.com` 的 A 记录
|
||||
换 IP 时,旧客户端会连到旧机器。
|
||||
|
||||
> 还有两条退路,代价更大,一般不用:
|
||||
> - 走 **80 端口明文**:把 `location /api/ws` 贴进现有 80 块,客户端选 `PROTO_WS`。没有证书问题,
|
||||
> 但整条隧道是明文(只剩既有 XOR/Shine 混淆)。
|
||||
> - 给客户端加一个「SNI/Host 单独覆盖」的配置项,让地址仍是域名、SNI 用一个不存在的名字。
|
||||
> 需要改代码和重新出客户端,只有在必须保留域名地址时才值得做。
|
||||
|
||||
要点:
|
||||
|
||||
- `proxy_http_version 1.1` + 两条 `Upgrade` 头缺一不可,否则 nginx 会把升级请求当普通请求代理。
|
||||
- 关 `proxy_buffering`,否则 nginx 攒包,画面与控制会明显延迟。
|
||||
- `X-Real-IP` / `X-Forwarded-For` 只有在服务端的 `YAMA_TRUSTED_PROXIES` 覆盖 `127.0.0.1`
|
||||
时才被采信(默认已覆盖)。
|
||||
|
||||
## 6. 部署清单
|
||||
|
||||
1. 服务端:**无需改动**即可接受 WS 升级(两套实现都是同端口嗅探)。Go 版可选加环境变量
|
||||
`YAMA_WS_PATH=/api/ws`(不设 = 任意路径)、`YAMA_TRUSTED_PROXIES`(默认够用);MFC 版
|
||||
不校验路径,转发头只信回环对端(§4.2)。
|
||||
2. nginx:按 §5 加 server 块或 location,`nginx -t && nginx -s reload`。
|
||||
3. DNS:`ws.xxx.com` 指向该机器。
|
||||
4. 生成客户端:协议选 `WebSocket+TLS`,地址填 `ws.xxx.com`,端口 443。
|
||||
5. 日志确认:
|
||||
- Go 服务端 `WebSocket transport on device port enabled: path=/api/ws`、
|
||||
`WebSocket device from <真实 IP>`;MFC 服务端 `[WS] ... upgraded via reverse proxy,
|
||||
real client <真实 IP>`(仅回环对端且带转发头时才有这一行);
|
||||
- 客户端 `[WS] WebSocket 已就绪: ws.xxx.com:443/api/ws (TLS)`。
|
||||
|
||||
## 7. 验证方法(本次已做)
|
||||
|
||||
- `server/go`:`go test ./...` 全绿,`ws_test.go` 覆盖升级、隧道、ping/pong、1 MiB 大帧、
|
||||
坏握手拒绝、转发 IP(含「XFF 末尾优先 / 开头伪造被无视」)、信任代理解析,以及
|
||||
「无换行的超长请求行在 8 KiB 上限处被拒」;`server_test.go` 覆盖直连对端在嗅探前即计入
|
||||
每 IP 上限、回环反代被豁免。
|
||||
- 客户端:`client/WsChannel.h` 用一份**独立的 Python 最小 WS 服务端**(std lib 实现,非同一套
|
||||
代码)交叉验证:1/5/125/126/130/4096/70000 字节全部往返一致、`Host: localhost:18080`
|
||||
正确、客户端帧带掩码、服务端主动 ping 被回 pong。
|
||||
- 并发写:另一份 Python 校验端一边每 5 帧发一次 ping、一边逐帧校验 3000×300 字节的载荷,
|
||||
客户端同时从发送线程写数据帧、从接收线程回 pong。修复前在 ~40 帧处即出现解帧错位
|
||||
(`BAD_PAYLOAD`/发送失败),修复后 3000 帧全部逐字节正确。
|
||||
- 互操作:把该测试客户端直接指向真实 Go 服务端(`-port 16543`,`YAMA_WS_PATH=/api/ws`),
|
||||
服务端日志出现 `WebSocket device from 127.0.0.1`,握手通过。
|
||||
- MFC 服务端(Debug x64,设备端口 6543,同时开着 TLS):
|
||||
- 独立 Python 最小客户端对 6543 跑 9 项断言全通过:101 状态行、`Sec-WebSocket-Accept`
|
||||
与 `base64(sha1(key+GUID))` 一致、`Upgrade`/`Connection` 回显、ping→pong(服务端帧不带
|
||||
掩码)、数据帧后连接保持、close 回显、**升级请求跨两个 TCP 段**仍升级成功、**帧与升级
|
||||
请求粘在同一段**里也能解出;同一套断言加 `ssl` 包一层(TLSv1.2 ECDHE-RSA-AES256-GCM)
|
||||
再跑一遍全通过,即 WSS。
|
||||
- 转发头:`X-Forwarded-For: 198.51.100.7, 203.0.113.9` 时日志记
|
||||
`[WS] 127.0.0.1 upgraded via reverse proxy, real client 203.0.113.9`(取最后一段)。
|
||||
- 端到端:让 Debug 服务端向真实客户端下发它自己的 payload(其中配置为 `PROTO_WS`),
|
||||
客户端日志 `[WS] WebSocket 已就绪: 127.0.0.1:6543/api/ws` → 登录 → 收到主控配置
|
||||
(1000 字节)→ 上线列表出现该设备并长时间保活(心跳往返即双向数据帧都在工作)。
|
||||
|
||||
- 信任锚热重载(Windows):独立 harness(`tlsreload_test.cpp` + 真实 `TlsChannel.cpp`,锚
|
||||
走 exe 同目录 `yama-ca.pem`)覆盖 6 个场景全部通过:无锚→明文、有效锚→TLS、坏锚首次
|
||||
加载→fail-closed、无锚→下发锚后重载生效(明文→TLS)、坏锚重载→保持 TLS 不中断、撤销
|
||||
锚→回到明文。Linux 侧的热重载此前已随 `TlsTrustAnchorSave/Remove` 实现。
|
||||
- 构建:`ghost` x64/x86 Debug、`ServerDll.dll`、MFC 服务端 Debug x64、Linux
|
||||
`IOCPClient.cpp` / `TlsChannelLinux.cpp` 语法检查均通过。
|
||||
|
||||
## 8. 限制与非目标
|
||||
|
||||
- **MFC 服务端与 Go 服务端都已实现设备端口的 WS 嗅探**,生成界面里的协议选项两边通用;
|
||||
差别只在细节:MFC 侧不校验 upgrade 路径(`/api/ws` 只是客户端习惯,反代转到哪个路径都行)。
|
||||
每 IP 限流两边都是**两段式**(直连对端 / 反代后的真实设备),见 §4.1 与 §4.2。
|
||||
- MFC 侧的转发头信任范围是**回环对端**(与 Go 的默认 `TrustedProxies` 一致);反代与服务端
|
||||
不同机部署时,要么让反代用 Proxy Protocol v2(既有的 `ParseProxyProtocolV2` 会先改
|
||||
`PeerName`),要么把反代地址加进白名单——WS 层不采信非回环对端的转发头。此时限流按
|
||||
「反代 IP」那一个桶算,**务必把反代地址加进白名单**,否则阈值一响就是全体设备一起被封。
|
||||
- 试用模式的 WAN 入站检测(`m_bTrialMode && !IsPrivateIPv4Str(clientIP)`)在 accept 时判定,
|
||||
经反代接入时 `clientIP` 是反代地址(回环或内网),该合规检查会被绕过;转发真实 IP 要到
|
||||
升级线程里才有。若这是硬性合规要求,需单独评估(本特性未改变这一点,只是让它的漏检更
|
||||
容易发生)。
|
||||
- 裸 `PROTO_WS` 是明文,只适合内网或回环(nginx 已在同一台机器上终止 TLS 的情形用 WSS 即可)。
|
||||
- macOS / Android 客户端没有 TLS 实现,只能选 `PROTO_WS`(明文),走不了 443。
|
||||
- 经反代接入时地址只应填**一个域名**(多地址取第一个做 Host/SNI)。
|
||||
- 不改应用协议、不改 MCP、不改 Web 控制台。
|
||||
|
||||
## 9. 远程协议切换(在线列表右键 → 协议切换)
|
||||
|
||||
动机:客户端在线升级只换 DLL,外壳每次注入的连接配置仍是编译时的 TCP 直连入口,所以
|
||||
「已经在跑」的机器没法被搬到反代入口上。协议切换就是补这一环:由主控下发一次命令,客户端
|
||||
把新入口落盘并重连,此后(含再次在线升级)都按落盘的入口连。
|
||||
|
||||
- 菜单:与「实验功能」平级、紧跟在它下面,三个单选项 `直连 TCP / WS / WSS`。单选状态取
|
||||
选中主机连接的真实传输(`context::GetProtocol()`:`TCP`/`WS`/`WSS`),不取客户端自报。
|
||||
选中主机的客户端没有能力位 `CLIENT_CAP_PROTO_SWITCH(0x0020)` 时整组置灰(只有 Windows
|
||||
客户端实现了该命令)。
|
||||
- 命令:`COMMAND_SET_PROTO = 177`,载荷 `ProtoSwitchPacket`(113 字节:`proto` + 反代
|
||||
`host[100]` + `port[8]` + `certLen`),WS/WSS 后面再跟反代信任锚 PEM 正文;`host`/`port`
|
||||
全空表示「还原到安装时的直连入口」。
|
||||
- 服务端:WS/WSS 先弹输入框问反代入口(`域名:端口`,记住上次填的 `[ws] Entry`);WSS 额外
|
||||
要求 `ServerTlsIdentity::IsReady()` 并读取 `[tls] CertPath` 的 PEM 一并下发——没有锚的
|
||||
客户端会把 WSS 降级成明文 WS,等于静默降级,所以直接拒绝。
|
||||
- 客户端落盘(`settings` 下):`proto_override` / `entry_host` / `entry_port` /
|
||||
`entry_try_at` 为当前覆盖;`base_*` 是首次切换时记下的安装入口(「还原」用它);`prev_*`
|
||||
是每次切换前的入口(自动回退用它)。重连循环在建连前 `ApplyProtoSwitch` 覆盖入口——位置
|
||||
在「外壳注入完配置之后、建连之前」,因此换 DLL 也压不回去。(该函数返回 `void`:它既写
|
||||
配置也改 `CONNECT_ADDRESS`,返回值无法表达「部分完成」,早期版本里的 `return false`
|
||||
只是提前退出,调用方一直忽略它。)
|
||||
- 撤销自动回退的判据是**登录被接受**,不是「连接建立」。客户端在收到
|
||||
`CMD_MASTERSETTING` 时把当前连接标记为已登录(服务端只有在把本机加入在线列表之后才下发
|
||||
它),重连循环每轮心跳都检查一次,命中才 `ConfirmProtoSwitch` 把 `entry_try_at` 清零。
|
||||
只看 `IsConnected()` 是不够的:那只是 TCP/TLS/WS 握手完成,新入口能建连但登录始终不被
|
||||
接受(选错后端 / 反代指到别的 WS 服务 / 服务端登录阶段丢弃)时,提前撤销会让自动回退
|
||||
永久失效,客户端卡在错误入口反复重连。
|
||||
- 随包下发的信任锚先落盘再 `TlsReload`;**加载失败即放弃本次切换**——回滚 `tls_cert`、
|
||||
不写 `proto_override`/`entry_*`、不断连,并把失败原因用 `ClientMsg` 回报操作端。否则客户端
|
||||
会进入 `TlsLoadError()` 的 fail-closed 状态,切过去只是「新入口连不上,等 5 分钟回退」。
|
||||
- 自动回退:新入口 5 分钟内一直登不上,回到 `prev_*` 并把它改写成新的覆盖(不是清空,否则
|
||||
下一轮会落进「还原」分支又跳回直连入口)。分享实例(`m_bShared`)忽略该命令——它的入口
|
||||
由分享方控制。
|
||||
- `ProtoSwitchPacket::certLen` 不做字节序转换:当前服务端与 Windows 客户端同为小端,无影响;
|
||||
将来若出现大端平台的客户端,需要补一次 `ntohl`/`htonl`。
|
||||
|
||||
## 10. 审查遗留(已知边界,未改动)
|
||||
|
||||
以下条目来自 PR 审查,记录在此以免重复讨论。带「已处理」的是复查后**已经改掉**的,
|
||||
留在这里说明当时的判断,其余评估后保留现状:
|
||||
|
||||
- **`GetPeerName(SOCKET)` 只走 `sockaddr_in`(IPv4)**:`ServerWsSession.cpp::IsLoopbackPeer`
|
||||
里的 `::1` / `::ffff:127.0.0.1` 分支目前是死代码。将来若监听 IPv6,转发头信任也需要跟着
|
||||
改,否则会静默失效。
|
||||
- **`tlsPreClassify` 名不副实**:已处理——WS 的 "GET " 前缀缓冲拆成独立的 `wsPreClassify`,
|
||||
`tlsPreClassify` 回归 ClientHello 嗅探单一职责(两条路径仍按先后串行,互不重叠)。
|
||||
- **`WsChannel::Reset()` 与接收线程的帧状态**:已处理——`Disconnect()` 可能来自心跳/命令线程,
|
||||
不只是接收线程,所以 `Reset()` 现在只翻转原子的 `m_ready`;`m_remaining` / `m_masked` /
|
||||
`m_maskPos` 改由 `ResetFrames()` 清,且只在 `Handshake()` 里(连接线程、接收线程尚未起来)
|
||||
调用。这样这几个字段始终只有一个线程访问,不用加锁。
|
||||
- **客户端单帧载荷上限 256 MB**(`WsChannel::kMaxFramePayload`,与 `ServerWsSession` 同值):
|
||||
超过即按错误断开。没有上限时一个错误长度字段就能把 `m_remaining` 定在天文数字上,
|
||||
连接「活着但永远收不到新包」。正常业务的最大单包远小于此值。
|
||||
- **`DispatchPlain` 对明文首包引入「攒够 6 字节再解析」**:这是既有路径的行为变更。当前首包
|
||||
是登录包(远大于 6 字节),实际无影响;极端情况下(<6 字节的合法首包)会多等一轮收包。
|
||||
- **客户端不校验 `Sec-WebSocket-Accept`**:见 §3;明文 WS 下中间人可伪造 101,已在 §8 明确
|
||||
裸 WS 只适合内网。
|
||||
- **Go `wrapWebSocket` 的 `Peek`**:已改为即使 `ReadTimeout == 0` 也用 `wsHandshakeTimeout`
|
||||
(10 s,取与 `ReadTimeout` 的较小值)封顶,慢速对端不再能长期占住 goroutine 与限流槽。
|
||||
@@ -26,6 +26,7 @@ include_directories(../compress)
|
||||
# 添加可执行文件
|
||||
set(SOURCES
|
||||
main.cpp
|
||||
ScreenPreview.cpp # 屏幕预览(缩略图)抓屏,见 ScreenPreview.h
|
||||
../client/Buffer.cpp
|
||||
../client/IOCPClient.cpp
|
||||
../client/TlsChannelLinux.cpp # Linux 客户端单向 TLS(OpenSSL),见 client/TlsChannel.h
|
||||
|
||||
@@ -5,6 +5,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
|
||||
## 功能特性
|
||||
|
||||
- **远程桌面** - 实时屏幕截图传输,支持鼠标/键盘控制,支持多种压缩算法
|
||||
- **屏幕预览** - 服务端双击主机弹缩略图、在线列表缩略图、MCP `get_screenshot`
|
||||
- **远程终端** - 基于 PTY 的交互式 Shell
|
||||
- **文件管理** - 远程文件浏览、上传、下载
|
||||
- **进程管理** - 查看和管理远程进程
|
||||
@@ -25,6 +26,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
|
||||
| 系统信息采集 | main.cpp | `LoginServer.cpp` | ✅ 完整 |
|
||||
| 守护进程 | daemonize() | Windows 服务 | ✅ 完整 |
|
||||
| 剪贴板同步 | `ClipboardHandler.h` | `ScreenManager.cpp` | ✅ 服务端↔Linux |
|
||||
| 屏幕预览(缩略图) | `ScreenPreview.cpp` | `client/ScreenPreview.cpp` | ✅ 完整(X11 抓屏 → 缩放 → 原始 BGRA 上报,由服务端统一编码 JPEG;双击预览、列表缩略图、MCP `get_screenshot` 均可用。无 `DISPLAY` 时不声明能力位,服务端不会发请求) |
|
||||
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) |
|
||||
| C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) |
|
||||
| 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 |
|
||||
|
||||
+1
-264
@@ -5,6 +5,7 @@
|
||||
#include "ClipboardHandler.h"
|
||||
#include "common/FileTransferV2.h"
|
||||
#include "X264Encoder.h"
|
||||
#include "X11Loader.h"
|
||||
#include <dlfcn.h>
|
||||
#include <sys/stat.h>
|
||||
#include <thread>
|
||||
@@ -50,68 +51,6 @@ struct MSG64_LNX {
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
// X11 类型前向声明(避免 #include <X11/Xlib.h>)
|
||||
typedef struct _XDisplay Display;
|
||||
typedef unsigned long XID;
|
||||
typedef XID Window;
|
||||
typedef XID Drawable;
|
||||
typedef XID Pixmap;
|
||||
typedef struct _XGC *GC;
|
||||
|
||||
struct XImage {
|
||||
int width, height;
|
||||
int xoffset;
|
||||
int format;
|
||||
char *data;
|
||||
int byte_order;
|
||||
int bitmap_unit;
|
||||
int bitmap_bit_order;
|
||||
int bitmap_pad;
|
||||
int depth;
|
||||
int bytes_per_line;
|
||||
int bits_per_pixel;
|
||||
unsigned long red_mask;
|
||||
unsigned long green_mask;
|
||||
unsigned long blue_mask;
|
||||
// 后续字段省略,XDestroyImage 通过函数指针释放
|
||||
void *obdata;
|
||||
struct funcs {
|
||||
void *p[8]; // create_image, destroy_image, ...
|
||||
} f;
|
||||
};
|
||||
|
||||
// X11 错误处理(防止 BadMatch 等错误导致进程退出)
|
||||
static int x11_error_handler(Display* dpy, void* evt)
|
||||
{
|
||||
// 忽略所有 X11 错误,由调用方检查返回值
|
||||
return 0;
|
||||
}
|
||||
|
||||
// XCreateGC 需要的 XGCValues 结构体(布局与 Xlib 一致)
|
||||
struct XGCValues_LNX {
|
||||
int function;
|
||||
unsigned long plane_mask;
|
||||
unsigned long foreground;
|
||||
unsigned long background;
|
||||
int line_width;
|
||||
int line_style;
|
||||
int cap_style;
|
||||
int join_style;
|
||||
int fill_style;
|
||||
int fill_rule;
|
||||
int arc_mode;
|
||||
unsigned long tile; // Pixmap = XID
|
||||
unsigned long stipple; // Pixmap = XID
|
||||
int ts_x_origin;
|
||||
int ts_y_origin;
|
||||
unsigned long font; // Font = XID
|
||||
int subwindow_mode;
|
||||
};
|
||||
|
||||
// X11 GC 常量
|
||||
#define GCSubwindowMode (1L<<15)
|
||||
#define IncludeInferiors 1
|
||||
|
||||
// ============== 屏幕算法常量 ==============
|
||||
// 常量定义已移至 commands.h: ALGORITHM_GRAY, ALGORITHM_DIFF, ALGORITHM_H264, ALGORITHM_RGB565
|
||||
|
||||
@@ -390,208 +329,6 @@ static unsigned long VKtoKeySym(unsigned int vk)
|
||||
}
|
||||
}
|
||||
|
||||
// XFixes cursor image structure (for cursor type detection)
|
||||
struct XFixesCursorImage {
|
||||
short x, y;
|
||||
unsigned short width, height;
|
||||
unsigned short xhot, yhot;
|
||||
unsigned long cursor_serial;
|
||||
unsigned long* pixels;
|
||||
// Atom cursor_name; // Only in XFixes 2.0+
|
||||
};
|
||||
|
||||
// X11 函数指针类型
|
||||
typedef Display* (*fn_XOpenDisplay)(const char*);
|
||||
typedef int (*fn_XCloseDisplay)(Display*);
|
||||
typedef XImage* (*fn_XGetImage)(Display*, Drawable, int, int, unsigned int, unsigned int, unsigned long, int);
|
||||
typedef int (*fn_XDestroyImage)(XImage*);
|
||||
typedef int (*fn_XSetErrorHandler)(int (*)(Display*, void*));
|
||||
typedef Pixmap (*fn_XCreatePixmap)(Display*, Drawable, unsigned int, unsigned int, unsigned int);
|
||||
typedef int (*fn_XFreePixmap)(Display*, Pixmap);
|
||||
typedef GC (*fn_XCreateGC)(Display*, Drawable, unsigned long, void*);
|
||||
typedef int (*fn_XFreeGC)(Display*, GC);
|
||||
typedef int (*fn_XCopyArea)(Display*, Drawable, Drawable, GC, int, int, unsigned int, unsigned int, int, int);
|
||||
typedef int (*fn_XDefaultDepth)(Display*, int);
|
||||
typedef int (*fn_XSync)(Display*, int);
|
||||
typedef unsigned long (*fn_XKeysymToKeycode)(Display*, unsigned long);
|
||||
typedef int (*fn_XFlush)(Display*);
|
||||
typedef int (*fn_XClearArea)(Display*, Window, int, int, unsigned int, unsigned int, int);
|
||||
typedef int (*fn_XQueryPointer)(Display*, Window, Window*, Window*, int*, int*, int*, int*, unsigned int*);
|
||||
typedef int (*fn_XFree)(void*);
|
||||
|
||||
// XTest 扩展函数指针类型(用于模拟鼠标/键盘输入)
|
||||
typedef int (*fn_XTestFakeMotionEvent)(Display*, int, int, int, unsigned long);
|
||||
typedef int (*fn_XTestFakeButtonEvent)(Display*, unsigned int, int, unsigned long);
|
||||
typedef int (*fn_XTestFakeKeyEvent)(Display*, unsigned int, int, unsigned long);
|
||||
|
||||
// XFixes 扩展函数指针类型(用于光标类型检测)
|
||||
typedef int (*fn_XFixesQueryExtension)(Display*, int*, int*);
|
||||
typedef XFixesCursorImage* (*fn_XFixesGetCursorImage)(Display*);
|
||||
|
||||
// X11 动态加载包装
|
||||
class X11Loader
|
||||
{
|
||||
public:
|
||||
fn_XOpenDisplay pXOpenDisplay;
|
||||
fn_XCloseDisplay pXCloseDisplay;
|
||||
fn_XGetImage pXGetImage;
|
||||
fn_XDestroyImage pXDestroyImage;
|
||||
|
||||
// Xlib 宏的替代:通过偏移读取 Display 内部结构
|
||||
// 这些函数通过 dlsym 获取
|
||||
typedef int (*fn_XDefaultScreen)(Display*);
|
||||
typedef int (*fn_XDisplayWidth)(Display*, int);
|
||||
typedef int (*fn_XDisplayHeight)(Display*, int);
|
||||
typedef Window (*fn_XRootWindow)(Display*, int);
|
||||
|
||||
fn_XDefaultScreen pXDefaultScreen;
|
||||
fn_XDisplayWidth pXDisplayWidth;
|
||||
fn_XDisplayHeight pXDisplayHeight;
|
||||
fn_XRootWindow pXRootWindow;
|
||||
|
||||
// Pixmap 相关(解决合成窗口管理器下 XGetImage BadMatch 问题)
|
||||
fn_XSetErrorHandler pXSetErrorHandler;
|
||||
fn_XCreatePixmap pXCreatePixmap;
|
||||
fn_XFreePixmap pXFreePixmap;
|
||||
fn_XCreateGC pXCreateGC;
|
||||
fn_XFreeGC pXFreeGC;
|
||||
fn_XCopyArea pXCopyArea;
|
||||
fn_XDefaultDepth pXDefaultDepth;
|
||||
fn_XSync pXSync;
|
||||
fn_XKeysymToKeycode pXKeysymToKeycode;
|
||||
fn_XFlush pXFlush;
|
||||
fn_XClearArea pXClearArea;
|
||||
fn_XQueryPointer pXQueryPointer;
|
||||
fn_XFree pXFree;
|
||||
|
||||
// XTest 扩展(用于模拟输入)
|
||||
fn_XTestFakeMotionEvent pXTestFakeMotionEvent;
|
||||
fn_XTestFakeButtonEvent pXTestFakeButtonEvent;
|
||||
fn_XTestFakeKeyEvent pXTestFakeKeyEvent;
|
||||
|
||||
// XFixes 扩展(用于光标类型检测)
|
||||
fn_XFixesQueryExtension pXFixesQueryExtension;
|
||||
fn_XFixesGetCursorImage pXFixesGetCursorImage;
|
||||
|
||||
X11Loader() : m_handle(nullptr), m_xtst_handle(nullptr), m_xfixes_handle(nullptr)
|
||||
{
|
||||
pXOpenDisplay = nullptr;
|
||||
pXCloseDisplay = nullptr;
|
||||
pXGetImage = nullptr;
|
||||
pXDestroyImage = nullptr;
|
||||
pXDefaultScreen = nullptr;
|
||||
pXDisplayWidth = nullptr;
|
||||
pXDisplayHeight = nullptr;
|
||||
pXRootWindow = nullptr;
|
||||
pXSetErrorHandler = nullptr;
|
||||
pXCreatePixmap = nullptr;
|
||||
pXFreePixmap = nullptr;
|
||||
pXCreateGC = nullptr;
|
||||
pXFreeGC = nullptr;
|
||||
pXCopyArea = nullptr;
|
||||
pXDefaultDepth = nullptr;
|
||||
pXSync = nullptr;
|
||||
pXKeysymToKeycode = nullptr;
|
||||
pXFlush = nullptr;
|
||||
pXClearArea = nullptr;
|
||||
pXQueryPointer = nullptr;
|
||||
pXFree = nullptr;
|
||||
pXTestFakeMotionEvent = nullptr;
|
||||
pXTestFakeButtonEvent = nullptr;
|
||||
pXTestFakeKeyEvent = nullptr;
|
||||
pXFixesQueryExtension = nullptr;
|
||||
pXFixesGetCursorImage = nullptr;
|
||||
}
|
||||
|
||||
bool Load()
|
||||
{
|
||||
m_handle = dlopen("libX11.so.6", RTLD_LAZY);
|
||||
if (!m_handle) m_handle = dlopen("libX11.so", RTLD_LAZY);
|
||||
if (!m_handle) return false;
|
||||
|
||||
pXOpenDisplay = (fn_XOpenDisplay)dlsym(m_handle, "XOpenDisplay");
|
||||
pXCloseDisplay = (fn_XCloseDisplay)dlsym(m_handle, "XCloseDisplay");
|
||||
pXGetImage = (fn_XGetImage)dlsym(m_handle, "XGetImage");
|
||||
pXDestroyImage = (fn_XDestroyImage)dlsym(m_handle, "XDestroyImage");
|
||||
pXDefaultScreen = (fn_XDefaultScreen)dlsym(m_handle, "XDefaultScreen");
|
||||
pXDisplayWidth = (fn_XDisplayWidth)dlsym(m_handle, "XDisplayWidth");
|
||||
pXDisplayHeight = (fn_XDisplayHeight)dlsym(m_handle, "XDisplayHeight");
|
||||
pXRootWindow = (fn_XRootWindow)dlsym(m_handle, "XRootWindow");
|
||||
|
||||
// Pixmap 相关函数
|
||||
pXSetErrorHandler = (fn_XSetErrorHandler)dlsym(m_handle, "XSetErrorHandler");
|
||||
pXCreatePixmap = (fn_XCreatePixmap)dlsym(m_handle, "XCreatePixmap");
|
||||
pXFreePixmap = (fn_XFreePixmap)dlsym(m_handle, "XFreePixmap");
|
||||
pXCreateGC = (fn_XCreateGC)dlsym(m_handle, "XCreateGC");
|
||||
pXFreeGC = (fn_XFreeGC)dlsym(m_handle, "XFreeGC");
|
||||
pXCopyArea = (fn_XCopyArea)dlsym(m_handle, "XCopyArea");
|
||||
pXDefaultDepth = (fn_XDefaultDepth)dlsym(m_handle, "XDefaultDepth");
|
||||
pXSync = (fn_XSync)dlsym(m_handle, "XSync");
|
||||
pXKeysymToKeycode = (fn_XKeysymToKeycode)dlsym(m_handle, "XKeysymToKeycode");
|
||||
pXFlush = (fn_XFlush)dlsym(m_handle, "XFlush");
|
||||
pXClearArea = (fn_XClearArea)dlsym(m_handle, "XClearArea");
|
||||
pXQueryPointer = (fn_XQueryPointer)dlsym(m_handle, "XQueryPointer");
|
||||
pXFree = (fn_XFree)dlsym(m_handle, "XFree");
|
||||
|
||||
// 加载 XTest 扩展库(用于模拟鼠标/键盘输入)
|
||||
m_xtst_handle = dlopen("libXtst.so.6", RTLD_LAZY);
|
||||
if (!m_xtst_handle) m_xtst_handle = dlopen("libXtst.so", RTLD_LAZY);
|
||||
if (m_xtst_handle) {
|
||||
pXTestFakeMotionEvent = (fn_XTestFakeMotionEvent)dlsym(m_xtst_handle, "XTestFakeMotionEvent");
|
||||
pXTestFakeButtonEvent = (fn_XTestFakeButtonEvent)dlsym(m_xtst_handle, "XTestFakeButtonEvent");
|
||||
pXTestFakeKeyEvent = (fn_XTestFakeKeyEvent)dlsym(m_xtst_handle, "XTestFakeKeyEvent");
|
||||
}
|
||||
|
||||
// 加载 XFixes 扩展库(用于光标类型检测)
|
||||
m_xfixes_handle = dlopen("libXfixes.so.3", RTLD_LAZY);
|
||||
if (!m_xfixes_handle) m_xfixes_handle = dlopen("libXfixes.so", RTLD_LAZY);
|
||||
if (m_xfixes_handle) {
|
||||
pXFixesQueryExtension = (fn_XFixesQueryExtension)dlsym(m_xfixes_handle, "XFixesQueryExtension");
|
||||
pXFixesGetCursorImage = (fn_XFixesGetCursorImage)dlsym(m_xfixes_handle, "XFixesGetCursorImage");
|
||||
}
|
||||
|
||||
// 基本 X11 函数必须全部存在;XTest/XFixes 函数可选
|
||||
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
|
||||
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
|
||||
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
|
||||
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync &&
|
||||
pXKeysymToKeycode && pXFlush;
|
||||
}
|
||||
|
||||
// 检查 XTest 扩展是否可用
|
||||
bool HasXTest() const
|
||||
{
|
||||
return pXTestFakeMotionEvent && pXTestFakeButtonEvent && pXTestFakeKeyEvent;
|
||||
}
|
||||
|
||||
// 检查 XFixes 扩展是否可用
|
||||
bool HasXFixes() const
|
||||
{
|
||||
return pXFixesGetCursorImage != nullptr;
|
||||
}
|
||||
|
||||
~X11Loader()
|
||||
{
|
||||
if (m_xfixes_handle) {
|
||||
dlclose(m_xfixes_handle);
|
||||
m_xfixes_handle = nullptr;
|
||||
}
|
||||
if (m_xtst_handle) {
|
||||
dlclose(m_xtst_handle);
|
||||
m_xtst_handle = nullptr;
|
||||
}
|
||||
if (m_handle) {
|
||||
dlclose(m_handle);
|
||||
m_handle = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void* m_handle;
|
||||
void* m_xtst_handle;
|
||||
void* m_xfixes_handle;
|
||||
};
|
||||
|
||||
class ScreenHandler : public IOCPManager
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
#include "ScreenPreview.h"
|
||||
#include "X11Loader.h"
|
||||
#include "common/commands.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
// 一次抓屏独占一条 X 连接:Xlib 的 Display 不是线程安全的,预览在工作线程里跑,
|
||||
// 不能复用 ScreenHandler 的那条连接;用完即关,避免长驻连接占着 X server 资源。
|
||||
struct XSession {
|
||||
X11Loader x11;
|
||||
Display* dpy = nullptr;
|
||||
|
||||
bool Open()
|
||||
{
|
||||
// 没有 DISPLAY 必然是纯命令行/无桌面环境,连库都不必加载
|
||||
const char* display = getenv("DISPLAY");
|
||||
if (display == nullptr || display[0] == '\0') {
|
||||
return false;
|
||||
}
|
||||
if (!x11.Load() || !x11.CanCapture()) {
|
||||
return false;
|
||||
}
|
||||
// 与 ScreenHandler 一致:忽略 X11 协议错误,由返回值判断失败
|
||||
x11.pXSetErrorHandler(x11_error_handler);
|
||||
dpy = x11.pXOpenDisplay(display);
|
||||
return dpy != nullptr;
|
||||
}
|
||||
|
||||
~XSession()
|
||||
{
|
||||
if (dpy) {
|
||||
x11.pXCloseDisplay(dpy);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 盒式滤波缩放,直接从 XImage 读到目标缓冲,不保留整屏中间副本。
|
||||
// 返回 false 表示像素格式不受支持(非 32bpp)。
|
||||
bool DownscaleBox(const XImage* img, int tw, int th, std::vector<unsigned char>& out)
|
||||
{
|
||||
if (img == nullptr || img->bits_per_pixel != 32 || img->bytes_per_line <= 0) {
|
||||
return false;
|
||||
}
|
||||
const int sw = img->width;
|
||||
const int sh = img->height;
|
||||
if (sw <= 0 || sh <= 0 || tw <= 0 || th <= 0 || tw > sw || th > sh) {
|
||||
return false;
|
||||
}
|
||||
|
||||
out.resize((size_t)tw * th * 4);
|
||||
const unsigned char* base = (const unsigned char*)img->data;
|
||||
for (int dy = 0; dy < th; dy++) {
|
||||
// 目标行覆盖的源行区间 [sy0, sy1),区间非空因为 th <= sh
|
||||
int sy0 = (int)((long long)dy * sh / th);
|
||||
int sy1 = (int)((long long)(dy + 1) * sh / th);
|
||||
if (sy1 <= sy0) sy1 = sy0 + 1;
|
||||
|
||||
unsigned char* dst = out.data() + (size_t)dy * tw * 4;
|
||||
for (int dx = 0; dx < tw; dx++) {
|
||||
int sx0 = (int)((long long)dx * sw / tw);
|
||||
int sx1 = (int)((long long)(dx + 1) * sw / tw);
|
||||
if (sx1 <= sx0) sx1 = sx0 + 1;
|
||||
|
||||
unsigned int sb = 0, sg = 0, sr = 0;
|
||||
unsigned int count = 0;
|
||||
for (int sy = sy0; sy < sy1; sy++) {
|
||||
// X11 ZPixmap 32bpp 每像素 4 字节,字节序为 B,G,R,X(X 不用);
|
||||
// 行尾可能有对齐填充,必须按 bytes_per_line 定位
|
||||
const unsigned char* row = base + (size_t)sy * img->bytes_per_line;
|
||||
for (int sx = sx0; sx < sx1; sx++) {
|
||||
const unsigned char* px = row + (size_t)sx * 4;
|
||||
sb += px[0];
|
||||
sg += px[1];
|
||||
sr += px[2];
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
dst[0] = (unsigned char)(sb / count);
|
||||
dst[1] = (unsigned char)(sg / count);
|
||||
dst[2] = (unsigned char)(sr / count);
|
||||
dst[3] = 0xFF;
|
||||
dst += 4;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ScreenPreview::IsAvailable()
|
||||
{
|
||||
XSession session;
|
||||
if (!session.Open()) {
|
||||
return false;
|
||||
}
|
||||
int screen = session.x11.pXDefaultScreen(session.dpy);
|
||||
return session.x11.pXDisplayWidth(session.dpy, screen) > 0 &&
|
||||
session.x11.pXDisplayHeight(session.dpy, screen) > 0;
|
||||
}
|
||||
|
||||
int ScreenPreview::Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH)
|
||||
{
|
||||
outW = 0;
|
||||
outH = 0;
|
||||
out.clear();
|
||||
|
||||
// 与 Windows 端一致:上限防滥用,下限防止 1 像素宽的退化请求
|
||||
if (maxWidth < 64) maxWidth = 64;
|
||||
if (maxWidth > 1920) maxWidth = 1920;
|
||||
|
||||
XSession session;
|
||||
if (!session.Open()) {
|
||||
return SCREEN_PREVIEW_NOT_SUPPORTED;
|
||||
}
|
||||
X11Loader& x11 = session.x11;
|
||||
Display* dpy = session.dpy;
|
||||
|
||||
int screen = x11.pXDefaultScreen(dpy);
|
||||
int sw = x11.pXDisplayWidth(dpy, screen);
|
||||
int sh = x11.pXDisplayHeight(dpy, screen);
|
||||
if (sw <= 0 || sh <= 0) {
|
||||
return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
}
|
||||
|
||||
// 等比缩放到 maxWidth 以内(不放大);再把高度限制在 1080,避免竖屏 4K 这类
|
||||
// 极端宽高比把 BGRX 包撑到几十 MB(服务端只按宽度提要求,不管比例)
|
||||
int tw = sw, th = sh;
|
||||
if (tw > maxWidth) {
|
||||
th = (int)((long long)sh * maxWidth / sw);
|
||||
tw = maxWidth;
|
||||
}
|
||||
if (th > 1080) {
|
||||
tw = (int)((long long)tw * 1080 / th);
|
||||
th = 1080;
|
||||
}
|
||||
// 宽高取偶数,便于 JPEG 编码
|
||||
tw &= ~1;
|
||||
th &= ~1;
|
||||
if (tw < 2) tw = 2;
|
||||
if (th < 2) th = 2;
|
||||
if (tw > sw) tw = sw;
|
||||
if (th > sh) th = sh;
|
||||
|
||||
// root → 离屏 Pixmap → XGetImage:绕开合成窗口管理器下的 BadMatch
|
||||
Window root = x11.pXRootWindow(dpy, screen);
|
||||
int depth = x11.pXDefaultDepth(dpy, screen);
|
||||
Pixmap pixmap = x11.pXCreatePixmap(dpy, root, (unsigned int)sw, (unsigned int)sh, (unsigned int)depth);
|
||||
if (pixmap == 0) {
|
||||
return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
}
|
||||
|
||||
XGCValues_LNX gcv;
|
||||
memset(&gcv, 0, sizeof(gcv));
|
||||
gcv.subwindow_mode = IncludeInferiors; // 连同子窗口内容一起抓
|
||||
GC gc = x11.pXCreateGC(dpy, root, GCSubwindowMode, &gcv);
|
||||
if (gc == nullptr) {
|
||||
x11.pXFreePixmap(dpy, pixmap);
|
||||
return SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
}
|
||||
|
||||
int result = SCREEN_PREVIEW_CAPTURE_FAILED;
|
||||
x11.pXCopyArea(dpy, root, pixmap, gc, 0, 0, (unsigned int)sw, (unsigned int)sh, 0, 0);
|
||||
x11.pXSync(dpy, 0); // 等待拷贝完成
|
||||
|
||||
// AllPlanes = ~0UL, ZPixmap = 2
|
||||
XImage* img = x11.pXGetImage(dpy, pixmap, 0, 0, (unsigned int)sw, (unsigned int)sh, ~0UL, 2);
|
||||
if (img != nullptr) {
|
||||
if (DownscaleBox(img, tw, th, out)) {
|
||||
outW = tw;
|
||||
outH = th;
|
||||
result = SCREEN_PREVIEW_OK;
|
||||
} else {
|
||||
out.clear();
|
||||
}
|
||||
x11.pXDestroyImage(img);
|
||||
}
|
||||
|
||||
x11.pXFreeGC(dpy, gc);
|
||||
x11.pXFreePixmap(dpy, pixmap);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
// 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ)—— Linux 端一次性抓屏
|
||||
//
|
||||
// 与 Windows 端 client/ScreenPreview.h 对应,区别只有一处:Linux 没有可依赖的
|
||||
// JPEG 编码库(桌面版默认只带 libjpeg.so.8,其结构体布局随发行版 ABI 变化,
|
||||
// 不适合 dlopen 后手搓),所以这里只做 抓屏 → 等比缩放 → BGRA 原始像素,
|
||||
// 由服务端在 IO 线程统一编码成 JPEG(见 2015RemoteDlg.cpp 的预览包规范化)。
|
||||
//
|
||||
// 抓屏路径与 ScreenHandler 相同:root window → 离屏 Pixmap(XCopyArea,
|
||||
// IncludeInferiors)→ XGetImage,规避合成窗口管理器下的 BadMatch。
|
||||
#include <vector>
|
||||
#include <cstdint>
|
||||
|
||||
class ScreenPreview
|
||||
{
|
||||
public:
|
||||
// 本机当前能否截图(X11 库可加载 + 能打开 display + 主屏尺寸有效)。
|
||||
// 服务端按 CLIENT_CAP_SCREEN_PREVIEW 决定要不要下发预览请求,能力位就取自它。
|
||||
static bool IsAvailable();
|
||||
|
||||
// 抓主屏并等比缩放到 maxWidth 以内(不放大、高不超过 1080),返回 ScreenPreviewStatus。
|
||||
// out 为自上而下逐行、每像素 B,G,R,X 四字节(X=0xFF),无行首填充。
|
||||
static int Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH);
|
||||
};
|
||||
@@ -0,0 +1,279 @@
|
||||
#pragma once
|
||||
// X11 运行时加载(编译期不依赖 X11 开发包,运行时 dlopen libX11.so)
|
||||
//
|
||||
// 从 ScreenHandler.h 抽出:远程桌面(ScreenHandler)和屏幕预览(ScreenPreview)
|
||||
// 都要抓屏,共用这套类型定义与加载器,避免两份 dlsym 表各自漂移。
|
||||
#include <dlfcn.h>
|
||||
|
||||
// X11 类型前向声明(避免 #include <X11/Xlib.h>)
|
||||
typedef struct _XDisplay Display;
|
||||
typedef unsigned long XID;
|
||||
typedef XID Window;
|
||||
typedef XID Drawable;
|
||||
typedef XID Pixmap;
|
||||
typedef struct _XGC *GC;
|
||||
|
||||
struct XImage {
|
||||
int width, height;
|
||||
int xoffset;
|
||||
int format;
|
||||
char *data;
|
||||
int byte_order;
|
||||
int bitmap_unit;
|
||||
int bitmap_bit_order;
|
||||
int bitmap_pad;
|
||||
int depth;
|
||||
int bytes_per_line;
|
||||
int bits_per_pixel;
|
||||
unsigned long red_mask;
|
||||
unsigned long green_mask;
|
||||
unsigned long blue_mask;
|
||||
// 后续字段省略,XDestroyImage 通过函数指针释放
|
||||
void *obdata;
|
||||
struct funcs {
|
||||
void *p[8]; // create_image, destroy_image, ...
|
||||
} f;
|
||||
};
|
||||
|
||||
// X11 错误处理(防止 BadMatch 等错误导致进程退出)
|
||||
static inline int x11_error_handler(Display* dpy, void* evt)
|
||||
{
|
||||
// 忽略所有 X11 错误,由调用方检查返回值
|
||||
return 0;
|
||||
}
|
||||
|
||||
// XCreateGC 需要的 XGCValues 结构体(布局与 Xlib 一致)
|
||||
struct XGCValues_LNX {
|
||||
int function;
|
||||
unsigned long plane_mask;
|
||||
unsigned long foreground;
|
||||
unsigned long background;
|
||||
int line_width;
|
||||
int line_style;
|
||||
int cap_style;
|
||||
int join_style;
|
||||
int fill_style;
|
||||
int fill_rule;
|
||||
int arc_mode;
|
||||
unsigned long tile; // Pixmap = XID
|
||||
unsigned long stipple; // Pixmap = XID
|
||||
int ts_x_origin;
|
||||
int ts_y_origin;
|
||||
unsigned long font; // Font = XID
|
||||
int subwindow_mode;
|
||||
};
|
||||
|
||||
// X11 GC 常量
|
||||
#define GCSubwindowMode (1L<<15)
|
||||
#define IncludeInferiors 1
|
||||
|
||||
// XFixes cursor image structure (for cursor type detection)
|
||||
struct XFixesCursorImage {
|
||||
short x, y;
|
||||
unsigned short width, height;
|
||||
unsigned short xhot, yhot;
|
||||
unsigned long cursor_serial;
|
||||
unsigned long* pixels;
|
||||
// Atom cursor_name; // Only in XFixes 2.0+
|
||||
};
|
||||
|
||||
// X11 函数指针类型
|
||||
typedef Display* (*fn_XOpenDisplay)(const char*);
|
||||
typedef int (*fn_XCloseDisplay)(Display*);
|
||||
typedef XImage* (*fn_XGetImage)(Display*, Drawable, int, int, unsigned int, unsigned int, unsigned long, int);
|
||||
typedef int (*fn_XDestroyImage)(XImage*);
|
||||
typedef int (*fn_XSetErrorHandler)(int (*)(Display*, void*));
|
||||
typedef Pixmap (*fn_XCreatePixmap)(Display*, Drawable, unsigned int, unsigned int, unsigned int);
|
||||
typedef int (*fn_XFreePixmap)(Display*, Pixmap);
|
||||
typedef GC (*fn_XCreateGC)(Display*, Drawable, unsigned long, void*);
|
||||
typedef int (*fn_XFreeGC)(Display*, GC);
|
||||
typedef int (*fn_XCopyArea)(Display*, Drawable, Drawable, GC, int, int, unsigned int, unsigned int, int, int);
|
||||
typedef int (*fn_XDefaultDepth)(Display*, int);
|
||||
typedef int (*fn_XSync)(Display*, int);
|
||||
typedef unsigned long (*fn_XKeysymToKeycode)(Display*, unsigned long);
|
||||
typedef int (*fn_XFlush)(Display*);
|
||||
typedef int (*fn_XClearArea)(Display*, Window, int, int, unsigned int, unsigned int, int);
|
||||
typedef int (*fn_XQueryPointer)(Display*, Window, Window*, Window*, int*, int*, int*, int*, unsigned int*);
|
||||
typedef int (*fn_XFree)(void*);
|
||||
|
||||
// XTest 扩展函数指针类型(用于模拟鼠标/键盘输入)
|
||||
typedef int (*fn_XTestFakeMotionEvent)(Display*, int, int, int, unsigned long);
|
||||
typedef int (*fn_XTestFakeButtonEvent)(Display*, unsigned int, int, unsigned long);
|
||||
typedef int (*fn_XTestFakeKeyEvent)(Display*, unsigned int, int, unsigned long);
|
||||
|
||||
// XFixes 扩展函数指针类型(用于光标类型检测)
|
||||
typedef int (*fn_XFixesQueryExtension)(Display*, int*, int*);
|
||||
typedef XFixesCursorImage* (*fn_XFixesGetCursorImage)(Display*);
|
||||
|
||||
// X11 动态加载包装
|
||||
class X11Loader
|
||||
{
|
||||
public:
|
||||
fn_XOpenDisplay pXOpenDisplay;
|
||||
fn_XCloseDisplay pXCloseDisplay;
|
||||
fn_XGetImage pXGetImage;
|
||||
fn_XDestroyImage pXDestroyImage;
|
||||
|
||||
// Xlib 宏的替代:通过偏移读取 Display 内部结构
|
||||
// 这些函数通过 dlsym 获取
|
||||
typedef int (*fn_XDefaultScreen)(Display*);
|
||||
typedef int (*fn_XDisplayWidth)(Display*, int);
|
||||
typedef int (*fn_XDisplayHeight)(Display*, int);
|
||||
typedef Window (*fn_XRootWindow)(Display*, int);
|
||||
|
||||
fn_XDefaultScreen pXDefaultScreen;
|
||||
fn_XDisplayWidth pXDisplayWidth;
|
||||
fn_XDisplayHeight pXDisplayHeight;
|
||||
fn_XRootWindow pXRootWindow;
|
||||
|
||||
// Pixmap 相关(解决合成窗口管理器下 XGetImage BadMatch 问题)
|
||||
fn_XSetErrorHandler pXSetErrorHandler;
|
||||
fn_XCreatePixmap pXCreatePixmap;
|
||||
fn_XFreePixmap pXFreePixmap;
|
||||
fn_XCreateGC pXCreateGC;
|
||||
fn_XFreeGC pXFreeGC;
|
||||
fn_XCopyArea pXCopyArea;
|
||||
fn_XDefaultDepth pXDefaultDepth;
|
||||
fn_XSync pXSync;
|
||||
fn_XKeysymToKeycode pXKeysymToKeycode;
|
||||
fn_XFlush pXFlush;
|
||||
fn_XClearArea pXClearArea;
|
||||
fn_XQueryPointer pXQueryPointer;
|
||||
fn_XFree pXFree;
|
||||
|
||||
// XTest 扩展(用于模拟输入)
|
||||
fn_XTestFakeMotionEvent pXTestFakeMotionEvent;
|
||||
fn_XTestFakeButtonEvent pXTestFakeButtonEvent;
|
||||
fn_XTestFakeKeyEvent pXTestFakeKeyEvent;
|
||||
|
||||
// XFixes 扩展(用于光标类型检测)
|
||||
fn_XFixesQueryExtension pXFixesQueryExtension;
|
||||
fn_XFixesGetCursorImage pXFixesGetCursorImage;
|
||||
|
||||
X11Loader() : m_handle(nullptr), m_xtst_handle(nullptr), m_xfixes_handle(nullptr)
|
||||
{
|
||||
pXOpenDisplay = nullptr;
|
||||
pXCloseDisplay = nullptr;
|
||||
pXGetImage = nullptr;
|
||||
pXDestroyImage = nullptr;
|
||||
pXDefaultScreen = nullptr;
|
||||
pXDisplayWidth = nullptr;
|
||||
pXDisplayHeight = nullptr;
|
||||
pXRootWindow = nullptr;
|
||||
pXSetErrorHandler = nullptr;
|
||||
pXCreatePixmap = nullptr;
|
||||
pXFreePixmap = nullptr;
|
||||
pXCreateGC = nullptr;
|
||||
pXFreeGC = nullptr;
|
||||
pXCopyArea = nullptr;
|
||||
pXDefaultDepth = nullptr;
|
||||
pXSync = nullptr;
|
||||
pXKeysymToKeycode = nullptr;
|
||||
pXFlush = nullptr;
|
||||
pXClearArea = nullptr;
|
||||
pXQueryPointer = nullptr;
|
||||
pXFree = nullptr;
|
||||
pXTestFakeMotionEvent = nullptr;
|
||||
pXTestFakeButtonEvent = nullptr;
|
||||
pXTestFakeKeyEvent = nullptr;
|
||||
pXFixesQueryExtension = nullptr;
|
||||
pXFixesGetCursorImage = nullptr;
|
||||
}
|
||||
|
||||
bool Load()
|
||||
{
|
||||
m_handle = dlopen("libX11.so.6", RTLD_LAZY);
|
||||
if (!m_handle) m_handle = dlopen("libX11.so", RTLD_LAZY);
|
||||
if (!m_handle) return false;
|
||||
|
||||
pXOpenDisplay = (fn_XOpenDisplay)dlsym(m_handle, "XOpenDisplay");
|
||||
pXCloseDisplay = (fn_XCloseDisplay)dlsym(m_handle, "XCloseDisplay");
|
||||
pXGetImage = (fn_XGetImage)dlsym(m_handle, "XGetImage");
|
||||
pXDestroyImage = (fn_XDestroyImage)dlsym(m_handle, "XDestroyImage");
|
||||
pXDefaultScreen = (fn_XDefaultScreen)dlsym(m_handle, "XDefaultScreen");
|
||||
pXDisplayWidth = (fn_XDisplayWidth)dlsym(m_handle, "XDisplayWidth");
|
||||
pXDisplayHeight = (fn_XDisplayHeight)dlsym(m_handle, "XDisplayHeight");
|
||||
pXRootWindow = (fn_XRootWindow)dlsym(m_handle, "XRootWindow");
|
||||
|
||||
// Pixmap 相关函数
|
||||
pXSetErrorHandler = (fn_XSetErrorHandler)dlsym(m_handle, "XSetErrorHandler");
|
||||
pXCreatePixmap = (fn_XCreatePixmap)dlsym(m_handle, "XCreatePixmap");
|
||||
pXFreePixmap = (fn_XFreePixmap)dlsym(m_handle, "XFreePixmap");
|
||||
pXCreateGC = (fn_XCreateGC)dlsym(m_handle, "XCreateGC");
|
||||
pXFreeGC = (fn_XFreeGC)dlsym(m_handle, "XFreeGC");
|
||||
pXCopyArea = (fn_XCopyArea)dlsym(m_handle, "XCopyArea");
|
||||
pXDefaultDepth = (fn_XDefaultDepth)dlsym(m_handle, "XDefaultDepth");
|
||||
pXSync = (fn_XSync)dlsym(m_handle, "XSync");
|
||||
pXKeysymToKeycode = (fn_XKeysymToKeycode)dlsym(m_handle, "XKeysymToKeycode");
|
||||
pXFlush = (fn_XFlush)dlsym(m_handle, "XFlush");
|
||||
pXClearArea = (fn_XClearArea)dlsym(m_handle, "XClearArea");
|
||||
pXQueryPointer = (fn_XQueryPointer)dlsym(m_handle, "XQueryPointer");
|
||||
pXFree = (fn_XFree)dlsym(m_handle, "XFree");
|
||||
|
||||
// 加载 XTest 扩展库(用于模拟鼠标/键盘输入)
|
||||
m_xtst_handle = dlopen("libXtst.so.6", RTLD_LAZY);
|
||||
if (!m_xtst_handle) m_xtst_handle = dlopen("libXtst.so", RTLD_LAZY);
|
||||
if (m_xtst_handle) {
|
||||
pXTestFakeMotionEvent = (fn_XTestFakeMotionEvent)dlsym(m_xtst_handle, "XTestFakeMotionEvent");
|
||||
pXTestFakeButtonEvent = (fn_XTestFakeButtonEvent)dlsym(m_xtst_handle, "XTestFakeButtonEvent");
|
||||
pXTestFakeKeyEvent = (fn_XTestFakeKeyEvent)dlsym(m_xtst_handle, "XTestFakeKeyEvent");
|
||||
}
|
||||
|
||||
// 加载 XFixes 扩展库(用于光标类型检测)
|
||||
m_xfixes_handle = dlopen("libXfixes.so.3", RTLD_LAZY);
|
||||
if (!m_xfixes_handle) m_xfixes_handle = dlopen("libXfixes.so", RTLD_LAZY);
|
||||
if (m_xfixes_handle) {
|
||||
pXFixesQueryExtension = (fn_XFixesQueryExtension)dlsym(m_xfixes_handle, "XFixesQueryExtension");
|
||||
pXFixesGetCursorImage = (fn_XFixesGetCursorImage)dlsym(m_xfixes_handle, "XFixesGetCursorImage");
|
||||
}
|
||||
|
||||
// 基本 X11 函数必须全部存在;XTest/XFixes 函数可选
|
||||
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
|
||||
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
|
||||
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
|
||||
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync &&
|
||||
pXKeysymToKeycode && pXFlush;
|
||||
}
|
||||
|
||||
// 只关心抓屏的那一小部分函数是否齐备(ScreenPreview 用,不要求 XTest/XFixes)
|
||||
bool CanCapture() const
|
||||
{
|
||||
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
|
||||
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
|
||||
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
|
||||
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync;
|
||||
}
|
||||
|
||||
// 检查 XTest 扩展是否可用
|
||||
bool HasXTest() const
|
||||
{
|
||||
return pXTestFakeMotionEvent && pXTestFakeButtonEvent && pXTestFakeKeyEvent;
|
||||
}
|
||||
|
||||
// 检查 XFixes 扩展是否可用
|
||||
bool HasXFixes() const
|
||||
{
|
||||
return pXFixesGetCursorImage != nullptr;
|
||||
}
|
||||
|
||||
~X11Loader()
|
||||
{
|
||||
if (m_xfixes_handle) {
|
||||
dlclose(m_xfixes_handle);
|
||||
m_xfixes_handle = nullptr;
|
||||
}
|
||||
if (m_xtst_handle) {
|
||||
dlclose(m_xtst_handle);
|
||||
m_xtst_handle = nullptr;
|
||||
}
|
||||
if (m_handle) {
|
||||
dlclose(m_handle);
|
||||
m_handle = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void* m_handle;
|
||||
void* m_xtst_handle;
|
||||
void* m_xfixes_handle;
|
||||
};
|
||||
BIN
Binary file not shown.
+105
@@ -26,7 +26,9 @@
|
||||
#include <map>
|
||||
#include <cmath>
|
||||
#include "ScreenHandler.h"
|
||||
#include "ScreenPreview.h"
|
||||
#include "SystemManager.h"
|
||||
#include "common/ClientLogHandler.h"
|
||||
#include "common/FileManager.h"
|
||||
#include "ClipboardHandler.h"
|
||||
#include "common/FileTransferV2.h"
|
||||
@@ -382,6 +384,66 @@ void* FileManagerThread(void* /*param*/)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
|
||||
// 服务端取走首包后会关掉这条子连接,所以这里发完就等连接断开即可。
|
||||
void* ClientLogThread(void* /*param*/)
|
||||
{
|
||||
RunSubConnThread<ClientLogHandler>(
|
||||
"ClientLogThread",
|
||||
[](IOCPClient* c) { return std::unique_ptr<ClientLogHandler>(new ClientLogHandler(c)); },
|
||||
[](IOCPClient* c, ClientLogHandler*) {
|
||||
Mprintf(">>> ClientLogThread [%p] Send: TOKEN_REPORT_LOG\n", c);
|
||||
});
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// ============== 屏幕预览(对应 Windows 端 COMMAND_SCREEN_PREVIEW_REQ) ==============
|
||||
|
||||
// 同一时刻只跑一个抓屏任务:列表缩略图是周期性刷新,服务端还可能重发/并发请求,
|
||||
// 多余的直接丢弃,让服务端 4s 超时后按"预览不可用"降级(与 Windows 端限流一致)。
|
||||
static std::atomic<int> g_previewInFlight(0);
|
||||
|
||||
static void ScreenPreviewThread(ScreenPreviewReq req)
|
||||
{
|
||||
// 抓屏/缩放全程可能在几十毫秒量级,跑在独立线程里,不阻塞接收线程
|
||||
struct InFlightGuard {
|
||||
~InFlightGuard() { g_previewInFlight.fetch_sub(1); }
|
||||
} guard;
|
||||
|
||||
std::vector<unsigned char> pixels;
|
||||
int w = 0, h = 0;
|
||||
int st = ScreenPreview::Capture(req.maxWidth, pixels, w, h);
|
||||
bool ok = (st == SCREEN_PREVIEW_OK) && !pixels.empty();
|
||||
if (!ok) {
|
||||
pixels.clear();
|
||||
}
|
||||
|
||||
uint32_t bytes = ok ? (uint32_t)pixels.size() : 0;
|
||||
std::vector<char> pkt(sizeof(ScreenPreviewRspHeader) + bytes);
|
||||
ScreenPreviewRspHeader* hdr = (ScreenPreviewRspHeader*)pkt.data();
|
||||
memset(hdr, 0, sizeof(*hdr));
|
||||
hdr->token = TOKEN_SCREEN_PREVIEW_RSP;
|
||||
hdr->reqId = req.reqId;
|
||||
hdr->status = (uint8_t)st;
|
||||
// 成功时发原始 BGRA,由服务端统一编码成 JPEG(Linux 无可靠的 JPEG 编码库);
|
||||
// 失败时 format 无意义,填 JPEG 保持包头合法
|
||||
hdr->format = ok ? SCREEN_PREVIEW_FMT_BGRX : SCREEN_PREVIEW_FMT_JPEG;
|
||||
hdr->width = (uint16_t)w;
|
||||
hdr->height = (uint16_t)h;
|
||||
hdr->bytes = bytes;
|
||||
if (ok) {
|
||||
memcpy(pkt.data() + sizeof(*hdr), pixels.data(), pixels.size());
|
||||
}
|
||||
|
||||
// Send2Server 内部持锁,可在工作线程调用;进程退出/断线时不再回包
|
||||
if (g_pMainClient && g_pMainClient->IsConnected() && g_bExit == S_CLIENT_NORMAL) {
|
||||
g_pMainClient->Send2Server(pkt.data(), (int)pkt.size());
|
||||
}
|
||||
if (!ok) {
|
||||
Mprintf("** Screen preview capture failed: status=%d ***\n", st);
|
||||
}
|
||||
}
|
||||
|
||||
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
|
||||
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
|
||||
// 新锚从下一条新连接开始生效。
|
||||
@@ -430,6 +492,27 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
|
||||
std::thread(FileManagerThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
|
||||
// 与 Windows 端一致:回日志必须开子连接。服务端取走首包后 CancelIO 关的是
|
||||
// 子连接;若回在主连接上,被关掉的就是主连接本身。
|
||||
std::thread(ClientLogThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
|
||||
} else if (szBuffer[0] == COMMAND_SCREEN_PREVIEW_REQ) {
|
||||
if (ulLength < sizeof(ScreenPreviewReq)) return TRUE;
|
||||
ScreenPreviewReq req;
|
||||
memcpy(&req, szBuffer, sizeof(req));
|
||||
// 抓屏可能耗几十毫秒,必须离开接收线程;超额请求直接丢弃(服务端会超时降级)
|
||||
if (g_previewInFlight.fetch_add(1) >= 1) {
|
||||
g_previewInFlight.fetch_sub(1);
|
||||
return TRUE;
|
||||
}
|
||||
try {
|
||||
std::thread(ScreenPreviewThread, req).detach();
|
||||
} catch (const std::exception& e) {
|
||||
// 线程起不来时必须把在途计数还回去,否则后面所有预览请求都会被当成"忙"丢掉
|
||||
g_previewInFlight.fetch_sub(1);
|
||||
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
|
||||
}
|
||||
} else if (szBuffer[0] == CMD_HEARTBEAT_ACK) {
|
||||
if (ulLength >= 1 + sizeof(HeartbeatACK)) {
|
||||
HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1);
|
||||
@@ -1115,6 +1198,18 @@ static void RefreshLoginTls(LOGIN_INFOR& info)
|
||||
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
|
||||
}
|
||||
|
||||
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
|
||||
// 只在本机当前真有可抓的 X11 桌面时才声明,无桌面的服务器不该被服务端要求截图。
|
||||
// 与 RefreshLoginTls 一样只在主线程登录前调用,每次重连都会重新判断。
|
||||
static void RefreshLoginCaps(LOGIN_INFOR& info)
|
||||
{
|
||||
unsigned int caps = LOGIN_INFOR::DefaultCaps();
|
||||
if (ScreenPreview::IsAvailable()) {
|
||||
caps |= CLIENT_CAP_SCREEN_PREVIEW;
|
||||
}
|
||||
info.SetCaps(caps);
|
||||
}
|
||||
|
||||
// 用法: ./ghost [-d] [IP] [端口]
|
||||
// -d 后台守护进程模式
|
||||
// 示例: ./ghost -d 192.168.1.100 6543
|
||||
@@ -1284,6 +1379,13 @@ int main(int argc, char* argv[])
|
||||
|
||||
std::unique_ptr<IOCPClient> ClientObject(new IOCPClient(g_bExit, false));
|
||||
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
|
||||
// 不传 conn 的构造路径拿不到注入的 CONNECT_ADDRESS,协议只能显式喂进去:否则哪怕
|
||||
// g_SETTINGS.protoType 配成 WS/WSS,也会静默按明文 TCP 直连(日志里一个字都没有)。
|
||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
|
||||
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
|
||||
(int)(unsigned char)g_SETTINGS.protoType);
|
||||
}
|
||||
g_pMainClient = ClientObject.get(); // 自升级失败回报用
|
||||
while (!g_bExit) {
|
||||
clock_t c = clock();
|
||||
@@ -1296,6 +1398,8 @@ int main(int argc, char* argv[])
|
||||
ClientAuth::OnNewConnection();
|
||||
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
|
||||
RefreshLoginTls(logInfo);
|
||||
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
|
||||
|
||||
// 新连接:把 ACK 看门狗喂到当前时间,避免循环刚进来就被误判为超时
|
||||
@@ -1315,6 +1419,7 @@ int main(int argc, char* argv[])
|
||||
}
|
||||
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
|
||||
RefreshLoginTls(logInfo);
|
||||
RefreshLoginCaps(logInfo);
|
||||
ClientObject->SendLoginInfo(logInfo);
|
||||
Mprintf(">> Resent login info after group change\n");
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
#include "../common/client_auth_state.h"
|
||||
#include "../common/posix_net_helpers.h"
|
||||
#include "../common/sub_conn_thread.h"
|
||||
#include "../common/ClientLogHandler.h"
|
||||
#import "Permissions.h"
|
||||
#import "ScreenHandler.h"
|
||||
#import "InputHandler.h"
|
||||
@@ -721,6 +722,19 @@ void* FileManagerworkingThread(void* /*param*/)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
|
||||
// 服务端取走首包后会关掉这条子连接,发完等连接断开即可。
|
||||
void* ClientLogworkingThread(void* /*param*/)
|
||||
{
|
||||
RunSubConnThread<ClientLogHandler>(
|
||||
"ClientLogworkingThread",
|
||||
[](IOCPClient* c) { return std::unique_ptr<ClientLogHandler>(new ClientLogHandler(c)); },
|
||||
[](IOCPClient* c, ClientLogHandler*) {
|
||||
Mprintf(">>> ClientLogworkingThread [%p] Send: TOKEN_REPORT_LOG\n", c);
|
||||
});
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
{
|
||||
if (szBuffer == nullptr || ulLength == 0)
|
||||
@@ -747,6 +761,11 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength)
|
||||
} else if (szBuffer[0] == COMMAND_LIST_DRIVE) {
|
||||
std::thread(FileManagerworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user);
|
||||
} else if (szBuffer[0] == COMMAND_QUERY_LOG) {
|
||||
// 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是
|
||||
// 子连接;若回在主连接上,被关掉的就是主连接本身)。
|
||||
std::thread(ClientLogworkingThread, nullptr).detach();
|
||||
Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user);
|
||||
} else if (szBuffer[0] == COMMAND_C2C_PREPARE) {
|
||||
// C2C 准备接收通知
|
||||
FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr);
|
||||
@@ -923,6 +942,13 @@ int main(int argc, const char* argv[])
|
||||
// Create client
|
||||
auto ClientObject = std::make_unique<IOCPClient>(g_bExit, false);
|
||||
ClientObject->setManagerCallBack(NULL, DataProcess, NULL);
|
||||
// 同 Linux:不传 conn 就取不到注入的 CONNECT_ADDRESS,协议必须显式喂进去,
|
||||
// 否则配成 WS/WSS 也只会静默按明文 TCP 直连。
|
||||
ClientObject->SetDefaultProto((int)(unsigned char)g_SETTINGS.protoType);
|
||||
if (g_SETTINGS.protoType == PROTO_WS || g_SETTINGS.protoType == PROTO_WSS) {
|
||||
Mprintf("[WS] 按配置的传输协议连接: proto=%d(WSS 需要 TLS 支持,不支持的平台会 fail-closed)\n",
|
||||
(int)(unsigned char)g_SETTINGS.protoType);
|
||||
}
|
||||
|
||||
// Main event loop
|
||||
NSLog(@"Starting main loop...");
|
||||
|
||||
Binary file not shown.
@@ -746,6 +746,7 @@ CMy2015RemoteDlg::CMy2015RemoteDlg(CWnd* pParent): CDialogLangEx(CMy2015RemoteDl
|
||||
m_bmOnline[72].LoadBitmap(IDB_BITMAP_PREVIEW_QUALITY); // 高级→屏幕预览质量等级
|
||||
m_bmOnline[73].LoadBitmap(IDB_BITMAP_FILE_SPEED); // 高级→文件传输速度
|
||||
m_bmOnline[74].LoadBitmap(IDB_BITMAP_DISCLAIMER); // 其他→免责声明
|
||||
m_bmOnline[75].LoadBitmap(IDB_BITMAP_COPYNAME); // 右键→复制名称
|
||||
for (int i = 0; i < PAYLOAD_MAXTYPE; i++) {
|
||||
m_ServerDLL[i] = nullptr;
|
||||
m_ServerBin[i] = nullptr;
|
||||
@@ -1078,6 +1079,9 @@ BEGIN_MESSAGE_MAP(CMy2015RemoteDlg, CDialogEx)
|
||||
ON_COMMAND(ID_EXPERIMENT_DRAWING_BOARD, &CMy2015RemoteDlg::OnExperimentDrawingBoard)
|
||||
ON_COMMAND(ID_EXPERIMENT_TLS_ENABLE, &CMy2015RemoteDlg::OnExperimentTlsEnable)
|
||||
ON_COMMAND(ID_EXPERIMENT_TLS_DISABLE, &CMy2015RemoteDlg::OnExperimentTlsDisable)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_TCP, &CMy2015RemoteDlg::OnProtoSwitchTcp)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_WS, &CMy2015RemoteDlg::OnProtoSwitchWs)
|
||||
ON_COMMAND(ID_PROTO_SWITCH_WSS, &CMy2015RemoteDlg::OnProtoSwitchWss)
|
||||
ON_COMMAND(ID_TRIGGER_SETTINGS, &CMy2015RemoteDlg::OnTriggerSettings)
|
||||
ON_COMMAND(ID_SHELLCODE_AES_C_ARRAY, &CMy2015RemoteDlg::OnShellcodeAesCArray)
|
||||
ON_COMMAND(ID_PARAM_KBLOGGER, &CMy2015RemoteDlg::OnParamKblogger)
|
||||
@@ -1122,6 +1126,7 @@ BEGIN_MESSAGE_MAP(CMy2015RemoteDlg, CDialogEx)
|
||||
ON_MESSAGE(WM_SPLITTER_MOVED, &CMy2015RemoteDlg::OnSplitterMoved)
|
||||
ON_MESSAGE(WM_SPLITTER_RELEASED, &CMy2015RemoteDlg::OnSplitterReleased)
|
||||
ON_COMMAND(ID_COPY_CLIENT_INFO, &CMy2015RemoteDlg::OnCopyClientInfo)
|
||||
ON_COMMAND(ID_ONLINE_COPY_NAME, &CMy2015RemoteDlg::OnOnlineCopyName)
|
||||
ON_COMMAND(ID_ONLINE_ACTIVE_WND, &CMy2015RemoteDlg::OnOnlineActiveWnd)
|
||||
ON_COMMAND(ID_ONLINE_VIEW_WND, &CMy2015RemoteDlg::OnOnlineWindowManager)
|
||||
ON_COMMAND(ID_ENABLE_DEV_DEBUG, &CMy2015RemoteDlg::OnEnableDevDebug)
|
||||
@@ -4596,6 +4601,7 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
|
||||
Menu.SetMenuItemBitmaps(ID_ONLINE_UNINSTALL, MF_BYCOMMAND, &m_bmOnline[15], &m_bmOnline[15]);
|
||||
Menu.SetMenuItemBitmaps(ID_ONLINE_PRIVATE_SCREEN, MF_BYCOMMAND, &m_bmOnline[16], &m_bmOnline[16]);
|
||||
Menu.SetMenuItemBitmaps(ID_ONLINE_REGROUP, MF_BYCOMMAND, &m_bmOnline[17], &m_bmOnline[17]);
|
||||
Menu.SetMenuItemBitmaps(ID_ONLINE_COPY_NAME, MF_BYCOMMAND, &m_bmOnline[75], &m_bmOnline[75]);
|
||||
Menu.SetMenuItemBitmaps(ID_ONLINE_INJ_NOTEPAD, MF_BYCOMMAND, &m_bmOnline[18], &m_bmOnline[18]);
|
||||
Menu.SetMenuItemBitmaps(ID_PROXY_PORT, MF_BYCOMMAND, &m_bmOnline[19], &m_bmOnline[19]);
|
||||
// Session management icons (shutdown/reboot/logout)
|
||||
@@ -4616,6 +4622,54 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
|
||||
Menu.SetMenuItemBitmaps(ID_EXPERIMENT_TLS_ENABLE, MF_BYCOMMAND, &m_bmOnline[69], &m_bmOnline[69]);
|
||||
Menu.SetMenuItemBitmaps(ID_EXPERIMENT_TLS_DISABLE, MF_BYCOMMAND, &m_bmOnline[70], &m_bmOnline[70]);
|
||||
|
||||
// --- 协议切换子菜单:与「实验功能」平级,紧跟在它下面 ---
|
||||
// 三个单选项:直连 TCP / WS(明文,经反代)/ WSS(TLS,经反代)。当前协议取选中
|
||||
// 主机连接的 GetProtocol()——这是连接的真实传输,比客户端自报可信。
|
||||
// 没选中主机、或选中的客户端版本没有 COMMAND_SET_PROTO(能力位
|
||||
// CLIENT_CAP_PROTO_SWITCH),整组置灰——与「实验功能」等静态子菜单的表现一致。
|
||||
CMenu* pExperimentMenu = FindSubMenuByCommand(SubMenu, ID_EXPERIMENT_TLS_ENABLE);
|
||||
if (pExperimentMenu) {
|
||||
CString curProto;
|
||||
int selectedCount = 0;
|
||||
bool supported = true;
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION protoPos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (protoPos) {
|
||||
int protoItem = m_CList_Online.GetNextSelectedItem(protoPos);
|
||||
context* protoCtx = GetContextByListIndex(protoItem);
|
||||
if (!protoCtx || !protoCtx->IsLogin()) continue;
|
||||
++selectedCount;
|
||||
if (curProto.IsEmpty()) curProto = protoCtx->GetProtocol().c_str();
|
||||
if (!protoCtx->SupportsProtoSwitch()) supported = false;
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
|
||||
CMenu protoMenu;
|
||||
if (protoMenu.CreatePopupMenu()) {
|
||||
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_TCP, _T("直连 TCP"));
|
||||
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_WS, _T("WS(经反向代理,明文)"));
|
||||
protoMenu.AppendMenuL(MF_STRING, ID_PROTO_SWITCH_WSS, _T("WSS(经反向代理,TLS)"));
|
||||
UINT checked = curProto == _T("WS") ? ID_PROTO_SWITCH_WS
|
||||
: curProto == _T("WSS") ? ID_PROTO_SWITCH_WSS
|
||||
: ID_PROTO_SWITCH_TCP;
|
||||
protoMenu.CheckMenuRadioItem(ID_PROTO_SWITCH_TCP, ID_PROTO_SWITCH_WSS,
|
||||
checked, MF_BYCOMMAND);
|
||||
if (selectedCount == 0 || !supported) {
|
||||
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_TCP, MF_BYCOMMAND | MF_GRAYED);
|
||||
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_WS, MF_BYCOMMAND | MF_GRAYED);
|
||||
protoMenu.EnableMenuItem(ID_PROTO_SWITCH_WSS, MF_BYCOMMAND | MF_GRAYED);
|
||||
}
|
||||
for (UINT i = 0; i < SubMenu->GetMenuItemCount(); i++) {
|
||||
if (SubMenu->GetSubMenu(i) == pExperimentMenu) {
|
||||
// 子菜单句柄交给父菜单,随本地 CMenu 一起销毁
|
||||
SubMenu->InsertMenu(i + 1, MF_BYPOSITION | MF_POPUP | MF_STRING,
|
||||
(UINT_PTR)protoMenu.Detach(), _TR("协议切换"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Menu.ModifyMenuL(ID_ONLINE_AUTHORIZE, MF_BYCOMMAND | MF_STRING, ID_ONLINE_AUTHORIZE, _T("发送授权"));
|
||||
|
||||
// ============================================================
|
||||
@@ -4743,7 +4797,36 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
|
||||
|
||||
// 刷新菜单显示
|
||||
DrawMenuBar();
|
||||
SubMenu->TrackPopupMenu(TPM_LEFTALIGN, Point.x, Point.y, this);
|
||||
|
||||
// 菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发:这期间只要有主机上下线,
|
||||
// 列表就会重排(ApplySort/erase),而虚拟列表的选中项是按行号保存的,行号的含义
|
||||
// 随之改变;命令处理函数又是点击那一刻才按行号解析主机。于是「对 A 主机点的菜单」
|
||||
// 会落到重排后占据同一行的 B 主机上。这里先按 clientID 记住用户选中的主机,
|
||||
// 菜单返回后把选中项恢复到这些主机的当前行号,最后才派发命令。
|
||||
std::vector<uint64_t> selectedIds;
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION selPos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (selPos) {
|
||||
int selItem = m_CList_Online.GetNextSelectedItem(selPos);
|
||||
context* selCtx = GetContextByListIndex(selItem);
|
||||
if (selCtx) selectedIds.push_back(selCtx->GetClientID());
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
|
||||
// TPM_RETURNCMD:由我们自己在恢复选中项之后再派发命令。用 Win32 入口是因为
|
||||
// CMenu::TrackPopupMenu 的返回值被声明成 BOOL,拿命令 ID 只能靠隐式截断。
|
||||
UINT cmd = ::TrackPopupMenu(SubMenu->GetSafeHmenu(), TPM_LEFTALIGN | TPM_RETURNCMD,
|
||||
Point.x, Point.y, 0, GetSafeHwnd(), nullptr);
|
||||
if (cmd != 0) {
|
||||
// 恢复选中项只是让界面显示与目标一致;真正的目标是下面这份 clientID 快照。
|
||||
// 处理函数里往往还要先弹确认框/输入框,模态期间列表会再重排一次,所以不能让
|
||||
// 处理函数回头按行号读选中项。保存外层值是为了应对嵌套弹出的菜单。
|
||||
RestoreSelectionByIds(selectedIds);
|
||||
std::vector<uint64_t> outer = std::move(m_CtxMenuTargets);
|
||||
m_CtxMenuTargets = selectedIds;
|
||||
SendMessage(WM_COMMAND, (WPARAM)cmd, 0);
|
||||
m_CtxMenuTargets = std::move(outer);
|
||||
}
|
||||
|
||||
*pResult = 0;
|
||||
}
|
||||
@@ -4796,10 +4879,10 @@ void CMy2015RemoteDlg::OnExperimentTlsEnable()
|
||||
return;
|
||||
}
|
||||
// 二次确认:避免误点就切换被控端 TLS。
|
||||
// 生效时机因客户端而异:Windows 写注册表、下次启动生效;Linux 落盘后立即热切换并
|
||||
// 断开重连(见 client/TlsChannelLinux.cpp 的 TlsReload),正在进行的远程会话会中断。
|
||||
// 两平台都是立即生效:客户端收到命令后落盘信任锚(Windows 注册表 / Linux 配置文件)、
|
||||
// 热重载 TLS 状态(各平台 TlsChannel 的 TlsReload)并断开重连,正在进行的远程会话会中断。
|
||||
if (IDYES != MessageBoxL(_T("确定对选中主机启用 TLS 传输吗?\n"
|
||||
"(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)"),
|
||||
"(客户端立即生效并断线重连,正在进行的远程会话会中断)"),
|
||||
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
|
||||
|
||||
// 读取服务端证书(信任锚),随启用指令一并下发;客户端写入注册表 settings\tls_cert。
|
||||
@@ -4832,12 +4915,117 @@ void CMy2015RemoteDlg::OnExperimentTlsDisable()
|
||||
return;
|
||||
}
|
||||
if (IDYES != MessageBoxL(_T("确定取消选中主机的 TLS 传输吗?\n"
|
||||
"(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)"),
|
||||
"(客户端立即生效并断线重连,正在进行的远程会话会中断)"),
|
||||
_T("提示"), MB_ICONQUESTION | MB_YESNO)) return;
|
||||
BYTE bToken = COMMAND_TLS_DISABLE; //向被控端发送停用 TLS 传输命令
|
||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||
}
|
||||
|
||||
// ---- 协议切换(在线列表右键 → 协议切换 → 直连 TCP / WS / WSS)----
|
||||
//
|
||||
// 服务端只负责下发目标入口和协议:客户端把入口写进本机配置后断开重连,在线升级换 DLL
|
||||
// 也不会被外壳注入的 protoType 按回 TCP(见 client/ClientDll.cpp 的 ApplyProtoSwitch)。
|
||||
// 新入口 5 分钟内登不上去,客户端自动回退到切换前的入口。
|
||||
void CMy2015RemoteDlg::OnProtoSwitchTcp() { SwitchSelectedProtocol(ID_PROTO_SWITCH_TCP); }
|
||||
void CMy2015RemoteDlg::OnProtoSwitchWs() { SwitchSelectedProtocol(ID_PROTO_SWITCH_WS); }
|
||||
void CMy2015RemoteDlg::OnProtoSwitchWss() { SwitchSelectedProtocol(ID_PROTO_SWITCH_WSS); }
|
||||
|
||||
VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
|
||||
{
|
||||
const BYTE proto = nID == ID_PROTO_SWITCH_WS ? (BYTE)PROTO_WS
|
||||
: nID == ID_PROTO_SWITCH_WSS ? (BYTE)PROTO_WSS
|
||||
: (BYTE)PROTO_TCP;
|
||||
const bool restore = (proto == PROTO_TCP);
|
||||
|
||||
// 选中主机的能力校验:老客户端不认识 COMMAND_SET_PROTO,收到只会丢弃。
|
||||
int selected = 0, unsupported = 0;
|
||||
EnterCriticalSection(&m_cs);
|
||||
for (context* ctx : ResolveCommandTargets()) {
|
||||
if (!ctx->IsLogin()) continue;
|
||||
++selected;
|
||||
if (!ctx->SupportsProtoSwitch()) ++unsupported;
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
if (selected == 0) return;
|
||||
if (unsupported > 0) {
|
||||
MessageBoxL(_T("选中的主机里有客户端版本不支持协议切换(需要新版客户端)"),
|
||||
_T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
|
||||
// WS/WSS 需要反向代理入口(域名:端口),用输入框问,记住上次填的
|
||||
std::string host;
|
||||
int port = 0;
|
||||
std::string certPem;
|
||||
if (!restore) {
|
||||
CInputDialog dlg(this);
|
||||
// 提示语只能用关键信息:IDC_STATIC_INPUT_PROMPT 宽 81 个对话框单位(约 121 px),
|
||||
// 放不下完整句子,超出的部分会被直接裁掉。
|
||||
dlg.Init(_TR("协议切换"), _TR("反代入口(域名:端口):"));
|
||||
dlg.SetHistoryKey("proto_entry");
|
||||
CString lastEntry = THIS_CFG.GetStr("ws", "Entry", "").c_str();
|
||||
if (!lastEntry.IsEmpty()) dlg.m_str = lastEntry;
|
||||
if (dlg.DoModal() != IDOK) return;
|
||||
CString text = dlg.m_str;
|
||||
text.Trim();
|
||||
int colon = text.ReverseFind(':');
|
||||
if (colon <= 0 || colon == text.GetLength() - 1) {
|
||||
MessageBoxL(_T("反向代理入口格式不正确,应为 域名:端口"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
host = text.Left(colon).GetString();
|
||||
port = atoi(text.Mid(colon + 1).GetString());
|
||||
if (host.empty() || port <= 0 || port > 65535 || host.size() >= 100) {
|
||||
MessageBoxL(_T("反向代理入口格式不正确,应为 域名:端口"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
THIS_CFG.SetStr("ws", "Entry", std::string(text.GetString())); // 记住上次入口
|
||||
|
||||
// WSS 需要客户端持有能校验反代证书的信任锚:随切换指令一起下发。
|
||||
// 没有证书就不让切——客户端无锚时会按明文 WS 回退,等于静默降级。
|
||||
if (proto == PROTO_WSS) {
|
||||
if (!ServerTlsIdentity::IsReady()) {
|
||||
MessageBoxL(_T("服务端未启用 TLS 证书,无法切换到 WSS"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
std::ifstream certFile(THIS_CFG.GetStr("tls", "CertPath", ""), std::ios::binary);
|
||||
if (certFile.is_open()) {
|
||||
std::ostringstream ss;
|
||||
ss << certFile.rdbuf();
|
||||
certPem = ss.str();
|
||||
}
|
||||
if (certPem.empty()) {
|
||||
MessageBoxL(_T("读取服务端 TLS 证书失败,无法切换到 WSS"), _T("提示"), MB_ICONWARNING);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CString confirm = restore
|
||||
? _TR("确定把选中主机切回直连 TCP 吗?\n"
|
||||
"(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)")
|
||||
: _TR("确定切换选中主机的传输协议吗?\n"
|
||||
"(客户端立即断线重连,正在进行的远程会话会中断;"
|
||||
"新入口 5 分钟内连不上将自动回退)");
|
||||
// confirm 已是翻译后的文本:MessageBoxL 宏会再做一次 _T() 拼接,不能传变量。
|
||||
if (IDYES != MessageBox(confirm, _TR("协议切换"), MB_ICONQUESTION | MB_YESNO)) return;
|
||||
|
||||
// 报文:[COMMAND_SET_PROTO][ProtoSwitchPacket][PEM]
|
||||
std::vector<BYTE> pkt(1 + sizeof(ProtoSwitchPacket), 0);
|
||||
pkt[0] = (BYTE)COMMAND_SET_PROTO;
|
||||
ProtoSwitchPacket* p = (ProtoSwitchPacket*)(pkt.data() + 1);
|
||||
p->proto = proto;
|
||||
if (!restore) {
|
||||
strcpy_s(p->host, host.c_str());
|
||||
sprintf_s(p->port, "%d", port);
|
||||
if (!certPem.empty()) {
|
||||
p->certLen = (uint32_t)certPem.size();
|
||||
pkt.insert(pkt.end(), certPem.begin(), certPem.end());
|
||||
}
|
||||
}
|
||||
SendSelectedCommand(pkt.data(), (ULONG)pkt.size());
|
||||
}
|
||||
|
||||
|
||||
// 从资源中读取被控端文件,并根据用户选择修改连接信息后返回给发送线程
|
||||
BYTE* ReadExeFromResource(DWORD& outSize, int resourceId, const char* resName, int iType, int iStartup,
|
||||
@@ -5056,20 +5244,17 @@ void CMy2015RemoteDlg::OnOnlineDelete()
|
||||
if (IDYES != MessageBoxL(_T("确定删除选定的被控计算机吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
|
||||
return;
|
||||
|
||||
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
|
||||
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
|
||||
EnterCriticalSection(&m_cs);
|
||||
std::vector<context*> targets = ResolveCommandTargets();
|
||||
LeaveCriticalSection(&m_cs);
|
||||
|
||||
BYTE bToken = COMMAND_BYE; //向被控端发送一个COMMAND_SYSTEM
|
||||
SendSelectedCommand(&bToken, sizeof(BYTE)); //Context PreSending PostSending
|
||||
|
||||
EnterCriticalSection(&m_cs);
|
||||
// 收集选中的索引(从大到小排序,避免删除时索引变化问题)
|
||||
std::vector<int> selectedItems;
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (Pos) {
|
||||
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
|
||||
}
|
||||
std::sort(selectedItems.rbegin(), selectedItems.rend());
|
||||
|
||||
for (int iItem : selectedItems) {
|
||||
context* ctx = GetContextByListIndex(iItem);
|
||||
for (context* ctx : targets) {
|
||||
if (!ctx) continue;
|
||||
|
||||
CString strIP = ctx->GetClientData(ONLINELIST_IP);
|
||||
@@ -5116,18 +5301,14 @@ VOID CMy2015RemoteDlg::OnOnlineWindowManager()
|
||||
// 是否继续远程控制:如果选择多个,则继续;如果选择单个且用户锁屏无SYSTEM权限,则提示
|
||||
BOOL CMy2015RemoteDlg::ShouldRemoteControl()
|
||||
{
|
||||
context* ContextObject = nullptr;
|
||||
EnterCriticalSection(&m_cs);
|
||||
int count = m_CList_Online.GetSelectedCount();
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
CString activeWnd, userName;
|
||||
if (Pos) {
|
||||
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
|
||||
ContextObject = GetContextByListIndex(iItem);
|
||||
if (ContextObject) {
|
||||
activeWnd = ContextObject->GetClientData(ONLINELIST_LOGINTIME);
|
||||
userName = ContextObject->GetAdditionalData(RES_USERNAME);
|
||||
}
|
||||
int count = 0;
|
||||
EnterCriticalSection(&m_cs);
|
||||
std::vector<context*> targets = ResolveCommandTargets();
|
||||
count = (int)targets.size();
|
||||
if (!targets.empty()) {
|
||||
activeWnd = targets[0]->GetClientData(ONLINELIST_LOGINTIME);
|
||||
userName = targets[0]->GetAdditionalData(RES_USERNAME);
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
if (count == 1 && userName != "SYSTEM" && activeWnd.Find("Locked") == 0) {
|
||||
@@ -5336,11 +5517,7 @@ void CMy2015RemoteDlg::OnOnlineBuildClient()
|
||||
VOID CMy2015RemoteDlg::SendSelectedCommand(PBYTE szBuffer, ULONG ulLength, contextModifier cb, void* user)
|
||||
{
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while(Pos) {
|
||||
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
|
||||
context* ContextObject = GetContextByListIndex(iItem);
|
||||
if (!ContextObject) continue;
|
||||
for (context* ContextObject : ResolveCommandTargets()) {
|
||||
if (!ContextObject->IsLogin() && szBuffer[0] != COMMAND_BYE)
|
||||
continue;
|
||||
if (szBuffer[0] == COMMAND_UPDATE) {
|
||||
@@ -6852,15 +7029,19 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
|
||||
// (IO 线程不接触 UI;clientId 用于循环快照路由到对应窗口)。
|
||||
// 不用 WPARAM 携带 ID:32 位 Windows 上 WPARAM 是 32 位,会截 64 位 clientID。
|
||||
if (len < sizeof(ScreenPreviewRspHeader)) break;
|
||||
// Linux 客户端回的是原始 BGRA,统一在这里转成 JPEG;畸形包直接丢弃
|
||||
std::vector<BYTE> previewPkt(szBuffer, szBuffer + len);
|
||||
if (!NormalizeScreenPreviewPacket(previewPkt))
|
||||
break;
|
||||
// P2c:MCP 挂起时接管(屏幕预览 = 主连接 RPC,不能 CancelIO)。
|
||||
// reqId 关联:命中 MCP 的 expectedReqId 才取走,避免误吞 MFC 预览在途响应。
|
||||
uint64_t previewDevId = ContextObject->GetClientID();
|
||||
const ScreenPreviewRspHeader* previewHdr = reinterpret_cast<const ScreenPreviewRspHeader*>(szBuffer);
|
||||
if (McpServer().TakePreviewResponse(previewDevId, previewHdr->reqId, szBuffer, len))
|
||||
const ScreenPreviewRspHeader* previewHdr = reinterpret_cast<const ScreenPreviewRspHeader*>(previewPkt.data());
|
||||
if (McpServer().TakePreviewResponse(previewDevId, previewHdr->reqId, previewPkt.data(), (ULONG)previewPkt.size()))
|
||||
break;
|
||||
auto* msg = new CMy2015RemoteDlg::PreviewRspMsg{
|
||||
ContextObject->GetClientID(),
|
||||
std::vector<BYTE>(szBuffer, szBuffer + len)
|
||||
std::move(previewPkt)
|
||||
};
|
||||
if (!g_2015RemoteDlg->PostMessageA(WM_PREVIEW_RESPONSE, 0, (LPARAM)msg)) {
|
||||
delete msg;
|
||||
@@ -7415,6 +7596,95 @@ context* CMy2015RemoteDlg::GetContextByListIndex(int iItem)
|
||||
return m_HostList[realIdx];
|
||||
}
|
||||
|
||||
// 按 clientID 把选中项恢复到它们当前所在的行号。
|
||||
//
|
||||
// 主机列表是虚拟列表(LVS_OWNERDATA),选中项按**行号**保存,而行号的含义会随
|
||||
// m_HostList 重排而改变:上下线时 OnTimer 会 ApplySort() + RebuildFilteredIndices(),
|
||||
// 主机下线时 RemoveFromHostList() 直接 erase,两者都会让行号整体位移。
|
||||
// 右键菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发,所以用户在菜单里点下去
|
||||
// 时,行号很可能已经指向另一台主机;命令处理函数又是点击那一刻才按行号解析主机
|
||||
// (GetContextByListIndex),结果就是「对 A 主机点的菜单」落到了 B 主机上。
|
||||
//
|
||||
// 调用方在弹菜单前用 clientID 记住用户选中的主机,菜单返回后调用本函数把选中项搬回
|
||||
// 这些主机,再派发命令,命令处理函数看到的就还是用户当初选的那批主机。
|
||||
//
|
||||
// 菜单打开期间下线的主机已不在列表里,无法恢复,其选中项被丢弃:处理函数会看到
|
||||
// 「没选中」并给出提示,而不是误操作另一台主机——这是安全的失败方式。
|
||||
void CMy2015RemoteDlg::RestoreSelectionByIds(const std::vector<uint64_t>& ids)
|
||||
{
|
||||
int firstRow = -1;
|
||||
{
|
||||
CLock lock(m_cs);
|
||||
|
||||
// 先清空全部选中(-1 表示作用于所有行)
|
||||
m_CList_Online.SetItemState(-1, 0, LVIS_SELECTED);
|
||||
|
||||
for (uint64_t id : ids) {
|
||||
auto it = m_ClientIndex.find(id);
|
||||
if (it == m_ClientIndex.end()) continue; // 该主机已下线
|
||||
const size_t hostIdx = it->second;
|
||||
if (hostIdx >= m_HostList.size()) continue;
|
||||
// 索引映射若因并发更新而陈旧,宁可不选,也不能选到别的主机
|
||||
if (!m_HostList[hostIdx] || m_HostList[hostIdx]->GetClientID() != id) continue;
|
||||
|
||||
// 在过滤索引里找它的当前显示行
|
||||
int row = -1;
|
||||
for (size_t fi = 0; fi < m_FilteredIndices.size(); ++fi) {
|
||||
if (m_FilteredIndices[fi] == hostIdx) {
|
||||
row = (int)fi;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (row < 0) continue; // 被当前分组过滤排除
|
||||
|
||||
m_CList_Online.SetItemState(row, LVIS_SELECTED, LVIS_SELECTED);
|
||||
if (firstRow < 0) firstRow = row;
|
||||
}
|
||||
}
|
||||
|
||||
// 滚动和重绘会同步触发绘制,放到锁外,不占着主机列表锁
|
||||
if (firstRow >= 0) {
|
||||
m_CList_Online.SetItemState(firstRow, LVIS_FOCUSED, LVIS_FOCUSED);
|
||||
m_CList_Online.EnsureVisible(firstRow, FALSE);
|
||||
}
|
||||
// 重排期间列表用了 LVSICF_NOINVALIDATEALL,可见行可能还是旧内容,补一次重绘
|
||||
m_CList_Online.Invalidate(FALSE);
|
||||
}
|
||||
|
||||
// 取本次命令要作用的主机。
|
||||
//
|
||||
// 平时就是列表里的选中项;右键菜单派发期间 m_CtxMenuTargets 非空,此时以快照为准。
|
||||
// 原因:菜单点击到命令真正执行之间还夹着 MessageBoxL / DoModal 等模态框,模态循环里
|
||||
// WM_TIMER 照常派发,列表会 ApplySort/erase 重排,此时再按行号读选中项就会读到另一台
|
||||
// 主机。快照按 clientID 保存,与行号无关。
|
||||
//
|
||||
// 调用方需持有 m_cs(本函数内部不加锁)。
|
||||
std::vector<context*> CMy2015RemoteDlg::ResolveCommandTargets()
|
||||
{
|
||||
std::vector<context*> targets;
|
||||
if (!m_CtxMenuTargets.empty()) {
|
||||
targets.reserve(m_CtxMenuTargets.size());
|
||||
for (uint64_t id : m_CtxMenuTargets) {
|
||||
auto it = m_ClientIndex.find(id);
|
||||
if (it == m_ClientIndex.end()) continue; // 菜单打开期间已下线
|
||||
const size_t hostIdx = it->second;
|
||||
if (hostIdx >= m_HostList.size()) continue;
|
||||
context* ctx = m_HostList[hostIdx];
|
||||
// 索引映射若因并发更新而陈旧,宁可不操作,也不能操作到别的主机
|
||||
if (!ctx || ctx->GetClientID() != id) continue;
|
||||
targets.push_back(ctx);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (pos) {
|
||||
context* ctx = GetContextByListIndex(m_CList_Online.GetNextSelectedItem(pos));
|
||||
if (ctx) targets.push_back(ctx);
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
// 从 m_HostList 中移除 context 并更新索引映射。
|
||||
//
|
||||
// 重要:MarkDeviceOffline / m_ActiveWndW.erase 等"主机下线"副作用必须**只在
|
||||
@@ -8480,10 +8750,6 @@ LRESULT CMy2015RemoteDlg::OnOpenKeyboardDialog(WPARAM wParam, LPARAM lParam)
|
||||
|
||||
LRESULT CMy2015RemoteDlg::OnOpenProxyDialog(WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
if (!ENABLE_HPSOCKET) {
|
||||
ShowMessage("Operation Failed", "This feature is unavailable due to HPSocket disabled");
|
||||
return S_OK;
|
||||
}
|
||||
return OpenDialog<CProxyMapDlg, IDD_PROXY>(wParam, lParam);
|
||||
}
|
||||
|
||||
@@ -8660,16 +8926,15 @@ void CMy2015RemoteDlg::OnOnlineHostnote()
|
||||
BOOL modified = FALSE;
|
||||
uint64_t key = 0;
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (Pos) {
|
||||
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
|
||||
context* ContextObject = GetContextByListIndex(iItem);
|
||||
if (!ContextObject) continue;
|
||||
// 输入框是模态的,期间列表可能已重排,目标按 clientID 还原,避免备注写到别的主机
|
||||
for (context* ContextObject : ResolveCommandTargets()) {
|
||||
m_ClientMap->SetClientMapData(ContextObject->GetClientID(), MAP_NOTE, dlg.m_str);
|
||||
// 虚拟列表:刷新该行以显示新备注
|
||||
m_CList_Online.RedrawItems(iItem, iItem);
|
||||
modified = TRUE;
|
||||
}
|
||||
if (modified) {
|
||||
// 虚拟列表:整表重绘,让新备注显示出来
|
||||
m_CList_Online.Invalidate(FALSE);
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
if (modified) {
|
||||
m_ClientMap->SaveToFile(GetDbPath());
|
||||
@@ -9535,6 +9800,98 @@ void CMy2015RemoteDlg::ChooseScreenPreviewParams(context* ctx, WORD& maxWidth, B
|
||||
jpegQuality = q;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// GDI+ 的 JPEG 编码器 CLSID(Windows 自带,进程内即可用;与 Bmp2Video 的同名逻辑互不影响)
|
||||
bool FindJpegEncoderClsid(CLSID& clsid)
|
||||
{
|
||||
UINT num = 0, size = 0;
|
||||
if (Gdiplus::GetImageEncodersSize(&num, &size) != Gdiplus::Ok || size == 0) return false;
|
||||
|
||||
std::vector<BYTE> buf(size);
|
||||
Gdiplus::ImageCodecInfo* info = reinterpret_cast<Gdiplus::ImageCodecInfo*>(buf.data());
|
||||
if (Gdiplus::GetImageEncoders(num, size, info) != Gdiplus::Ok) return false;
|
||||
for (UINT i = 0; i < num; ++i) {
|
||||
if (wcscmp(info[i].MimeType, L"image/jpeg") == 0) {
|
||||
clsid = info[i].Clsid;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// 预览响应规范化:Windows 客户端直接回 JPEG,Linux 客户端没有可靠的 JPEG 编码库,
|
||||
// 回的是原始 BGRA(SCREEN_PREVIEW_FMT_BGRX)。统一在 IO 线程入口转成 JPEG,下游
|
||||
// (浮窗 / 列表缩略图 / MCP get_screenshot)就只需要认识 JPEG 一种格式。
|
||||
// 返回 false 表示这个包畸形、不可用,调用方应直接丢弃。
|
||||
bool CMy2015RemoteDlg::NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt)
|
||||
{
|
||||
if (pkt.size() < sizeof(ScreenPreviewRspHeader)) return false;
|
||||
ScreenPreviewRspHeader* hdr = reinterpret_cast<ScreenPreviewRspHeader*>(pkt.data());
|
||||
if (hdr->token != TOKEN_SCREEN_PREVIEW_RSP) return false;
|
||||
if (hdr->format != SCREEN_PREVIEW_FMT_BGRX) return true; // JPEG / 预留格式:原样放行
|
||||
|
||||
// 抓屏失败的响应没有像素可转,原样放行,让下游按 status 报"预览不可用"
|
||||
if (hdr->status != SCREEN_PREVIEW_OK) return true;
|
||||
|
||||
// 尺寸与长度校验:请求侧 maxWidth 已限制在 [64,1920],高度按 16:10 上限放宽到 2160
|
||||
const int w = hdr->width, h = hdr->height;
|
||||
if (w < 2 || h < 2 || w > 1920 || h > 2160) return false;
|
||||
const size_t pixels = (size_t)w * h * 4;
|
||||
if (hdr->bytes != pixels || pkt.size() < sizeof(*hdr) + pixels) return false;
|
||||
|
||||
std::vector<BYTE> jpeg;
|
||||
{
|
||||
// Bitmap 直接引用包内像素(不复制),所以编码必须在 pkt 被 resize 之前、且
|
||||
// 在本作用域内完成析构。用栈对象:本 TU 的 `new` 被 MFC 重定义成 DEBUG_NEW,
|
||||
// Gdiplus 的 operator new 不接受那种三参形式。
|
||||
Gdiplus::Bitmap bmp(w, h, w * 4, PixelFormat32bppRGB, pkt.data() + sizeof(*hdr));
|
||||
if (bmp.GetLastStatus() != Gdiplus::Ok) return false;
|
||||
|
||||
CLSID clsid;
|
||||
if (!FindJpegEncoderClsid(clsid)) return false;
|
||||
|
||||
// Linux 端不上报质量(它不编码),这里跟随缩略图默认档 70
|
||||
Gdiplus::EncoderParameters params;
|
||||
params.Count = 1;
|
||||
params.Parameter[0].Guid = Gdiplus::EncoderQuality;
|
||||
params.Parameter[0].Type = Gdiplus::EncoderParameterValueTypeLong;
|
||||
params.Parameter[0].NumberOfValues = 1;
|
||||
ULONG quality = 70;
|
||||
params.Parameter[0].Value = &quality;
|
||||
|
||||
IStream* stream = nullptr;
|
||||
if (FAILED(::CreateStreamOnHGlobal(NULL, TRUE, &stream))) return false;
|
||||
if (bmp.Save(stream, &clsid, ¶ms) == Gdiplus::Ok) {
|
||||
// 取实际写入长度:GlobalSize 按堆块对齐,尾部填充字节不能算进 JPEG
|
||||
LARGE_INTEGER zero = {};
|
||||
ULARGE_INTEGER end = {}, start = {};
|
||||
if (SUCCEEDED(stream->Seek(zero, STREAM_SEEK_END, &end)) &&
|
||||
end.QuadPart > 0 && end.QuadPart <= 16 * 1024 * 1024 &&
|
||||
SUCCEEDED(stream->Seek(zero, STREAM_SEEK_SET, &start))) {
|
||||
jpeg.resize((size_t)end.QuadPart);
|
||||
ULONG read = 0;
|
||||
if (FAILED(stream->Read(jpeg.data(), (ULONG)jpeg.size(), &read)) ||
|
||||
read != jpeg.size()) {
|
||||
jpeg.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
stream->Release();
|
||||
}
|
||||
if (jpeg.empty()) return false;
|
||||
|
||||
// 用 JPEG 覆盖原像素区;宽高沿用客户端上报值(客户端就是按这两个尺寸缩放的)
|
||||
pkt.resize(sizeof(*hdr) + jpeg.size());
|
||||
hdr = reinterpret_cast<ScreenPreviewRspHeader*>(pkt.data()); // resize 后重新取
|
||||
memcpy(pkt.data() + sizeof(*hdr), jpeg.data(), jpeg.size());
|
||||
hdr->format = SCREEN_PREVIEW_FMT_JPEG;
|
||||
hdr->bytes = (uint32_t)jpeg.size();
|
||||
return true;
|
||||
}
|
||||
|
||||
void CMy2015RemoteDlg::SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality)
|
||||
{
|
||||
if (!ctx) return;
|
||||
@@ -11271,11 +11628,8 @@ void CMy2015RemoteDlg::OnOnlineRunAsAdmin()
|
||||
if (MessageBoxL("确定要以管理员权限重新启动目标应用程序吗?\n此操作可能触发 UAC 账户控制。",
|
||||
"提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (Pos) {
|
||||
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
|
||||
context* ContextObject = GetContextByListIndex(iItem);
|
||||
if (!ContextObject) continue;
|
||||
// 确认框期间列表可能已重排,目标按 clientID 还原
|
||||
for (context* ContextObject : ResolveCommandTargets()) {
|
||||
BYTE token = CMD_RUNASADMIN;
|
||||
ContextObject->Send2Client(&token, sizeof(token));
|
||||
}
|
||||
@@ -11319,20 +11673,17 @@ void CMy2015RemoteDlg::OnOnlineUninstall()
|
||||
if (IDYES != MessageBoxL(_T("确定卸载选定的被控程序吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
|
||||
return;
|
||||
|
||||
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
|
||||
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
|
||||
EnterCriticalSection(&m_cs);
|
||||
std::vector<context*> targets = ResolveCommandTargets();
|
||||
LeaveCriticalSection(&m_cs);
|
||||
|
||||
BYTE bToken = TOKEN_UNINSTALL;
|
||||
SendSelectedCommand(&bToken, sizeof(BYTE));
|
||||
|
||||
EnterCriticalSection(&m_cs);
|
||||
// 收集选中的索引(从大到小排序,避免删除时索引变化问题)
|
||||
std::vector<int> selectedItems;
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (Pos) {
|
||||
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
|
||||
}
|
||||
std::sort(selectedItems.rbegin(), selectedItems.rend());
|
||||
|
||||
for (int iItem : selectedItems) {
|
||||
context* ctx = GetContextByListIndex(iItem);
|
||||
for (context* ctx : targets) {
|
||||
if (!ctx) continue;
|
||||
|
||||
CString strIP = ctx->GetClientData(ONLINELIST_IP);
|
||||
@@ -11517,11 +11868,8 @@ void CMy2015RemoteDlg::MachineManage(MachineCommand type)
|
||||
{
|
||||
if (MessageBoxL("此操作需客户端具有管理员权限,确定继续吗? ", "提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
while (Pos) {
|
||||
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
|
||||
context* ContextObject = GetContextByListIndex(iItem);
|
||||
if (!ContextObject) continue;
|
||||
// 确认框期间列表可能已重排,目标由 ResolveCommandTargets 按 clientID 还原
|
||||
for (context* ContextObject : ResolveCommandTargets()) {
|
||||
BYTE token[32] = { TOKEN_MACHINE_MANAGE, type };
|
||||
ContextObject->Send2Client(token, sizeof(token));
|
||||
}
|
||||
@@ -12593,13 +12941,9 @@ void CMy2015RemoteDlg::ProxyClientTcpPort(bool isStandard, bool autoRun)
|
||||
info->Schedule.Mode = autoRun ? SCH_MODE_STARTUP : SCH_MODE_NONE;
|
||||
FrpcParam param(key.c_str(), timestamp, ip.c_str(), serverPort, localPort, remotePort);
|
||||
EnterCriticalSection(&m_cs);
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
BOOL sent = FALSE;
|
||||
const char* validDate = isStandard ? "Jan 29 2026" : "Dec 22 2025";
|
||||
while (Pos) {
|
||||
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
|
||||
context* ctx = GetContextByListIndex(iItem);
|
||||
if (!ctx) continue;
|
||||
for (context* ctx : ResolveCommandTargets()) {
|
||||
if (!ctx->IsLogin())
|
||||
continue;
|
||||
CString bits = ctx->GetAdditionalData(RES_PROGRAM_BITS);
|
||||
@@ -13382,6 +13726,41 @@ void CMy2015RemoteDlg::OnCopyClientInfo()
|
||||
CloseClipboard();
|
||||
}
|
||||
|
||||
// 右键→复制名称:把选中主机的名称写进剪贴板(多选用分号连接)。
|
||||
// "名称"就是列表第一列显示的内容——有备注取备注,否则取计算机名;列数据是 CP_ACP
|
||||
// 的 CString,和 OnGetdispinfo 用同一套解码方式,保证复制到的文字与屏幕一致。
|
||||
void CMy2015RemoteDlg::OnOnlineCopyName()
|
||||
{
|
||||
std::wstring names;
|
||||
EnterCriticalSection(&m_cs);
|
||||
int nItem = m_CList_Online.GetNextItem(-1, LVNI_SELECTED);
|
||||
while (nItem != -1) {
|
||||
context* ctx = GetContextByListIndex(nItem);
|
||||
if (ctx) {
|
||||
CString note = m_ClientMap->GetClientMapData(ctx->GetClientID(), MAP_NOTE);
|
||||
CString text = !note.IsEmpty() ? note : ctx->GetClientData(ONLINELIST_COMPUTER_NAME);
|
||||
int wlen = text.IsEmpty() ? 0 : MultiByteToWideChar(CP_ACP, 0, text, -1, NULL, 0);
|
||||
if (wlen > 1) {
|
||||
std::wstring w(wlen - 1, L'\0');
|
||||
MultiByteToWideChar(CP_ACP, 0, text, -1, &w[0], wlen);
|
||||
if (!names.empty()) names += L';';
|
||||
names += w;
|
||||
}
|
||||
}
|
||||
nItem = m_CList_Online.GetNextItem(nItem, LVNI_SELECTED);
|
||||
}
|
||||
LeaveCriticalSection(&m_cs);
|
||||
|
||||
if (names.empty()) return;
|
||||
|
||||
// 复用本文件已有的 UTF-8 版剪贴板写入,不再造第三份 CF_UNICODETEXT 代码
|
||||
int len = WideCharToMultiByte(CP_UTF8, 0, names.c_str(), (int)names.size(), NULL, 0, NULL, NULL);
|
||||
if (len <= 0) return;
|
||||
std::string utf8(len, '\0');
|
||||
WideCharToMultiByte(CP_UTF8, 0, names.c_str(), (int)names.size(), &utf8[0], len, NULL, NULL);
|
||||
SetClipboardText(utf8.c_str());
|
||||
}
|
||||
|
||||
void CMy2015RemoteDlg::OnOnlineActiveWnd()
|
||||
{
|
||||
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
|
||||
|
||||
@@ -412,6 +412,16 @@ public:
|
||||
std::string m_v2KeyPath; // V2 密钥文件路径
|
||||
void RebuildFilteredIndices(); // 重建过滤索引
|
||||
context* GetContextByListIndex(int iItem); // 根据列表索引获取 context(考虑分组过滤)
|
||||
// 按 clientID 把选中项恢复到它们当前所在的行号。虚拟列表的选中项是按行号保存的,
|
||||
// 而 m_HostList 会随主机上下线重排,同一个行号重排后往往指向另一台主机。
|
||||
void RestoreSelectionByIds(const std::vector<uint64_t>& ids);
|
||||
// 本次命令的目标主机:右键菜单派发期间(m_CtxMenuTargets 非空)以 clientID 快照为准,
|
||||
// 否则取列表当前选中项。调用方需持有 m_cs。
|
||||
std::vector<context*> ResolveCommandTargets();
|
||||
// 右键菜单发起时锁定的目标主机(clientID 快照)。菜单弹出到命令真正执行之间还会插入
|
||||
// MessageBoxL / DoModal 等模态框,模态循环里 WM_TIMER 照常派发、列表照常重排,命令
|
||||
// 处理函数若在那之后再按行号读选中项,就会读到另一台主机。只在 UI 线程访问。
|
||||
std::vector<uint64_t> m_CtxMenuTargets;
|
||||
|
||||
// 启发式 ID 迁移:新客户端首次上线时,按 (ComputerName, ProgramPath) 在 m_ClientMap
|
||||
// 里找老条目,若唯一匹配则把元数据(备注/位置/级别/授权)拷贝到 newId。
|
||||
@@ -453,7 +463,7 @@ public:
|
||||
bool IsDllRequestLimited(const std::string& ip);
|
||||
void RecordDllRequest(const std::string& ip);
|
||||
CMenu m_MainMenu;
|
||||
CBitmap m_bmOnline[75];
|
||||
CBitmap m_bmOnline[76];
|
||||
uint64_t m_superID;
|
||||
std::map<HWND, CDialogBase *> m_RemoteWnds;
|
||||
FileTransformCmd m_CmdList;
|
||||
@@ -545,6 +555,11 @@ public:
|
||||
afx_msg void OnExperimentDrawingBoard();
|
||||
afx_msg void OnExperimentTlsEnable();
|
||||
afx_msg void OnExperimentTlsDisable();
|
||||
// 协议切换(在线列表右键菜单,与「实验功能」平级):直连 TCP / WS / WSS
|
||||
afx_msg void OnProtoSwitchTcp();
|
||||
afx_msg void OnProtoSwitchWs();
|
||||
afx_msg void OnProtoSwitchWss();
|
||||
VOID SwitchSelectedProtocol(UINT nID);
|
||||
afx_msg void OnOnlineDelete();
|
||||
afx_msg void OnOnlineUpdate();
|
||||
afx_msg void OnAbout();
|
||||
@@ -621,6 +636,9 @@ public:
|
||||
void ChooseScreenPreviewParams(context* ctx, WORD& maxWidth, BYTE& jpegQuality) const;
|
||||
// 发起预览请求;reqId 应与 m_PreviewReqId 同步
|
||||
void SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality);
|
||||
// 预览响应规范化:Linux 客户端回原始 BGRA(SCREEN_PREVIEW_FMT_BGRX),在 IO 线程入口
|
||||
// 统一转成 JPEG,下游(浮窗/列表缩略图/MCP)只处理 JPEG。返回 false 表示畸形包,应丢弃。
|
||||
static bool NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt);
|
||||
// 收到 TOKEN_SCREEN_PREVIEW_RSP(在主线程处理)
|
||||
afx_msg LRESULT OnPreviewResponse(WPARAM wParam, LPARAM lParam);
|
||||
afx_msg void OnOnlineUnauthorize();
|
||||
@@ -722,6 +740,7 @@ public:
|
||||
afx_msg LRESULT OnSplitterMoved(WPARAM wParam, LPARAM lParam);
|
||||
afx_msg LRESULT OnSplitterReleased(WPARAM wParam, LPARAM lParam);
|
||||
afx_msg void OnCopyClientInfo();
|
||||
afx_msg void OnOnlineCopyName();
|
||||
afx_msg void OnOnlineActiveWnd();
|
||||
afx_msg void OnEnableDevDebug();
|
||||
afx_msg void OnOnlineClientLog();
|
||||
|
||||
@@ -344,11 +344,8 @@
|
||||
<ClInclude Include="PluginSettingsDlg.h" />
|
||||
<ClInclude Include="PreviewTipWnd.h" />
|
||||
<ClInclude Include="TriggerSettingsDlg.h" />
|
||||
<ClInclude Include="proxy\HPSocket.h" />
|
||||
<ClInclude Include="proxy\HPTypeDef.h" />
|
||||
<ClInclude Include="proxy\ProxyConnectServer.h" />
|
||||
<ClInclude Include="proxy\ProxyMapDlg.h" />
|
||||
<ClInclude Include="proxy\SocketInterface.h" />
|
||||
<ClInclude Include="pwd_gen.h" />
|
||||
<ClInclude Include="RegisterDlg.h" />
|
||||
<ClInclude Include="Resource.h" />
|
||||
@@ -356,6 +353,7 @@
|
||||
<ClInclude Include="SearchBarDlg.h" />
|
||||
<ClInclude Include="Server.h" />
|
||||
<ClInclude Include="ServerTlsSession.h" />
|
||||
<ClInclude Include="ServerWsSession.h" />
|
||||
<ClInclude Include="ServicesDlg.h" />
|
||||
<ClInclude Include="ConnectionsDlg.h" />
|
||||
<ClInclude Include="SettingDlg.h" />
|
||||
@@ -469,6 +467,7 @@
|
||||
<ClCompile Include="IOCPKCPServer.cpp" />
|
||||
<ClCompile Include="IOCPServer.cpp" />
|
||||
<ClCompile Include="ServerTlsSession.cpp" />
|
||||
<ClCompile Include="ServerWsSession.cpp" />
|
||||
<ClCompile Include="IOCPUDPServer.cpp" />
|
||||
<ClCompile Include="IPHistoryDlg.cpp" />
|
||||
<ClCompile Include="KeyBoardDlg.cpp" />
|
||||
@@ -538,8 +537,12 @@
|
||||
<Image Include="res\Bitmap\BrowseWnd.bmp" />
|
||||
<Image Include="res\Bitmap\CancelShare.bmp" />
|
||||
<Image Include="res\Bitmap\ClientLog.bmp" />
|
||||
<Image Include="res\Bitmap\CopyName.bmp" />
|
||||
<Image Include="res\Bitmap\DesktopQuality.bmp" />
|
||||
<Image Include="res\Bitmap\Disclaimer.bmp" />
|
||||
<Image Include="res\Bitmap\DrawingBoard.bmp" />
|
||||
<Image Include="res\Bitmap\FileManager.bmp" />
|
||||
<Image Include="res\Bitmap\FileSpeed.bmp" />
|
||||
<Image Include="res\Bitmap\Forbidden.bmp" />
|
||||
<Image Include="res\bitmap\compress.bmp" />
|
||||
<Image Include="res\Bitmap\Copy.bmp" />
|
||||
@@ -575,6 +578,7 @@
|
||||
<Image Include="res\Bitmap\PluginConfig.bmp" />
|
||||
<Image Include="res\Bitmap\PortProxyAuto.bmp" />
|
||||
<Image Include="res\Bitmap\PortProxyStd.bmp" />
|
||||
<Image Include="res\Bitmap\PreviewQuality.bmp" />
|
||||
<Image Include="res\Bitmap\PrivacyShield.bmp" />
|
||||
<Image Include="res\Bitmap\PrivateScreen.bmp" />
|
||||
<Image Include="res\Bitmap\proxy.bmp" />
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
<ClCompile Include="ZstaPickerDlg.cpp" />
|
||||
<ClCompile Include="IOCPServer.cpp" />
|
||||
<ClCompile Include="ServerTlsSession.cpp" />
|
||||
<ClCompile Include="ServerWsSession.cpp" />
|
||||
<ClCompile Include="McpTlsProxy.cpp" />
|
||||
<ClCompile Include="KeyBoardDlg.cpp" />
|
||||
<ClCompile Include="Loader.c" />
|
||||
@@ -125,11 +126,8 @@
|
||||
<ClInclude Include="ZstaPickerDlg.h" />
|
||||
<ClInclude Include="IOCPServer.h" />
|
||||
<ClInclude Include="KeyBoardDlg.h" />
|
||||
<ClInclude Include="proxy\HPSocket.h" />
|
||||
<ClInclude Include="proxy\HPTypeDef.h" />
|
||||
<ClInclude Include="proxy\ProxyConnectServer.h" />
|
||||
<ClInclude Include="proxy\ProxyMapDlg.h" />
|
||||
<ClInclude Include="proxy\SocketInterface.h" />
|
||||
<ClInclude Include="pwd_gen.h" />
|
||||
<ClInclude Include="RegisterDlg.h" />
|
||||
<ClInclude Include="Resource.h" />
|
||||
@@ -162,6 +160,7 @@
|
||||
<ClInclude Include="IOCPUDPServer.h" />
|
||||
<ClInclude Include="Server.h" />
|
||||
<ClInclude Include="ServerTlsSession.h" />
|
||||
<ClInclude Include="ServerWsSession.h" />
|
||||
<ClInclude Include="McpTlsProxy.h" />
|
||||
<ClInclude Include="CDrawingBoard.h" />
|
||||
<ClInclude Include="IOCPKCPServer.h" />
|
||||
@@ -369,5 +368,10 @@
|
||||
<Image Include="res\Bitmap\DrawingBoard.bmp" />
|
||||
<Image Include="res\Bitmap\TlsEnable.bmp" />
|
||||
<Image Include="res\Bitmap\TlsDisable.bmp" />
|
||||
<Image Include="res\Bitmap\DesktopQuality.bmp" />
|
||||
<Image Include="res\Bitmap\PreviewQuality.bmp" />
|
||||
<Image Include="res\Bitmap\FileSpeed.bmp" />
|
||||
<Image Include="res\Bitmap\Disclaimer.bmp" />
|
||||
<Image Include="res\Bitmap\CopyName.bmp" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -609,6 +609,8 @@ void CBuildDlg::OnBnClickedOk()
|
||||
File.Close();
|
||||
CString tip = index == IndexTestRun_DLL ? "\r\n" + _TR("提示: 请生成\"ServerDll.dll\",以便程序正常运行。") : _T("");
|
||||
tip += g_ConnectAddress.protoType==PROTO_KCP ? "\n" + _TR("提示: 使用KCP协议生成服务,必须设置主控UDP协议参数为1。") : _T("");
|
||||
tip += (g_ConnectAddress.protoType==PROTO_WS || g_ConnectAddress.protoType==PROTO_WSS) ?
|
||||
"\n" + _TR("提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名。") : _T("");
|
||||
std::string upx;
|
||||
int sel = m_ComboCompress.GetCurSel();
|
||||
if(sel == CLIENT_COMPRESS_UPX)upx = ReleaseUPX();
|
||||
@@ -840,6 +842,11 @@ BOOL CBuildDlg::OnInitDialog()
|
||||
m_ComboProto.InsertStringL(PROTO_HTTP, "HTTP");
|
||||
m_ComboProto.InsertStringL(PROTO_RANDOM, "随机");
|
||||
m_ComboProto.InsertStringL(PROTO_KCP, "KCP");
|
||||
// 序号即 protoType,中间不能有空洞(下方 GetCurSel 直接当协议值用)。
|
||||
// 该下拉框资源带 CBS_SORT 样式:InsertString 不受它影响,能保持这里的顺序,
|
||||
// 换成 AddString 会按字母序重排,HTTP 抢到第 0 项,默认协议就错了。
|
||||
m_ComboProto.InsertStringL(PROTO_WS, "WebSocket");
|
||||
m_ComboProto.InsertStringL(PROTO_WSS, "WS+TLS");
|
||||
m_ComboProto.SetCurSel(PROTO_TCP);
|
||||
|
||||
m_ComboEncrypt.InsertStringL(PROTOCOL_SHINE, "Shine");
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "common/IPWhitelist.h"
|
||||
#include "common/IPBlacklist.h"
|
||||
#include "ServerTlsSession.h"
|
||||
#include "ServerWsSession.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <ws2tcpip.h>
|
||||
@@ -947,26 +948,33 @@ DWORD WINAPI IOCPServer::TlsHandshakeThreadProc(LPVOID lParam)
|
||||
|
||||
// 注意顺序:解析仍在本线程持有引用期间完成(对象不会在这段窗口里被回收);
|
||||
// 释放引用之后才允许任何可能 RemoveStaleContext 的动作(#215)。
|
||||
bool wsTookOver = false;
|
||||
if (ok && !pendingPlain.empty()) {
|
||||
// 与工作线程同样的解压上下文,只是现建现用(首包只解析这一批)。
|
||||
// 走 DispatchPlain:WSS 的首个明文就是 "GET /api/ws HTTP/1.1...",
|
||||
// 由它判定升级并交给 WS 升级线程(此时本线程不能再 PostRecv)。
|
||||
ZSTD_DCtx* dctx = ZSTD_createDCtx();
|
||||
z_stream z = {};
|
||||
inflateInit2(&z, 15);
|
||||
ok = ctx->IsRemoved.load(std::memory_order_acquire) ? TRUE
|
||||
: ParseReceivedData(ctx, pendingPlain.data(), (DWORD)pendingPlain.size(),
|
||||
This->m_NotifyProc, dctx, &z);
|
||||
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
|
||||
: This->DispatchPlain(ctx, pendingPlain.data(), (DWORD)pendingPlain.size(), dctx, &z);
|
||||
inflateEnd(&z);
|
||||
ZSTD_freeDCtx(dctx);
|
||||
if (!ok) {
|
||||
if (r < 0) {
|
||||
ok = false;
|
||||
Mprintf("[TLS] pending first packet parse failed for %s (closing)\n",
|
||||
ctx->GetPeerName().c_str());
|
||||
} else if (r == 0) {
|
||||
wsTookOver = true;
|
||||
}
|
||||
}
|
||||
|
||||
ctx->IoRefCount.fetch_sub(1);
|
||||
|
||||
if (ok) {
|
||||
This->PostRecv(ctx); // 交还 IOCP 接收
|
||||
if (!wsTookOver) {
|
||||
This->PostRecv(ctx); // 交还 IOCP 接收
|
||||
}
|
||||
} else {
|
||||
Mprintf("[TLS] handshake failed for %s (fail-closed)\n", ctx->GetPeerName().c_str());
|
||||
This->RemoveStaleContext(ctx);
|
||||
@@ -1001,6 +1009,146 @@ BOOL IOCPServer::StartTlsHandshake(CONTEXT_OBJECT* ContextObject)
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
delete ContextObject->tls;
|
||||
ContextObject->tls = NULL;
|
||||
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
|
||||
return FALSE;
|
||||
}
|
||||
CloseHandle(h);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// 握手线程参数:把触发判定的首批明文("GET ...")与连接上下文一起移交。
|
||||
struct WsHandshakeParam {
|
||||
IOCPServer* server;
|
||||
CONTEXT_OBJECT* ctx;
|
||||
std::vector<BYTE> initial;
|
||||
};
|
||||
|
||||
// 与 TlsHandshakeThreadProc 同一模式(方案 A):升级期间用一个阻塞线程独占 socket,
|
||||
// 完成后把连接交还 IOCP 接收(PostRecv)。线程持有 ctx 的一枚 IoRefCount,结束时释放。
|
||||
DWORD WINAPI IOCPServer::WsHandshakeThreadProc(LPVOID lParam)
|
||||
{
|
||||
WsHandshakeParam* p = (WsHandshakeParam*)lParam;
|
||||
IOCPServer* This = p->server;
|
||||
CONTEXT_OBJECT* ctx = p->ctx;
|
||||
std::vector<BYTE> initial = std::move(p->initial);
|
||||
delete p;
|
||||
|
||||
if (ctx->IsRemoved.load(std::memory_order_acquire)) {
|
||||
ctx->IoRefCount.fetch_sub(1);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 与 TLS 握手线程相同的 socket 准备工作:尽量切回阻塞,并加超时,避免慢速对端拖住线程。
|
||||
u_long nb = 0;
|
||||
if (ioctlsocket(ctx->sClientSocket, FIONBIO, &nb) == SOCKET_ERROR)
|
||||
Mprintf("[WS] handshake: ioctlsocket(FIONBIO=0) failed err=%d\n", WSAGetLastError());
|
||||
int tmo = 15000; // 15s 升级超时
|
||||
setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tmo, sizeof(tmo));
|
||||
setsockopt(ctx->sClientSocket, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tmo, sizeof(tmo));
|
||||
|
||||
// wss = TLS 里的 WebSocket:TLS 会话(若有)在这里只做字节加解密,升级请求与帧都是明文。
|
||||
bool tlsReady = (ctx->tlsState.load(std::memory_order_acquire) == TLS_Ready);
|
||||
std::vector<BYTE> pending;
|
||||
std::string err;
|
||||
bool ok = (ctx->ws != NULL) &&
|
||||
ctx->ws->Handshake(ctx->sClientSocket, tlsReady ? ctx->tls : NULL, initial,
|
||||
pending, ctx->GetPeerName(), &err);
|
||||
if (!ok) {
|
||||
Mprintf("[WS] upgrade failed for %s: %s (fail-closed)\n",
|
||||
ctx->GetPeerName().c_str(), err.c_str());
|
||||
}
|
||||
|
||||
bool wsTookOver = false;
|
||||
if (ok) {
|
||||
// 反代同机部署时,直接对端是回环地址,升级请求里的转发头才可信;据此把对端地址
|
||||
// 改写成真实客户端 IP,使在线列表 / 封禁 / 白名单看到的是设备而不是反代。
|
||||
const std::string& fwd = ctx->ws->ForwardedIP();
|
||||
if (!fwd.empty()) {
|
||||
Mprintf("[WS] %s upgraded via reverse proxy, real client %s\n",
|
||||
ctx->GetPeerName().c_str(), fwd.c_str());
|
||||
ctx->SetPeerName(fwd);
|
||||
|
||||
// 两段式限流(与 Go 端 limitDirectPeer / handleConnection 同构)。accept 阶段按
|
||||
// getpeername 计的那一次对经反代的连接没有意义:反代同机时对端是回环地址,
|
||||
// IPWhitelist 对回环恒为 true,黑名单 / 封禁 / 计数全部不生效。真实设备 IP 到
|
||||
// 这里才知道,所以在这里按真实 IP 重做一次。直连连接(fwd 为空)在 accept 阶段
|
||||
// 已经计过数,不重复计数。
|
||||
bool blocked = This->IsIPBlacklisted(fwd);
|
||||
if (!blocked) {
|
||||
blocked = This->IsIPBanned(fwd);
|
||||
if (!blocked) {
|
||||
This->RecordConnection(fwd); // 超阈值时内部会 BanIP
|
||||
blocked = This->IsIPBanned(fwd); // 本次连接把计数顶过阈值
|
||||
}
|
||||
}
|
||||
if (blocked) {
|
||||
Mprintf("[WS] real client %s rejected by IP ban/rate limit (fail-closed)\n", fwd.c_str());
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (ok) {
|
||||
ctx->wsState.store(WS_Ready, std::memory_order_release);
|
||||
|
||||
// 升级响应落盘后,同批字节里可能已经有客户端的第一帧(WSS 分批解密时常见)。
|
||||
// 必须在交还 IOCP 之前喂给解帧路径,否则要等客户端再发一包——而它正在等我们。
|
||||
if (!pending.empty()) {
|
||||
ZSTD_DCtx* dctx = ZSTD_createDCtx();
|
||||
z_stream z = {};
|
||||
inflateInit2(&z, 15);
|
||||
int r = ctx->IsRemoved.load(std::memory_order_acquire) ? 1
|
||||
: This->DispatchPlain(ctx, pending.data(), (DWORD)pending.size(), dctx, &z);
|
||||
inflateEnd(&z);
|
||||
ZSTD_freeDCtx(dctx);
|
||||
if (r < 0) {
|
||||
ok = false;
|
||||
Mprintf("[WS] first frame dispatch failed for %s (closing)\n", ctx->GetPeerName().c_str());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ctx->wsState.store(WS_None, std::memory_order_release);
|
||||
}
|
||||
} else {
|
||||
ctx->wsState.store(WS_None, std::memory_order_release);
|
||||
}
|
||||
|
||||
ctx->IoRefCount.fetch_sub(1);
|
||||
|
||||
if (ok) {
|
||||
This->PostRecv(ctx); // 交还 IOCP 接收
|
||||
} else {
|
||||
This->RemoveStaleContext(ctx);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// 判定为 WS 升级请求后:CAS 认领状态、创建会话、预支一枚 IoRefCount、启动升级线程。
|
||||
BOOL IOCPServer::StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vector<BYTE>& initial)
|
||||
{
|
||||
int expected = WS_Undecided;
|
||||
if (!ContextObject->wsState.compare_exchange_strong(expected, WS_Handshaking,
|
||||
std::memory_order_acq_rel)) {
|
||||
return FALSE; // 已有别的线程认领(或状态机异常),不做二次升级
|
||||
}
|
||||
|
||||
if (ContextObject->ws == NULL) {
|
||||
ContextObject->ws = new ServerWsSession();
|
||||
}
|
||||
|
||||
WsHandshakeParam* p = new WsHandshakeParam;
|
||||
p->server = this;
|
||||
p->ctx = ContextObject;
|
||||
p->initial = initial;
|
||||
|
||||
// 预支引用:升级线程结束时释放。此引用保证升级期间对象不被回收。
|
||||
ContextObject->IoRefCount.fetch_add(1);
|
||||
|
||||
HANDLE h = CreateThread(NULL, 0, WsHandshakeThreadProc, p, 0, NULL);
|
||||
if (h == NULL) {
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
ContextObject->FreeWs();
|
||||
ContextObject->wsState.store(WS_None, std::memory_order_release);
|
||||
delete p; // 线程没跑起来,参数(含挪过来的 initial)由本线程释放
|
||||
return FALSE;
|
||||
}
|
||||
CloseHandle(h);
|
||||
@@ -1009,6 +1157,18 @@ BOOL IOCPServer::StartTlsHandshake(CONTEXT_OBJECT* ContextObject)
|
||||
|
||||
BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z)
|
||||
{
|
||||
// 握手线程独占 socket(TLS 或 WS 升级期间):正常不应出现 IORead,出现即属异常,fail-closed。
|
||||
// 必须放在函数最开头——WSS 升级时 tlsState 已经是 TLS_Ready,若把判断放在 TLS 分支之后,
|
||||
// 这段字节会先走解密分支再进 DispatchPlain,被当成业务协议解析,同时与握手线程并发读
|
||||
// 同一个 socket。放在最前面才能同时覆盖明文与 TLS 两条路径。
|
||||
if (ContextObject->wsState.load(std::memory_order_acquire) == WS_Handshaking) {
|
||||
Mprintf("[WS] unexpected IORead during handshake for %s (closing)\n",
|
||||
ContextObject->GetPeerName().c_str());
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
RemoveStaleContext(ContextObject);
|
||||
return -2;
|
||||
}
|
||||
|
||||
int st = ContextObject->tlsState.load(std::memory_order_acquire);
|
||||
|
||||
// ---- 未分类:按 ClientHello 头嗅探明文 / TLS(见设计文档 §5.2)----
|
||||
@@ -1040,15 +1200,21 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
|
||||
}
|
||||
|
||||
// 明文:把嗅探阶段攒下的字节回放给现有解析路径,然后清空缓冲。
|
||||
// 首包若以 "GET " 开头则由 DispatchPlain 判定为 WebSocket 升级。
|
||||
ContextObject->tlsState.store(TLS_Plain, std::memory_order_release);
|
||||
std::vector<BYTE> replay = std::move(ContextObject->tlsPreClassify);
|
||||
ContextObject->tlsPreClassify.clear();
|
||||
if (FALSE == ParseReceivedData(ContextObject, replay.data(), (DWORD)replay.size(), m_NotifyProc, ctx, z)) {
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
RemoveStaleContext(ContextObject);
|
||||
return -2;
|
||||
{
|
||||
int r = DispatchPlain(ContextObject, replay.data(), (DWORD)replay.size(), ctx, z);
|
||||
if (r < 0) {
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
RemoveStaleContext(ContextObject);
|
||||
return -2;
|
||||
}
|
||||
if (r > 0) {
|
||||
PostRecv(ContextObject);
|
||||
}
|
||||
}
|
||||
PostRecv(ContextObject);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
@@ -1069,16 +1235,20 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
|
||||
PostRecv(ContextObject); // 本轮无完整明文(TLS 记录分片/握手告警),继续收
|
||||
return TRUE;
|
||||
}
|
||||
if (FALSE == ParseReceivedData(ContextObject, plain.data(), (DWORD)plain.size(), m_NotifyProc, ctx, z)) {
|
||||
int r = DispatchPlain(ContextObject, plain.data(), (DWORD)plain.size(), ctx, z);
|
||||
if (r < 0) {
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
RemoveStaleContext(ContextObject);
|
||||
return -2;
|
||||
}
|
||||
PostRecv(ContextObject);
|
||||
if (r > 0) {
|
||||
PostRecv(ContextObject);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// TLS_Handshaking:握手线程独占 socket,正常不应出现 IORead;若出现属异常,fail-closed。
|
||||
// (WS_Handshaking 在函数开头已判定,不在这里。)
|
||||
if (st == TLS_Handshaking) {
|
||||
Mprintf("[TLS] unexpected IORead during handshake for %s (closing)\n",
|
||||
ContextObject->GetPeerName().c_str());
|
||||
@@ -1087,13 +1257,126 @@ BOOL IOCPServer::OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans
|
||||
return -2;
|
||||
}
|
||||
|
||||
// TLS_Plain:明文直通(原路径)。
|
||||
if (FALSE == ParseReceivedData(ContextObject, (PBYTE)ContextObject->szBuffer, dwTrans, m_NotifyProc, ctx, z)) {
|
||||
// TLS_Plain:明文直通(原路径)。WS 连接在这里先解帧。
|
||||
// dwTrans == 0 是对端干净关闭(FIN)。WS 改造前这条分支直接调 ParseReceivedData,
|
||||
// 它对 dataLen == 0 返回 FALSE 从而拆连接;换成 DispatchPlain 后该语义丢了——0 字节
|
||||
// 一路返回 1 → PostRecv,而 FIN 已经消费掉,这条连接就停在 CLOSE_WAIT 里,直到
|
||||
// keepalive(3 分钟)才回收(实测:对端 FIN 后连接一直留在 CLOSE_WAIT,进程不空转)。
|
||||
// 期间它占着 IOCP 上下文、挂着一枚 WSARecv 和限流槽。这里补回与另外两条分支一致的收尾。
|
||||
if (dwTrans == 0) {
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
RemoveStaleContext(ContextObject);
|
||||
return -2;
|
||||
}
|
||||
PostRecv(ContextObject);
|
||||
{
|
||||
int r = DispatchPlain(ContextObject, (const BYTE*)ContextObject->szBuffer, dwTrans, ctx, z);
|
||||
if (r < 0) {
|
||||
ContextObject->IoRefCount.fetch_sub(1);
|
||||
RemoveStaleContext(ContextObject);
|
||||
return -2;
|
||||
}
|
||||
if (r > 0) {
|
||||
PostRecv(ContextObject);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
// 分发一段应用层字节(明文,或 TLS 解密后的明文)。
|
||||
// 返回 1 = 已处理完,调用方可以 PostRecv 继续收;0 = WS 升级线程已接管 socket,不要 PostRecv;
|
||||
// -1 = 出错,调用方关闭连接。
|
||||
//
|
||||
// WS_Undecided 阶段先攒够 6 字节再判定(与 ClientHello 嗅探同样的下限):首个明文分片
|
||||
// 可能只有请求头的一部分,按前缀能不能判死都不安全。
|
||||
int IOCPServer::DispatchPlain(CONTEXT_OBJECT* ContextObject, const BYTE* data, DWORD len,
|
||||
ZSTD_DCtx* ctx, z_stream* z)
|
||||
{
|
||||
int ws = ContextObject->wsState.load(std::memory_order_acquire);
|
||||
if (ws == WS_Ready) {
|
||||
return DispatchWsFrameData(ContextObject, data, len, ctx, z) ? 1 : -1;
|
||||
}
|
||||
if (len == 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (ws == WS_Undecided) {
|
||||
// WS 有自己的缓冲(该状态机在 HTTPS 升级 / 反代路径上也会用到),不再借 tlsPreClassify。
|
||||
ContextObject->wsPreClassify.insert(ContextObject->wsPreClassify.end(), data, data + len);
|
||||
if (ContextObject->wsPreClassify.size() < 6) {
|
||||
return 1; // 头还没攒够,继续收
|
||||
}
|
||||
std::vector<BYTE> first;
|
||||
first.swap(ContextObject->wsPreClassify);
|
||||
ContextObject->wsPreClassify.clear();
|
||||
if (first.size() >= 4 && memcmp(first.data(), "GET ", 4) == 0) {
|
||||
if (!StartWsHandshake(ContextObject, first)) {
|
||||
Mprintf("[WS] StartWsHandshake failed for %s (fail-closed)\n",
|
||||
ContextObject->GetPeerName().c_str());
|
||||
return -1;
|
||||
}
|
||||
return 0; // 升级线程接管 socket
|
||||
}
|
||||
ContextObject->wsState.store(WS_None, std::memory_order_release);
|
||||
return ParseReceivedData(ContextObject, first.data(), (DWORD)first.size(), m_NotifyProc, ctx, z) ? 1 : -1;
|
||||
}
|
||||
|
||||
return ParseReceivedData(ContextObject, (PBYTE)data, len, m_NotifyProc, ctx, z) ? 1 : -1;
|
||||
}
|
||||
|
||||
// 把 WS 帧载荷交给解析路径,同时写回控制帧应答(pong / close 回显)。
|
||||
BOOL IOCPServer::DispatchWsFrameData(CONTEXT_OBJECT* ContextObject, const BYTE* wire, DWORD len,
|
||||
ZSTD_DCtx* ctx, z_stream* z)
|
||||
{
|
||||
if (ContextObject->ws == NULL) {
|
||||
return FALSE;
|
||||
}
|
||||
std::vector<BYTE> app, replies;
|
||||
int r = ContextObject->ws->Feed(wire, (int)len, app, replies);
|
||||
if (!replies.empty() && !SendWsReplies(ContextObject, replies)) {
|
||||
return FALSE;
|
||||
}
|
||||
if (r < 0) {
|
||||
return FALSE; // 协议错误或对端 close
|
||||
}
|
||||
if (app.empty()) {
|
||||
return TRUE;
|
||||
}
|
||||
return ParseReceivedData(ContextObject, app.data(), (DWORD)app.size(), m_NotifyProc, ctx, z);
|
||||
}
|
||||
|
||||
// 写回一段完整的 WS 帧(与 Send2Client 走同一条发送路径:追加到 OutCompressedBuffer,
|
||||
// TLS 连接只加密本次新追加的尾部,最后按 bSendPending 协议投递 IOWrite)。
|
||||
BOOL IOCPServer::SendWsReplies(CONTEXT_OBJECT* ContextObject, const std::vector<BYTE>& replies)
|
||||
{
|
||||
CAutoCLock L(ContextObject->SendLock);
|
||||
bool tlsReady = (ContextObject->tlsState.load(std::memory_order_acquire) == TLS_Ready);
|
||||
ULONG oldLen = ContextObject->OutCompressedBuffer.GetBufferLength();
|
||||
if (!ContextObject->OutCompressedBuffer.WriteBuffer((PBYTE)replies.data(), (DWORD)replies.size())) {
|
||||
return FALSE;
|
||||
}
|
||||
if (tlsReady) {
|
||||
ULONG newLen = ContextObject->OutCompressedBuffer.GetBufferLength() - oldLen;
|
||||
std::vector<BYTE> wire;
|
||||
if (ContextObject->tls->Encrypt(ContextObject->OutCompressedBuffer.GetBuffer(oldLen),
|
||||
(int)newLen, wire) != (int)newLen) {
|
||||
ContextObject->OutCompressedBuffer.TruncateBuffer(oldLen);
|
||||
Mprintf("[TLS] Encrypt failed for %s (fail-closed)\n", ContextObject->GetPeerName().c_str());
|
||||
return FALSE;
|
||||
}
|
||||
ContextObject->OutCompressedBuffer.TruncateBuffer(oldLen);
|
||||
ContextObject->OutCompressedBuffer.WriteBuffer(wire.data(), (DWORD)wire.size());
|
||||
}
|
||||
|
||||
if (!ContextObject->bSendPending) {
|
||||
ContextObject->bSendPending = true;
|
||||
OVERLAPPEDPLUS* OverlappedPlus = new OVERLAPPEDPLUS(IOWrite);
|
||||
BOOL bOk = PostQueuedCompletionStatus(m_hCompletionPort, 0, (ULONG_PTR)ContextObject, &OverlappedPlus->m_ol);
|
||||
if ((!bOk && GetLastError() != ERROR_IO_PENDING)) {
|
||||
ContextObject->bSendPending = false;
|
||||
SAFE_DELETE(OverlappedPlus);
|
||||
return FALSE;
|
||||
}
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
@@ -1164,9 +1447,44 @@ BOOL IOCPServer::OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffe
|
||||
// 新明文由 WriteContextData 追加在尾部。若把整个缓冲区重新加密,会把旧密文二次加密,
|
||||
// 客户端解密后得到的是「旧 TLS 记录」→ Unknown header 17 03 03。故只加密本次新追加的尾部。
|
||||
bool tlsReady = (ContextObject->tlsState.load(std::memory_order_acquire) == TLS_Ready);
|
||||
ULONG oldLen = tlsReady ? ContextObject->OutCompressedBuffer.GetBufferLength() : 0;
|
||||
// WS(含 WSS):同样只处理本次新追加的尾部——前缀可能还有在途未发完的帧/密文。
|
||||
const bool wsStateReady = (ContextObject->wsState.load(std::memory_order_acquire) == WS_Ready);
|
||||
if (wsStateReady && (ContextObject->ws == NULL || !ContextObject->ws->IsOpen())) {
|
||||
// 升级过 WS 但会话已关(Feed 报错 / 收到 close)而状态还没降级:绝不能把应用字节
|
||||
// 当裸字节发出去,对端会解帧错位。丢弃本次发送,并主动 shutdown 让挂起的 recv
|
||||
// 立刻返回 0 字节——否则接收路径要等对端 FIN 才醒,期间这条连接既发不出也收不到,
|
||||
// 只能靠心跳超时兜底(最坏要几分钟)。
|
||||
//
|
||||
// 这里不能直接调 RemoveStaleContext:它会等待 IoRefCount 归零,而本函数的调用方
|
||||
// 常常就处在一个 IoRef 里(发送失败→兜底发送),等于自己等自己,5 秒后超时放行,
|
||||
// 反而可能把已回收复用的 CONTEXT_OBJECT 交回给调用者。shutdown 是异步且无阻塞的,
|
||||
// 真正的收尾仍由接收路径的 -2 返回值触发。
|
||||
Mprintf("[WS] session closed for %s, dropping send\n", ContextObject->GetPeerName().c_str());
|
||||
shutdown(ContextObject->sClientSocket, SD_BOTH);
|
||||
return FALSE;
|
||||
}
|
||||
bool wsReady = wsStateReady;
|
||||
ULONG oldLen = (tlsReady || wsReady) ? ContextObject->OutCompressedBuffer.GetBufferLength() : 0;
|
||||
|
||||
if (WriteContextData(ContextObject, szBuffer, ulOriginalLength, ContextObject->Zcctx)) {
|
||||
// WebSocket:一次发送 = 一帧(与 Go 端 wsConn.Write 对齐)。必须在 TLS 加密之前完成,
|
||||
// 这样 TLS 加密的「新追加尾部」就是整帧字节(应用字节 → WS 帧 → TLS 记录)。
|
||||
if (wsReady) {
|
||||
ULONG totalLen = ContextObject->OutCompressedBuffer.GetBufferLength();
|
||||
ULONG appLen = totalLen - oldLen;
|
||||
if (appLen > 0 && ContextObject->ws->IsOpen()) {
|
||||
std::vector<BYTE> framed;
|
||||
if (!ContextObject->ws->Frame((const BYTE*)ContextObject->OutCompressedBuffer.GetBuffer(oldLen),
|
||||
(int)appLen, framed)) {
|
||||
Mprintf("[WS] frame failed for %s (dropping send)\n", ContextObject->GetPeerName().c_str());
|
||||
ContextObject->OutCompressedBuffer.TruncateBuffer(oldLen);
|
||||
return FALSE;
|
||||
}
|
||||
ContextObject->OutCompressedBuffer.TruncateBuffer(oldLen);
|
||||
ContextObject->OutCompressedBuffer.WriteBuffer(framed.data(), (DWORD)framed.size());
|
||||
}
|
||||
}
|
||||
|
||||
// 单向 TLS:只加密新追加的明文尾部,产出密文后与前缀旧密文拼接,使缓冲区始终保持
|
||||
// 一串合法 TLS 记录;之后 IOWrite / OnClientPostSending 完全不变(见设计文档 §5.5)。
|
||||
if (tlsReady) {
|
||||
|
||||
@@ -92,6 +92,7 @@ private:
|
||||
static DWORD WINAPI WorkThreadProc(LPVOID lParam);
|
||||
static DWORD WINAPI RttPollThreadProc(LPVOID lParam);
|
||||
static DWORD WINAPI TlsHandshakeThreadProc(LPVOID lParam);
|
||||
static DWORD WINAPI WsHandshakeThreadProc(LPVOID lParam);
|
||||
|
||||
BOOL InitializeIOCP(VOID);
|
||||
VOID OnAccept();
|
||||
@@ -103,6 +104,10 @@ private:
|
||||
BOOL OnClientInitializing(PCONTEXT_OBJECT ContextObject, DWORD dwTrans);
|
||||
BOOL OnClientReceiving(PCONTEXT_OBJECT ContextObject, DWORD dwTrans, ZSTD_DCtx* ctx, z_stream* z);
|
||||
BOOL StartTlsHandshake(CONTEXT_OBJECT* ContextObject);
|
||||
BOOL StartWsHandshake(CONTEXT_OBJECT* ContextObject, const std::vector<BYTE>& initial);
|
||||
int DispatchPlain(CONTEXT_OBJECT* ContextObject, const BYTE* data, DWORD len, ZSTD_DCtx* ctx, z_stream* z);
|
||||
BOOL DispatchWsFrameData(CONTEXT_OBJECT* ContextObject, const BYTE* wire, DWORD len, ZSTD_DCtx* ctx, z_stream* z);
|
||||
BOOL SendWsReplies(CONTEXT_OBJECT* ContextObject, const std::vector<BYTE>& replies);
|
||||
BOOL OnClientPreSending(CONTEXT_OBJECT* ContextObject, PBYTE szBuffer, size_t ulOriginalLength);
|
||||
BOOL OnClientPostSending(CONTEXT_OBJECT* ContextObject, ULONG ulCompressedLength);
|
||||
int AddWorkThread(int n)
|
||||
|
||||
@@ -480,4 +480,106 @@ void ApplyToolAnnotations(Json::Value& tools) {
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 批量只读调用(ids[])=====
|
||||
|
||||
bool IsBatchReadOnlyTool(const std::string& t) {
|
||||
static const char* kReadOnly[] = {
|
||||
"get_host_detail", "list_processes", "list_windows", "list_services",
|
||||
"list_files", "list_registry", "get_client_log", "get_activity_history",
|
||||
"list_network_connections",
|
||||
"host_list_processes", "host_list_windows", "host_list_network_state",
|
||||
"host_list_software", "host_list_browser_history", "host_list_favorites",
|
||||
"host_list_win32_services", "host_list_driver_services",
|
||||
"host_list_scheduled_tasks", "host_get_hosts_file",
|
||||
};
|
||||
for (const char* x : kReadOnly) if (t == x) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// 批量调用的 structuredContent 形状(与 BuildBatchCall 的输出一一对应)。
|
||||
Json::Value MakeBatchOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
|
||||
auto strProp = [](const char* desc) {
|
||||
Json::Value p(Json::objectValue);
|
||||
p["type"] = "string";
|
||||
if (desc) p["description"] = desc;
|
||||
return p;
|
||||
};
|
||||
auto intProp = [](const char* desc) {
|
||||
Json::Value p(Json::objectValue);
|
||||
p["type"] = "integer";
|
||||
if (desc) p["description"] = desc;
|
||||
return p;
|
||||
};
|
||||
auto boolProp = [](const char* desc) {
|
||||
Json::Value p(Json::objectValue);
|
||||
p["type"] = "boolean";
|
||||
if (desc) p["description"] = desc;
|
||||
return p;
|
||||
};
|
||||
|
||||
props["tool"] = strProp(u8"被批量调用的工具名");
|
||||
props["total"] = intProp(u8"请求里的 id 台数");
|
||||
props["succeeded"] = intProp(u8"成功的台数");
|
||||
props["failed"] = intProp(u8"失败的台数");
|
||||
props["skipped"] = intProp(u8"因整体时限用尽而未下发的台数(不是主机侧错误)");
|
||||
|
||||
// results[]:每台一条。data 就是该工具单机调用时的 structuredContent,
|
||||
// 所以这里不能给 data 收窄成固定字段,只能声明为 object。
|
||||
Json::Value itemProps(Json::objectValue);
|
||||
itemProps["id"] = strProp(u8"主机 id");
|
||||
itemProps["ok"] = boolProp(u8"该台是否成功");
|
||||
Json::Value dataProp(Json::objectValue);
|
||||
dataProp["type"] = "object";
|
||||
dataProp["description"] = u8"该台成功时的单机 structuredContent(字段随工具而定)";
|
||||
itemProps["data"] = dataProp;
|
||||
itemProps["text"] = strProp(u8"该台失败时的错误文字");
|
||||
Json::Value errProp(Json::objectValue);
|
||||
errProp["type"] = "object";
|
||||
errProp["description"] = u8"该台失败时的错误对象(code / message)";
|
||||
itemProps["error"] = errProp;
|
||||
|
||||
Json::Value resultsProp(Json::objectValue);
|
||||
resultsProp["type"] = "array";
|
||||
Json::Value items(Json::objectValue);
|
||||
items["type"] = "object";
|
||||
items["properties"] = itemProps;
|
||||
resultsProp["items"] = items;
|
||||
props["results"] = resultsProp;
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("results");
|
||||
schema["required"] = required;
|
||||
return schema;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void ApplyBatchOutputSchema(Json::Value& tools) {
|
||||
if (!tools.isArray()) return;
|
||||
for (Json::Value& tool : tools) {
|
||||
if (!tool.isObject()) continue;
|
||||
if (!tool.isMember("name") || !tool["name"].isString()) continue;
|
||||
if (!IsBatchReadOnlyTool(tool["name"].asString())) continue;
|
||||
// 用 isMember 判定,避免 operator[] 往工具对象里插一个 null 成员
|
||||
if (!tool.isMember("outputSchema") || !tool["outputSchema"].isObject()) continue;
|
||||
|
||||
Json::Value single = tool["outputSchema"];
|
||||
Json::Value anyOf(Json::arrayValue);
|
||||
anyOf.append(single);
|
||||
anyOf.append(MakeBatchOutputSchema());
|
||||
|
||||
Json::Value wrapped(Json::objectValue);
|
||||
wrapped["type"] = "object";
|
||||
wrapped["anyOf"] = anyOf;
|
||||
tool["outputSchema"] = wrapped;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace McpInternal
|
||||
@@ -142,6 +142,21 @@ void MakeIdOrIdsRequired(Json::Value& schema);
|
||||
// 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」
|
||||
std::string PageSummary(const PageWindow& w, const char* unit);
|
||||
|
||||
// ===== 批量只读调用(ids[])=====
|
||||
//
|
||||
// 支持批量的只读工具清单(写操作一律不支持,避免一次误操作波及多台主机)。
|
||||
// 清单同时被两处使用:tools/call 的入口判定,以及 tools/list 的 outputSchema 补丁。
|
||||
bool IsBatchReadOnlyTool(const std::string& toolName);
|
||||
|
||||
// 给 tools/list 里的批量只读工具补第二个 outputSchema 分支。
|
||||
//
|
||||
// 单机调用返回工具自己的字段(如 host / processes / entries),批量调用返回
|
||||
// { tool, total, succeeded, failed, skipped, results[] }——两者形状完全不同。
|
||||
// 只声明单机形状会让任何 ids 调用在客户端校验 structuredContent 时直接失败
|
||||
// (实测 -32602: data must have required property 'host'),而 inputSchema 又
|
||||
// 明确写着「支持 ids 批量」,等于把批量能力整条封死。这里统一改成 anyOf 两支。
|
||||
void ApplyBatchOutputSchema(Json::Value& tools);
|
||||
|
||||
// ===== 工具注解(A3)=====
|
||||
//
|
||||
// 给 tools/list 里的每个工具补 MCP annotations(readOnlyHint / destructiveHint /
|
||||
|
||||
+313
-35
@@ -770,6 +770,9 @@ std::string BuildRegistryRoots(const Json::Value& id) {
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
// path 恒为 "":根键这一层没有路径,但补上它能让「列根键」与「列子键」返回同一组
|
||||
// 字段(path/keys,子键那次多一个 values),调用方不必按分支判断。
|
||||
structuredContent["path"] = "";
|
||||
structuredContent["keys"] = keys;
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
@@ -1180,7 +1183,7 @@ Json::Value BuildWindowListOutputSchema() {
|
||||
return schema;
|
||||
}
|
||||
|
||||
// get_activity_history 的 outputSchema(records 数组 + 原始文本)
|
||||
// get_activity_history 的 outputSchema(records 数组 + 原始文本 + 翻页字段)
|
||||
Json::Value BuildActivityHistoryOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
|
||||
@@ -1189,12 +1192,21 @@ Json::Value BuildActivityHistoryOutputSchema() {
|
||||
Json::Value items(Json::objectValue);
|
||||
items["type"] = "string";
|
||||
recordsProp["items"] = items;
|
||||
recordsProp["description"] = u8"本次窗口内的记录,每条一行「[时间] [标题] 时长」。新在前。";
|
||||
props["records"] = recordsProp;
|
||||
|
||||
Json::Value rawProp(Json::objectValue);
|
||||
rawProp["type"] = "string";
|
||||
rawProp["description"] = u8"与 records 同源的纯文本(records 按行拼接),窗口外的记录不包含。";
|
||||
props["activityHistory"] = rawProp;
|
||||
|
||||
Json::Value truncProp(Json::objectValue);
|
||||
truncProp["type"] = "boolean";
|
||||
truncProp["description"] = u8"因 64 KB 字节预算而比 limit 少返回了条目(此时 hasMore 也为 true)。";
|
||||
props["truncated"] = truncProp;
|
||||
|
||||
AppendPageOutputProps(props); // total / totalAll / offset / limit / hasMore
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
@@ -1484,6 +1496,7 @@ Json::Value BuildListRegistryOutputSchema() {
|
||||
|
||||
Json::Value valsProp(Json::objectValue);
|
||||
valsProp["type"] = "array";
|
||||
valsProp["description"] = u8"该键下的值;path 为空(列根键)时不返回本字段";
|
||||
Json::Value valItems(Json::objectValue);
|
||||
valItems["type"] = "object";
|
||||
Json::Value valProps(Json::objectValue);
|
||||
@@ -1500,9 +1513,11 @@ Json::Value BuildListRegistryOutputSchema() {
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
// 只把 keys 标成必填。values 在「列根键」分支里不存在(根键下没有值),
|
||||
// 早先把它一并 required,导致文档描述的第一种用法(省略 path)必然被
|
||||
// 客户端判为不符合 outputSchema(-32602: data must have required property 'values')。
|
||||
Json::Value required(Json::arrayValue);
|
||||
required.append("keys");
|
||||
required.append("values");
|
||||
schema["required"] = required;
|
||||
return schema;
|
||||
}
|
||||
@@ -1560,14 +1575,62 @@ Json::Value BuildExecCommandOutputSchema() {
|
||||
return schema;
|
||||
}
|
||||
|
||||
// get_client_log 的 outputSchema(原始日志文本)
|
||||
// get_client_log 的 inputSchema:{ id } + limit / filter(+ ids 批量)
|
||||
//
|
||||
// 不加 limit 时,一次快照是客户端 ring buffer 的全量(最多 1000 行、实测 90 KB),
|
||||
// 单条工具结果直接超出客户端上限——取到了却塞不下,等于取不到。默认只回末尾
|
||||
// 200 行:故障排查看的是最后发生了什么,不是开机时的第一行。
|
||||
Json::Value BuildClientLogInputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
|
||||
Json::Value idProp(Json::objectValue);
|
||||
idProp["type"] = "string";
|
||||
idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段;与 ids 二选一";
|
||||
props["id"] = idProp;
|
||||
|
||||
Json::Value limitProp(Json::objectValue);
|
||||
limitProp["type"] = "integer";
|
||||
limitProp["description"] = u8"最多返回末尾多少行,默认 200,上限 2000;返回的是最近的日志,不是开头的";
|
||||
props["limit"] = limitProp;
|
||||
|
||||
Json::Value filterProp(Json::objectValue);
|
||||
filterProp["type"] = "string";
|
||||
filterProp["description"] = u8"只看包含该子串的行(ASCII 不区分大小写,如 error / TIMEOUT);过滤后再取末尾 limit 行";
|
||||
props["filter"] = filterProp;
|
||||
|
||||
AppendBatchIdsProp(props);
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
MakeIdOrIdsRequired(schema);
|
||||
return schema;
|
||||
}
|
||||
|
||||
// get_client_log 的 outputSchema(日志文本 + 行数统计)
|
||||
Json::Value BuildClientLogOutputSchema() {
|
||||
Json::Value props(Json::objectValue);
|
||||
|
||||
Json::Value logProp(Json::objectValue);
|
||||
logProp["type"] = "string";
|
||||
logProp["description"] = u8"日志文本(按行,\\n 分隔);已按 limit/filter 裁剪";
|
||||
props["log"] = logProp;
|
||||
|
||||
auto intProp = [](const char* desc) {
|
||||
Json::Value p(Json::objectValue);
|
||||
p["type"] = "integer";
|
||||
p["description"] = desc;
|
||||
return p;
|
||||
};
|
||||
props["lines_total"] = intProp(u8"客户端快照的总行数");
|
||||
props["lines_matched"] = intProp(u8"filter 命中后的行数(无 filter 时等于 lines_total)");
|
||||
props["lines_returned"] = intProp(u8"本次实际返回的行数");
|
||||
|
||||
Json::Value truncProp(Json::objectValue);
|
||||
truncProp["type"] = "boolean";
|
||||
truncProp["description"] = u8"true 表示命中行数多于本次返回,log 只是末尾一段";
|
||||
props["truncated"] = truncProp;
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
@@ -1939,9 +2002,9 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_activity_history";
|
||||
tool["description"] = u8"获取指定在线主机的历史活动记录(前台窗口驻留时长,每行一条「[时间] [标题] 时长」)。主连接 RPC、一次性返回。";
|
||||
tool["description"] = u8"获取指定在线主机的历史活动记录(前台窗口驻留时长,每行一条「[时间] [标题] 时长」)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;客户端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
|
||||
|
||||
tool["inputSchema"] = BuildGetHostDetailInputSchema(); // 复用 { id } 必填 schema
|
||||
tool["inputSchema"] = BuildPagedHostListInputSchema(); // { id | ids } + limit/offset
|
||||
tool["outputSchema"] = BuildActivityHistoryOutputSchema();
|
||||
|
||||
tools.append(tool);
|
||||
@@ -1951,7 +2014,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_screenshot";
|
||||
tool["description"] = u8"截取指定在线主机的一帧屏幕,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。仅 Windows 客户端支持(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。";
|
||||
tool["description"] = u8"截取指定在线主机的一帧屏幕,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。";
|
||||
|
||||
tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选
|
||||
tool["outputSchema"] = BuildScreenshotOutputSchema();
|
||||
@@ -1987,9 +2050,9 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
{
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "get_client_log";
|
||||
tool["description"] = u8"获取指定在线主机 YAMA 客户端的内存运行日志(最近最多 1000 条,含时间戳/源文件/行号)。客户端持续增量上报,本工具取当前时刻的全量快照后即断开。只读。";
|
||||
tool["description"] = u8"获取指定在线主机 YAMA 客户端的内存运行日志(客户端 ring buffer,最多 1000 行,含时间戳/源文件/行号)。客户端持续增量上报,本工具取当前时刻的快照后即断开。默认只返回末尾 200 行(故障排查看的是最后发生了什么);可用 limit 调整(上限 2000)、filter 只保留包含某子串的行。返回里的 lines_total / lines_matched / lines_returned / truncated 说明裁剪情况。只读。";
|
||||
|
||||
tool["inputSchema"] = BuildGetHostDetailInputSchema(); // 复用 { id } 必填 schema
|
||||
tool["inputSchema"] = BuildClientLogInputSchema();
|
||||
tool["outputSchema"] = BuildClientLogOutputSchema();
|
||||
|
||||
tools.append(tool);
|
||||
@@ -2331,7 +2394,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
if (CMcpServer::Instance().IsFileTransferEnabled() && !CMcpServer::Instance().IsReadonly()) {
|
||||
Json::Value tool(Json::objectValue);
|
||||
tool["name"] = "copy_files_c2c";
|
||||
tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。返回 transfer_id/file_count/total_bytes/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
|
||||
tool["description"] = u8"在两个在线主机之间直接拷贝文件(V2 C2C:源主机自己发、目标主机自己收,服务端只中继,不在主控落盘)。源主机必须是 Windows;目标主机可以是 Windows 或 Linux/macOS。paths 为源主机绝对路径(文件或目录,目录递归、保留相对目录结构);dst_dir 为目标主机保存目录(不存在自动创建),Windows 目标用 D:\\Incoming 这类绝对路径,Linux/macOS 目标用 /home/user/incoming 这类绝对 POSIX 路径。overwrite 默认 false:目标目录已存在同名顶层项时跳过并计入 skipped(目标端是无条件覆盖写,不跳过就会每次全量重发);预检本身失败(目标主机忙/超时/拒绝访问)不报错,退回全发并置 skip_check_failed=true。返回 transfer_id/file_count/total_bytes/skipped/skip_check_failed/receiver_ack:receiver_ack=true 表示目标端已确认写入(Linux 客户端回执),false 表示目标端没有回执(Windows 目标、老客户端或 macOS),此时需要确证请用 list_files 复核。";
|
||||
tool["inputSchema"] = BuildCopyFilesC2CInputSchema();
|
||||
tool["outputSchema"] = BuildCopyFilesC2COutputSchema();
|
||||
tools.append(tool);
|
||||
@@ -2448,6 +2511,12 @@ std::string BuildToolsListResult(const Json::Value& id) {
|
||||
// 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。
|
||||
ApplyToolAnnotations(tools);
|
||||
|
||||
// 22) 批量只读工具补第二个 outputSchema 分支(N2):批量结果的形状是
|
||||
// { tool, total, ..., results[] },与单机形状不同;只声明单机形状会让
|
||||
// 任何 ids 调用在客户端校验 structuredContent 时以 -32602 失败。
|
||||
// 同样放在最后一步,三个注册点一视同仁。
|
||||
ApplyBatchOutputSchema(tools);
|
||||
|
||||
result["tools"] = tools;
|
||||
return BuildResult(id, result);
|
||||
}
|
||||
@@ -2906,21 +2975,72 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar
|
||||
text.assign((const char*)data.data() + 1, data.size() - 1);
|
||||
|
||||
// 拆行:每行一条记录,过滤空行(含 Dump 末尾的换行)。
|
||||
Json::Value records(Json::arrayValue);
|
||||
// 顺序是「新在前」:客户端 m_records 用 push_front 维护,Dump() 又把进行中的
|
||||
// 当前窗口放在最前面。所以 offset=0 天然就是“最近 limit 条”,不需要先取
|
||||
// total 再倒着算 offset——这正是日志类数据最常用的取法。
|
||||
Json::Value all(Json::arrayValue);
|
||||
size_t start = 0;
|
||||
while (start <= text.size()) {
|
||||
size_t nl = text.find('\n', start);
|
||||
std::string line = text.substr(start, (nl == std::string::npos ? text.size() : nl) - start);
|
||||
if (!line.empty()) records.append(line);
|
||||
if (!line.empty()) all.append(line);
|
||||
if (nl == std::string::npos) break;
|
||||
start = nl + 1;
|
||||
}
|
||||
int count = (int)records.size();
|
||||
|
||||
// 分页:实测一次 501 条会把上下文撑爆(P2-1)。本工具无服务端过滤,
|
||||
// total == totalAll,ApplyPageWindow 的默认口径即可。
|
||||
PageWindow page = ResolvePageWindow(args);
|
||||
Json::Value records(Json::arrayValue);
|
||||
ApplyPageWindow(all, page, records);
|
||||
|
||||
// 字节预算:limit 上限 1000,窗口内若标题很长仍可能过大。从窗口末尾裁
|
||||
// (保留最新的那些),裁掉的部分由 truncated 与 hasMore 一起表达。
|
||||
const size_t kMaxBytes = 64 * 1024;
|
||||
bool byteTrimmed = false;
|
||||
{
|
||||
size_t bytes = 0;
|
||||
int kept = 0;
|
||||
for (const Json::Value& r : records) {
|
||||
const std::string s = r.asString();
|
||||
if (bytes + s.size() + 1 > kMaxBytes) { byteTrimmed = true; break; }
|
||||
bytes += s.size() + 1;
|
||||
++kept;
|
||||
}
|
||||
if (byteTrimmed) {
|
||||
// 至少留一条,保证调用方按 offset+returned 前进时不会原地打转
|
||||
// (单条超过 64 KB 在窗口标题上几乎不可能,这里只是兜底)。
|
||||
if (kept == 0) {
|
||||
kept = 1;
|
||||
Json::Value one(Json::arrayValue);
|
||||
one.append(records[0]);
|
||||
records = one;
|
||||
} else {
|
||||
Json::Value trimmed(Json::arrayValue);
|
||||
for (int i = 0; i < kept; ++i) trimmed.append(records[i]);
|
||||
records = trimmed;
|
||||
}
|
||||
page.returned = kept;
|
||||
// 还有没有更早的记录,按「已返回到的绝对位置」算,而不是一律置 true:
|
||||
// 末尾那条自己超预算时,offset+kept 已经等于 total,不该再报 hasMore。
|
||||
page.hasMore = (page.offset + kept < page.total);
|
||||
}
|
||||
}
|
||||
|
||||
// activityHistory 是同一份数据的纯文本形态:必须按窗口重建,
|
||||
// 否则整包原文会绕过分页,等于没分页。
|
||||
std::string shown;
|
||||
for (const Json::Value& r : records) {
|
||||
shown += r.asString();
|
||||
shown += '\n';
|
||||
}
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
structuredContent["records"] = records;
|
||||
structuredContent["activityHistory"] = text;
|
||||
structuredContent["activityHistory"] = shown;
|
||||
structuredContent["truncated"] = byteTrimmed;
|
||||
WritePageFields(structuredContent, page);
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
// 正文外的 JSON 块只放 records:activityHistory 是同一份数据的原文,
|
||||
@@ -2932,7 +3052,11 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = std::string(u8"共 ") + std::to_string(count) + std::string(u8" 条历史活动记录。");
|
||||
item["text"] = std::string(u8"共 ") + std::to_string(page.total) + std::string(u8" 条历史活动记录(新在前),本次返回第 ") +
|
||||
std::to_string(page.offset) + std::string(u8" 条起的 ") + std::to_string(page.returned) + std::string(u8" 条") +
|
||||
(page.hasMore ? std::string(u8";hasMore=true 表示还有更早的记录,可用 offset=") +
|
||||
std::to_string(page.offset + page.returned) + std::string(u8" 继续取。")
|
||||
: std::string(u8"。"));
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
@@ -2951,7 +3075,8 @@ std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, C
|
||||
if (!ctx)
|
||||
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
|
||||
|
||||
// 能力位门槛:仅 Windows 客户端声明 CLIENT_CAP_SCREEN_PREVIEW(非 Windows 返回明确错误)
|
||||
// 能力位门槛:只有能抓屏的客户端才声明 CLIENT_CAP_SCREEN_PREVIEW
|
||||
// (Windows 恒声明;Linux 仅在登录时探测到可用 X11 桌面才声明),否则返回明确错误
|
||||
if (!ctx->SupportsScreenPreview())
|
||||
return BuildError(id, -32005, "Host does not support screen preview");
|
||||
|
||||
@@ -3638,7 +3763,11 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM
|
||||
|
||||
std::vector<BYTE> data;
|
||||
if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs()))
|
||||
return BuildError(id, -32001, "Timeout waiting for client log");
|
||||
return BuildError(id, -32001,
|
||||
u8"Timeout waiting for client log. 客户端在超时内没有回传日志:常见原因是该客户端"
|
||||
u8"版本尚未实现日志上报(Linux/MAC 需 2026-10-30 之后的客户端),也可能是子连接"
|
||||
u8"建立失败。可先用 get_host_detail 看 capabilities,或改用 download_file 直接取"
|
||||
u8"客户端日志文件。");
|
||||
|
||||
// data[0]=token,其后为 Logger 内存 ring buffer 的日志文本(无 '\0' 终止)。
|
||||
// 客户端在子连接建立时 m_sentIdx=0 返回全量,随后每 3s 推增量;MessageHandle 在
|
||||
@@ -3653,16 +3782,100 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM
|
||||
log = ToUtf8(raw.c_str(), cp);
|
||||
}
|
||||
|
||||
// 行级裁剪:客户端快照是全量(最多 1000 行、实测 90 KB),直接整段塞进结果会超出
|
||||
// 客户端的工具结果上限。默认只回末尾 200 行——排障关心的是最后发生了什么。
|
||||
int limit = 200;
|
||||
if (args.isMember("limit") && args["limit"].isInt())
|
||||
limit = args["limit"].asInt();
|
||||
if (limit <= 0) limit = 200;
|
||||
if (limit > 2000) limit = 2000;
|
||||
const std::string filter = GetStringArg(args, "filter");
|
||||
|
||||
std::vector<std::string> lines;
|
||||
{
|
||||
size_t b = 0;
|
||||
while (b < log.size()) {
|
||||
size_t e = log.find('\n', b);
|
||||
std::string one = (e == std::string::npos) ? log.substr(b) : log.substr(b, e - b);
|
||||
if (!one.empty() && one.back() == '\r') one.pop_back();
|
||||
lines.push_back(one);
|
||||
if (e == std::string::npos) break;
|
||||
b = e + 1;
|
||||
}
|
||||
}
|
||||
const int linesTotal = (int)lines.size();
|
||||
|
||||
std::vector<std::string> matched;
|
||||
matched.reserve(lines.size());
|
||||
for (const auto& one : lines) {
|
||||
if (filter.empty() || ContainsCI(one, filter))
|
||||
matched.push_back(one);
|
||||
}
|
||||
const int linesMatched = (int)matched.size();
|
||||
|
||||
// 从末尾往前取:同时受 limit 行数与 64 KB 字节预算约束(单行可能是超长的堆栈或
|
||||
// 报文转储,只按行数截断仍可能撑爆结果)。两个约束哪个先到就用哪个。
|
||||
const size_t kMaxBytes = 64 * 1024;
|
||||
std::string shown;
|
||||
int linesReturned = 0;
|
||||
bool contentTruncated = false;
|
||||
{
|
||||
size_t budget = kMaxBytes;
|
||||
size_t firstKept = (size_t)linesMatched; // 保留 [firstKept, linesMatched)
|
||||
while (firstKept > 0 && (int)((size_t)linesMatched - firstKept) < limit) {
|
||||
const size_t need = matched[firstKept - 1].size() + 1;
|
||||
if (need > budget) break;
|
||||
budget -= need;
|
||||
--firstKept;
|
||||
}
|
||||
|
||||
if (firstKept == (size_t)linesMatched && linesMatched > 0) {
|
||||
// 末尾一行自己就超过预算:至少回它的尾部(排障看的是最后发生了什么),
|
||||
// 而不是回空串让人以为客户端没有日志。
|
||||
const std::string& last = matched.back();
|
||||
if (last.size() > kMaxBytes) {
|
||||
shown = last.substr(last.size() - kMaxBytes);
|
||||
contentTruncated = true;
|
||||
} else {
|
||||
shown = last;
|
||||
}
|
||||
shown += '\n';
|
||||
linesReturned = 1;
|
||||
} else {
|
||||
for (size_t i = firstKept; i < (size_t)linesMatched; ++i) {
|
||||
shown += matched[i];
|
||||
shown += '\n';
|
||||
}
|
||||
linesReturned = linesMatched - (int)firstKept;
|
||||
}
|
||||
}
|
||||
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value structuredContent(Json::objectValue);
|
||||
structuredContent["log"] = log;
|
||||
structuredContent["log"] = shown;
|
||||
structuredContent["lines_total"] = linesTotal;
|
||||
structuredContent["lines_matched"] = linesMatched;
|
||||
structuredContent["lines_returned"] = linesReturned;
|
||||
structuredContent["truncated"] = (linesMatched > linesReturned) || contentTruncated;
|
||||
result["structuredContent"] = structuredContent;
|
||||
|
||||
std::string text;
|
||||
if (linesTotal == 0) {
|
||||
text = u8"客户端暂无内存日志。";
|
||||
} else {
|
||||
text = std::string(u8"客户端运行日志:共 ") + std::to_string(linesTotal) + std::string(u8" 行");
|
||||
if (!filter.empty())
|
||||
text += std::string(u8",匹配 \"") + filter + std::string(u8"\" 的 ") + std::to_string(linesMatched) + std::string(u8" 行");
|
||||
text += std::string(u8",返回末尾 ") + std::to_string(linesReturned) + std::string(u8" 行");
|
||||
if (linesMatched > linesReturned || contentTruncated)
|
||||
text += std::string(u8"(还有更多,可调大 limit 或加 filter)");
|
||||
text += std::string(u8"。");
|
||||
}
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = log.empty() ? std::string(u8"客户端暂无内存日志。")
|
||||
: std::string(u8"客户端运行日志快照如下。");
|
||||
item["text"] = text;
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
@@ -5854,7 +6067,8 @@ static bool UploadSendChunkHeadless(void* user, FileChunkPacketV2* chunk, unsign
|
||||
// 复用 list_files 的 COMMAND_LIST_DRIVE→TOKEN_DRIVE_LIST→COMMAND_LIST_FILES→TOKEN_FILE_LIST 链路。
|
||||
static bool ListRemoteTopLevelNames(CMy2015RemoteDlg* parent, uint64_t devId,
|
||||
const std::string& remoteDirAnsi,
|
||||
std::set<std::string>& names) {
|
||||
std::set<std::string>& names,
|
||||
bool foldCase = true) {
|
||||
CMcpServer& mcp = CMcpServer::Instance();
|
||||
if (!mcp.BeginPending(devId, "list_files", remoteDirAnsi)) return false;
|
||||
context* ctx = FindMainContext(parent, devId);
|
||||
@@ -5882,7 +6096,7 @@ static bool ListRemoteTopLevelNames(CMy2015RemoteDlg* parent, uint64_t devId,
|
||||
off += nlen + 1;
|
||||
if (off + 16 > len) break;
|
||||
off += 16; // sizeHigh/sizeLow/ft(8)
|
||||
names.insert(AsciiLower(std::string(name, nlen)));
|
||||
names.insert(foldCase ? AsciiLower(std::string(name, nlen)) : std::string(name, nlen));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -6284,6 +6498,12 @@ Json::Value BuildCopyFilesC2CInputSchema() {
|
||||
to["description"] = u8"超时毫秒(默认 600000=10 分钟,上限 3600000=1 小时);超时不代表传输失败";
|
||||
props["timeout_ms"] = to;
|
||||
|
||||
Json::Value ow(Json::objectValue);
|
||||
ow["type"] = "boolean";
|
||||
ow["description"] = u8"目标目录已存在同名顶层项时是否覆盖重传。默认 false:跳过并计入 skipped(不发起传输)。"
|
||||
u8"目标端收包是无条件覆盖写,所以默认 false 才能避免重复调用时全量重发。";
|
||||
props["overwrite"] = ow;
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
schema["properties"] = props;
|
||||
@@ -6305,6 +6525,8 @@ Json::Value BuildCopyFilesC2COutputSchema() {
|
||||
Json::Value s5(Json::objectValue); s5["type"] = "integer"; props["file_count"] = s5;
|
||||
Json::Value s6(Json::objectValue); s6["type"] = "integer"; props["total_bytes"] = s6;
|
||||
Json::Value s7(Json::objectValue); s7["type"] = "boolean"; props["receiver_ack"] = s7;
|
||||
Json::Value s8(Json::objectValue); s8["type"] = "integer"; props["skipped"] = s8;
|
||||
Json::Value s9(Json::objectValue); s9["type"] = "boolean"; props["skip_check_failed"] = s9;
|
||||
|
||||
Json::Value schema(Json::objectValue);
|
||||
schema["type"] = "object";
|
||||
@@ -6408,6 +6630,9 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
|
||||
dstDirAnsi.pop_back();
|
||||
if (dstDirAnsi.empty() || HasDotDotSegment(dstDirAnsi))
|
||||
return BuildError(id, -32602, "Invalid dst_dir: " + dstDirUtf8);
|
||||
// 不带尾分隔符的形态,供 overwrite=false 的目录列举使用:客户端拼 "%s\*.*",
|
||||
// 带尾分隔符会拼成 "C:\\*.*" 导致 FindFirstFile 失败(与 search_file 同一处坑)。
|
||||
const std::string dstDirListAnsi = dstDirAnsi;
|
||||
if (posixDst) {
|
||||
// POSIX 目标:接收端把 '\' 当分隔符归一化,接 C:\x 会落成 /C:/x 之类;只收 '/' 根路径。
|
||||
if (dstDirAnsi[0] != '/' || dstDirAnsi.find('\\') != std::string::npos)
|
||||
@@ -6433,6 +6658,64 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
|
||||
pathAnsi.push_back(ansi);
|
||||
}
|
||||
|
||||
// ===== overwrite=false:先列目标目录一层,跳过已存在的同名顶层项 =====
|
||||
// 目标端收包是无条件覆盖写,服务端不预检的话每次调用都会把整份文件重发一遍
|
||||
// (实测同一份 11 MB 日志连传两次都重写,且两次返回值完全相同,调用方无从分辨)。
|
||||
// 预检只在 overwrite=false 时做;目标目录尚不存在时 ListRemoteTopLevelNames 返回空集,
|
||||
// 正好等价于「无同名项」。预检本身失败(主机忙/超时/拒绝访问)不回错误,退回全发并
|
||||
// 置 skip_check_failed=true——不能让「检查失败」把一次本该成功的传输挡掉。
|
||||
const bool overwrite = (args.isMember("overwrite") && args["overwrite"].isBool())
|
||||
? args["overwrite"].asBool() : false;
|
||||
|
||||
int skipped = 0;
|
||||
bool skipCheckFailed = false;
|
||||
std::vector<std::string> sendPathAnsi;
|
||||
if (overwrite) {
|
||||
sendPathAnsi = pathAnsi;
|
||||
} else {
|
||||
std::set<std::string> existing;
|
||||
// POSIX 目标区分大小写,Windows 目标不区分(与目标文件系统语义一致)。
|
||||
if (!ListRemoteTopLevelNames(parent, dstId, dstDirListAnsi, existing, !posixDst)) {
|
||||
skipCheckFailed = true;
|
||||
sendPathAnsi = pathAnsi;
|
||||
} else {
|
||||
for (unsigned int i = 0; i < paths.size(); ++i) {
|
||||
const std::string u8 = paths[i].asString();
|
||||
const size_t sep = u8.find_last_of("\\/");
|
||||
const std::string base = (sep == std::string::npos) ? u8 : u8.substr(sep + 1);
|
||||
const std::string key = posixDst ? base : AsciiLower(base);
|
||||
if (!base.empty() && existing.count(key)) { ++skipped; continue; }
|
||||
sendPathAnsi.push_back(pathAnsi[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 全部被跳过:直接返回成功,不发起传输。
|
||||
if (sendPathAnsi.empty()) {
|
||||
Json::Value result(Json::objectValue);
|
||||
Json::Value sc(Json::objectValue);
|
||||
sc["transfer_id"] = std::string();
|
||||
sc["src_id"] = std::to_string(srcId);
|
||||
sc["dst_id"] = std::to_string(dstId);
|
||||
sc["dst_dir"] = dstDirUtf8;
|
||||
sc["file_count"] = (Json::UInt)0;
|
||||
sc["total_bytes"] = (Json::UInt64)0;
|
||||
sc["receiver_ack"] = false;
|
||||
sc["skipped"] = skipped;
|
||||
sc["skip_check_failed"] = false;
|
||||
result["structuredContent"] = sc;
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
Json::Value item(Json::objectValue);
|
||||
item["type"] = "text";
|
||||
item["text"] = std::string(u8"C2C 未传输:") + std::to_string(skipped)
|
||||
+ u8" 个顶层项在目标目录中已存在(overwrite=false),全部跳过。";
|
||||
content.append(item);
|
||||
result["content"] = content;
|
||||
result["isError"] = false;
|
||||
return BuildResult(id, result);
|
||||
}
|
||||
|
||||
const uint64_t transferID = GenerateTransferID();
|
||||
if (!mcp.BeginC2CTransfer(srcId, dstId, transferID))
|
||||
return BuildError(id, -32003, "Device busy: source or destination host already has a transfer in flight");
|
||||
@@ -6452,7 +6735,7 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
|
||||
pkt.insert(pkt.end(), (const BYTE*)&hdr, (const BYTE*)&hdr + sizeof(hdr));
|
||||
pkt.insert(pkt.end(), dstDirAnsi.begin(), dstDirAnsi.end());
|
||||
pkt.push_back(0);
|
||||
for (const std::string& p : pathAnsi) {
|
||||
for (const std::string& p : sendPathAnsi) {
|
||||
pkt.insert(pkt.end(), p.begin(), p.end());
|
||||
pkt.push_back(0);
|
||||
}
|
||||
@@ -6529,6 +6812,8 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
|
||||
// receiver_ack=true 只可能来自 POSIX 接收端(Linux 客户端写完最后一包回执);
|
||||
// Windows 目标与老客户端没有回执,false 时请用 list_files 在目标主机上复核。
|
||||
sc["receiver_ack"] = r.recvAck;
|
||||
sc["skipped"] = skipped;
|
||||
sc["skip_check_failed"] = skipCheckFailed;
|
||||
result["structuredContent"] = sc;
|
||||
|
||||
Json::Value content(Json::arrayValue);
|
||||
@@ -6536,6 +6821,10 @@ std::string BuildCopyFilesC2C(const Json::Value& id, const Json::Value& args, CM
|
||||
item["type"] = "text";
|
||||
item["text"] = std::string(u8"C2C 发送完成:") + std::to_string(r.fileCount) + u8" 个文件("
|
||||
+ std::to_string(r.totalBytes) + u8" 字节),目标主机保存目录 " + dstDirUtf8
|
||||
+ (skipped ? (std::string(u8";另有 ") + std::to_string(skipped) + u8" 个已存在被跳过")
|
||||
: std::string())
|
||||
+ (skipCheckFailed ? std::string(u8";未能预检目标目录(主机忙或超时),本次按全量发送")
|
||||
: std::string())
|
||||
+ (r.recvAck ? u8"。目标端已确认写入。"
|
||||
: u8"。目标端无回执:请用 list_files 或 exec_command 在目标主机上复核。");
|
||||
content.append(item);
|
||||
@@ -8473,19 +8762,8 @@ static const size_t kBatchMaxIds = 50;
|
||||
// 所以真实上限约为 50s + 单机超时(20s)。要更紧就得把 deadline 一路传进各工具。
|
||||
static const long long kBatchDeadlineMs = 50000;
|
||||
|
||||
bool IsBatchReadOnlyTool(const std::string& t) {
|
||||
static const char* kReadOnly[] = {
|
||||
"get_host_detail", "list_processes", "list_windows", "list_services",
|
||||
"list_files", "list_registry", "get_client_log", "get_activity_history",
|
||||
"list_network_connections",
|
||||
"host_list_processes", "host_list_windows", "host_list_network_state",
|
||||
"host_list_software", "host_list_browser_history", "host_list_favorites",
|
||||
"host_list_win32_services", "host_list_driver_services",
|
||||
"host_list_scheduled_tasks", "host_get_hosts_file",
|
||||
};
|
||||
for (const char* x : kReadOnly) if (t == x) return true;
|
||||
return false;
|
||||
}
|
||||
// IsBatchReadOnlyTool 定义在 McpInternal.cpp:tools/list 要用它补 outputSchema,
|
||||
// tools/call 要用它做批量入口判定,两处必须共用同一份清单,故不再在此重复定义。
|
||||
|
||||
// 单主机分派:批量路径复用它,保证批量与单机走同一套实现。
|
||||
std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName,
|
||||
|
||||
@@ -339,6 +339,17 @@ enum ServerTlsState {
|
||||
TLS_Ready = 3, // TLS 握手完成,收包解密 / 发包加密
|
||||
};
|
||||
class ServerTlsSession; // 定义见 ServerTlsSession.h(避免把 Schannel 头拖进本文件)
|
||||
class ServerWsSession; // 定义见 ServerWsSession.h(WebSocket 传输层)
|
||||
|
||||
// 每连接 WebSocket 状态(与 Go 服务端 wsConn 同构,见 docs/WebSocket_Transport_Design.md)。
|
||||
// 明文与 TLS 设备都可能升级成 WS:首包是 "GET " 即按 HTTP Upgrade 处理;TLS 设备在
|
||||
// 握手完成后的首个明文分片里再看这一眼。
|
||||
enum ServerWsState {
|
||||
WS_Undecided = 0, // 还没见到首个应用字节(TLS 连接在握手完成后才可能判定)
|
||||
WS_None = 1, // 已判定为普通设备(非 WebSocket)
|
||||
WS_Handshaking = 2, // 升级握手进行中,握手线程独占 socket
|
||||
WS_Ready = 3, // 升级完成,收包解帧 / 发包加帧
|
||||
};
|
||||
|
||||
typedef class CONTEXT_OBJECT : public context
|
||||
{
|
||||
@@ -353,6 +364,7 @@ public:
|
||||
FreeCompressBuffer();
|
||||
FreeSendCompressBuffer();
|
||||
FreeTls();
|
||||
FreeWs();
|
||||
if (Zcctx) {
|
||||
ZSTD_freeCCtx(Zcctx);
|
||||
Zcctx = nullptr;
|
||||
@@ -414,6 +426,14 @@ public:
|
||||
ServerTlsSession* tls = nullptr; // 每连接 TLS 会话(握手线程独占→就绪后共用)
|
||||
std::vector<BYTE> tlsPreClassify; // 分类前缓冲的首批字节(嗅探 ClientHello 头)
|
||||
|
||||
// ---- WebSocket 传输层状态(分层在 TLS 之上:WSS = TLS 里的 WS)----
|
||||
std::atomic<int> wsState{ WS_Undecided }; // ServerWsState
|
||||
ServerWsSession* ws = nullptr; // 每连接 WS 会话(升级线程独占→就绪后共用)
|
||||
// WS 升级前的首包缓冲(判定 "GET " 用)。与 tlsPreClassify 刻意分开:两者服务于不同的
|
||||
// 状态机,此前串行复用同一个 vector(TLS 判定完 move 走再 clear,WS 又塞回来),字段名
|
||||
// 与用途对不上,排查时容易误读。两条路径仍按先后串行,互不重叠。
|
||||
std::vector<BYTE> wsPreClassify;
|
||||
|
||||
// 子连接身份校验:客户端发 TOKEN_CONN_AUTH 通过验证后置位。
|
||||
// 主连接(走 TOKEN_LOGIN 流程)不参与此机制。当前阶段宽容(未通过也接受),
|
||||
// 仅作为标记供后续命令处理 / 未来收紧策略使用。
|
||||
@@ -520,8 +540,15 @@ public:
|
||||
// 释放每连接 TLS 会话。定义在 ServerTlsSession.cpp(需 ServerTlsSession 完整类型才能 delete)。
|
||||
void FreeTls();
|
||||
|
||||
// 释放每连接 WebSocket 会话。定义在 ServerWsSession.cpp(同上)。
|
||||
void FreeWs();
|
||||
|
||||
std::string GetProtocol() const override
|
||||
{
|
||||
const int ws = wsState.load(std::memory_order_acquire);
|
||||
if (ws == WS_Ready || ws == WS_Handshaking) {
|
||||
return tlsState.load(std::memory_order_acquire) == TLS_Ready ? "WSS" : "WS";
|
||||
}
|
||||
return Parser.m_Masker && Parser.m_Masker->GetMaskType() == MaskTypeNone ? "TCP" : "HTTP";
|
||||
}
|
||||
int GetServerPort() const override
|
||||
@@ -568,6 +595,10 @@ public:
|
||||
FreeTls();
|
||||
tlsState.store(TLS_Unclassified, std::memory_order_release);
|
||||
tlsPreClassify.clear();
|
||||
// 复用对象池时重置 WebSocket 状态:释放旧会话、回到未判定、清空首包缓冲。
|
||||
FreeWs();
|
||||
wsState.store(WS_Undecided, std::memory_order_release);
|
||||
wsPreClassify.clear();
|
||||
// 复用对象池时清空发送进行中标志,避免上次连接残留的 bSendPending 抑制新连接的发送。
|
||||
bSendPending = false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,481 @@
|
||||
// ServerWsSession.cpp — 设备端口 WebSocket 传输层(服务端侧)实现
|
||||
//
|
||||
// 语义对齐 Go 服务端 server/go/server/ws.go:
|
||||
// * 升级请求逐行解析,头部总量上限 8 KiB(对端可控,不能无上限缓冲);
|
||||
// * 只接受 Upgrade: websocket + Connection: upgrade(逗号分隔、大小写不敏感);
|
||||
// * Sec-WebSocket-Accept = base64(SHA1(key + GUID));
|
||||
// * 客户端帧通常带掩码,解帧时按 4 字节掩码异或;服务端发帧一律不加掩码;
|
||||
// * 控制帧(close/ping/pong)必须在数据帧之间处理,且载荷 ≤125 字节;
|
||||
// * 只有直接对端是回环地址时才相信 X-Forwarded-For / X-Real-IP,取 XFF 的最后一项
|
||||
// (反代追加自己看到的地址,客户端预置的前缀因此无效)。
|
||||
#include "StdAfx.h"
|
||||
#include "ServerWsSession.h"
|
||||
#include "ServerTlsSession.h"
|
||||
#include "Server.h" // CONTEXT_OBJECT::FreeWs()
|
||||
|
||||
#include <bcrypt.h>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#pragma comment(lib, "bcrypt.lib")
|
||||
|
||||
namespace {
|
||||
|
||||
// RFC 6455 规定的握手魔数,accept = base64(sha1(key + GUID))
|
||||
const char kWsMagicGUID[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
// 握手请求头上限:客户端可控,必须有上限(与 Go 的 wsMaxHandshakeBytes 同为 8 KiB)
|
||||
const size_t kMaxHandshakeBytes = 8192;
|
||||
|
||||
// 升级期间单次同步 I/O 的等待上限(与握手线程设的 SO_RCVTIMEO/SO_SNDTIMEO 一致)
|
||||
const int kIoTimeoutMs = 15000;
|
||||
|
||||
// 单帧载荷上限:屏幕/文件分块远小于此值;超过即视为协议错误,避免长度字段撑爆内存
|
||||
const long long kMaxFramePayload = 256LL * 1024 * 1024;
|
||||
|
||||
const BYTE kBase64Table[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
std::string Base64Encode(const BYTE* data, size_t len)
|
||||
{
|
||||
std::string out;
|
||||
out.reserve(((len + 2) / 3) * 4);
|
||||
for (size_t i = 0; i < len; i += 3) {
|
||||
unsigned v = (unsigned)data[i] << 16;
|
||||
if (i + 1 < len) v |= (unsigned)data[i + 1] << 8;
|
||||
if (i + 2 < len) v |= data[i + 2];
|
||||
out.push_back((char)kBase64Table[(v >> 18) & 0x3F]);
|
||||
out.push_back((char)kBase64Table[(v >> 12) & 0x3F]);
|
||||
out.push_back(i + 1 < len ? (char)kBase64Table[(v >> 6) & 0x3F] : '=');
|
||||
out.push_back(i + 2 < len ? (char)kBase64Table[v & 0x3F] : '=');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool Sha1(const BYTE* data, size_t len, BYTE out[20])
|
||||
{
|
||||
BCRYPT_ALG_HANDLE alg = NULL;
|
||||
if (BCryptOpenAlgorithmProvider(&alg, BCRYPT_SHA1_ALGORITHM, NULL, 0) != 0) {
|
||||
return false;
|
||||
}
|
||||
bool ok = false;
|
||||
DWORD objLen = 0, got = 0;
|
||||
if (BCryptGetProperty(alg, BCRYPT_OBJECT_LENGTH, (PUCHAR)&objLen, sizeof(objLen), &got, 0) == 0) {
|
||||
std::vector<BYTE> obj(objLen);
|
||||
BCRYPT_HASH_HANDLE h = NULL;
|
||||
if (BCryptCreateHash(alg, &h, obj.data(), objLen, NULL, 0, 0) == 0) {
|
||||
ok = BCryptHashData(h, (PUCHAR)data, (ULONG)len, 0) == 0 &&
|
||||
BCryptFinishHash(h, out, 20, 0) == 0;
|
||||
BCryptDestroyHash(h);
|
||||
}
|
||||
}
|
||||
BCryptCloseAlgorithmProvider(alg, 0);
|
||||
return ok;
|
||||
}
|
||||
|
||||
std::string WsAcceptKey(const std::string& key)
|
||||
{
|
||||
std::string material = key + kWsMagicGUID;
|
||||
BYTE digest[20] = { 0 };
|
||||
if (!Sha1((const BYTE*)material.data(), material.size(), digest)) {
|
||||
return std::string();
|
||||
}
|
||||
return Base64Encode(digest, sizeof(digest));
|
||||
}
|
||||
|
||||
std::string TrimWs(const std::string& s)
|
||||
{
|
||||
size_t b = 0, e = s.size();
|
||||
while (b < e && (s[b] == ' ' || s[b] == '\t' || s[b] == '\r' || s[b] == '\n')) b++;
|
||||
while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t' || s[e - 1] == '\r' || s[e - 1] == '\n')) e--;
|
||||
return s.substr(b, e - b);
|
||||
}
|
||||
|
||||
std::string ToLowerAscii(const std::string& s)
|
||||
{
|
||||
std::string out = s;
|
||||
for (size_t i = 0; i < out.size(); i++) {
|
||||
if (out[i] >= 'A' && out[i] <= 'Z') out[i] = (char)(out[i] - 'A' + 'a');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 逗号分隔的头值里是否含 token(大小写不敏感),用于 Connection: keep-alive, Upgrade
|
||||
bool HeaderHasToken(const std::string& value, const char* token)
|
||||
{
|
||||
size_t start = 0;
|
||||
while (start <= value.size()) {
|
||||
size_t comma = value.find(',', start);
|
||||
std::string part = TrimWs(value.substr(start, comma == std::string::npos ? std::string::npos : comma - start));
|
||||
if (ToLowerAscii(part) == token) return true;
|
||||
if (comma == std::string::npos) break;
|
||||
start = comma + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool IsIPLiteral(const std::string& s)
|
||||
{
|
||||
if (s.empty()) return false;
|
||||
IN_ADDR v4 = {};
|
||||
if (inet_pton(AF_INET, s.c_str(), &v4) == 1) return true;
|
||||
IN6_ADDR v6 = {};
|
||||
return inet_pton(AF_INET6, s.c_str(), &v6) == 1;
|
||||
}
|
||||
|
||||
// 去掉 "1.2.3.4:5678" 的端口(裸 IPv6 字面量保留原样)
|
||||
std::string StripPort(const std::string& s)
|
||||
{
|
||||
size_t colon = s.rfind(':');
|
||||
if (colon != std::string::npos && s.find(':') == colon) {
|
||||
if (IsIPLiteral(s.substr(0, colon))) return s.substr(0, colon);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// 只有回环对端才允许用转发头改写真实地址(与 Go 的默认 TrustedProxies 一致):
|
||||
// 反代与服务端同机部署时,设备连接的直接对端一定是回环地址。
|
||||
bool IsLoopbackPeer(const std::string& peer)
|
||||
{
|
||||
return peer == "::1" || peer == "::ffff:127.0.0.1" || peer.compare(0, 4, "127.") == 0;
|
||||
}
|
||||
|
||||
// 从转发头取真实地址:XFF 的最后一项优先(反代追加,客户端预置的无效),X-Real-IP 兜底。
|
||||
// 只接受 IP 字面量,避免头里塞进任意字符串当作对端标识。
|
||||
std::string PickForwardedIP(const std::string& xff, const std::string& realIp)
|
||||
{
|
||||
if (!xff.empty()) {
|
||||
size_t comma = xff.rfind(',');
|
||||
std::string last = StripPort(TrimWs(comma == std::string::npos ? xff : xff.substr(comma + 1)));
|
||||
if (IsIPLiteral(last)) return last;
|
||||
}
|
||||
std::string ip = StripPort(TrimWs(realIp));
|
||||
return IsIPLiteral(ip) ? ip : std::string();
|
||||
}
|
||||
|
||||
void AppendFrame(std::vector<BYTE>& out, BYTE opcode, const BYTE* payload, int len)
|
||||
{
|
||||
out.push_back((BYTE)(0x80 | opcode)); // FIN + opcode,服务端帧不加掩码
|
||||
if (len < 126) {
|
||||
out.push_back((BYTE)len);
|
||||
} else if (len <= 0xFFFF) {
|
||||
out.push_back(126);
|
||||
out.push_back((BYTE)((len >> 8) & 0xFF));
|
||||
out.push_back((BYTE)(len & 0xFF));
|
||||
} else {
|
||||
out.push_back(127);
|
||||
unsigned long long v = (unsigned long long)len;
|
||||
for (int i = 7; i >= 0; i--) {
|
||||
out.push_back((BYTE)((v >> (8 * i)) & 0xFF));
|
||||
}
|
||||
}
|
||||
if (len > 0) {
|
||||
out.insert(out.end(), payload, payload + len);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// 升级线程在 IOCP 的子套接字上做同步 I/O。该套接字可能是非阻塞的(监听套接字经
|
||||
// WSAEventSelect 置为非阻塞后,accept 出的子套接字继承非阻塞态;线程里 FIONBIO=0 会以
|
||||
// WSAEINVAL 失败)。故 recv/send 遇 WSAEWOULDBLOCK 时用 select 等可读/可写再重试,
|
||||
// 而不是当致命错误——否则「客户端请求头还没到齐」会被误判为升级失败。与
|
||||
// ServerTlsSession 的 WaitSocketReady 同一策略。
|
||||
bool WaitSocketReady(SOCKET sock, bool forRead, int timeoutMs)
|
||||
{
|
||||
fd_set fds;
|
||||
FD_ZERO(&fds);
|
||||
FD_SET(sock, &fds);
|
||||
timeval tv;
|
||||
tv.tv_sec = timeoutMs / 1000;
|
||||
tv.tv_usec = (timeoutMs % 1000) * 1000;
|
||||
return select(0, forRead ? &fds : NULL, forRead ? NULL : &fds, NULL, &tv) > 0;
|
||||
}
|
||||
|
||||
bool ServerWsSession::ReadByte(BYTE& b, std::string* err)
|
||||
{
|
||||
for (;;) {
|
||||
if (!m_stash.empty()) {
|
||||
b = m_stash.front();
|
||||
m_stash.erase(m_stash.begin());
|
||||
return true;
|
||||
}
|
||||
if (m_tls == NULL) {
|
||||
int n = ::recv(m_sock, (char*)&b, 1, 0);
|
||||
if (n == 1) return true;
|
||||
if (n == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) {
|
||||
if (WaitSocketReady(m_sock, true, kIoTimeoutMs)) continue;
|
||||
if (err) *err = "timeout during upgrade";
|
||||
return false;
|
||||
}
|
||||
if (err) *err = (n == 0) ? "connection closed during upgrade" : "recv failed during upgrade";
|
||||
return false;
|
||||
}
|
||||
// WSS:收密文、解密,只消费到头结束为止;多读出来的明文留给 pending
|
||||
BYTE raw[4096];
|
||||
int n = ::recv(m_sock, (char*)raw, (int)sizeof(raw), 0);
|
||||
if (n == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) {
|
||||
if (WaitSocketReady(m_sock, true, kIoTimeoutMs)) continue;
|
||||
if (err) *err = "TLS timeout during upgrade";
|
||||
return false;
|
||||
}
|
||||
if (n <= 0) {
|
||||
if (err) *err = (n == 0) ? "TLS connection closed during upgrade" : "TLS recv failed during upgrade";
|
||||
return false;
|
||||
}
|
||||
std::vector<BYTE> plain;
|
||||
if (m_tls->Decrypt(raw, n, plain) < 0) {
|
||||
if (err) *err = "TLS decrypt failed during upgrade";
|
||||
return false;
|
||||
}
|
||||
m_stash.swap(plain); // 可能为空(这一批只是握手记录),循环再收
|
||||
}
|
||||
}
|
||||
|
||||
bool ServerWsSession::WriteWire(const BYTE* data, int len)
|
||||
{
|
||||
std::vector<BYTE> wire;
|
||||
const BYTE* p = data;
|
||||
if (m_tls) {
|
||||
if (m_tls->Encrypt(data, len, wire) != len) return false;
|
||||
p = wire.data();
|
||||
len = (int)wire.size();
|
||||
}
|
||||
int sent = 0;
|
||||
while (sent < len) {
|
||||
int n = ::send(m_sock, (const char*)p + sent, len - sent, 0);
|
||||
if (n == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK) {
|
||||
if (!WaitSocketReady(m_sock, false, kIoTimeoutMs)) return false;
|
||||
continue; // 非阻塞套接字发送缓冲满:等可写后重试
|
||||
}
|
||||
if (n <= 0) return false;
|
||||
sent += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ServerWsSession::Handshake(SOCKET sock, ServerTlsSession* tls, const std::vector<BYTE>& initial,
|
||||
std::vector<BYTE>& pending, const std::string& peer, std::string* err)
|
||||
{
|
||||
m_sock = sock;
|
||||
m_tls = tls;
|
||||
m_open = false;
|
||||
m_stash = initial;
|
||||
m_forwardedIP.clear();
|
||||
|
||||
std::string head;
|
||||
for (;;) {
|
||||
if (head.size() > kMaxHandshakeBytes) {
|
||||
if (err) *err = "upgrade head too large";
|
||||
return false;
|
||||
}
|
||||
BYTE b = 0;
|
||||
if (!ReadByte(b, err)) return false;
|
||||
head.push_back((char)b);
|
||||
if (head.size() >= 4 && head.compare(head.size() - 4, 4, "\r\n\r\n") == 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 解析请求行与头 ----
|
||||
std::string path, upgrade, connection, key, xff, realIp;
|
||||
size_t pos = 0;
|
||||
bool firstLine = true;
|
||||
while (pos < head.size()) {
|
||||
size_t eol = head.find("\r\n", pos);
|
||||
if (eol == std::string::npos) break; // 只有结尾的 \r\n\r\n
|
||||
std::string line = head.substr(pos, eol - pos);
|
||||
pos = eol + 2;
|
||||
if (line.empty()) break;
|
||||
if (firstLine) {
|
||||
firstLine = false;
|
||||
// "GET <path> HTTP/1.1"
|
||||
size_t sp1 = line.find(' ');
|
||||
size_t sp2 = line.rfind(' ');
|
||||
if (sp1 == std::string::npos || sp2 == sp1) {
|
||||
if (err) *err = "malformed request line";
|
||||
return false;
|
||||
}
|
||||
std::string method = line.substr(0, sp1);
|
||||
std::string version = line.substr(sp2 + 1);
|
||||
if (method != "GET" || version.compare(0, 7, "HTTP/1.") != 0) {
|
||||
if (err) *err = "not a WebSocket upgrade request";
|
||||
return false;
|
||||
}
|
||||
path = line.substr(sp1 + 1, sp2 - sp1 - 1);
|
||||
size_t q = path.find('?');
|
||||
if (q != std::string::npos) path = path.substr(0, q);
|
||||
continue;
|
||||
}
|
||||
size_t colon = line.find(':');
|
||||
if (colon == std::string::npos) {
|
||||
if (err) *err = "malformed header line";
|
||||
return false;
|
||||
}
|
||||
std::string name = ToLowerAscii(TrimWs(line.substr(0, colon)));
|
||||
std::string value = TrimWs(line.substr(colon + 1));
|
||||
if (name == "upgrade") {
|
||||
upgrade = value;
|
||||
} else if (name == "connection") {
|
||||
connection += (connection.empty() ? "" : ",") + value; // 重复头按 RFC 合并
|
||||
} else if (name == "sec-websocket-key") {
|
||||
key = value;
|
||||
} else if (name == "x-forwarded-for") {
|
||||
xff = value;
|
||||
} else if (name == "x-real-ip") {
|
||||
realIp = value;
|
||||
}
|
||||
}
|
||||
|
||||
if (!HeaderHasToken(upgrade, "websocket") || !HeaderHasToken(connection, "upgrade") || key.empty()) {
|
||||
if (err) *err = "missing Upgrade/Connection/Sec-WebSocket-Key";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string accept = WsAcceptKey(key);
|
||||
if (accept.empty()) {
|
||||
if (err) *err = "SHA1 unavailable for Sec-WebSocket-Accept";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string resp =
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: " + accept + "\r\n\r\n";
|
||||
if (!WriteWire((const BYTE*)resp.data(), (int)resp.size())) {
|
||||
if (err) *err = "send upgrade response failed";
|
||||
return false;
|
||||
}
|
||||
|
||||
// 升级完成后剩余字节就是客户端紧随其后的首帧(只有 WSS 分批解密时才会出现)
|
||||
pending.assign(m_stash.begin(), m_stash.end());
|
||||
m_stash.clear();
|
||||
|
||||
if (IsLoopbackPeer(peer)) {
|
||||
m_forwardedIP = PickForwardedIP(xff, realIp);
|
||||
}
|
||||
|
||||
m_open = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
int ServerWsSession::Feed(const BYTE* wire, int len, std::vector<BYTE>& app, std::vector<BYTE>& replies)
|
||||
{
|
||||
if (!m_open) return -1;
|
||||
if (len > 0) {
|
||||
m_in.insert(m_in.end(), wire, wire + len);
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
// ---- 当前数据帧还没读完:按剩余长度切片交付(大帧不整体缓冲)----
|
||||
if (m_remaining > 0) {
|
||||
if (m_pos >= m_in.size()) break;
|
||||
size_t avail = m_in.size() - m_pos;
|
||||
size_t take = ((long long)avail < m_remaining) ? avail : (size_t)m_remaining;
|
||||
if (m_masked) {
|
||||
for (size_t i = 0; i < take; i++) {
|
||||
m_in[m_pos + i] ^= m_mask[m_maskPos];
|
||||
m_maskPos = (m_maskPos + 1) & 3;
|
||||
}
|
||||
}
|
||||
app.insert(app.end(), m_in.begin() + m_pos, m_in.begin() + m_pos + take);
|
||||
m_pos += take;
|
||||
m_remaining -= (long long)take;
|
||||
continue;
|
||||
}
|
||||
|
||||
// ---- 读帧头 ----
|
||||
size_t avail = m_in.size() - m_pos;
|
||||
if (avail < 2) break;
|
||||
const BYTE* h = m_in.data() + m_pos;
|
||||
if (h[0] & 0x70) return -1; // 未协商扩展却置了 RSV 位
|
||||
BYTE opcode = (BYTE)(h[0] & 0x0F);
|
||||
bool fin = (h[0] & 0x80) != 0;
|
||||
bool masked = (h[1] & 0x80) != 0;
|
||||
long long plen = h[1] & 0x7F;
|
||||
size_t hdrLen = 2;
|
||||
if (plen == 126) {
|
||||
if (avail < 4) break;
|
||||
plen = ((long long)h[2] << 8) | h[3];
|
||||
hdrLen = 4;
|
||||
} else if (plen == 127) {
|
||||
if (avail < 10) break;
|
||||
plen = 0;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
plen = (plen << 8) | h[2 + i];
|
||||
}
|
||||
if (plen < 0) return -1;
|
||||
hdrLen = 10;
|
||||
}
|
||||
BYTE mask[4] = { 0, 0, 0, 0 };
|
||||
if (masked) {
|
||||
if (avail < hdrLen + 4) break;
|
||||
memcpy(mask, h + hdrLen, 4);
|
||||
hdrLen += 4;
|
||||
}
|
||||
if (plen > kMaxFramePayload) return -1;
|
||||
|
||||
if (opcode >= 0x8) {
|
||||
// 控制帧:载荷 ≤125,必须整帧到齐才能处理
|
||||
if (!fin || plen > 125) return -1;
|
||||
if (avail < hdrLen + (size_t)plen) break;
|
||||
BYTE payload[125] = { 0 };
|
||||
memcpy(payload, h + hdrLen, (size_t)plen);
|
||||
if (masked) {
|
||||
for (long long i = 0; i < plen; i++) payload[i] ^= mask[i & 3];
|
||||
}
|
||||
m_pos += hdrLen + (size_t)plen;
|
||||
if (opcode == 0x8) { // close:回显后按关闭处理
|
||||
AppendFrame(replies, 0x8, payload, (int)plen);
|
||||
m_open = false;
|
||||
return -1;
|
||||
}
|
||||
if (opcode == 0x9) { // ping → pong
|
||||
AppendFrame(replies, 0xA, payload, (int)plen);
|
||||
}
|
||||
// 0xA (pong) 及其它控制帧直接忽略
|
||||
continue;
|
||||
}
|
||||
|
||||
if (opcode != 0x0 && opcode != 0x1 && opcode != 0x2) return -1;
|
||||
m_pos += hdrLen;
|
||||
m_remaining = plen;
|
||||
m_masked = masked;
|
||||
memcpy(m_mask, mask, 4);
|
||||
m_maskPos = 0;
|
||||
}
|
||||
|
||||
Compact();
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool ServerWsSession::Frame(const BYTE* app, int len, std::vector<BYTE>& wire)
|
||||
{
|
||||
if (!m_open || len < 0) return false;
|
||||
AppendFrame(wire, 0x2, app, len);
|
||||
return true;
|
||||
}
|
||||
|
||||
void ServerWsSession::Compact()
|
||||
{
|
||||
if (m_pos == 0) return;
|
||||
if (m_pos >= m_in.size()) {
|
||||
m_in.clear();
|
||||
m_pos = 0;
|
||||
} else if (m_pos >= 65536 || m_pos * 2 >= m_in.size()) {
|
||||
m_in.erase(m_in.begin(), m_in.begin() + m_pos);
|
||||
m_pos = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// 释放每连接 WS 会话(CONTEXT_OBJECT 析构 / 对象池复用时调用)。
|
||||
// 与 FreeTls 一致:调用点保证此时没有线程还在使用该会话(见 RemoveStaleContext 的
|
||||
// IoRefCount 约束;握手线程持有一枚引用)。
|
||||
void CONTEXT_OBJECT::FreeWs()
|
||||
{
|
||||
if (ws) {
|
||||
delete ws;
|
||||
ws = NULL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// ServerWsSession.h — MFC 服务端设备端口的 WebSocket 传输层
|
||||
//
|
||||
// 与 Go 服务端 server/go/server/ws.go 的 wrapWebSocket / wsConn 同构:在同一端口上
|
||||
// 与明文、TLS 设备共存,首包是 "GET " 时按 HTTP Upgrade 升级,之后把每帧载荷原样交回
|
||||
// 既有解析路径;发送方向「一次发送 = 一帧」,与 wsConn.Write 对齐。
|
||||
//
|
||||
// 与 TLS 是分层而不是并列的关系:wss = TLS 里的 WebSocket。本类不碰加密,tls 非空时
|
||||
// 所有字节都经 ServerTlsSession 加解密(顺序:应用字节 → WS 帧 → TLS 记录)。
|
||||
//
|
||||
// 线程模型:Handshake 在专用握手线程上阻塞执行(与 TlsHandshakeThreadProc 同一模式,
|
||||
// 握手期间独占 socket);握手完成后 Feed 只由 IOCP 工作线程调用(每连接同一时刻只有
|
||||
// 一个未决 WSARecv,天然串行);Frame 由发送方在 CONTEXT_OBJECT::SendLock 内调用。
|
||||
#pragma once
|
||||
|
||||
#include <WinSock2.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class ServerTlsSession;
|
||||
|
||||
class ServerWsSession
|
||||
{
|
||||
public:
|
||||
ServerWsSession() {}
|
||||
~ServerWsSession() {}
|
||||
|
||||
// 升级握手。initial 是触发判定的首批明文(以 "GET " 开头,可能只是请求头的一部分);
|
||||
// pending 返回升级完成后多读到的线缆字节(可能是客户端紧随其后的首帧),由调用方交
|
||||
// 给 Feed;peer 是直接对端地址,用于判断是否信任 X-Forwarded-For。失败返回 false 并
|
||||
// 置 err(调用方关闭连接,fail-closed)。
|
||||
bool Handshake(SOCKET sock, ServerTlsSession* tls, const std::vector<BYTE>& initial,
|
||||
std::vector<BYTE>& pending, const std::string& peer, std::string* err);
|
||||
|
||||
// 解帧:线缆字节 wire 还原成应用字节 app,产出需要写回的完整帧 replies(应答 ping、
|
||||
// 回显 close)。返回 0 正常;-1 表示协议错误或对端已关闭,调用方应关闭连接
|
||||
// (replies 仍须先发出)。
|
||||
int Feed(const BYTE* wire, int len, std::vector<BYTE>& app, std::vector<BYTE>& replies);
|
||||
|
||||
// 封装:把一段应用字节封成一帧二进制帧(服务端帧不加掩码)。
|
||||
bool Frame(const BYTE* app, int len, std::vector<BYTE>& wire);
|
||||
|
||||
// 供外部在握手/升级完成后标记连接已关闭。
|
||||
void MarkClosed() { m_open = false; }
|
||||
bool IsOpen() const { return m_open; }
|
||||
|
||||
// 代理转发的真实客户端地址(仅在直接对端是回环地址、且升级请求带了转发头时非空)。
|
||||
const std::string& ForwardedIP() const { return m_forwardedIP; }
|
||||
|
||||
private:
|
||||
bool ReadByte(BYTE& b, std::string* err);
|
||||
bool WriteWire(const BYTE* data, int len);
|
||||
void Compact();
|
||||
|
||||
SOCKET m_sock = INVALID_SOCKET;
|
||||
ServerTlsSession* m_tls = NULL;
|
||||
std::vector<BYTE> m_stash; // 已从 socket 读出、尚未消费的字节(TLS 时是明文)
|
||||
std::string m_forwardedIP;
|
||||
|
||||
std::vector<BYTE> m_in; // 尚未解完的线缆字节
|
||||
size_t m_pos = 0; // m_in 中已消费到的位置
|
||||
long long m_remaining = 0; // 当前数据帧剩余载荷
|
||||
bool m_masked = false; // 当前数据帧是否带掩码
|
||||
BYTE m_mask[4] = { 0, 0, 0, 0 };
|
||||
int m_maskPos = 0;
|
||||
bool m_open = false; // 升级完成后为 true,收到 close / 出错后为 false
|
||||
};
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
// 程序版本号 [建议格式: X.Y.Z]
|
||||
// 影响:关于对话框、标题栏
|
||||
#define BRAND_VERSION "1.4.1"
|
||||
#define BRAND_VERSION "1.4.2"
|
||||
|
||||
// 启动画面名称 [建议大写,更有 Logo 感]
|
||||
// 影响:启动画面 Logo 文字(大号艺术字体渲染)
|
||||
|
||||
@@ -104,4 +104,12 @@ public:
|
||||
if (caps.IsEmpty()) return false;
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_SCREEN_PREVIEW) != 0;
|
||||
}
|
||||
|
||||
// 检查客户端是否支持远程协议切换(COMMAND_SET_PROTO)。老客户端没有这个命令,
|
||||
// 收到也会走 default 丢弃,服务端据此把「协议切换」菜单置灰。
|
||||
bool SupportsProtoSwitch() const {
|
||||
CString caps = GetClientData(ONLINELIST_CAPABILITIES);
|
||||
if (caps.IsEmpty()) return false;
|
||||
return (strtoul(caps.GetString(), nullptr, 16) & CLIENT_CAP_PROTO_SWITCH) != 0;
|
||||
}
|
||||
};
|
||||
@@ -279,6 +279,7 @@ Web
|
||||
通用=Allgemein
|
||||
高级 (非必填项)=Erweitert (Optional)
|
||||
提示: 多个上线地址用分号分隔,99个字符以内。仅供学习和自用,严禁用于非法目的使用。=Tipp: Mehrere Adressen durch Semikolons getrennt, max. 99 Zeichen.
|
||||
提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名。=Tipp: WebSocket benoetigt einen Reverse-Proxy (z. B. nginx auf 443), der auf den Steuerungsport weiterleitet; als Adresse die Domain eintragen.
|
||||
|
||||
; ============================================
|
||||
; Service Manager
|
||||
@@ -387,6 +388,7 @@ Rar
|
||||
; ============================================
|
||||
修改备注=Notiz bearbeiten
|
||||
修改分组=Gruppe bearbeiten
|
||||
复制名称=Namen kopieren
|
||||
添加关注=Ueberwachung hinzufuegen
|
||||
客户管理=Clientverwaltung
|
||||
转移主机=Host uebertragen
|
||||
@@ -978,6 +980,23 @@ NtCreateThreadEx(shellcodeע
|
||||
; FormatL - Proxy Dialog
|
||||
; ============================================
|
||||
SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n=SOCKS-Proxy-Server: <127.0.0.1:%d>\r\n
|
||||
; Proxy mapping session log (CProxyMapDlg)
|
||||
%u 新连接\r\n=%u Neue Verbindung\r\n
|
||||
%u 返回标示 %u %u\r\n=%u Begruessung Antwort %u %u\r\n
|
||||
%u IPV4 连接 %s:%u...\r\n=%u IPv4 Verbindung %s:%u...\r\n
|
||||
%u 域名 连接 %s:%u\r\n=%u Hostname Verbindung %s:%u\r\n
|
||||
%u IPV6连接 不支持...\r\n=%u IPv6 nicht unterstuetzt...\r\n
|
||||
%u 不符要求, 断开 %u %u %u\r\n=%u Ungueltige Anfrage, Trennung %u %u %u\r\n
|
||||
%u 连接成功\r\n=%u Verbunden\r\n
|
||||
%u 连接失败\r\n=%u Verbindung fehlgeschlagen\r\n
|
||||
%u 握手超时, 断开\r\n=%u Handshake-Timeout, Trennung\r\n
|
||||
%u 握手数据过多, 断开\r\n=%u Zu viele Handshake-Daten, Trennung\r\n
|
||||
%u 本地连接断开\r\n=%u Lokale Verbindung getrennt\r\n
|
||||
%u 本地连接断开 (上行 %s, 下行 %s)\r\n=%u Lokale Verbindung getrennt (gesendet %s, empfangen %s)\r\n
|
||||
%u << 上行 %s\r\n=%u << gesendet %s\r\n
|
||||
%u >> 下行 %s\r\n=%u >> empfangen %s\r\n
|
||||
%u 客户端请求断开\r\n=%u Client fordert Trennung\r\n
|
||||
%u 下行发送失败, 断开\r\n=%u Senden an Client fehlgeschlagen, Trennung\r\n
|
||||
|
||||
; ============================================
|
||||
; _TR - Additional Dialog Init/Prompt Strings
|
||||
@@ -2092,10 +2111,22 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Zertifikat/privater Schluessel konnte nicht geladen werden; Verschluesselung ist inaktiv. Bitte Pfad und Format pruefen (PEM-Zertifikat, PKCS#8-Schluessel).
|
||||
TLS传输=TLS-Transport
|
||||
取消TLS=TLS deaktivieren
|
||||
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren?\n(Linux-Clients wechseln sofort und verbinden sich neu; Windows-Clients erst nach dem Neustart)
|
||||
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Linux-Clients wechseln sofort und verbinden sich neu; Windows-Clients erst nach dem Neustart)
|
||||
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts aktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
|
||||
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=TLS-Transport fuer die ausgewaehlten Hosts deaktivieren?\n(Clients wirken sofort und verbinden sich neu; laufende Sitzungen werden unterbrochen)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server-TLS-Zertifikat ist nicht aktiviert; TLS-Transport der Clients kann nicht umgeschaltet werden
|
||||
读取服务端 TLS 证书失败,无法下发=Server-TLS-Zertifikat konnte nicht gelesen werden; Verteilung nicht moeglich
|
||||
; ===== Protokollwechsel (Protocol Switch) =====
|
||||
协议切换=Protokollwechsel
|
||||
直连 TCP=Direktes TCP
|
||||
WS(经反向代理,明文)=WS (ueber Reverse-Proxy, Klartext)
|
||||
WSS(经反向代理,TLS)=WSS (ueber Reverse-Proxy, TLS)
|
||||
反代入口(域名:端口):=Proxy (Domain:Port):
|
||||
反向代理入口格式不正确,应为 域名:端口=Ungueltiger Reverse-Proxy-Eingang; erwartet wird Domain:Port
|
||||
服务端未启用 TLS 证书,无法切换到 WSS=Server-TLS-Zertifikat ist nicht aktiviert; Wechsel zu WSS nicht moeglich
|
||||
读取服务端 TLS 证书失败,无法切换到 WSS=Server-TLS-Zertifikat konnte nicht gelesen werden; Wechsel zu WSS nicht moeglich
|
||||
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=Einige ausgewaehlte Hosts laufen mit einem Client ohne Protokollwechsel-Unterstuetzung (neuerer Client erforderlich)
|
||||
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=Ausgewaehlte Hosts zurueck auf direktes TCP schalten?\n(Clients verbinden sich sofort neu; ist der direkte Port nicht erreichbar, fallen sie nach 5 Minuten auf den aktuellen Eingang zurueck)
|
||||
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=Transportprotokoll der ausgewaehlten Hosts umschalten?\n(Clients verbinden sich sofort neu, laufende Sitzungen werden unterbrochen; ist der neue Eingang 5 Minuten lang nicht erreichbar, wird automatisch zurueckgefallen)
|
||||
白名单=Whitelist
|
||||
确定将选中日志中的 IP 加入白名单吗?=IP aus den ausgewaehlten Log-Eintraegen zur Whitelist hinzufuegen?
|
||||
已将 %d 个 IP 加入白名单=%d IP(s) zur Whitelist hinzugefuegt
|
||||
|
||||
@@ -282,6 +282,7 @@ Web
|
||||
通用=General
|
||||
高级 (非必填项)=Advanced (Optional)
|
||||
提示: 多个上线地址用分号分隔,99个字符以内。仅供学习和自用,严禁用于非法目的使用。=Tip: Multiple addresses separated by semicolons, max 99 chars.
|
||||
提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名。=Tip: WebSocket requires a reverse proxy (e.g. nginx on 443) forwarding to the control port; enter the domain as the address.
|
||||
|
||||
; ============================================
|
||||
; Service Manager
|
||||
@@ -390,6 +391,7 @@ Rar
|
||||
; ============================================
|
||||
修改备注=Edit Note
|
||||
修改分组=Edit Group
|
||||
复制名称=Copy Name
|
||||
添加关注=Add Watch
|
||||
客户管理=Client Mgmt
|
||||
转移主机=Transfer Host
|
||||
@@ -982,6 +984,23 @@ NtCreateThreadEx(shellcodeע
|
||||
; FormatL - Proxy Dialog
|
||||
; ============================================
|
||||
SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n=SOCKS proxy server: <127.0.0.1:%d>\r\n
|
||||
; Proxy mapping session log (CProxyMapDlg)
|
||||
%u 新连接\r\n=%u New connection\r\n
|
||||
%u 返回标示 %u %u\r\n=%u Greeting reply %u %u\r\n
|
||||
%u IPV4 连接 %s:%u...\r\n=%u IPv4 connect %s:%u...\r\n
|
||||
%u 域名 连接 %s:%u\r\n=%u Hostname connect %s:%u\r\n
|
||||
%u IPV6连接 不支持...\r\n=%u IPv6 unsupported...\r\n
|
||||
%u 不符要求, 断开 %u %u %u\r\n=%u Bad request, disconnecting %u %u %u\r\n
|
||||
%u 连接成功\r\n=%u Connected\r\n
|
||||
%u 连接失败\r\n=%u Connection failed\r\n
|
||||
%u 握手超时, 断开\r\n=%u Handshake timeout, disconnecting\r\n
|
||||
%u 握手数据过多, 断开\r\n=%u Too much handshake data, disconnecting\r\n
|
||||
%u 本地连接断开\r\n=%u Local connection closed\r\n
|
||||
%u 本地连接断开 (上行 %s, 下行 %s)\r\n=%u Local connection closed (sent %s, received %s)\r\n
|
||||
%u << 上行 %s\r\n=%u << sent %s\r\n
|
||||
%u >> 下行 %s\r\n=%u >> received %s\r\n
|
||||
%u 客户端请求断开\r\n=%u Client requested disconnect\r\n
|
||||
%u 下行发送失败, 断开\r\n=%u Downlink send failed, disconnecting\r\n
|
||||
|
||||
; ============================================
|
||||
; _TR - Additional Dialog Init/Prompt Strings
|
||||
@@ -2111,8 +2130,8 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=Failed to load certificate/private key; encryption is not active. Check the file path and format (PEM certificate, PKCS#8 private key).
|
||||
TLS传输=TLS Transport
|
||||
取消TLS=Disable TLS
|
||||
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=Enable TLS transport for the selected host?\n(Linux clients switch immediately and reconnect; Windows clients apply it on next start)
|
||||
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=Disable TLS transport for the selected host?\n(Linux clients switch immediately and reconnect; Windows clients apply it on next start)
|
||||
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=Enable TLS transport for the selected host?\n(Clients apply it immediately and reconnect; any active remote session is interrupted)
|
||||
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=Disable TLS transport for the selected host?\n(Clients apply it immediately and reconnect; any active remote session is interrupted)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=Server TLS certificate is not enabled; cannot toggle client TLS transport
|
||||
读取服务端 TLS 证书失败,无法下发=Failed to read the server TLS certificate; cannot distribute
|
||||
白名单=Whitelist
|
||||
@@ -2137,3 +2156,16 @@ Y
|
||||
画面 %dx%d;上报 %s;系数为真实除以上报=Frame %dx%d; reported %s; factor: real/reported
|
||||
缩放系数需在 0.2 到 5.0 之间。=Scale factors must be between 0.2 and 5.0.
|
||||
已按 画面/上报 自动填写,可修改=Auto-filled from frame/reported; editable
|
||||
|
||||
; ===== 协议切换 (Protocol Switch) =====
|
||||
协议切换=Protocol Switch
|
||||
直连 TCP=Direct TCP
|
||||
WS(经反向代理,明文)=WS (via reverse proxy, plaintext)
|
||||
WSS(经反向代理,TLS)=WSS (via reverse proxy, TLS)
|
||||
反代入口(域名:端口):=Proxy (host:port):
|
||||
反向代理入口格式不正确,应为 域名:端口=Invalid reverse proxy entry; expected host:port
|
||||
服务端未启用 TLS 证书,无法切换到 WSS=Server TLS certificate is not enabled; cannot switch to WSS
|
||||
读取服务端 TLS 证书失败,无法切换到 WSS=Failed to read the server TLS certificate; cannot switch to WSS
|
||||
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=Some selected hosts run a client without protocol switching support (a newer client is required)
|
||||
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=Switch the selected hosts back to direct TCP?\n(Clients reconnect immediately; if the direct port stays unreachable, they revert to the current entry after 5 minutes)
|
||||
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=Switch the transport protocol for the selected hosts?\n(Clients reconnect immediately and any active remote session is interrupted; if the new entry stays unreachable for 5 minutes, the client reverts automatically)
|
||||
@@ -282,6 +282,7 @@ Web
|
||||
通用=通用
|
||||
高级 (非必填项)=進階 (非必填項)
|
||||
提示: 多个上线地址用分号分隔,99个字符以内。仅供学习和自用,严禁用于非法目的使用。=提示: 多個上線位址用分號分隔,99個字元以內。僅供學習和自用,嚴禁用於非法目的使用。
|
||||
提示: WebSocket协议需经反向代理(如nginx 443)转发到主控端口,地址填域名。=提示: WebSocket 協定需經反向代理(如 nginx 443)轉發到主控連接埠,位址請填網域。
|
||||
|
||||
; ============================================
|
||||
; Service Manager
|
||||
@@ -390,6 +391,7 @@ Rar
|
||||
; ============================================
|
||||
修改备注=修改備註
|
||||
修改分组=修改群組
|
||||
复制名称=複製名稱
|
||||
添加关注=新增關注
|
||||
客户管理=用戶管理
|
||||
转移主机=轉移主機
|
||||
@@ -980,6 +982,23 @@ NtCreateThreadEx(shellcodeע
|
||||
; FormatL - Proxy Dialog
|
||||
; ============================================
|
||||
SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n=SOCKS 代理軟體請設定伺服器為: <127.0.0.1:%d>\r\n
|
||||
; Proxy mapping session log (CProxyMapDlg)
|
||||
%u 新连接\r\n=%u 新連線\r\n
|
||||
%u 返回标示 %u %u\r\n=%u 回覆標示 %u %u\r\n
|
||||
%u IPV4 连接 %s:%u...\r\n=%u IPV4 連線 %s:%u...\r\n
|
||||
%u 域名 连接 %s:%u\r\n=%u 網域 連線 %s:%u\r\n
|
||||
%u IPV6连接 不支持...\r\n=%u IPV6連線 不支援...\r\n
|
||||
%u 不符要求, 断开 %u %u %u\r\n=%u 不符要求, 中斷 %u %u %u\r\n
|
||||
%u 连接成功\r\n=%u 連線成功\r\n
|
||||
%u 连接失败\r\n=%u 連線失敗\r\n
|
||||
%u 握手超时, 断开\r\n=%u 握手逾時, 中斷\r\n
|
||||
%u 握手数据过多, 断开\r\n=%u 握手資料過多, 中斷\r\n
|
||||
%u 本地连接断开\r\n=%u 本端連線中斷\r\n
|
||||
%u 本地连接断开 (上行 %s, 下行 %s)\r\n=%u 本端連線中斷 (上行 %s, 下行 %s)\r\n
|
||||
%u << 上行 %s\r\n=%u << 上行 %s\r\n
|
||||
%u >> 下行 %s\r\n=%u >> 下行 %s\r\n
|
||||
%u 客户端请求断开\r\n=%u 用戶端請求中斷\r\n
|
||||
%u 下行发送失败, 断开\r\n=%u 下行傳送失敗, 中斷\r\n
|
||||
|
||||
; ============================================
|
||||
; _TR - Additional Dialog Init/Prompt Strings
|
||||
@@ -2102,8 +2121,8 @@ TLS
|
||||
证书/私钥加载失败,加密功能未生效。请检查文件路径与格式(证书 PEM、私钥 PKCS#8)。=憑證/私鑰載入失敗,加密功能未生效。請檢查檔案路徑與格式(憑證 PEM、私鑰 PKCS#8)。
|
||||
TLS传输=TLS 傳輸
|
||||
取消TLS=停用 TLS
|
||||
确定对选中主机启用 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=確定對選取主機啟用 TLS 傳輸嗎?\n(Linux 用戶端立即生效並斷線重連;Windows 用戶端下次啟動生效)
|
||||
确定取消选中主机的 TLS 传输吗?\n(Linux 客户端立即生效并断线重连;Windows 客户端下次启动生效)=確定取消選取主機的 TLS 傳輸嗎?\n(Linux 用戶端立即生效並斷線重連;Windows 用戶端下次啟動生效)
|
||||
确定对选中主机启用 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=確定對選取主機啟用 TLS 傳輸嗎?\n(用戶端立即生效並斷線重連,正在進行的遠端工作階段會中斷)
|
||||
确定取消选中主机的 TLS 传输吗?\n(客户端立即生效并断线重连,正在进行的远程会话会中断)=確定取消選取主機的 TLS 傳輸嗎?\n(用戶端立即生效並斷線重連,正在進行的遠端工作階段會中斷)
|
||||
服务端未启用 TLS 证书,无法切换客户端 TLS 传输=伺服器未啟用 TLS 憑證,無法切換用戶端 TLS 傳輸
|
||||
读取服务端 TLS 证书失败,无法下发=讀取伺服器 TLS 憑證失敗,無法下發
|
||||
白名单=白名單
|
||||
@@ -2128,3 +2147,16 @@ Y
|
||||
画面 %dx%d;上报 %s;系数为真实除以上报=畫面 %dx%d;上報 %s;係數為真實除以上報
|
||||
缩放系数需在 0.2 到 5.0 之间。=縮放係數需在 0.2 到 5.0 之間。
|
||||
已按 画面/上报 自动填写,可修改=已依 畫面/上報 自動填入,可修改
|
||||
|
||||
; ===== 协议切换 (Protocol Switch) =====
|
||||
协议切换=協定切換
|
||||
直连 TCP=直連 TCP
|
||||
WS(经反向代理,明文)=WS(經反向代理,明文)
|
||||
WSS(经反向代理,TLS)=WSS(經反向代理,TLS)
|
||||
反代入口(域名:端口):=反代入口(網域:埠):
|
||||
反向代理入口格式不正确,应为 域名:端口=反向代理入口格式不正確,應為 網域:連接埠
|
||||
服务端未启用 TLS 证书,无法切换到 WSS=伺服器未啟用 TLS 憑證,無法切換到 WSS
|
||||
读取服务端 TLS 证书失败,无法切换到 WSS=讀取伺服器 TLS 憑證失敗,無法切換到 WSS
|
||||
选中的主机里有客户端版本不支持协议切换(需要新版客户端)=選取的主機中有用戶端版本不支援協定切換(需要新版用戶端)
|
||||
确定把选中主机切回直连 TCP 吗?\n(客户端立即断线重连;若直连端口不可达,5 分钟后自动回退到当前入口)=確定將選取主機切回直連 TCP 嗎?\n(用戶端立即斷線重連;若直連連接埠不可達,5 分鐘後自動回退到目前入口)
|
||||
确定切换选中主机的传输协议吗?\n(客户端立即断线重连,正在进行的远程会话会中断;新入口 5 分钟内连不上将自动回退)=確定切換選取主機的傳輸協定嗎?\n(用戶端立即斷線重連,正在進行的遠端工作階段會中斷;新入口 5 分鐘內連不上將自動回退)
|
||||
@@ -1,821 +0,0 @@
|
||||
/*
|
||||
* Copyright: JessMA Open Source (ldcsaa@gmail.com)
|
||||
*
|
||||
* Author : Bruce Liang
|
||||
* Website : https://github.com/ldcsaa
|
||||
* Project : https://github.com/ldcsaa/HP-Socket
|
||||
* Blog : http://www.cnblogs.com/ldcsaa
|
||||
* Wiki : http://www.oschina.net/p/hp-socket
|
||||
* QQ Group : 44636872, 75375912
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
/******************************************************************************
|
||||
Module: HPSocket
|
||||
|
||||
Usage:
|
||||
方法一:
|
||||
--------------------------------------------------------------------------------------
|
||||
0. 应用程序包含 HPTypeDef.h / SocketInterface.h / HPSocket.h 头文件
|
||||
1. 调用 HP_Create_Xxx() 函数创建 HPSocket 对象
|
||||
2. 使用完毕后调用 HP_Destroy_Xxx() 函数销毁 HPSocket 对象
|
||||
|
||||
方法二:
|
||||
--------------------------------------------------------------------------------------
|
||||
0. 应用程序包含 SocketInterface.h 和 HPSocket.h 头文件
|
||||
1. 创建 CXxxPtr 智能指针,通过智能指针使用 HPSocket 对象
|
||||
|
||||
Release:
|
||||
<-- 动态链接库 -->
|
||||
1. x86/HPSocket.dll - (32位/MBCS/Release)
|
||||
2. x86/HPSocket_D.dll - (32位/MBCS/DeBug)
|
||||
3. x86/HPSocket_U.dll - (32位/UNICODE/Release)
|
||||
4. x86/HPSocket_UD.dll - (32位/UNICODE/DeBug)
|
||||
5. x64/HPSocket.dll - (64位/MBCS/Release)
|
||||
6. x64/HPSocket_D.dll - (64位/MBCS/DeBug)
|
||||
7. x64/HPSocket_U.dll - (64位/UNICODE/Release)
|
||||
8. x64/HPSocket_UD.dll - (64位/UNICODE/DeBug)
|
||||
|
||||
<-- 静态链接库 -->
|
||||
!!注意!!:使用 HPSocket 静态库时,需要在工程属性中定义预处理宏 -> HPSOCKET_STATIC_LIB
|
||||
1. x86/static/HPSocket.lib - (32位/MBCS/Release)
|
||||
2. x86/static/HPSocket_D.lib - (32位/MBCS/DeBug)
|
||||
3. x86/static/HPSocket_U.lib - (32位/UNICODE/Release)
|
||||
4. x86/static/HPSocket_UD.lib - (32位/UNICODE/DeBug)
|
||||
5. x64/static/HPSocket.lib - (64位/MBCS/Release)
|
||||
6. x64/static/HPSocket_D.lib - (64位/MBCS/DeBug)
|
||||
7. x64/static/HPSocket_U.lib - (64位/UNICODE/Release)
|
||||
8. x64/static/HPSocket_UD.lib - (64位/UNICODE/DeBug)
|
||||
|
||||
******************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "SocketInterface.h"
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/****************************************************************** TCP/UDP Exports ******************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
/**************************************************/
|
||||
/************** HPSocket 对象智能指针 **************/
|
||||
|
||||
template<class T, class _Listener, class _Creator> class CHPObjectPtr
|
||||
{
|
||||
public:
|
||||
CHPObjectPtr& Reset(T* pObj = nullptr)
|
||||
{
|
||||
if(pObj != m_pObj) {
|
||||
if(m_pObj)
|
||||
_Creator::Destroy(m_pObj);
|
||||
|
||||
m_pObj = pObj;
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
CHPObjectPtr& Attach(T* pObj)
|
||||
{
|
||||
return Reset(pObj);
|
||||
}
|
||||
|
||||
T* Detach()
|
||||
{
|
||||
T* pObj = m_pObj;
|
||||
m_pObj = nullptr;
|
||||
|
||||
return pObj;
|
||||
}
|
||||
|
||||
BOOL IsValid () const
|
||||
{
|
||||
return m_pObj != nullptr ;
|
||||
}
|
||||
T* Get () const
|
||||
{
|
||||
return m_pObj ;
|
||||
}
|
||||
T* operator -> () const
|
||||
{
|
||||
return m_pObj ;
|
||||
}
|
||||
operator T* () const
|
||||
{
|
||||
return m_pObj ;
|
||||
}
|
||||
|
||||
CHPObjectPtr& operator = (T* pObj)
|
||||
{
|
||||
return Reset(pObj) ;
|
||||
}
|
||||
|
||||
public:
|
||||
CHPObjectPtr(_Listener* pListener = nullptr)
|
||||
{
|
||||
m_pObj = _Creator::Create(pListener);
|
||||
}
|
||||
|
||||
CHPObjectPtr(BOOL bCreate, _Listener* pListener = nullptr)
|
||||
{
|
||||
m_pObj = bCreate ? _Creator::Create(pListener) : nullptr;
|
||||
}
|
||||
|
||||
virtual ~CHPObjectPtr()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
private:
|
||||
CHPObjectPtr(const CHPObjectPtr&);
|
||||
CHPObjectPtr& operator = (const CHPObjectPtr&);
|
||||
|
||||
protected:
|
||||
T* m_pObj;
|
||||
};
|
||||
|
||||
/**************************************************/
|
||||
/**************** HPSocket 导出函数 ****************/
|
||||
|
||||
// 创建 ITcpServer 对象
|
||||
HPSOCKET_API ITcpServer* HP_Create_TcpServer(ITcpServerListener* pListener);
|
||||
// 创建 ITcpAgent 对象
|
||||
HPSOCKET_API ITcpAgent* HP_Create_TcpAgent(ITcpAgentListener* pListener);
|
||||
// 创建 ITcpClient 对象
|
||||
HPSOCKET_API ITcpClient* HP_Create_TcpClient(ITcpClientListener* pListener);
|
||||
// 创建 ITcpPullServer 对象
|
||||
HPSOCKET_API ITcpPullServer* HP_Create_TcpPullServer(ITcpServerListener* pListener);
|
||||
// 创建 ITcpPullAgent 对象
|
||||
HPSOCKET_API ITcpPullAgent* HP_Create_TcpPullAgent(ITcpAgentListener* pListener);
|
||||
// 创建 ITcpPullClient 对象
|
||||
HPSOCKET_API ITcpPullClient* HP_Create_TcpPullClient(ITcpClientListener* pListener);
|
||||
// 创建 ITcpPackServer 对象
|
||||
HPSOCKET_API ITcpPackServer* HP_Create_TcpPackServer(ITcpServerListener* pListener);
|
||||
// 创建 ITcpPackAgent 对象
|
||||
HPSOCKET_API ITcpPackAgent* HP_Create_TcpPackAgent(ITcpAgentListener* pListener);
|
||||
// 创建 ITcpPackClient 对象
|
||||
HPSOCKET_API ITcpPackClient* HP_Create_TcpPackClient(ITcpClientListener* pListener);
|
||||
|
||||
// 销毁 ITcpServer 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpServer(ITcpServer* pServer);
|
||||
// 销毁 ITcpAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpAgent(ITcpAgent* pAgent);
|
||||
// 销毁 ITcpClient 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpClient(ITcpClient* pClient);
|
||||
// 销毁 ITcpPullServer 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPullServer(ITcpPullServer* pServer);
|
||||
// 销毁 ITcpPullAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPullAgent(ITcpPullAgent* pAgent);
|
||||
// 销毁 ITcpPullClient 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPullClient(ITcpPullClient* pClient);
|
||||
// 销毁 ITcpPackServer 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPackServer(ITcpPackServer* pServer);
|
||||
// 销毁 ITcpPackAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPackAgent(ITcpPackAgent* pAgent);
|
||||
// 销毁 ITcpPackClient 对象
|
||||
HPSOCKET_API void HP_Destroy_TcpPackClient(ITcpPackClient* pClient);
|
||||
|
||||
#ifdef _UDP_SUPPORT
|
||||
|
||||
// 创建 IUdpServer 对象
|
||||
HPSOCKET_API IUdpServer* HP_Create_UdpServer(IUdpServerListener* pListener);
|
||||
// 创建 IUdpClient 对象
|
||||
HPSOCKET_API IUdpClient* HP_Create_UdpClient(IUdpClientListener* pListener);
|
||||
// 创建 IUdpCast 对象
|
||||
HPSOCKET_API IUdpCast* HP_Create_UdpCast(IUdpCastListener* pListener);
|
||||
// 创建 IUdpNode 对象
|
||||
HPSOCKET_API IUdpNode* HP_Create_UdpNode(IUdpNodeListener* pListener);
|
||||
// 创建 IUdpArqServer 对象
|
||||
HPSOCKET_API IUdpArqServer* HP_Create_UdpArqServer(IUdpServerListener* pListener);
|
||||
// 创建 IUdpArqClient 对象
|
||||
HPSOCKET_API IUdpArqClient* HP_Create_UdpArqClient(IUdpClientListener* pListener);
|
||||
|
||||
// 销毁 IUdpServer 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpServer(IUdpServer* pServer);
|
||||
// 销毁 IUdpClient 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpClient(IUdpClient* pClient);
|
||||
// 销毁 IUdpCast 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpCast(IUdpCast* pCast);
|
||||
// 销毁 IUdpNode 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpNode(IUdpNode* pNode);
|
||||
// 销毁 IUdpArqServer 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpArqServer(IUdpArqServer* pServer);
|
||||
// 销毁 IUdpArqClient 对象
|
||||
HPSOCKET_API void HP_Destroy_UdpArqClient(IUdpArqClient* pClient);
|
||||
|
||||
#endif
|
||||
|
||||
// ITcpServer 对象创建器
|
||||
struct TcpServer_Creator {
|
||||
static ITcpServer* Create(ITcpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpServer* pServer)
|
||||
{
|
||||
HP_Destroy_TcpServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpAgent 对象创建器
|
||||
struct TcpAgent_Creator {
|
||||
static ITcpAgent* Create(ITcpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_TcpAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpClient 对象创建器
|
||||
struct TcpClient_Creator {
|
||||
static ITcpClient* Create(ITcpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpClient* pClient)
|
||||
{
|
||||
HP_Destroy_TcpClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPullServer 对象创建器
|
||||
struct TcpPullServer_Creator {
|
||||
static ITcpPullServer* Create(ITcpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPullServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPullServer* pServer)
|
||||
{
|
||||
HP_Destroy_TcpPullServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPullAgent 对象创建器
|
||||
struct TcpPullAgent_Creator {
|
||||
static ITcpPullAgent* Create(ITcpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPullAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPullAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_TcpPullAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPullClient 对象创建器
|
||||
struct TcpPullClient_Creator {
|
||||
static ITcpPullClient* Create(ITcpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPullClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPullClient* pClient)
|
||||
{
|
||||
HP_Destroy_TcpPullClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPackServer 对象创建器
|
||||
struct TcpPackServer_Creator {
|
||||
static ITcpPackServer* Create(ITcpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPackServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPackServer* pServer)
|
||||
{
|
||||
HP_Destroy_TcpPackServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPackAgent 对象创建器
|
||||
struct TcpPackAgent_Creator {
|
||||
static ITcpPackAgent* Create(ITcpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPackAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPackAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_TcpPackAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpPackClient 对象创建器
|
||||
struct TcpPackClient_Creator {
|
||||
static ITcpPackClient* Create(ITcpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_TcpPackClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(ITcpPackClient* pClient)
|
||||
{
|
||||
HP_Destroy_TcpPackClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// ITcpServer 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpServer, ITcpServerListener, TcpServer_Creator> CTcpServerPtr;
|
||||
// ITcpAgent 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpAgent, ITcpAgentListener, TcpAgent_Creator> CTcpAgentPtr;
|
||||
// ITcpClient 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpClient, ITcpClientListener, TcpClient_Creator> CTcpClientPtr;
|
||||
// ITcpPullServer 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPullServer, ITcpServerListener, TcpPullServer_Creator> CTcpPullServerPtr;
|
||||
// ITcpPullAgent 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPullAgent, ITcpAgentListener, TcpPullAgent_Creator> CTcpPullAgentPtr;
|
||||
// ITcpPullClient 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPullClient, ITcpClientListener, TcpPullClient_Creator> CTcpPullClientPtr;
|
||||
// ITcpPackServer 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPackServer, ITcpServerListener, TcpPackServer_Creator> CTcpPackServerPtr;
|
||||
// ITcpPackAgent 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPackAgent, ITcpAgentListener, TcpPackAgent_Creator> CTcpPackAgentPtr;
|
||||
// ITcpPackClient 对象智能指针
|
||||
typedef CHPObjectPtr<ITcpPackClient, ITcpClientListener, TcpPackClient_Creator> CTcpPackClientPtr;
|
||||
|
||||
#ifdef _UDP_SUPPORT
|
||||
|
||||
// IUdpServer 对象创建器
|
||||
struct UdpServer_Creator {
|
||||
static IUdpServer* Create(IUdpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpServer* pServer)
|
||||
{
|
||||
HP_Destroy_UdpServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpClient 对象创建器
|
||||
struct UdpClient_Creator {
|
||||
static IUdpClient* Create(IUdpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpClient* pClient)
|
||||
{
|
||||
HP_Destroy_UdpClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpCast 对象创建器
|
||||
struct UdpCast_Creator {
|
||||
static IUdpCast* Create(IUdpCastListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpCast(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpCast* pCast)
|
||||
{
|
||||
HP_Destroy_UdpCast(pCast);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpNode 对象创建器
|
||||
struct UdpNode_Creator {
|
||||
static IUdpNode* Create(IUdpNodeListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpNode(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpNode* pNode)
|
||||
{
|
||||
HP_Destroy_UdpNode(pNode);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpArqServer 对象创建器
|
||||
struct UdpArqServer_Creator {
|
||||
static IUdpArqServer* Create(IUdpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpArqServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpArqServer* pServer)
|
||||
{
|
||||
HP_Destroy_UdpArqServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpArqClient 对象创建器
|
||||
struct UdpArqClient_Creator {
|
||||
static IUdpArqClient* Create(IUdpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_UdpArqClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IUdpArqClient* pClient)
|
||||
{
|
||||
HP_Destroy_UdpArqClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IUdpServer 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpServer, IUdpServerListener, UdpServer_Creator> CUdpServerPtr;
|
||||
// IUdpClient 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpClient, IUdpClientListener, UdpClient_Creator> CUdpClientPtr;
|
||||
// IUdpCast 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpCast, IUdpCastListener, UdpCast_Creator> CUdpCastPtr;
|
||||
// IUdpNode 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpNode, IUdpNodeListener, UdpNode_Creator> CUdpNodePtr;
|
||||
// IUdpArqServer 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpArqServer, IUdpServerListener, UdpArqServer_Creator> CUdpArqServerPtr;
|
||||
// IUdpArqClient 对象智能指针
|
||||
typedef CHPObjectPtr<IUdpArqClient, IUdpClientListener, UdpArqClient_Creator> CUdpArqClientPtr;
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/*************************************************************** Global Function Exports *************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
// 获取 HPSocket 版本号(4 个字节分别为:主版本号,子版本号,修正版本号,构建编号)
|
||||
HPSOCKET_API DWORD HP_GetHPSocketVersion();
|
||||
|
||||
// 获取错误描述文本
|
||||
HPSOCKET_API LPCTSTR HP_GetSocketErrorDesc(EnSocketError enCode);
|
||||
// 调用系统的 GetLastError() 方法获取系统错误代码
|
||||
HPSOCKET_API DWORD SYS_GetLastError ();
|
||||
// 调用系统的 WSAGetLastError() 方法获取系统错误代码
|
||||
HPSOCKET_API int SYS_WSAGetLastError();
|
||||
// 调用系统的 setsockopt()
|
||||
HPSOCKET_API int SYS_SetSocketOption(SOCKET sock, int level, int name, LPVOID val, int len);
|
||||
// 调用系统的 getsockopt()
|
||||
HPSOCKET_API int SYS_GetSocketOption(SOCKET sock, int level, int name, LPVOID val, int* len);
|
||||
// 调用系统的 ioctlsocket()
|
||||
HPSOCKET_API int SYS_IoctlSocket(SOCKET sock, long cmd, ULONG* arg);
|
||||
// 调用系统的 WSAIoctl()
|
||||
HPSOCKET_API int SYS_WSAIoctl(SOCKET sock, DWORD dwIoControlCode, LPVOID lpvInBuffer, DWORD cbInBuffer, LPVOID lpvOutBuffer, DWORD cbOutBuffer, LPDWORD lpcbBytesReturned);
|
||||
|
||||
// 设置 socket 选项:IPPROTO_TCP -> TCP_NODELAY
|
||||
HPSOCKET_API int SYS_SSO_NoDelay(SOCKET sock, BOOL bNoDelay);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_DONTLINGER
|
||||
HPSOCKET_API int SYS_SSO_DontLinger(SOCKET sock, BOOL bDont);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_LINGER
|
||||
HPSOCKET_API int SYS_SSO_Linger(SOCKET sock, USHORT l_onoff, USHORT l_linger);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_RCVBUF
|
||||
HPSOCKET_API int SYS_SSO_RecvBuffSize(SOCKET sock, int size);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_SNDBUF
|
||||
HPSOCKET_API int SYS_SSO_SendBuffSize(SOCKET sock, int size);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_RCVTIMEO
|
||||
HPSOCKET_API int SYS_SSO_RecvTimeOut(SOCKET sock, int ms);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_SNDTIMEO
|
||||
HPSOCKET_API int SYS_SSO_SendTimeOut(SOCKET sock, int ms);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_EXCLUSIVEADDRUSE / SO_REUSEADDR
|
||||
HPSOCKET_API int SYS_SSO_ReuseAddress(SOCKET sock, EnReuseAddressPolicy opt);
|
||||
// 设置 socket 选项:SOL_SOCKET -> SO_EXCLUSIVEADDRUSE
|
||||
HPSOCKET_API int SYS_SSO_ExclusiveAddressUse(SOCKET sock, BOOL bExclusive);
|
||||
|
||||
// 获取 SOCKET 本地地址信息
|
||||
HPSOCKET_API BOOL SYS_GetSocketLocalAddress(SOCKET socket, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
|
||||
// 获取 SOCKET 远程地址信息
|
||||
HPSOCKET_API BOOL SYS_GetSocketRemoteAddress(SOCKET socket, TCHAR lpszAddress[], int& iAddressLen, USHORT& usPort);
|
||||
|
||||
/* 枚举主机 IP 地址 */
|
||||
HPSOCKET_API BOOL SYS_EnumHostIPAddresses(LPCTSTR lpszHost, EnIPAddrType enType, LPTIPAddr** lpppIPAddr, int& iIPAddrCount);
|
||||
/* 释放 LPTIPAddr* */
|
||||
HPSOCKET_API BOOL SYS_FreeHostIPAddresses(LPTIPAddr* lppIPAddr);
|
||||
/* 检查字符串是否符合 IP 地址格式 */
|
||||
HPSOCKET_API BOOL SYS_IsIPAddress(LPCTSTR lpszAddress, EnIPAddrType* penType = nullptr);
|
||||
/* 通过主机名获取 IP 地址 */
|
||||
HPSOCKET_API BOOL SYS_GetIPAddress(LPCTSTR lpszHost, TCHAR lpszIP[], int& iIPLenth, EnIPAddrType& enType);
|
||||
|
||||
/* 64 位网络字节序转主机字节序 */
|
||||
HPSOCKET_API ULONGLONG SYS_NToH64(ULONGLONG value);
|
||||
/* 64 位主机字节序转网络字节序 */
|
||||
HPSOCKET_API ULONGLONG SYS_HToN64(ULONGLONG value);
|
||||
/* 短整型高低字节交换 */
|
||||
HPSOCKET_API USHORT SYS_SwapEndian16(USHORT value);
|
||||
/* 长整型高低字节交换 */
|
||||
HPSOCKET_API DWORD SYS_SwapEndian32(DWORD value);
|
||||
/* 检查是否小端字节序 */
|
||||
HPSOCKET_API BOOL SYS_IsLittleEndian();
|
||||
|
||||
/* 分配内存 */
|
||||
HPSOCKET_API LPBYTE SYS_Malloc(int size);
|
||||
/* 重新分配内存 */
|
||||
HPSOCKET_API LPBYTE SYS_Realloc(LPBYTE p, int size);
|
||||
/* 释放内存 */
|
||||
HPSOCKET_API VOID SYS_Free(LPBYTE p);
|
||||
/* 分配内存块 */
|
||||
HPSOCKET_API LPVOID SYS_Calloc(int number, int size);
|
||||
|
||||
// CP_XXX -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_CodePageToUnicodeEx(int iCodePage, const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> CP_XXX
|
||||
HPSOCKET_API BOOL SYS_UnicodeToCodePageEx(int iCodePage, const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// GBK -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_GbkToUnicodeEx(const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> GBK
|
||||
HPSOCKET_API BOOL SYS_UnicodeToGbkEx(const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// UTF8 -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_Utf8ToUnicodeEx(const char szSrc[], int iSrcLength, WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> UTF8
|
||||
HPSOCKET_API BOOL SYS_UnicodeToUtf8Ex(const WCHAR szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// GBK -> UTF8
|
||||
HPSOCKET_API BOOL SYS_GbkToUtf8Ex(const char szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
// UTF8 -> GBK
|
||||
HPSOCKET_API BOOL SYS_Utf8ToGbkEx(const char szSrc[], int iSrcLength, char szDest[], int& iDestLength);
|
||||
|
||||
// CP_XXX -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_CodePageToUnicode(int iCodePage, const char szSrc[], WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> CP_XXX
|
||||
HPSOCKET_API BOOL SYS_UnicodeToCodePage(int iCodePage, const WCHAR szSrc[], char szDest[], int& iDestLength);
|
||||
// GBK -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_GbkToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> GBK
|
||||
HPSOCKET_API BOOL SYS_UnicodeToGbk(const WCHAR szSrc[], char szDest[], int& iDestLength);
|
||||
// UTF8 -> UNICODE
|
||||
HPSOCKET_API BOOL SYS_Utf8ToUnicode(const char szSrc[], WCHAR szDest[], int& iDestLength);
|
||||
// UNICODE -> UTF8
|
||||
HPSOCKET_API BOOL SYS_UnicodeToUtf8(const WCHAR szSrc[], char szDest[], int& iDestLength);
|
||||
// GBK -> UTF8
|
||||
HPSOCKET_API BOOL SYS_GbkToUtf8(const char szSrc[], char szDest[], int& iDestLength);
|
||||
// UTF8 -> GBK
|
||||
HPSOCKET_API BOOL SYS_Utf8ToGbk(const char szSrc[], char szDest[], int& iDestLength);
|
||||
|
||||
// 计算 Base64 编码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessBase64EncodeBound(DWORD dwSrcLen);
|
||||
// 计算 Base64 解码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessBase64DecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
// Base64 编码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_Base64Encode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Base64 解码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_Base64Decode(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
|
||||
// 计算 URL 编码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessUrlEncodeBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
// 计算 URL 解码后长度
|
||||
HPSOCKET_API DWORD SYS_GuessUrlDecodeBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
// URL 编码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_UrlEncode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// URL 解码(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_UrlDecode(BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
|
||||
#ifdef _ZLIB_SUPPORT
|
||||
|
||||
// 普通压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
// (默认参数:iLevel -> -1,iMethod -> 8,iWindowBits -> 15,iMemLevel -> 8,iStrategy -> 0)
|
||||
HPSOCKET_API int SYS_Compress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// 高级压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iLevel -> -1,iMethod -> 8,iWindowBits -> 15,iMemLevel -> 8,iStrategy -> 0)
|
||||
HPSOCKET_API int SYS_CompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iLevel = -1, int iMethod = 8, int iWindowBits = 15, int iMemLevel = 8, int iStrategy = 0);
|
||||
// 普通解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iWindowBits -> 15)
|
||||
HPSOCKET_API int SYS_Uncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// 高级解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iWindowBits -> 15)
|
||||
HPSOCKET_API int SYS_UncompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iWindowBits = 15);
|
||||
// 推测压缩结果长度
|
||||
HPSOCKET_API DWORD SYS_GuessCompressBound(DWORD dwSrcLen, BOOL bGZip = FALSE);
|
||||
|
||||
// Gzip 压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_GZipCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Gzip 解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_GZipUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// 推测 Gzip 解压结果长度(如果返回 0 或不合理值则说明输入内容并非有效的 Gzip 格式)
|
||||
HPSOCKET_API DWORD SYS_GZipGuessUncompressBound(const BYTE* lpszSrc, DWORD dwSrcLen);
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef _BROTLI_SUPPORT
|
||||
|
||||
// Brotli 压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
// (默认参数:iQuality -> 11,iWindow -> 22,iMode -> 0)
|
||||
HPSOCKET_API int SYS_BrotliCompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Brotli 高级压缩(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
//(默认参数:iQuality -> 11,iWindow -> 22,iMode -> 0)
|
||||
HPSOCKET_API int SYS_BrotliCompressEx(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen, int iQuality = 11, int iWindow = 22, int iMode = 0);
|
||||
// Brotli 解压(返回值:0 -> 成功,-3 -> 输入数据不正确,-5 -> 输出缓冲区不足)
|
||||
HPSOCKET_API int SYS_BrotliUncompress(const BYTE* lpszSrc, DWORD dwSrcLen, BYTE* lpszDest, DWORD& dwDestLen);
|
||||
// Brotli 推测压缩结果长度
|
||||
HPSOCKET_API DWORD SYS_BrotliGuessCompressBound(DWORD dwSrcLen);
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/******************************************************************** HTTP Exports *******************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#ifdef _HTTP_SUPPORT
|
||||
|
||||
// 创建 IHttpServer 对象
|
||||
HPSOCKET_API IHttpServer* HP_Create_HttpServer(IHttpServerListener* pListener);
|
||||
// 创建 IHttpAgent 对象
|
||||
HPSOCKET_API IHttpAgent* HP_Create_HttpAgent(IHttpAgentListener* pListener);
|
||||
// 创建 IHttpClient 对象
|
||||
HPSOCKET_API IHttpClient* HP_Create_HttpClient(IHttpClientListener* pListener);
|
||||
// 创建 IHttpSyncClient 对象
|
||||
HPSOCKET_API IHttpSyncClient* HP_Create_HttpSyncClient(IHttpClientListener* pListener = nullptr);
|
||||
|
||||
// 销毁 IHttpServer 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpServer(IHttpServer* pServer);
|
||||
// 销毁 IHttpAgent 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpAgent(IHttpAgent* pAgent);
|
||||
// 销毁 IHttpClient 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpClient(IHttpClient* pClient);
|
||||
// 销毁 IHttpSyncClient 对象
|
||||
HPSOCKET_API void HP_Destroy_HttpSyncClient(IHttpSyncClient* pClient);
|
||||
|
||||
// IHttpServer 对象创建器
|
||||
struct HttpServer_Creator {
|
||||
static IHttpServer* Create(IHttpServerListener* pListener)
|
||||
{
|
||||
return HP_Create_HttpServer(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpServer* pServer)
|
||||
{
|
||||
HP_Destroy_HttpServer(pServer);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpAgent 对象创建器
|
||||
struct HttpAgent_Creator {
|
||||
static IHttpAgent* Create(IHttpAgentListener* pListener)
|
||||
{
|
||||
return HP_Create_HttpAgent(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpAgent* pAgent)
|
||||
{
|
||||
HP_Destroy_HttpAgent(pAgent);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpClient 对象创建器
|
||||
struct HttpClient_Creator {
|
||||
static IHttpClient* Create(IHttpClientListener* pListener)
|
||||
{
|
||||
return HP_Create_HttpClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpClient* pClient)
|
||||
{
|
||||
HP_Destroy_HttpClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpSyncClient 对象创建器
|
||||
struct HttpSyncClient_Creator {
|
||||
static IHttpSyncClient* Create(IHttpClientListener* pListener = nullptr)
|
||||
{
|
||||
return HP_Create_HttpSyncClient(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHttpSyncClient* pClient)
|
||||
{
|
||||
HP_Destroy_HttpSyncClient(pClient);
|
||||
}
|
||||
};
|
||||
|
||||
// IHttpServer 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpServer, IHttpServerListener, HttpServer_Creator> CHttpServerPtr;
|
||||
// IHttpAgent 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpAgent, IHttpAgentListener, HttpAgent_Creator> CHttpAgentPtr;
|
||||
// IHttpClient 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpClient, IHttpClientListener, HttpClient_Creator> CHttpClientPtr;
|
||||
// IHttpSyncClient 对象智能指针
|
||||
typedef CHPObjectPtr<IHttpSyncClient, IHttpClientListener, HttpSyncClient_Creator> CHttpSyncClientPtr;
|
||||
|
||||
/**************************************************************************/
|
||||
/*************************** HTTP Cookie 管理方法 **************************/
|
||||
|
||||
/* 从文件加载 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_LoadFromFile(LPCSTR lpszFile, BOOL bKeepExists = TRUE);
|
||||
/* 保存 Cookie 到文件 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_SaveToFile(LPCSTR lpszFile, BOOL bKeepExists = TRUE);
|
||||
/* 清理 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_ClearCookies(LPCSTR lpszDomain = nullptr, LPCSTR lpszPath = nullptr);
|
||||
/* 清理过期 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_RemoveExpiredCookies(LPCSTR lpszDomain = nullptr, LPCSTR lpszPath = nullptr);
|
||||
/* 设置 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_SetCookie(LPCSTR lpszName, LPCSTR lpszValue, LPCSTR lpszDomain, LPCSTR lpszPath, int iMaxAge = -1, BOOL bHttpOnly = FALSE, BOOL bSecure = FALSE, int enSameSite = 0, BOOL bOnlyUpdateValueIfExists = TRUE);
|
||||
/* 删除 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_DeleteCookie(LPCSTR lpszDomain, LPCSTR lpszPath, LPCSTR lpszName);
|
||||
/* 设置是否允许第三方 Cookie */
|
||||
HPSOCKET_API void HP_HttpCookie_MGR_SetEnableThirdPartyCookie(BOOL bEnableThirdPartyCookie = TRUE);
|
||||
/* 检查是否允许第三方 Cookie */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_MGR_IsEnableThirdPartyCookie();
|
||||
|
||||
/* Cookie expires 字符串转换为整数 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_HLP_ParseExpires(LPCSTR lpszExpires, __time64_t& tmExpires);
|
||||
/* 整数转换为 Cookie expires 字符串 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_HLP_MakeExpiresStr(char lpszBuff[], int& iBuffLen, __time64_t tmExpires);
|
||||
/* 生成 Cookie 字符串 */
|
||||
HPSOCKET_API BOOL HP_HttpCookie_HLP_ToString(char lpszBuff[], int& iBuffLen, LPCSTR lpszName, LPCSTR lpszValue, LPCSTR lpszDomain, LPCSTR lpszPath, int iMaxAge /*= -1*/, BOOL bHttpOnly /*= FALSE*/, BOOL bSecure /*= FALSE*/, int enSameSite /*= 0*/);
|
||||
/* 获取当前 UTC 时间 */
|
||||
HPSOCKET_API __time64_t HP_HttpCookie_HLP_CurrentUTCTime();
|
||||
/* Max-Age -> expires */
|
||||
HPSOCKET_API __time64_t HP_HttpCookie_HLP_MaxAgeToExpires(int iMaxAge);
|
||||
/* expires -> Max-Age */
|
||||
HPSOCKET_API int HP_HttpCookie_HLP_ExpiresToMaxAge(__time64_t tmExpires);
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/************************************************************* HTTP Global Function Exports **********************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** Thread Pool Exports ****************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
// 创建 IHPThreadPool 对象
|
||||
HPSOCKET_API IHPThreadPool* HP_Create_ThreadPool(IHPThreadPoolListener* pListener = nullptr);
|
||||
// 销毁 IHPThreadPool 对象
|
||||
HPSOCKET_API void HP_Destroy_ThreadPool(IHPThreadPool* pThreadPool);
|
||||
|
||||
/*
|
||||
* 名称:创建 TSocketTask 对象
|
||||
* 描述:创建任务对象,该对象最终需由 HP_Destroy_SocketTaskObj() 销毁
|
||||
*
|
||||
* 参数: fnTaskProc -- 任务处理函数
|
||||
* pSender -- 发起对象
|
||||
* dwConnID -- 连接 ID
|
||||
* pBuffer -- 数据缓冲区
|
||||
* iBuffLen -- 数据缓冲区长度
|
||||
* enBuffType -- 数据缓冲区类型(默认:TBT_COPY)
|
||||
* TBT_COPY :(深拷贝)pBuffer 复制到 TSocketTask 对象。此后 TSocketTask 对象与 pBuffer 不再有任何关联
|
||||
* -> 适用于 pBuffer 不大或 pBuffer 生命周期不受控的场景
|
||||
* TBT_REFER :(浅拷贝)pBuffer 不复制到 TSocketTask 对象,需确保 TSocketTask 对象生命周期内 pBuffer 必须有效
|
||||
* -> 适用于 pBuffer 较大或 pBuffer 可重用,并且 pBuffer 生命周期受控的场景
|
||||
* TBT_ATTACH :(附属)执行浅拷贝,但 TSocketTask 对象会获得 pBuffer 的所有权,并负责释放 pBuffer,避免多次缓冲区拷贝
|
||||
* -> 注意:pBuffer 必须由 SYS_Malloc()/SYS_Calloc() 函数分配才能使用本类型,否则可能会发生内存访问错误
|
||||
* wParam -- 自定义参数
|
||||
* lParam -- 自定义参数
|
||||
* 返回值: LPTSocketTask
|
||||
*/
|
||||
HPSOCKET_API LPTSocketTask HP_Create_SocketTaskObj(Fn_SocketTaskProc fnTaskProc, PVOID pSender, CONNID dwConnID, LPCBYTE pBuffer, INT iBuffLen, EnTaskBufferType enBuffType = TBT_COPY, WPARAM wParam = 0, LPARAM lParam = 0);
|
||||
|
||||
// 销毁 TSocketTask 对象
|
||||
HPSOCKET_API void HP_Destroy_SocketTaskObj(LPTSocketTask pTask);
|
||||
|
||||
// IHPThreadPool 对象创建器
|
||||
struct HPThreadPool_Creator {
|
||||
static IHPThreadPool* Create(IHPThreadPoolListener* pListener = nullptr)
|
||||
{
|
||||
return HP_Create_ThreadPool(pListener);
|
||||
}
|
||||
|
||||
static void Destroy(IHPThreadPool* pThreadPool)
|
||||
{
|
||||
HP_Destroy_ThreadPool(pThreadPool);
|
||||
}
|
||||
};
|
||||
|
||||
// IHPThreadPool 对象智能指针
|
||||
typedef CHPObjectPtr<IHPThreadPool, IHPThreadPoolListener, HPThreadPool_Creator> CHPThreadPoolPtr;
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/********************************************************* Compressor / Decompressor Exports *********************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
/* 销毁压缩器对象 */
|
||||
HPSOCKET_API void HP_Destroy_Compressor(IHPCompressor* pCompressor);
|
||||
/* 销毁解压器对象 */
|
||||
HPSOCKET_API void HP_Destroy_Decompressor(IHPDecompressor* pDecompressor);
|
||||
|
||||
#ifdef _ZLIB_SUPPORT
|
||||
|
||||
/* 创建 ZLib 压缩器对象 */
|
||||
HPSOCKET_API IHPCompressor* HP_Create_ZLibCompressor(Fn_CompressDataCallback fnCallback, int iWindowBits = 15, int iLevel = -1, int iMethod = 8, int iMemLevel = 8, int iStrategy = 0, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 GZip 压缩器对象 */
|
||||
HPSOCKET_API IHPCompressor* HP_Create_GZipCompressor(Fn_CompressDataCallback fnCallback, int iLevel = -1, int iMethod = 8, int iMemLevel = 8, int iStrategy = 0, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 ZLib 解压器对象 */
|
||||
HPSOCKET_API IHPDecompressor* HP_Create_ZLibDecompressor(Fn_DecompressDataCallback fnCallback, int iWindowBits = 15, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 GZip 解压器对象 */
|
||||
HPSOCKET_API IHPDecompressor* HP_Create_GZipDecompressor(Fn_DecompressDataCallback fnCallback, DWORD dwBuffSize = 16 * 1024);
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef _BROTLI_SUPPORT
|
||||
|
||||
/* 创建 Brotli 压缩器对象 */
|
||||
HPSOCKET_API IHPCompressor* HP_Create_BrotliCompressor(Fn_CompressDataCallback fnCallback, int iQuality = 11, int iWindow = 22, int iMode = 0, DWORD dwBuffSize = 16 * 1024);
|
||||
/* 创建 Brotli 解压器对象 */
|
||||
HPSOCKET_API IHPDecompressor* HP_Create_BrotliDecompressor(Fn_DecompressDataCallback fnCallback, DWORD dwBuffSize = 16 * 1024);
|
||||
|
||||
#endif
|
||||
@@ -1,571 +0,0 @@
|
||||
/*
|
||||
* Copyright: JessMA Open Source (ldcsaa@gmail.com)
|
||||
*
|
||||
* Author : Bruce Liang
|
||||
* Website : https://github.com/ldcsaa
|
||||
* Project : https://github.com/ldcsaa/HP-Socket
|
||||
* Blog : http://www.cnblogs.com/ldcsaa
|
||||
* Wiki : http://www.oschina.net/p/hp-socket
|
||||
* QQ Group : 44636872, 75375912
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
/* HP-Socket 版本号 */
|
||||
#define HP_VERSION_MAJOR 6 // 主版本号
|
||||
#define HP_VERSION_MINOR 0 // 子版本号
|
||||
#define HP_VERSION_REVISE 3 // 修正版本号
|
||||
#define HP_VERSION_BUILD 1 // 构建编号
|
||||
|
||||
//#define _UDP_DISABLED // 禁用 UDP
|
||||
//#define _SSL_DISABLED // 禁用 SSL
|
||||
//#define _HTTP_DISABLED // 禁用 HTTP
|
||||
//#define _ZLIB_DISABLED // 禁用 ZLIB
|
||||
//#define _BROTLI_DISABLED // 禁用 BROTLI
|
||||
|
||||
/* 是否启用 UDP,如果定义了 _UDP_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_UDP_DISABLED)
|
||||
#ifndef _UDP_SUPPORT
|
||||
#define _UDP_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 SSL,如果定义了 _SSL_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_SSL_DISABLED)
|
||||
#ifndef _SSL_SUPPORT
|
||||
#define _SSL_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 HTTP,如果定义了 _HTTP_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_HTTP_DISABLED)
|
||||
#ifndef _HTTP_SUPPORT
|
||||
#define _HTTP_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 ZLIB,如果定义了 _ZLIB_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_ZLIB_DISABLED)
|
||||
#ifndef _ZLIB_SUPPORT
|
||||
#define _ZLIB_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* 是否启用 BROTLI,如果定义了 _BROTLI_DISABLED 则禁用(默认:启用) */
|
||||
#if !defined(_BROTLI_DISABLED)
|
||||
#ifndef _BROTLI_SUPPORT
|
||||
#define _BROTLI_SUPPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/**************************************************/
|
||||
/********** imports / exports HPSocket4C **********/
|
||||
|
||||
#ifdef HPSOCKET_STATIC_LIB
|
||||
#define HPSOCKET_API EXTERN_C
|
||||
#else
|
||||
#ifdef HPSOCKET_EXPORTS
|
||||
#define HPSOCKET_API EXTERN_C __declspec(dllexport)
|
||||
#else
|
||||
#define HPSOCKET_API EXTERN_C __declspec(dllimport)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#define __HP_CALL __stdcall
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** Base Type Definitions **************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
typedef const BYTE* LPCBYTE, PCBYTE;
|
||||
typedef ULONG_PTR TID, THR_ID, NTHR_ID, PID, PRO_ID;
|
||||
|
||||
/************************************************************************
|
||||
名称:连接 ID 数据类型
|
||||
描述:应用程序可以把 CONNID 定义为自身需要的类型(如:ULONG / ULONGLONG)
|
||||
************************************************************************/
|
||||
typedef ULONG_PTR CONNID, HP_CONNID;
|
||||
|
||||
/************************************************************************
|
||||
名称:通信组件服务状态
|
||||
描述:应用程序可以通过通信组件的 GetState() 方法获取组件当前服务状态
|
||||
************************************************************************/
|
||||
typedef enum EnServiceState {
|
||||
SS_STARTING = 0, // 正在启动
|
||||
SS_STARTED = 1, // 已经启动
|
||||
SS_STOPPING = 2, // 正在停止
|
||||
SS_STOPPED = 3, // 已经停止
|
||||
} En_HP_ServiceState;
|
||||
|
||||
/************************************************************************
|
||||
名称:Socket 操作类型
|
||||
描述:应用程序的 OnClose() 事件中通过该参数标识是哪种操作导致的错误
|
||||
************************************************************************/
|
||||
typedef enum EnSocketOperation {
|
||||
SO_UNKNOWN = 0, // Unknown
|
||||
SO_ACCEPT = 1, // Acccept
|
||||
SO_CONNECT = 2, // Connect
|
||||
SO_SEND = 3, // Send
|
||||
SO_RECEIVE = 4, // Receive
|
||||
SO_CLOSE = 5, // Close
|
||||
} En_HP_SocketOperation;
|
||||
|
||||
/************************************************************************
|
||||
名称:事件处理结果
|
||||
描述:事件的返回值,不同的返回值会影响通信组件的后续行为
|
||||
************************************************************************/
|
||||
typedef enum EnHandleResult {
|
||||
HR_OK = 0, // 成功
|
||||
HR_IGNORE = 1, // 忽略
|
||||
HR_ERROR = 2, // 错误
|
||||
} En_HP_HandleResult;
|
||||
|
||||
/************************************************************************
|
||||
名称:数据抓取结果
|
||||
描述:数据抓取操作的返回值
|
||||
************************************************************************/
|
||||
typedef enum EnFetchResult {
|
||||
FR_OK = 0, // 成功
|
||||
FR_LENGTH_TOO_LONG = 1, // 抓取长度过大
|
||||
FR_DATA_NOT_FOUND = 2, // 找不到 ConnID 对应的数据
|
||||
} En_HP_FetchResult;
|
||||
|
||||
/************************************************************************
|
||||
名称:数据发送策略
|
||||
描述:Server 组件和 Agent 组件的数据发送策略
|
||||
|
||||
* 打包发送策略(默认) :尽量把多个发送操作的数据组合在一起发送,增加传输效率
|
||||
* 安全发送策略 :尽量把多个发送操作的数据组合在一起发送,并控制传输速度,避免缓冲区溢出
|
||||
* 直接发送策略 :对每一个发送操作都直接投递,适用于负载不高但要求实时性较高的场合
|
||||
************************************************************************/
|
||||
typedef enum EnSendPolicy {
|
||||
SP_PACK = 0, // 打包模式(默认)
|
||||
SP_SAFE = 1, // 安全模式
|
||||
SP_DIRECT = 2, // 直接模式
|
||||
} En_HP_SendPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:OnSend 事件同步策略
|
||||
描述:Server 组件和 Agent 组件的 OnSend 事件同步策略
|
||||
|
||||
* 不同步(默认) :不同步 OnSend 事件,可能同时触发 OnReceive 和 OnClose 事件
|
||||
* 同步 OnClose :只同步 OnClose 事件,可能同时触发 OnReceive 事件
|
||||
* 同步 OnReceive :(只用于 TCP 组件)同步 OnReceive 和 OnClose 事件,不可能同时触发 OnReceive 或 OnClose 事件
|
||||
************************************************************************/
|
||||
typedef enum EnOnSendSyncPolicy {
|
||||
OSSP_NONE = 0, // 不同步(默认)
|
||||
OSSP_CLOSE = 1, // 同步 OnClose
|
||||
OSSP_RECEIVE = 2, // 同步 OnReceive(只用于 TCP 组件)
|
||||
} En_HP_OnSendSyncPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:地址重用选项
|
||||
描述:通信组件底层 socket 的地址重用选项
|
||||
************************************************************************/
|
||||
typedef enum EnReuseAddressPolicy {
|
||||
RAP_NONE = 0, // 不重用
|
||||
RAP_ADDR_ONLY = 1, // 仅重用地址
|
||||
RAP_ADDR_AND_PORT = 2, // 重用地址和端口
|
||||
} En_HP_ReuseAddressPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:操作结果代码
|
||||
描述:组件 Start() / Stop() 方法执行失败时,可通过 GetLastError() 获取错误代码
|
||||
************************************************************************/
|
||||
typedef enum EnSocketError {
|
||||
SE_OK = NO_ERROR, // 成功
|
||||
SE_ILLEGAL_STATE = 1, // 当前状态不允许操作
|
||||
SE_INVALID_PARAM = 2, // 非法参数
|
||||
SE_SOCKET_CREATE = 3, // 创建 SOCKET 失败
|
||||
SE_SOCKET_BIND = 4, // 绑定 SOCKET 失败
|
||||
SE_SOCKET_PREPARE = 5, // 设置 SOCKET 失败
|
||||
SE_SOCKET_LISTEN = 6, // 监听 SOCKET 失败
|
||||
SE_CP_CREATE = 7, // 创建完成端口失败
|
||||
SE_WORKER_THREAD_CREATE = 8, // 创建工作线程失败
|
||||
SE_DETECT_THREAD_CREATE = 9, // 创建监测线程失败
|
||||
SE_SOCKE_ATTACH_TO_CP = 10, // 绑定完成端口失败
|
||||
SE_CONNECT_SERVER = 11, // 连接服务器失败
|
||||
SE_NETWORK = 12, // 网络错误
|
||||
SE_DATA_PROC = 13, // 数据处理错误
|
||||
SE_DATA_SEND = 14, // 数据发送失败
|
||||
SE_GC_START = 15, // 垃圾回收启动失败
|
||||
|
||||
/***** SSL Socket 扩展操作结果代码 *****/
|
||||
SE_SSL_ENV_NOT_READY = 101, // SSL 环境未就绪
|
||||
} En_HP_SocketError;
|
||||
|
||||
/************************************************************************
|
||||
名称:播送模式
|
||||
描述:UDP 组件的播送模式(组播或广播)
|
||||
************************************************************************/
|
||||
typedef enum EnCastMode {
|
||||
CM_UNICAST = -1, // 单播
|
||||
CM_MULTICAST = 0, // 组播
|
||||
CM_BROADCAST = 1, // 广播
|
||||
} En_HP_CastMode;
|
||||
|
||||
/************************************************************************
|
||||
名称:IP 地址类型
|
||||
描述:IP 地址类型枚举值
|
||||
************************************************************************/
|
||||
typedef enum EnIPAddrType {
|
||||
IPT_ALL = 0, // 所有
|
||||
IPT_IPV4 = 1, // IPv4
|
||||
IPT_IPV6 = 2, // IPv6
|
||||
} En_HP_IPAddrType;
|
||||
|
||||
/************************************************************************
|
||||
名称:IP 地址条目结构体
|
||||
描述:IP 地址的地址簇/地址值结构体
|
||||
************************************************************************/
|
||||
typedef struct TIPAddr {
|
||||
En_HP_IPAddrType type;
|
||||
LPCTSTR address;
|
||||
} *LPTIPAddr, HP_TIPAddr, *HP_LPTIPAddr;
|
||||
|
||||
/************************************************************************
|
||||
名称:拒绝策略
|
||||
描述:调用被拒绝后的处理策略
|
||||
************************************************************************/
|
||||
typedef enum EnRejectedPolicy {
|
||||
TRP_CALL_FAIL = 0, // 立刻返回失败
|
||||
TRP_WAIT_FOR = 1, // 等待(直到成功、超时或线程池关闭等原因导致失败)
|
||||
TRP_CALLER_RUN = 2, // 调用者线程直接执行
|
||||
} En_HP_RejectedPolicy;
|
||||
|
||||
/************************************************************************
|
||||
名称:任务缓冲区类型
|
||||
描述:TSockeTask 对象创建和销毁时,根据不同类型的缓冲区类型作不同的处理
|
||||
************************************************************************/
|
||||
typedef enum EnTaskBufferType {
|
||||
TBT_COPY = 0, // 深拷贝
|
||||
TBT_REFER = 1, // 浅拷贝
|
||||
TBT_ATTACH = 2, // 附属(不负责创建,但负责销毁)
|
||||
} En_HP_TaskBufferType;
|
||||
|
||||
/************************************************************************
|
||||
名称:任务处理函数
|
||||
描述:任务处理入口函数
|
||||
参数:pvArg -- 自定义参数
|
||||
返回值:(无)
|
||||
************************************************************************/
|
||||
typedef VOID (__HP_CALL *Fn_TaskProc)(PVOID pvArg);
|
||||
typedef Fn_TaskProc HP_Fn_TaskProc;
|
||||
|
||||
struct TSocketTask;
|
||||
|
||||
/************************************************************************
|
||||
名称:Socket 任务处理函数
|
||||
描述:Socket 任务处理入口函数
|
||||
参数:pTask -- Socket 任务结构体指针
|
||||
返回值:(无)
|
||||
************************************************************************/
|
||||
typedef VOID (__HP_CALL *Fn_SocketTaskProc)(struct TSocketTask* pTask);
|
||||
typedef Fn_SocketTaskProc HP_Fn_SocketTaskProc;
|
||||
|
||||
/************************************************************************
|
||||
名称:Socket 任务结构体
|
||||
描述:封装 Socket 任务相关数据结构
|
||||
************************************************************************/
|
||||
typedef struct TSocketTask {
|
||||
HP_Fn_SocketTaskProc fn; // 任务处理函数
|
||||
PVOID sender; // 发起对象
|
||||
CONNID connID; // 连接 ID
|
||||
LPCBYTE buf; // 数据缓冲区
|
||||
INT bufLen; // 数据缓冲区长度
|
||||
En_HP_TaskBufferType bufType; // 缓冲区类型
|
||||
WPARAM wparam; // 自定义参数
|
||||
LPARAM lparam; // 自定义参数
|
||||
} *LPTSocketTask, HP_TSocketTask, *HP_LPTSocketTask;
|
||||
|
||||
/************************************************************************
|
||||
名称:获取 HPSocket 版本号
|
||||
描述:版本号(4 个字节分别为:主版本号,子版本号,修正版本号,构建编号)
|
||||
************************************************************************/
|
||||
inline DWORD GetHPSocketVersion()
|
||||
{
|
||||
return (HP_VERSION_MAJOR << 24) | (HP_VERSION_MINOR << 16) | (HP_VERSION_REVISE << 8) | HP_VERSION_BUILD;
|
||||
}
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** SSL Type Definitions ***************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#ifdef _SSL_SUPPORT
|
||||
|
||||
/************************************************************************
|
||||
名称:SSL 工作模式
|
||||
描述:标识 SSL 的工作模式,客户端模式或服务端模式
|
||||
************************************************************************/
|
||||
typedef enum EnSSLSessionMode {
|
||||
SSL_SM_CLIENT = 0, // 客户端模式
|
||||
SSL_SM_SERVER = 1, // 服务端模式
|
||||
} En_HP_SSLSessionMode;
|
||||
|
||||
/************************************************************************
|
||||
名称:SSL 验证模式
|
||||
描述:SSL 验证模式选项,SSL_VM_PEER 可以和后面两个选项组合一起
|
||||
************************************************************************/
|
||||
typedef enum EnSSLVerifyMode {
|
||||
SSL_VM_NONE = 0x00, // SSL_VERIFY_NONE
|
||||
SSL_VM_PEER = 0x01, // SSL_VERIFY_PEER
|
||||
SSL_VM_FAIL_IF_NO_PEER_CERT = 0x02, // SSL_VERIFY_FAIL_IF_NO_PEER_CERT
|
||||
SSL_VM_CLIENT_ONCE = 0x04, // SSL_VERIFY_CLIENT_ONCE
|
||||
} En_HP_SSLVerifyMode;
|
||||
|
||||
/************************************************************************
|
||||
名称:SSL Session 信息类型
|
||||
描述:用于 GetSSLSessionInfo(),标识输出的 Session 信息类型
|
||||
************************************************************************/
|
||||
typedef enum EnSSLSessionInfo {
|
||||
SSL_SSI_MIN = 0, //
|
||||
SSL_SSI_CTX = 0, // SSL CTX (输出类型:SSL_CTX*)
|
||||
SSL_SSI_CTX_METHOD = 1, // SSL CTX Mehtod (输出类型:SSL_METHOD*)
|
||||
SSL_SSI_CTX_CIPHERS = 2, // SSL CTX Ciphers (输出类型:STACK_OF(SSL_CIPHER)*)
|
||||
SSL_SSI_CTX_CERT_STORE = 3, // SSL CTX Cert Store (输出类型:X509_STORE*)
|
||||
SSL_SSI_SERVER_NAME_TYPE = 4, // Server Name Type (输出类型:int)
|
||||
SSL_SSI_SERVER_NAME = 5, // Server Name (输出类型:LPCSTR)
|
||||
SSL_SSI_VERSION = 6, // SSL Version (输出类型:LPCSTR)
|
||||
SSL_SSI_METHOD = 7, // SSL Method (输出类型:SSL_METHOD*)
|
||||
SSL_SSI_CERT = 8, // SSL Cert (输出类型:X509*)
|
||||
SSL_SSI_PKEY = 9, // SSL Private Key (输出类型:EVP_PKEY*)
|
||||
SSL_SSI_CURRENT_CIPHER = 10, // SSL Current Cipher (输出类型:SSL_CIPHER*)
|
||||
SSL_SSI_CIPHERS = 11, // SSL Available Ciphers(输出类型:STACK_OF(SSL_CIPHER)*)
|
||||
SSL_SSI_CLIENT_CIPHERS = 12, // SSL Client Ciphers (输出类型:STACK_OF(SSL_CIPHER)*)
|
||||
SSL_SSI_PEER_CERT = 13, // SSL Peer Cert (输出类型:X509*)
|
||||
SSL_SSI_PEER_CERT_CHAIN = 14, // SSL Peer Cert Chain (输出类型:STACK_OF(X509)*)
|
||||
SSL_SSI_VERIFIED_CHAIN = 15, // SSL Verified Chain (输出类型:STACK_OF(X509)*)
|
||||
SSL_SSI_MAX = 15, //
|
||||
} En_HP_SSLSessionInfo;
|
||||
|
||||
/************************************************************************
|
||||
名称:SNI 服务名称回调函数
|
||||
描述:根据服务器名称选择 SSL 证书
|
||||
参数:
|
||||
lpszServerName -- 服务器名称(域名)
|
||||
|
||||
返回值:
|
||||
0 -- 成功,使用默认 SSL 证书索引
|
||||
正数 -- 成功,使用返回值对应的 SNI 主机证书索引
|
||||
负数 -- 失败,中断 SSL 握手
|
||||
|
||||
************************************************************************/
|
||||
typedef int (__HP_CALL *Fn_SNI_ServerNameCallback)(LPCTSTR lpszServerName, PVOID pContext);
|
||||
typedef Fn_SNI_ServerNameCallback HP_Fn_SNI_ServerNameCallback;
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/**************************************************************** HTTP Type Definitions **************************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
#ifdef _HTTP_SUPPORT
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 版本
|
||||
描述:低字节:主版本号,高字节:次版本号
|
||||
************************************************************************/
|
||||
|
||||
typedef enum EnHttpVersion {
|
||||
HV_1_0 = MAKEWORD(1, 0), // HTTP/1.0
|
||||
HV_1_1 = MAKEWORD(1, 1) // HTTP/1.1
|
||||
} En_HP_HttpVersion;
|
||||
|
||||
/************************************************************************
|
||||
名称:URL 域
|
||||
描述:HTTP 请求行中 URL 段位的域定义
|
||||
************************************************************************/
|
||||
typedef enum EnHttpUrlField {
|
||||
HUF_SCHEMA = 0, // Schema
|
||||
HUF_HOST = 1, // Host
|
||||
HUF_PORT = 2, // Port
|
||||
HUF_PATH = 3, // Path
|
||||
HUF_QUERY = 4, // Query String
|
||||
HUF_FRAGMENT = 5, // Fragment
|
||||
HUF_USERINFO = 6, // User Info
|
||||
HUF_MAX = 7, // (Field Count)
|
||||
} En_HP_HttpUrlField;
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 解析结果标识
|
||||
描述:指示 HTTP 解析器是否继续执行解析操作
|
||||
************************************************************************/
|
||||
typedef enum EnHttpParseResult {
|
||||
HPR_OK = 0, // 解析成功
|
||||
HPR_SKIP_BODY = 1, // 跳过当前请求 BODY(仅用于 OnHeadersComplete 事件)
|
||||
HPR_UPGRADE = 2, // 升级协议(仅用于 OnHeadersComplete 事件)
|
||||
HPR_ERROR = -1, // 解析错误,终止解析,断开连接
|
||||
} En_HP_HttpParseResult;
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 协议升级类型
|
||||
描述:标识 HTTP 升级为哪种协议
|
||||
************************************************************************/
|
||||
typedef enum EnHttpUpgradeType {
|
||||
HUT_NONE = 0, // 没有升级
|
||||
HUT_WEB_SOCKET = 1, // WebSocket
|
||||
HUT_HTTP_TUNNEL = 2, // HTTP 隧道
|
||||
HUT_UNKNOWN = -1, // 未知类型
|
||||
} En_HP_HttpUpgradeType;
|
||||
|
||||
/************************************************************************
|
||||
名称:HTTP 状态码
|
||||
描述:HTTP 标准状态码
|
||||
************************************************************************/
|
||||
typedef enum EnHttpStatusCode {
|
||||
HSC_CONTINUE = 100,
|
||||
HSC_SWITCHING_PROTOCOLS = 101,
|
||||
HSC_PROCESSING = 102,
|
||||
HSC_EARLY_HINTS = 103,
|
||||
HSC_RESPONSE_IS_STALE = 110,
|
||||
HSC_REVALIDATION_FAILED = 111,
|
||||
HSC_DISCONNECTED_OPERATION = 112,
|
||||
HSC_HEURISTIC_EXPIRATION = 113,
|
||||
HSC_MISCELLANEOUS_WARNING = 199,
|
||||
|
||||
HSC_OK = 200,
|
||||
HSC_CREATED = 201,
|
||||
HSC_ACCEPTED = 202,
|
||||
HSC_NON_AUTHORITATIVE_INFORMATION = 203,
|
||||
HSC_NO_CONTENT = 204,
|
||||
HSC_RESET_CONTENT = 205,
|
||||
HSC_PARTIAL_CONTENT = 206,
|
||||
HSC_MULTI_STATUS = 207,
|
||||
HSC_ALREADY_REPORTED = 208,
|
||||
HSC_TRANSFORMATION_APPLIED = 214,
|
||||
HSC_IM_USED = 226,
|
||||
HSC_MISCELLANEOUS_PERSISTENT_WARNING = 299,
|
||||
|
||||
HSC_MULTIPLE_CHOICES = 300,
|
||||
HSC_MOVED_PERMANENTLY = 301,
|
||||
HSC_MOVED_TEMPORARILY = 302,
|
||||
HSC_SEE_OTHER = 303,
|
||||
HSC_NOT_MODIFIED = 304,
|
||||
HSC_USE_PROXY = 305,
|
||||
HSC_SWITCH_PROXY = 306,
|
||||
HSC_TEMPORARY_REDIRECT = 307,
|
||||
HSC_PERMANENT_REDIRECT = 308,
|
||||
|
||||
HSC_BAD_REQUEST = 400,
|
||||
HSC_UNAUTHORIZED = 401,
|
||||
HSC_PAYMENT_REQUIRED = 402,
|
||||
HSC_FORBIDDEN = 403,
|
||||
HSC_NOT_FOUND = 404,
|
||||
HSC_METHOD_NOT_ALLOWED = 405,
|
||||
HSC_NOT_ACCEPTABLE = 406,
|
||||
HSC_PROXY_AUTHENTICATION_REQUIRED = 407,
|
||||
HSC_REQUEST_TIMEOUT = 408,
|
||||
HSC_CONFLICT = 409,
|
||||
HSC_GONE = 410,
|
||||
HSC_LENGTH_REQUIRED = 411,
|
||||
HSC_PRECONDITION_FAILED = 412,
|
||||
HSC_REQUEST_ENTITY_TOO_LARGE = 413,
|
||||
HSC_REQUEST_URI_TOO_LONG = 414,
|
||||
HSC_UNSUPPORTED_MEDIA_TYPE = 415,
|
||||
HSC_REQUESTED_RANGE_NOT_SATISFIABLE = 416,
|
||||
HSC_EXPECTATION_FAILED = 417,
|
||||
HSC_IM_A_TEAPOT = 418,
|
||||
HSC_PAGE_EXPIRED = 419,
|
||||
HSC_ENHANCE_YOUR_CALM = 420,
|
||||
HSC_MISDIRECTED_REQUEST = 421,
|
||||
HSC_UNPROCESSABLE_ENTITY = 422,
|
||||
HSC_LOCKED = 423,
|
||||
HSC_FAILED_DEPENDENCY = 424,
|
||||
HSC_UNORDERED_COLLECTION = 425,
|
||||
HSC_UPGRADE_REQUIRED = 426,
|
||||
HSC_PRECONDITION_REQUIRED = 428,
|
||||
HSC_TOO_MANY_REQUESTS = 429,
|
||||
HSC_REQUEST_HEADER_FIELDS_TOO_LARGE_UNOFFICIAL = 430,
|
||||
HSC_REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
|
||||
HSC_LOGIN_TIMEOUT = 440,
|
||||
HSC_NO_RESPONSE = 444,
|
||||
HSC_RETRY_WITH = 449,
|
||||
HSC_BLOCKED_BY_PARENTAL_CONTROL = 450,
|
||||
HSC_UNAVAILABLE_FOR_LEGAL_REASONS = 451,
|
||||
HSC_CLIENT_CLOSED_LOAD_BALANCED_REQUEST = 460,
|
||||
HSC_INVALID_X_FORWARDED_FOR = 463,
|
||||
HSC_REQUEST_HEADER_TOO_LARGE = 494,
|
||||
HSC_SSL_CERTIFICATE_ERROR = 495,
|
||||
HSC_SSL_CERTIFICATE_REQUIRED = 496,
|
||||
HSC_HTTP_REQUEST_SENT_TO_HTTPS_PORT = 497,
|
||||
HSC_INVALID_TOKEN = 498,
|
||||
HSC_CLIENT_CLOSED_REQUEST = 499,
|
||||
|
||||
HSC_INTERNAL_SERVER_ERROR = 500,
|
||||
HSC_NOT_IMPLEMENTED = 501,
|
||||
HSC_BAD_GATEWAY = 502,
|
||||
HSC_SERVICE_UNAVAILABLE = 503,
|
||||
HSC_GATEWAY_TIMEOUT = 504,
|
||||
HSC_HTTP_VERSION_NOT_SUPPORTED = 505,
|
||||
HSC_VARIANT_ALSO_NEGOTIATES = 506,
|
||||
HSC_INSUFFICIENT_STORAGE = 507,
|
||||
HSC_LOOP_DETECTED = 508,
|
||||
HSC_BANDWIDTH_LIMIT_EXCEEDED = 509,
|
||||
HSC_NOT_EXTENDED = 510,
|
||||
HSC_NETWORK_AUTHENTICATION_REQUIRED = 511,
|
||||
HSC_WEB_SERVER_UNKNOWN_ERROR = 520,
|
||||
HSC_WEB_SERVER_IS_DOWN = 521,
|
||||
HSC_CONNECTION_TIMEOUT = 522,
|
||||
HSC_ORIGIN_IS_UNREACHABLE = 523,
|
||||
HSC_TIMEOUT_OCCURED = 524,
|
||||
HSC_SSL_HANDSHAKE_FAILED = 525,
|
||||
HSC_INVALID_SSL_CERTIFICATE = 526,
|
||||
HSC_RAILGUN_ERROR = 527,
|
||||
HSC_SITE_IS_OVERLOADED = 529,
|
||||
HSC_SITE_IS_FROZEN = 530,
|
||||
HSC_IDENTITY_PROVIDER_AUTHENTICATION_ERROR = 561,
|
||||
HSC_NETWORK_READ_TIMEOUT = 598,
|
||||
HSC_NETWORK_CONNECT_TIMEOUT = 599,
|
||||
|
||||
HSC_UNPARSEABLE_RESPONSE_HEADERS = 600
|
||||
} En_HP_HttpStatusCode;
|
||||
|
||||
/************************************************************************
|
||||
名称:Name/Value 结构体
|
||||
描述:字符串名值对结构体
|
||||
************************************************************************/
|
||||
typedef struct TNVPair {
|
||||
LPCSTR name;
|
||||
LPCSTR value;
|
||||
} HP_TNVPair,
|
||||
TParam, HP_TParam, *LPPARAM, *HP_LPPARAM,
|
||||
THeader, HP_THeader, *LPHEADER, *HP_LPHEADER,
|
||||
TCookie, HP_TCookie, *LPCOOKIE, *HP_LPCOOKIE;
|
||||
|
||||
#endif
|
||||
|
||||
/*****************************************************************************************************************************************************/
|
||||
/********************************************************** Compress / Decompress Definitions ********************************************************/
|
||||
/*****************************************************************************************************************************************************/
|
||||
|
||||
/************************************************************************
|
||||
名称:数据回调函数
|
||||
描述:回调处理过程中产生的数据输出
|
||||
参数:
|
||||
pData -- 数据缓冲区
|
||||
iLength -- 数据长度
|
||||
pContext -- 回调上下文
|
||||
|
||||
返回值:
|
||||
TRUE -- 成功
|
||||
FALSE -- 失败
|
||||
|
||||
************************************************************************/
|
||||
typedef BOOL (__HP_CALL *Fn_DataCallback)(const BYTE* pData, int iLength, PVOID pContext);
|
||||
typedef Fn_DataCallback Fn_CompressDataCallback;
|
||||
typedef Fn_DataCallback Fn_DecompressDataCallback;
|
||||
typedef Fn_DataCallback HP_Fn_DataCallback;
|
||||
typedef Fn_DataCallback HP_Fn_CompressDataCallback;
|
||||
typedef Fn_DataCallback HP_Fn_DecompressDataCallback;
|
||||
@@ -1,221 +1,306 @@
|
||||
#include "stdafx.h"
|
||||
#include "ProxyConnectServer.h"
|
||||
|
||||
#define MAX_SEND_BUFFER 65535 // 最大发送数据长度 1024*64
|
||||
#define MAX_RECV_BUFFER 65535 // 最大接收数据长度
|
||||
#include <chrono>
|
||||
|
||||
CProxyConnectServer::CProxyConnectServer(void) :m_TcpServer(this)
|
||||
#define PROXY_RECV_CHUNK (16 * 1024) // 单次 recv 的上限
|
||||
#define PROXY_POLL_MS 200 // select 轮询周期,决定 Shutdown/Disconnect 的响应时延
|
||||
#define PROXY_SEND_TIMEOUT_MS 5000 // 向本机连接发送的超时,避免卡住调用方线程
|
||||
|
||||
CProxyConnectServer::CProxyConnectServer()
|
||||
{
|
||||
Mprintf("CProxyConnectServer\r\n");
|
||||
m_bIsRun = TRUE;
|
||||
m_dwIndex = 0;
|
||||
memset(m_IDs, 0, sizeof(m_IDs));
|
||||
}
|
||||
|
||||
|
||||
CProxyConnectServer::~CProxyConnectServer(void)
|
||||
CProxyConnectServer::~CProxyConnectServer()
|
||||
{
|
||||
if (m_TcpServer->GetState() != SS_STOPPED)
|
||||
m_TcpServer->Stop();
|
||||
while (m_TcpServer->GetState() != SS_STOPPED) {
|
||||
Sleep(300);
|
||||
}
|
||||
Shutdown();
|
||||
Mprintf("~CProxyConnectServer\r\n");
|
||||
}
|
||||
|
||||
BOOL CProxyConnectServer::Initialize(NOTIFYPROC pNotifyProc, void*user, int nMaxConnections, int nPort)
|
||||
BOOL CProxyConnectServer::SetSocketOptions(SOCKET s) const
|
||||
{
|
||||
m_nMaxConnection = nMaxConnections;
|
||||
m_TcpServer->SetMaxConnectionCount(nMaxConnections);
|
||||
m_TcpServer->SetSendPolicy(SP_DIRECT);
|
||||
m_TcpServer->SetNoDelay(TRUE);
|
||||
m_pNotifyProc = pNotifyProc;
|
||||
m_pUser = user;
|
||||
m_nPort = nPort;
|
||||
m_bStop = FALSE;
|
||||
return m_TcpServer->Start(_T("0.0.0.0"), nPort);
|
||||
BOOL bNoDelay = TRUE;
|
||||
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (const char*)&bNoDelay, sizeof(bNoDelay));
|
||||
|
||||
DWORD dwSendTimeout = PROXY_SEND_TIMEOUT_MS;
|
||||
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (const char*)&dwSendTimeout, sizeof(dwSendTimeout));
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
EnHandleResult CProxyConnectServer::OnPrepareListen(ITcpServer* pSender, SOCKET soListen)
|
||||
BOOL CProxyConnectServer::Initialize(PROXYNOTIFYPROC pNotifyProc, PROXYCANRECVPROC pCanRecvProc,
|
||||
void* pUser, int nMaxConnections, int nPort)
|
||||
{
|
||||
SYS_SSO_SendBuffSize(soListen, MAX_SEND_BUFFER);
|
||||
SYS_SSO_RecvBuffSize(soListen, MAX_RECV_BUFFER);
|
||||
return HR_OK;
|
||||
}
|
||||
|
||||
EnHandleResult CProxyConnectServer::OnAccept(ITcpServer* pSender, CONNID dwConnID, UINT_PTR soClient)
|
||||
{
|
||||
if (!m_bIsRun)return HR_ERROR;
|
||||
|
||||
ClientContext* pContext = NULL;
|
||||
{
|
||||
m_Locker.lock();
|
||||
if (!m_listFreePool.IsEmpty()) {
|
||||
pContext = m_listFreePool.RemoveHead();
|
||||
} else {
|
||||
pContext = new(std::nothrow) ClientContext;
|
||||
}
|
||||
m_Locker.unlock();
|
||||
}
|
||||
if (pContext == NULL)
|
||||
return HR_ERROR;
|
||||
|
||||
pContext->InitMember(dwConnID, nullptr);
|
||||
pContext->m_Socket = dwConnID;
|
||||
char szAddress[64] = {};
|
||||
int iAddressLen = sizeof(szAddress);
|
||||
USHORT usPort = 0;
|
||||
pSender->GetRemoteAddress(dwConnID, szAddress, iAddressLen, usPort);
|
||||
Mprintf("CProxyConnectServer: new connection %s:%d\n", szAddress, usPort);
|
||||
pContext->ID = dwConnID;
|
||||
m_TcpServer->SetConnectionExtra(dwConnID, pContext);
|
||||
m_pNotifyProc(m_pUser, pContext, NC_CLIENT_CONNECT);
|
||||
return HR_OK;
|
||||
}
|
||||
|
||||
EnHandleResult CProxyConnectServer::OnSend(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength)
|
||||
{
|
||||
return HR_OK;
|
||||
}
|
||||
|
||||
EnHandleResult CProxyConnectServer::OnReceive(ITcpServer* pSender, CONNID dwConnID, int iLength)
|
||||
{
|
||||
ClientContext* pContext = NULL;
|
||||
if ((!m_TcpServer->GetConnectionExtra(dwConnID, (PVOID*)&pContext)) && (pContext != nullptr) && (iLength <= 0))
|
||||
return HR_ERROR;
|
||||
|
||||
PBYTE pData = new BYTE[iLength];
|
||||
m_TcpServer->Fetch(dwConnID, pData, iLength);
|
||||
pContext->InDeCompressedBuffer.ClearBuffer();
|
||||
BYTE bToken = COMMAND_PROXY_DATA;
|
||||
pContext->InDeCompressedBuffer.Write(&bToken, sizeof(bToken));
|
||||
pContext->InDeCompressedBuffer.Write((LPBYTE)&pContext->ID, sizeof(DWORD));
|
||||
pContext->InDeCompressedBuffer.Write((PBYTE)pData, iLength);
|
||||
SAFE_DELETE_ARRAY(pData);
|
||||
m_pNotifyProc(m_pUser, pContext, NC_RECEIVE);
|
||||
return HR_OK;
|
||||
}
|
||||
|
||||
EnHandleResult CProxyConnectServer::OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode)
|
||||
{
|
||||
ClientContext* pContext = NULL;
|
||||
if (m_TcpServer->GetConnectionExtra(dwConnID, (PVOID*)&pContext) && pContext != nullptr)
|
||||
m_TcpServer->SetConnectionExtra(dwConnID, NULL);
|
||||
if (!pContext)
|
||||
return HR_OK;
|
||||
|
||||
m_pNotifyProc(m_pUser, pContext, NC_CLIENT_DISCONNECT);
|
||||
pContext->InCompressedBuffer.ClearBuffer();
|
||||
pContext->InDeCompressedBuffer.ClearBuffer();
|
||||
pContext->OutCompressedBuffer.ClearBuffer();
|
||||
m_Locker.lock();
|
||||
m_listFreePool.AddTail(pContext);
|
||||
m_Locker.unlock();
|
||||
return HR_OK;
|
||||
}
|
||||
|
||||
EnHandleResult CProxyConnectServer::OnShutdown(ITcpServer* pSender)
|
||||
{
|
||||
return HR_OK;
|
||||
}
|
||||
|
||||
|
||||
BOOL CProxyConnectServer::Send(ClientContext* pContext, LPBYTE lpData, UINT nSize)
|
||||
{
|
||||
if (pContext == NULL)
|
||||
if (m_bRunning.load(std::memory_order_acquire))
|
||||
return FALSE;
|
||||
if (pNotifyProc == nullptr || nPort <= 0 || nPort > 65535)
|
||||
return FALSE;
|
||||
|
||||
BOOL rt = FALSE;;
|
||||
if (nSize > 0 && m_bIsRun) {
|
||||
pContext->OutCompressedBuffer.Write(lpData, nSize);
|
||||
rt = SendWithSplit(pContext->m_Socket, pContext->OutCompressedBuffer.GetBuffer(0),
|
||||
pContext->OutCompressedBuffer.GetBufferLength(), MAX_SEND_BUFFER);
|
||||
pContext->OutCompressedBuffer.ClearBuffer();
|
||||
SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
||||
if (s == INVALID_SOCKET) {
|
||||
Mprintf("CProxyConnectServer: socket() failed: %d\n", WSAGetLastError());
|
||||
return FALSE;
|
||||
}
|
||||
return rt;
|
||||
|
||||
// 用 SO_EXCLUSIVEADDRUSE 而不是 SO_REUSEADDR:Windows 上 SO_REUSEADDR 允许绑定一个
|
||||
// 已被别人监听的端口(甚至会抢走对方的连接),对话框「端口被占用就换随机端口」的重试
|
||||
// 逻辑会失效。EXCLUSIVE 让 bind 如实失败。
|
||||
BOOL bExclusive = TRUE;
|
||||
setsockopt(s, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&bExclusive, sizeof(bExclusive));
|
||||
|
||||
sockaddr_in addr = {};
|
||||
addr.sin_family = AF_INET;
|
||||
// 只监听回环。本代理没有认证,绑 0.0.0.0 会把本机变成一个对局域网/公网开放的
|
||||
// SOCKS5 出口;而对话框的提示、Chrome 启动参数用的都是 127.0.0.1,没有远程使用场景。
|
||||
addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
|
||||
addr.sin_port = htons((u_short)nPort);
|
||||
if (bind(s, (sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) {
|
||||
Mprintf("CProxyConnectServer: bind(%d) failed: %d\n", nPort, WSAGetLastError());
|
||||
closesocket(s);
|
||||
return FALSE;
|
||||
}
|
||||
if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
|
||||
Mprintf("CProxyConnectServer: listen(%d) failed: %d\n", nPort, WSAGetLastError());
|
||||
closesocket(s);
|
||||
return FALSE;
|
||||
}
|
||||
// 非阻塞:select 报可读后仍可能有竞争(对端在 accept 前 RST),避免 accept 卡住。
|
||||
u_long ulNonBlock = 1;
|
||||
ioctlsocket(s, FIONBIO, &ulNonBlock);
|
||||
SetSocketOptions(s);
|
||||
|
||||
m_pNotifyProc = pNotifyProc;
|
||||
m_pCanRecvProc = pCanRecvProc;
|
||||
m_pUser = pUser;
|
||||
m_nMaxConnection = nMaxConnections;
|
||||
m_nPort = (USHORT)nPort;
|
||||
m_listenSocket = s;
|
||||
m_bRunning.store(true, std::memory_order_release);
|
||||
|
||||
m_acceptThread = std::thread(&CProxyConnectServer::AcceptLoop, this);
|
||||
Mprintf("CProxyConnectServer: listening on 127.0.0.1:%d\n", nPort);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
|
||||
BOOL CProxyConnectServer::SendWithSplit(CONNID dwConnID, LPBYTE lpData, UINT nSize, UINT nSplitSize)
|
||||
void CProxyConnectServer::AcceptLoop()
|
||||
{
|
||||
int nSend = 0;
|
||||
UINT nSendRetry = 0;
|
||||
BOOL rt = TRUE;
|
||||
if (nSize >= nSplitSize) {
|
||||
UINT i = 0;
|
||||
nSendRetry = nSize / nSplitSize;
|
||||
for (i = 0; i < nSendRetry; i++) {
|
||||
rt = m_TcpServer->Send(dwConnID, lpData, nSplitSize);
|
||||
if (!rt)
|
||||
return rt;
|
||||
lpData += nSplitSize;
|
||||
nSend += nSplitSize;
|
||||
while (m_bRunning.load(std::memory_order_acquire)) {
|
||||
fd_set readSet;
|
||||
FD_ZERO(&readSet);
|
||||
FD_SET(m_listenSocket, &readSet);
|
||||
timeval tv = {};
|
||||
tv.tv_sec = 0;
|
||||
tv.tv_usec = PROXY_POLL_MS * 1000;
|
||||
|
||||
int sel = select(0, &readSet, nullptr, nullptr, &tv);
|
||||
if (!m_bRunning.load(std::memory_order_acquire))
|
||||
break;
|
||||
if (sel == SOCKET_ERROR) {
|
||||
Mprintf("CProxyConnectServer: select() failed: %d\n", WSAGetLastError());
|
||||
break;
|
||||
}
|
||||
if (nSize - nSend < nSplitSize) {
|
||||
if (nSize - nSend > 0) {
|
||||
rt = m_TcpServer->Send(dwConnID, lpData, nSize - nSend);
|
||||
if (!rt)
|
||||
return rt;
|
||||
ReapFinished();
|
||||
if (sel == 0)
|
||||
continue;
|
||||
|
||||
sockaddr_in peer = {};
|
||||
int peerLen = sizeof(peer);
|
||||
SOCKET s = accept(m_listenSocket, (sockaddr*)&peer, &peerLen);
|
||||
if (s == INVALID_SOCKET) {
|
||||
// 非阻塞 accept 的竞争(对端已断开)属正常,继续。
|
||||
if (WSAGetLastError() != WSAEWOULDBLOCK)
|
||||
Mprintf("CProxyConnectServer: accept() failed: %d\n", WSAGetLastError());
|
||||
continue;
|
||||
}
|
||||
if (m_nMaxConnection > 0 && GetConnectionCount() >= m_nMaxConnection) {
|
||||
Mprintf("CProxyConnectServer: reject, max connections (%d) reached\n", m_nMaxConnection);
|
||||
closesocket(s);
|
||||
continue;
|
||||
}
|
||||
SetSocketOptions(s);
|
||||
|
||||
auto pConn = std::make_shared<Conn>();
|
||||
pConn->sock = s;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connLock);
|
||||
CONNID id = m_nextId++;
|
||||
if (m_nextId == 0)
|
||||
m_nextId = 1; // 回绕后仍跳过 0
|
||||
while (m_conns.find(id) != m_conns.end()) {
|
||||
id = m_nextId++;
|
||||
if (m_nextId == 0)
|
||||
m_nextId = 1;
|
||||
}
|
||||
pConn->id = id;
|
||||
m_conns[id] = pConn;
|
||||
}
|
||||
} else {
|
||||
rt = m_TcpServer->Send(dwConnID, lpData, nSize);
|
||||
if (!rt)
|
||||
return rt;
|
||||
|
||||
char szPeer[64] = {};
|
||||
inet_ntop(AF_INET, &peer.sin_addr, szPeer, sizeof(szPeer));
|
||||
Mprintf("CProxyConnectServer: new connection #%u from %s:%u\n",
|
||||
pConn->id, szPeer, (UINT)ntohs(peer.sin_port));
|
||||
|
||||
// 先通知「新连接」(对话框据此建立会话状态),再开始收数据。
|
||||
m_pNotifyProc(m_pUser, pConn->id, nullptr, 0, NC_CLIENT_CONNECT);
|
||||
pConn->thread = std::thread(&CProxyConnectServer::RelayLoop, this, pConn);
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
void CProxyConnectServer::RelayLoop(std::shared_ptr<Conn> pConn)
|
||||
{
|
||||
std::vector<BYTE> buf(PROXY_RECV_CHUNK);
|
||||
|
||||
while (!pConn->stop.load(std::memory_order_acquire)) {
|
||||
// 流控:下游(主连接发往客户端的队列)堆积时不收数据,让本机连接的对端按
|
||||
// TCP 窗口自己减速。这里只是暂停 recv,socket 不关,Disconnect/Shutdown 仍有效。
|
||||
if (m_pCanRecvProc != nullptr && !m_pCanRecvProc(m_pUser, pConn->id)) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(PROXY_POLL_MS));
|
||||
continue;
|
||||
}
|
||||
|
||||
fd_set readSet;
|
||||
FD_ZERO(&readSet);
|
||||
FD_SET(pConn->sock, &readSet);
|
||||
timeval tv = {};
|
||||
tv.tv_sec = 0;
|
||||
tv.tv_usec = PROXY_POLL_MS * 1000;
|
||||
|
||||
int sel = select(0, &readSet, nullptr, nullptr, &tv);
|
||||
if (sel == SOCKET_ERROR)
|
||||
break;
|
||||
if (sel == 0)
|
||||
continue;
|
||||
|
||||
int nRecv = recv(pConn->sock, (char*)buf.data(), (int)buf.size(), 0);
|
||||
if (nRecv <= 0)
|
||||
break; // 0 = 对端关闭;<0 = 出错/已 shutdown
|
||||
m_pNotifyProc(m_pUser, pConn->id, buf.data(), (UINT)nRecv, NC_RECEIVE);
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pConn->sendLock);
|
||||
if (pConn->sock != INVALID_SOCKET) {
|
||||
closesocket(pConn->sock);
|
||||
pConn->sock = INVALID_SOCKET;
|
||||
}
|
||||
}
|
||||
Mprintf("CProxyConnectServer: connection #%u closed\n", pConn->id);
|
||||
m_pNotifyProc(m_pUser, pConn->id, nullptr, 0, NC_CLIENT_DISCONNECT);
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connLock);
|
||||
m_conns.erase(pConn->id);
|
||||
std::lock_guard<std::mutex> grave(m_graveLock);
|
||||
m_graveyard.push_back(pConn); // 由 accept 线程或 Shutdown 负责 join
|
||||
}
|
||||
pConn->finished.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
void CProxyConnectServer::ReapFinished()
|
||||
{
|
||||
std::vector<std::shared_ptr<Conn>> done;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_graveLock);
|
||||
done.swap(m_graveyard);
|
||||
}
|
||||
for (auto& pConn : done) {
|
||||
if (pConn->thread.joinable())
|
||||
pConn->thread.join();
|
||||
}
|
||||
}
|
||||
|
||||
BOOL CProxyConnectServer::Send(CONNID id, const BYTE* pData, UINT nSize)
|
||||
{
|
||||
if (pData == nullptr || nSize == 0)
|
||||
return FALSE;
|
||||
|
||||
std::shared_ptr<Conn> pConn;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connLock);
|
||||
auto it = m_conns.find(id);
|
||||
if (it == m_conns.end())
|
||||
return FALSE;
|
||||
pConn = it->second;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(pConn->sendLock);
|
||||
if (pConn->sock == INVALID_SOCKET)
|
||||
return FALSE;
|
||||
|
||||
UINT sent = 0;
|
||||
while (sent < nSize) {
|
||||
int n = send(pConn->sock, (const char*)pData + sent, (int)(nSize - sent), 0);
|
||||
if (n <= 0) {
|
||||
Mprintf("CProxyConnectServer: send #%u failed: %d\n", id, WSAGetLastError());
|
||||
return FALSE;
|
||||
}
|
||||
sent += (UINT)n;
|
||||
}
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
BOOL CProxyConnectServer::Disconnect(CONNID id)
|
||||
{
|
||||
std::shared_ptr<Conn> pConn;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connLock);
|
||||
auto it = m_conns.find(id);
|
||||
if (it == m_conns.end())
|
||||
return FALSE;
|
||||
pConn = it->second;
|
||||
}
|
||||
pConn->stop.store(true, std::memory_order_release);
|
||||
// 只 shutdown 不 close:关闭权归中继线程。这里与中继线程的 close 共用 sendLock,
|
||||
// 免得句柄已被关闭、又被系统复用给别的 socket 之后 shutdown 到别人身上。
|
||||
std::lock_guard<std::mutex> lock(pConn->sendLock);
|
||||
if (pConn->sock != INVALID_SOCKET)
|
||||
shutdown(pConn->sock, SD_BOTH);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
int CProxyConnectServer::GetConnectionCount()
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connLock);
|
||||
return (int)m_conns.size();
|
||||
}
|
||||
|
||||
void CProxyConnectServer::Shutdown()
|
||||
{
|
||||
DWORD dwCount = 65535;
|
||||
CONNID *pIDs = new CONNID[dwCount]();
|
||||
BOOL status = m_TcpServer->GetAllConnectionIDs(pIDs, dwCount);
|
||||
if (status && (dwCount > 0)) {
|
||||
for (DWORD i = 0; i < dwCount; i++) {
|
||||
Disconnect(pIDs[i]);
|
||||
}
|
||||
}
|
||||
m_TcpServer->Stop();
|
||||
m_bIsRun = FALSE;
|
||||
while (m_TcpServer->GetState() != SS_STOPPED)
|
||||
Sleep(10);
|
||||
if (!m_bRunning.exchange(false, std::memory_order_acq_rel))
|
||||
return;
|
||||
|
||||
m_Locker.lock();
|
||||
while (!m_listFreePool.IsEmpty())
|
||||
delete m_listFreePool.RemoveTail();
|
||||
m_Locker.unlock();
|
||||
|
||||
SAFE_DELETE_ARRAY(pIDs);
|
||||
}
|
||||
|
||||
void CProxyConnectServer::ClearClient()
|
||||
{
|
||||
DWORD dwCount = 65535;
|
||||
CONNID* pIDs = new CONNID[dwCount]();
|
||||
BOOL status = m_TcpServer->GetAllConnectionIDs(pIDs, dwCount);
|
||||
if (status && (dwCount > 0)) {
|
||||
for (DWORD i = 0; i < dwCount; i++) {
|
||||
m_TcpServer->Disconnect(pIDs[i]);
|
||||
}
|
||||
// 1) 停 accept:accept 线程的 select 有 200ms 超时,靠 m_bRunning 自然退出,
|
||||
// 避免在其他线程里 close 一个正被 select 的监听句柄。
|
||||
if (m_acceptThread.joinable())
|
||||
m_acceptThread.join();
|
||||
if (m_listenSocket != INVALID_SOCKET) {
|
||||
closesocket(m_listenSocket);
|
||||
m_listenSocket = INVALID_SOCKET;
|
||||
}
|
||||
|
||||
SAFE_DELETE_ARRAY(pIDs);
|
||||
}
|
||||
// 2) 断开并等待所有中继线程。
|
||||
std::vector<std::shared_ptr<Conn>> conns;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_connLock);
|
||||
for (auto& kv : m_conns)
|
||||
conns.push_back(kv.second);
|
||||
m_conns.clear();
|
||||
}
|
||||
for (auto& pConn : conns) {
|
||||
pConn->stop.store(true, std::memory_order_release);
|
||||
// 与 Disconnect 同理:shutdown 必须和中继线程的 closesocket 互斥,
|
||||
// 否则可能对一个已被回收复用的句柄动手。
|
||||
std::lock_guard<std::mutex> lock(pConn->sendLock);
|
||||
if (pConn->sock != INVALID_SOCKET)
|
||||
shutdown(pConn->sock, SD_BOTH);
|
||||
}
|
||||
for (auto& pConn : conns) {
|
||||
if (pConn->thread.joinable())
|
||||
pConn->thread.join();
|
||||
}
|
||||
|
||||
BOOL CProxyConnectServer::Disconnect(CONNID dwConnID)
|
||||
{
|
||||
m_TcpServer->Disconnect(dwConnID);
|
||||
return 0;
|
||||
}
|
||||
// 3) 收割自然退出但还没 join 的连接。
|
||||
ReapFinished();
|
||||
|
||||
BOOL CProxyConnectServer::IsConnected(CONNID dwConnID)
|
||||
{
|
||||
return m_TcpServer->IsConnected(dwConnID);
|
||||
}
|
||||
|
||||
BOOL CProxyConnectServer::IsOverMaxConnectionCount()
|
||||
{
|
||||
return (m_TcpServer->GetConnectionCount() > (DWORD)m_nMaxConnection);
|
||||
Mprintf("CProxyConnectServer: shutdown, %d connection(s) closed\n", (int)conns.size());
|
||||
}
|
||||
@@ -1,51 +1,109 @@
|
||||
#pragma once
|
||||
#include "HPSocket.h"
|
||||
#include "SocketInterface.h"
|
||||
#include "Buffer.h"
|
||||
#include <IOCPServer.h>
|
||||
|
||||
#define NC_CLIENT_CONNECT 0x0001
|
||||
#define NC_CLIENT_DISCONNECT 0x0002
|
||||
#define NC_TRANSMIT 0x0003
|
||||
#define NC_RECEIVE 0x0004
|
||||
// 本机 SOCKS5 监听器(代理映射的「本地侧」)。
|
||||
//
|
||||
// 原实现建立在 HP-Socket(https://github.com/ldcsaa/HP-Socket)之上,为这一个功能
|
||||
// 引入整套 SDK(库 + DLL)并不划算,且 HP-Socket 版一直以 ENABLE_HPSOCKET=0 关闭,
|
||||
// 从未真正跑过。这里用阻塞 socket + select 自实现,接口面按原对话框的实际用法裁剪:
|
||||
// 端口监听、每连接收发、按连接 id 断开、连接计数。
|
||||
//
|
||||
// 线程模型(对齐 server/2015Remote/SimpleWebSocket.h 与客户端 ProxyManager 的既有做法):
|
||||
// * 1 个 accept 线程,select 200ms 轮询,便于在 Shutdown 时自然退出;
|
||||
// * 每连接 1 个中继线程,select 200ms 轮询 socket 可读后 recv,只做字节转发;
|
||||
// * 回调(PROXYNOTIFYPROC)在 accept 线程 / 中继线程内同步调用,回调里可以调
|
||||
// Send/Disconnect,但不要等待本对象 Shutdown(会自锁)。
|
||||
// socket 的关闭权归中继线程独有:Disconnect 只置停止位并 shutdown(),由中继线程在
|
||||
// 退出前 closesocket,避免多线程同时关闭同一个句柄。
|
||||
|
||||
typedef void (CALLBACK* NOTIFYPROC)(void* user, ClientContext* ctx, UINT nCode);
|
||||
#include "stdafx.h"
|
||||
#include <WinSock2.h>
|
||||
#include <WS2tcpip.h>
|
||||
|
||||
typedef CList<ClientContext*, ClientContext* > ContextList;
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
class CProxyConnectServer :public CTcpPullServerListener
|
||||
// 连接 id。42 亿个够用,且与代理报文里那 4 字节 id 字段同宽(磁盘/线缆格式不变)。
|
||||
typedef uint32_t CONNID;
|
||||
|
||||
#define NC_CLIENT_CONNECT 0x0001
|
||||
#define NC_CLIENT_DISCONNECT 0x0002
|
||||
#define NC_TRANSMIT 0x0003
|
||||
#define NC_RECEIVE 0x0004
|
||||
|
||||
// nCode == NC_RECEIVE 时 pData/nLen 是本机连接上刚收到的字节(TCP 流的一片段,
|
||||
// 不保证对齐 SOCKS5 消息边界);其余 nCode 下 pData == nullptr、nLen == 0。
|
||||
typedef void (CALLBACK* PROXYNOTIFYPROC)(void* pUser, CONNID id, const BYTE* pData, UINT nLen, UINT nCode);
|
||||
|
||||
// 流控回调:中继线程每轮 recv 之前问一次「现在还能不能收」。返回 FALSE 时暂停
|
||||
// 读取(不 recv),让本机连接的对端按 TCP 窗口自行减速;返回 TRUE 后恢复。
|
||||
// 在本机连接的中继线程上调用,要求实现足够轻量、线程安全。
|
||||
typedef BOOL (CALLBACK* PROXYCANRECVPROC)(void* pUser, CONNID id);
|
||||
|
||||
class CProxyConnectServer
|
||||
{
|
||||
public:
|
||||
CProxyConnectServer(void);
|
||||
~CProxyConnectServer(void);
|
||||
CProxyConnectServer();
|
||||
~CProxyConnectServer();
|
||||
|
||||
BOOL Initialize(NOTIFYPROC pNotifyProc, void* user, int nMaxConnections, int nPort);
|
||||
BOOL Send(ClientContext* pContext, LPBYTE lpData, UINT nSize);
|
||||
BOOL SendWithSplit(CONNID dwConnID, LPBYTE lpData, UINT nSize, UINT nSplitSize);
|
||||
// 绑定 127.0.0.1:nPort 并开始 accept。nMaxConnections <= 0 表示不限制。
|
||||
// 只监听回环:这是个无认证的 SOCKS5 入口,绑 0.0.0.0 等于对局域网/公网开放代理;
|
||||
// 对话框里给用户的提示也是「代理服务器填 127.0.0.1」。
|
||||
BOOL Initialize(PROXYNOTIFYPROC pNotifyProc, PROXYCANRECVPROC pCanRecvProc,
|
||||
void* pUser, int nMaxConnections, int nPort);
|
||||
|
||||
// 停止监听、断开全部连接、等待所有线程退出。可重复调用。
|
||||
void Shutdown();
|
||||
void ClearClient();
|
||||
BOOL Disconnect(CONNID dwConnID);
|
||||
BOOL IsConnected(CONNID dwConnID);
|
||||
int IsOverMaxConnectionCount();
|
||||
|
||||
virtual EnHandleResult OnPrepareListen(ITcpServer* pSender, SOCKET soListen);
|
||||
virtual EnHandleResult OnAccept(ITcpServer* pSender, CONNID dwConnID, UINT_PTR soClient);
|
||||
virtual EnHandleResult OnSend(ITcpServer* pSender, CONNID dwConnID, const BYTE* pData, int iLength);
|
||||
virtual EnHandleResult OnReceive(ITcpServer* pSender, CONNID dwConnID, int iLength);
|
||||
virtual EnHandleResult OnClose(ITcpServer* pSender, CONNID dwConnID, EnSocketOperation enOperation, int iErrorCode);
|
||||
virtual EnHandleResult OnShutdown(ITcpServer* pSender);
|
||||
// 向本机连接发数据。全部字节发出返回 TRUE;连接不存在或出错返回 FALSE。
|
||||
BOOL Send(CONNID id, const BYTE* pData, UINT nSize);
|
||||
|
||||
CTcpPullServerPtr m_TcpServer;
|
||||
// 主动断开某个本机连接(中继线程会在 200ms 内退出并回调 NC_CLIENT_DISCONNECT)。
|
||||
BOOL Disconnect(CONNID id);
|
||||
|
||||
BOOL HasStarted() const
|
||||
{
|
||||
return m_bRunning.load(std::memory_order_acquire);
|
||||
}
|
||||
int GetConnectionCount();
|
||||
USHORT GetPort() const
|
||||
{
|
||||
return m_nPort;
|
||||
}
|
||||
|
||||
private:
|
||||
NOTIFYPROC m_pNotifyProc;
|
||||
void* m_pUser;
|
||||
ContextList m_listFreePool;
|
||||
CLock m_Locker;
|
||||
int m_nPort; // 插件端口
|
||||
CONNID m_IDs[65535]; // 所有连接ID
|
||||
LONG m_bStop; // 端口停止上线控制
|
||||
int m_nMaxConnection; // 最大连接数
|
||||
BOOL m_bIsRun; // 运行状态
|
||||
DWORD m_dwIndex; // 连接编号
|
||||
struct Conn {
|
||||
CONNID id = 0;
|
||||
SOCKET sock = INVALID_SOCKET;
|
||||
std::atomic<bool> stop{ false };
|
||||
std::atomic<bool> finished{ false }; // 中继线程已走完(可以 join)
|
||||
std::mutex sendLock; // 串行化 Send 与中继线程的 closesocket
|
||||
std::thread thread;
|
||||
};
|
||||
|
||||
void AcceptLoop();
|
||||
void RelayLoop(std::shared_ptr<Conn> pConn);
|
||||
void ReapFinished();
|
||||
BOOL SetSocketOptions(SOCKET s) const;
|
||||
|
||||
USHORT m_nPort = 0;
|
||||
int m_nMaxConnection = 0;
|
||||
SOCKET m_listenSocket = INVALID_SOCKET;
|
||||
std::thread m_acceptThread;
|
||||
std::atomic<bool> m_bRunning{ false };
|
||||
PROXYNOTIFYPROC m_pNotifyProc = nullptr;
|
||||
PROXYCANRECVPROC m_pCanRecvProc = nullptr; // 可为空,表示不限流
|
||||
void* m_pUser = nullptr;
|
||||
|
||||
std::mutex m_connLock;
|
||||
std::map<CONNID, std::shared_ptr<Conn>> m_conns;
|
||||
CONNID m_nextId = 1;
|
||||
|
||||
// 已退出、等待 join 的连接。由 accept 线程与 Shutdown 收割,避免线程句柄越积越多。
|
||||
std::vector<std::shared_ptr<Conn>> m_graveyard;
|
||||
std::mutex m_graveLock;
|
||||
};
|
||||
@@ -9,24 +9,61 @@
|
||||
#define new DEBUG_NEW
|
||||
#endif
|
||||
|
||||
#if !ENABLE_HPSOCKET
|
||||
HPSOCKET_API{
|
||||
ITcpPullServer * HP_Create_TcpPullServer(ITcpServerListener * pListener) { return 0; }
|
||||
void HP_Destroy_TcpPullServer(ITcpPullServer * pServer) {}
|
||||
int SYS_SSO_RecvBuffSize(SOCKET sock, int size) { return 0; }
|
||||
int SYS_SSO_SendBuffSize(SOCKET sock, int size) { return 0; }
|
||||
}
|
||||
#endif
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// CProxyMapDlg dialog
|
||||
|
||||
#define IDM_PROXY_CHROME 8000
|
||||
#define IDM_PROXY_CHROME 8000
|
||||
#define WM_PROXY_APPEND_LOG (WM_APP + 101) // wParam: 0 = 主窗格,1 = 副窗格;lParam: CString*
|
||||
|
||||
#define MAX_LOG_CHARS (256 * 1024) // 单个日志框保留的最大字符数(超出丢头部)
|
||||
|
||||
#define IDT_PROXY_HANDSHAKE 1
|
||||
#define IDT_PROXY_LOG_FLUSH 2
|
||||
#define PROXY_HANDSHAKE_TIMEOUT_MS 30000 // 握手/等客户端回结果的时间上限
|
||||
#define PROXY_TIMEOUT_TICK_MS 5000 // 超时扫描周期
|
||||
#define PROXY_LOG_FLUSH_MS 100 // 日志框合并刷新的窗口
|
||||
#define PROXY_MAX_PENDING ((size_t)64 * 1024) // 握手阶段最多缓存的字节数
|
||||
#define PROXY_OUTBUF_HIGH_WATER (2 * 1024 * 1024) // 主连接发送队列的高水位
|
||||
#define PROXY_LOG_INTERVAL_MS 1000 // 隧道数据进度的打印间隔(每连接)
|
||||
|
||||
// 人类的字节数。隧道里按 32KB 分片记账,直接打字节数既吵又不好读。
|
||||
static CString FormatBytes(ULONGLONG n)
|
||||
{
|
||||
CString str;
|
||||
if (n >= 1024ULL * 1024)
|
||||
str.FormatL(_T("%.2f MB"), n / (1024.0 * 1024.0));
|
||||
else if (n >= 1024ULL)
|
||||
str.FormatL(_T("%.1f KB"), n / 1024.0);
|
||||
else
|
||||
str.FormatL(_T("%I64u B"), n);
|
||||
return str;
|
||||
}
|
||||
|
||||
#define SOCKS5_VER 5
|
||||
#define SOCKS5_CMD_CONNECT 1
|
||||
#define SOCKS5_ATYP_IPV4 1
|
||||
#define SOCKS5_ATYP_HOST 3
|
||||
#define SOCKS5_ATYP_IPV6 4
|
||||
#define SOCKS5_REP_SUCCEEDED 0
|
||||
#define SOCKS5_REP_REFUSED 5
|
||||
#define SOCKS5_REP_CMD_UNSUPPORTED 7
|
||||
#define SOCKS5_REP_ATYP_UNSUPPORTED 8
|
||||
|
||||
CProxyMapDlg::CProxyMapDlg(CWnd* pParent, Server* pIOCPServer, ClientContext* pContext)
|
||||
: CDialogBase(CProxyMapDlg::IDD, pParent, pIOCPServer, pContext, IDI_Proxifier)
|
||||
{
|
||||
m_iocpLocal = NULL;
|
||||
m_nPort = 0;
|
||||
}
|
||||
|
||||
CProxyMapDlg::~CProxyMapDlg()
|
||||
{
|
||||
// 兜底:正常关闭走 OnCancel,已经把监听器停掉并置空;这里只处理没走到 OnCancel 的销毁
|
||||
// 路径,避免监听线程继续回调一个正在析构的对象。
|
||||
if (m_iocpLocal) {
|
||||
m_iocpLocal->Shutdown();
|
||||
SAFE_DELETE(m_iocpLocal);
|
||||
}
|
||||
}
|
||||
|
||||
void CProxyMapDlg::DoDataExchange(CDataExchange* pDX)
|
||||
@@ -39,6 +76,8 @@ void CProxyMapDlg::DoDataExchange(CDataExchange* pDX)
|
||||
BEGIN_MESSAGE_MAP(CProxyMapDlg, CDialog)
|
||||
ON_WM_SYSCOMMAND()
|
||||
ON_WM_SIZE()
|
||||
ON_WM_TIMER()
|
||||
ON_MESSAGE(WM_PROXY_APPEND_LOG, &CProxyMapDlg::OnProxyLog)
|
||||
END_MESSAGE_MAP()
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
@@ -49,56 +88,46 @@ BOOL CProxyMapDlg::OnInitDialog()
|
||||
|
||||
SetIcon(m_hIcon, TRUE); // Set big icon
|
||||
SetIcon(m_hIcon, FALSE); // Set small icon
|
||||
// TODO: Add extra initialization here
|
||||
m_iocpLocal = new CProxyConnectServer;
|
||||
|
||||
m_iocpLocal = new CProxyConnectServer;
|
||||
if (m_iocpLocal == NULL) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
m_Edit.SetLimitText(MAXDWORD);
|
||||
m_EditOther.SetLimitText(MAXDWORD);
|
||||
CString str;
|
||||
|
||||
// 开启IPCP服务器
|
||||
srand((unsigned int)time(NULL));
|
||||
|
||||
m_nPort = 5543; // 初始尝试端口
|
||||
// 监听端口:先试 5543,被占用就换 10000-65535 的随机端口。
|
||||
m_nPort = 5543;
|
||||
BOOL bSuccess = FALSE;
|
||||
const int nMaxRetries = 10;
|
||||
|
||||
for (int i = 0; i < nMaxRetries; ++i) {
|
||||
if (m_iocpLocal->Initialize(NotifyProc, this, 100000, m_nPort)) {
|
||||
if (m_iocpLocal->Initialize(NotifyProc, CanRecvProc, this, 100000, m_nPort)) {
|
||||
bSuccess = TRUE;
|
||||
break;
|
||||
}
|
||||
|
||||
// 端口冲突,生成 10000-65535 之间的随机端口
|
||||
// 提示:10000 + (0 到 55535)
|
||||
int nextPort = 10000 + (rand() % 55536);
|
||||
|
||||
// 避免随机到和刚才一样的端口
|
||||
while (nextPort == m_nPort) {
|
||||
nextPort = 10000 + (rand() % 55536);
|
||||
}
|
||||
m_nPort = nextPort;
|
||||
m_nPort = (USHORT)nextPort;
|
||||
}
|
||||
|
||||
if (!bSuccess) {
|
||||
MessageBoxL("初始化代理服务器失败!", "提示", MB_ICONINFORMATION);
|
||||
SAFE_DELETE(m_iocpLocal);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
TCHAR ip[256] = {};
|
||||
int len = sizeof(ip);
|
||||
m_iocpLocal->m_TcpServer->GetListenAddress(ip, len, m_nPort);
|
||||
|
||||
CString strString;
|
||||
strString.FormatL("%s - 代理服务", m_IPAddress);
|
||||
SetWindowText(strString);
|
||||
|
||||
CString str;
|
||||
str.FormatL(_T("SOCKS 代理软件请设置服务器为: <127.0.0.1:%d>\r\n"), m_nPort);
|
||||
AddLog(str.GetBuffer(0));
|
||||
LogLine(false, str.GetString());
|
||||
|
||||
CMenu* pSysMenu = GetSystemMenu(FALSE);
|
||||
if (pSysMenu != NULL) {
|
||||
@@ -106,6 +135,10 @@ BOOL CProxyMapDlg::OnInitDialog()
|
||||
pSysMenu->AppendMenuL(MF_STRING, IDM_PROXY_CHROME, _T("代理打开Chrome(请关闭所有Chrome进程)(&P)"));
|
||||
}
|
||||
|
||||
// 卡在握手阶段的连接不会自己退出(客户端不回结果、本地对端连上却不发数据),
|
||||
// 用定时器统一扫一遍。
|
||||
SetTimer(IDT_PROXY_HANDSHAKE, PROXY_TIMEOUT_TICK_MS, NULL);
|
||||
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
@@ -117,95 +150,331 @@ void CProxyMapDlg::OnCancel()
|
||||
ShowWindow(SW_HIDE);
|
||||
return;
|
||||
}
|
||||
m_iocpLocal->Shutdown();
|
||||
SAFE_DELETE(m_iocpLocal);
|
||||
KillTimer(IDT_PROXY_HANDSHAKE);
|
||||
if (m_iocpLocal) {
|
||||
// Shutdown 会等所有本地连接的中继线程退出,之后不会再有回调进来。
|
||||
m_iocpLocal->Shutdown();
|
||||
SAFE_DELETE(m_iocpLocal);
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
m_sessions.clear();
|
||||
}
|
||||
|
||||
CancelIO();
|
||||
|
||||
DialogBase::OnClose();
|
||||
}
|
||||
|
||||
void CALLBACK CProxyMapDlg::NotifyProc(void *user, ClientContext* pContext, UINT nCode)
|
||||
void CProxyMapDlg::LogLine(bool other, LPCTSTR text)
|
||||
{
|
||||
CProxyMapDlg* g_pProxyMap = (CProxyMapDlg*)user;
|
||||
if (g_pProxyMap->m_bIsClosed) return;
|
||||
if (m_bIsClosed || GetSafeHwnd() == NULL || text == NULL)
|
||||
return;
|
||||
// 回调可能来自监听/中继线程,控件只能在 UI 线程上碰:转成消息投递。
|
||||
// 队列满(PostMessage 失败)时必须自己释放,否则每丢一条就漏一个 CString。
|
||||
CString* pText = new CString(text);
|
||||
if (!PostMessage(WM_PROXY_APPEND_LOG, (WPARAM)(other ? 1 : 0), (LPARAM)pText))
|
||||
delete pText;
|
||||
}
|
||||
|
||||
DWORD index = pContext->ID;
|
||||
TCHAR szMsg[200] = { 0 };
|
||||
LRESULT CProxyMapDlg::OnProxyLog(WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
CString* pText = (CString*)lParam;
|
||||
if (pText == NULL)
|
||||
return 0;
|
||||
if (!m_bIsClosed) {
|
||||
CString& buffer = (wParam == 0) ? m_strLog : m_strLogOther;
|
||||
AppendLog(buffer, *pText);
|
||||
// 只累积、不刷控件:日志密集时每行都 SetWindowText 整段文本会把 UI 线程拖死,
|
||||
// 攒一小段时间合并刷新一次。
|
||||
if (wParam == 0)
|
||||
m_bLogDirtyMain = true;
|
||||
else
|
||||
m_bLogDirtyOther = true;
|
||||
if (!m_bLogFlushPending) {
|
||||
m_bLogFlushPending = (SetTimer(IDT_PROXY_LOG_FLUSH, PROXY_LOG_FLUSH_MS, NULL) != 0);
|
||||
}
|
||||
}
|
||||
delete pText;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void CProxyMapDlg::AppendLog(CString& buffer, LPCTSTR text)
|
||||
{
|
||||
// 模板里两个日志框都是 ES_READONLY(只能选择/复制),EM_REPLACESEL 会被系统忽略,
|
||||
// 所以自己维护一份文本再整段 SetWindowText(见 FlushLog)。
|
||||
buffer += text;
|
||||
if (buffer.GetLength() > MAX_LOG_CHARS) {
|
||||
buffer = buffer.Right(MAX_LOG_CHARS);
|
||||
int nl = buffer.Find('\n');
|
||||
if (nl > 0)
|
||||
buffer = buffer.Mid(nl + 1); // 从下一行的行首开始,避免半行
|
||||
}
|
||||
}
|
||||
|
||||
void CProxyMapDlg::FlushLog()
|
||||
{
|
||||
m_bLogFlushPending = false;
|
||||
if (m_bLogDirtyMain) {
|
||||
m_bLogDirtyMain = false;
|
||||
m_Edit.SetWindowText(m_strLog);
|
||||
m_Edit.SetSel(m_strLog.GetLength(), m_strLog.GetLength());
|
||||
m_Edit.SendMessage(EM_SCROLLCARET);
|
||||
}
|
||||
if (m_bLogDirtyOther) {
|
||||
m_bLogDirtyOther = false;
|
||||
m_EditOther.SetWindowText(m_strLogOther);
|
||||
m_EditOther.SetSel(m_strLogOther.GetLength(), m_strLogOther.GetLength());
|
||||
m_EditOther.SendMessage(EM_SCROLLCARET);
|
||||
}
|
||||
}
|
||||
|
||||
BOOL CProxyMapDlg::SendProxyPacket(BYTE token, CONNID id, const BYTE* pData, UINT nLen)
|
||||
{
|
||||
if (m_ContextObject == NULL || m_bIsClosed)
|
||||
return FALSE;
|
||||
|
||||
std::vector<BYTE> buf(5 + nLen);
|
||||
buf[0] = token;
|
||||
memcpy(&buf[1], &id, sizeof(CONNID));
|
||||
if (nLen > 0 && pData != NULL)
|
||||
memcpy(&buf[5], pData, nLen);
|
||||
return m_ContextObject->Send2Client(buf.data(), (ULONG)buf.size());
|
||||
}
|
||||
|
||||
void CALLBACK CProxyMapDlg::NotifyProc(void* user, CONNID id, const BYTE* pData, UINT nLen, UINT nCode)
|
||||
{
|
||||
CProxyMapDlg* dlg = (CProxyMapDlg*)user;
|
||||
if (dlg == NULL || dlg->m_bIsClosed || dlg->m_iocpLocal == NULL)
|
||||
return;
|
||||
try {
|
||||
switch (nCode) {
|
||||
case NC_CLIENT_CONNECT:
|
||||
wsprintf(szMsg, _TRF("%d 新连接\r\n"), index);
|
||||
break;
|
||||
case NC_CLIENT_DISCONNECT:
|
||||
if (pContext->m_bProxyConnected) {
|
||||
BYTE lpData[5] = "";
|
||||
lpData[0] = COMMAND_PROXY_CLOSE;
|
||||
memcpy(lpData + 1, &index, sizeof(DWORD));
|
||||
g_pProxyMap->m_ContextObject->Send2Client(lpData, 5);
|
||||
}
|
||||
wsprintf(szMsg, _TRF("%d 本地连接断开\r\n"), index);
|
||||
break;
|
||||
case NC_TRANSMIT:
|
||||
dlg->OnLocalConnect(id);
|
||||
break;
|
||||
case NC_RECEIVE:
|
||||
if (pContext->m_bProxyConnected == 2) {
|
||||
g_pProxyMap->m_ContextObject->Send2Client(pContext->InDeCompressedBuffer.GetBuffer(0),
|
||||
pContext->InDeCompressedBuffer.GetBufferLength());
|
||||
wsprintf(szMsg, _TRF("%d <==发 %d bytes\r\n"), index, pContext->InDeCompressedBuffer.GetBufferLength() - 5);
|
||||
} else if (pContext->m_bProxyConnected == 0) {
|
||||
char msg_auth_ok[] = { 0X05, 0X00 }; // VERSION SOCKS, AUTH MODE, OK
|
||||
LPBYTE lpData = pContext->InDeCompressedBuffer.GetBuffer(5);
|
||||
pContext->m_bProxyConnected = 1;
|
||||
g_pProxyMap->m_iocpLocal->Send(pContext, (LPBYTE)msg_auth_ok, sizeof(msg_auth_ok));
|
||||
wsprintf(szMsg, _TRF("%d 返回标示 %d %d %d\r\n"), index, lpData[0], lpData[1], lpData[2]);
|
||||
} else if (pContext->m_bProxyConnected == 1) {
|
||||
LPBYTE lpData = pContext->InDeCompressedBuffer.GetBuffer(5);
|
||||
BYTE buf[11] = {};
|
||||
if (lpData[0] == 5 && lpData[1] == 1 && (pContext->InDeCompressedBuffer.GetBufferLength() > 10)) {
|
||||
if (lpData[3] == 1) { // ipv4
|
||||
buf[0] = COMMAND_PROXY_CONNECT; // 1个字节 ip v4 连接
|
||||
memcpy(buf + 1, &index, 4); // 四个字节 套接字的编号
|
||||
memcpy(buf + 5, lpData + 4, 6); // 4字节ip 2字节端口
|
||||
g_pProxyMap->m_ContextObject->Send2Client(buf, sizeof(buf));
|
||||
in_addr inaddr = {};
|
||||
inaddr.s_addr = *(DWORD*)(buf + 5);
|
||||
char szmsg1[MAX_PATH];
|
||||
wsprintfA(szmsg1, "%d IPV4 连接 %s:%d...\r\n", index, inet_ntoa(inaddr), ntohs(*(USHORT*)(buf + 9)));
|
||||
} else if (lpData[3] == 3) { // 域名
|
||||
Socks5Info* Socks5Request = (Socks5Info*)lpData;
|
||||
BYTE* HostName = new BYTE[Socks5Request->IP_LEN + 8];
|
||||
ZeroMemory(HostName, Socks5Request->IP_LEN + 8);
|
||||
HostName[0] = COMMAND_PROXY_CONNECT_HOSTNAME;
|
||||
memcpy(HostName + 7, &Socks5Request->szIP, Socks5Request->IP_LEN);
|
||||
memcpy(HostName + 1, &index, 4);
|
||||
memcpy(HostName + 5, &Socks5Request->szIP + Socks5Request->IP_LEN, 2);
|
||||
g_pProxyMap->m_ContextObject->Send2Client(HostName, Socks5Request->IP_LEN + 8);
|
||||
SAFE_DELETE_ARRAY(HostName);
|
||||
wsprintf(szMsg, _TRF("域名 连接 %d \r\n"), index);
|
||||
} else if (lpData[3] == 4) { //ipv6
|
||||
char msg_ipv6_nok[] = { 0X05, 0X08, 0X00, 0X01, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00 }; // IPv6 not support
|
||||
wsprintf(szMsg, _TRF("%d IPV6连接 不支持..."), index);
|
||||
g_pProxyMap->m_iocpLocal->Send(pContext, (LPBYTE)msg_ipv6_nok, sizeof(msg_ipv6_nok));
|
||||
g_pProxyMap->m_iocpLocal->Disconnect(pContext->m_Socket);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
buf[0] = 5;
|
||||
buf[1] = 7;
|
||||
buf[2] = 0;
|
||||
buf[3] = lpData[3];
|
||||
g_pProxyMap->m_iocpLocal->Send(pContext, buf, sizeof(buf));
|
||||
g_pProxyMap->m_iocpLocal->Disconnect(pContext->m_Socket);
|
||||
wsprintf(szMsg, _TRF("%d 不符要求, 断开 %d %d %d\r\n"), index, lpData[0], lpData[1], lpData[3]);
|
||||
}
|
||||
}
|
||||
dlg->OnLocalReceive(id, pData, nLen);
|
||||
break;
|
||||
case NC_CLIENT_DISCONNECT:
|
||||
dlg->OnLocalDisconnect(id);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} catch (...) {}
|
||||
if (szMsg[0])
|
||||
g_pProxyMap->AddLog_other(szMsg);
|
||||
return;
|
||||
} catch (...) {
|
||||
Mprintf("CProxyMapDlg: notify #%u (code %u) raised an exception\n", id, nCode);
|
||||
}
|
||||
}
|
||||
|
||||
BOOL CALLBACK CProxyMapDlg::CanRecvProc(void* user, CONNID /*id*/)
|
||||
{
|
||||
CProxyMapDlg* dlg = (CProxyMapDlg*)user;
|
||||
if (dlg == NULL || dlg->m_bIsClosed || dlg->m_ContextObject == NULL)
|
||||
return FALSE;
|
||||
// 主连接的发送队列是异步 WSASend 的源:本机读得比客户端链路快时它会一直涨。
|
||||
// 到这里反过来把压力交还给 SOCKS 客户端 —— 暂停 recv,靠 TCP 窗口让浏览器/curl
|
||||
// 自己慢下来,避免服务端内存被一个下载任务吃光。
|
||||
return dlg->m_ContextObject->OutCompressedBuffer.GetBufferLength() < PROXY_OUTBUF_HIGH_WATER;
|
||||
}
|
||||
|
||||
void CProxyMapDlg::OnLocalConnect(CONNID id)
|
||||
{
|
||||
LocalSession s;
|
||||
s.lastTick = GetTickCount64();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
m_sessions[id] = s;
|
||||
}
|
||||
CString str;
|
||||
str.FormatL(_TRF("%u 新连接\r\n"), id);
|
||||
LogLine(true, str.GetString());
|
||||
}
|
||||
|
||||
void CProxyMapDlg::OnLocalReceive(CONNID id, const BYTE* pData, UINT nLen)
|
||||
{
|
||||
if (pData == NULL || nLen == 0)
|
||||
return;
|
||||
|
||||
std::vector<BYTE> toLocal; // 要回给本机 SOCKS 客户端的应答
|
||||
std::vector<BYTE> toClient; // 要下发给客户端的 CONNECT 报文
|
||||
std::vector<BYTE> forward; // 隧道阶段要转发的数据
|
||||
CString progress; // 隧道进度日志(限流后才有内容)
|
||||
bool bClose = false;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
auto it = m_sessions.find(id);
|
||||
if (it == m_sessions.end())
|
||||
return; // 会话已结束(例如刚被断开)
|
||||
LocalSession& s = it->second;
|
||||
s.lastTick = GetTickCount64();
|
||||
|
||||
if (s.state == ST_TUNNEL) {
|
||||
s.bytesToTarget += nLen;
|
||||
if (s.lastTick - s.lastLogTick >= PROXY_LOG_INTERVAL_MS) {
|
||||
s.lastLogTick = s.lastTick;
|
||||
progress.FormatL(_TRF("%u << 上行 %s\r\n"), id, FormatBytes(s.bytesToTarget).GetString());
|
||||
}
|
||||
forward.assign(pData, pData + nLen);
|
||||
} else if (s.pending.size() + nLen > PROXY_MAX_PENDING) {
|
||||
// 握手阶段塞进 64KB 还没成帧,不可能是正常的 SOCKS5 客户端。
|
||||
bClose = true;
|
||||
CString str;
|
||||
str.FormatL(_TRF("%u 握手数据过多, 断开\r\n"), id);
|
||||
LogLine(true, str.GetString());
|
||||
} else {
|
||||
s.pending.insert(s.pending.end(), pData, pData + nLen);
|
||||
bClose = !ParseSocks5(id, s, toLocal, toClient);
|
||||
}
|
||||
}
|
||||
|
||||
// 以下都在锁外:Send/Disconnect 可能触发中继线程的关闭路径,没必要持锁。
|
||||
if (!toLocal.empty() && !m_iocpLocal->Send(id, toLocal.data(), (UINT)toLocal.size()))
|
||||
bClose = true;
|
||||
if (!toClient.empty() && !m_ContextObject->Send2Client(toClient.data(), (ULONG)toClient.size()))
|
||||
bClose = true;
|
||||
if (!forward.empty()) {
|
||||
if (!SendProxyPacket(COMMAND_PROXY_DATA, id, forward.data(), (UINT)forward.size()))
|
||||
bClose = true;
|
||||
}
|
||||
if (!progress.IsEmpty())
|
||||
LogLine(true, progress.GetString());
|
||||
if (bClose)
|
||||
m_iocpLocal->Disconnect(id);
|
||||
}
|
||||
|
||||
// 按 TCP 字节流解析 SOCKS5 握手:一次 recv 可能只到半条消息,也可能把整条消息连着
|
||||
// 后续隧道数据一起带出来,所以用状态机 + 待处理缓冲逐条切分,不能假设「一次回调 = 一条消息」。
|
||||
// 需要下发的报文放进 toLocal / toClient,由调用方在锁外发送(本函数在 m_sessLock 内调用)。
|
||||
bool CProxyMapDlg::ParseSocks5(CONNID id, LocalSession& s,
|
||||
std::vector<BYTE>& toLocal, std::vector<BYTE>& toClient)
|
||||
{
|
||||
for (;;) {
|
||||
if (s.state == ST_GREETING) {
|
||||
// VER NMETHODS METHODS[NMETHODS]
|
||||
if (s.pending.size() < 2)
|
||||
return true;
|
||||
if (s.pending[0] != SOCKS5_VER)
|
||||
return false;
|
||||
const size_t need = 2 + (size_t)s.pending[1];
|
||||
if (s.pending.size() < need)
|
||||
return true;
|
||||
const BYTE ver = s.pending[0];
|
||||
const BYTE nmethods = s.pending[1];
|
||||
s.pending.erase(s.pending.begin(), s.pending.begin() + need);
|
||||
|
||||
// 本代理不需要认证:直接回「无认证」,不检查客户端提供了哪些方法。
|
||||
toLocal.push_back(SOCKS5_VER);
|
||||
toLocal.push_back(0x00);
|
||||
s.state = ST_REQUEST;
|
||||
|
||||
CString str;
|
||||
str.FormatL(_TRF("%u 返回标示 %u %u\r\n"), id, ver, nmethods);
|
||||
LogLine(true, str.GetString());
|
||||
continue; // 同一次 recv 里可能已经带着 CONNECT 请求
|
||||
}
|
||||
|
||||
if (s.state != ST_REQUEST)
|
||||
return true; // ST_CONNECTING 等结果、ST_TUNNEL 走转发,都不在这里推进
|
||||
|
||||
// VER CMD RSV ATYP DST.ADDR DST.PORT
|
||||
if (s.pending.size() < 4)
|
||||
return true;
|
||||
const BYTE ver = s.pending[0];
|
||||
const BYTE cmd = s.pending[1];
|
||||
const BYTE atyp = s.pending[3];
|
||||
if (ver != SOCKS5_VER || cmd != SOCKS5_CMD_CONNECT) {
|
||||
const BYTE reply[10] = { SOCKS5_VER, SOCKS5_REP_CMD_UNSUPPORTED, 0, atyp, 0, 0, 0, 0, 0, 0 };
|
||||
toLocal.assign(reply, reply + sizeof(reply));
|
||||
CString str;
|
||||
str.FormatL(_TRF("%u 不符要求, 断开 %u %u %u\r\n"), id, ver, cmd, atyp);
|
||||
LogLine(true, str.GetString());
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<BYTE> packet;
|
||||
CString str;
|
||||
if (atyp == SOCKS5_ATYP_IPV4) {
|
||||
if (s.pending.size() < 10)
|
||||
return true;
|
||||
packet.assign(11, 0);
|
||||
packet[0] = COMMAND_PROXY_CONNECT;
|
||||
memcpy(&packet[1], &id, sizeof(CONNID));
|
||||
memcpy(&packet[5], &s.pending[4], 6); // 4 字节 IPv4 + 2 字节端口
|
||||
s.pending.erase(s.pending.begin(), s.pending.begin() + 10);
|
||||
|
||||
in_addr inaddr = {};
|
||||
memcpy(&inaddr.s_addr, &packet[5], 4);
|
||||
char szDest[INET_ADDRSTRLEN] = {};
|
||||
inet_ntop(AF_INET, &inaddr, szDest, sizeof(szDest));
|
||||
u_short port = 0;
|
||||
memcpy(&port, &packet[9], 2);
|
||||
str.FormatL(_TRF("%u IPV4 连接 %s:%u...\r\n"), id, szDest, (UINT)ntohs(port));
|
||||
} else if (atyp == SOCKS5_ATYP_HOST) {
|
||||
const size_t hostLen = s.pending.size() > 4 ? s.pending[4] : 0;
|
||||
if (hostLen == 0)
|
||||
return false;
|
||||
const size_t need = 5 + hostLen + 2;
|
||||
if (s.pending.size() < need)
|
||||
return true;
|
||||
|
||||
packet.assign(7 + hostLen + 1, 0); // 末尾补的 1 字节是域名的 '\0'
|
||||
packet[0] = COMMAND_PROXY_CONNECT_HOSTNAME;
|
||||
memcpy(&packet[1], &id, sizeof(CONNID));
|
||||
memcpy(&packet[5], &s.pending[5 + hostLen], 2); // 端口
|
||||
memcpy(&packet[7], &s.pending[5], hostLen); // 域名(客户端按 gethostbyname 解析)
|
||||
s.pending.erase(s.pending.begin(), s.pending.begin() + need);
|
||||
|
||||
u_short port = 0;
|
||||
memcpy(&port, &packet[5], 2);
|
||||
str.FormatL(_TRF("%u 域名 连接 %s:%u\r\n"), id, (LPCSTR)&packet[7], (UINT)ntohs(port));
|
||||
} else if (atyp == SOCKS5_ATYP_IPV6) {
|
||||
const BYTE reply[10] = { SOCKS5_VER, SOCKS5_REP_ATYP_UNSUPPORTED, 0, SOCKS5_ATYP_IPV4, 0, 0, 0, 0, 0, 0 };
|
||||
toLocal.assign(reply, reply + sizeof(reply));
|
||||
str.FormatL(_TRF("%u IPV6连接 不支持...\r\n"), id);
|
||||
LogLine(true, str.GetString());
|
||||
return false;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 先置 connectSent 再由调用方下发:CONNECT 一旦发出,本地连接断开时就必须回 CLOSE,
|
||||
// 否则客户端的子连接和目标 socket 会一直挂着。
|
||||
s.connectSent = true;
|
||||
s.state = ST_CONNECTING;
|
||||
// pending 里可能已经粘着隧道数据,等客户端回 CONNECT_RESULT 后再转发(见 OnReceiveComplete)。
|
||||
toClient.swap(packet);
|
||||
LogLine(true, str.GetString());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void CProxyMapDlg::OnLocalDisconnect(CONNID id)
|
||||
{
|
||||
bool connectSent = false;
|
||||
ULONGLONG up = 0, down = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
auto it = m_sessions.find(id);
|
||||
if (it != m_sessions.end()) {
|
||||
connectSent = it->second.connectSent;
|
||||
up = it->second.bytesToTarget;
|
||||
down = it->second.bytesFromTarget;
|
||||
m_sessions.erase(it);
|
||||
}
|
||||
}
|
||||
// 已经向客户端下发过 CONNECT 的,要通知它关掉目标 socket,否则那条连接会挂在客户端。
|
||||
if (connectSent)
|
||||
SendProxyPacket(COMMAND_PROXY_CLOSE, id, NULL, 0);
|
||||
|
||||
CString str;
|
||||
if (up != 0 || down != 0) {
|
||||
str.FormatL(_TRF("%u 本地连接断开 (上行 %s, 下行 %s)\r\n"), id,
|
||||
FormatBytes(up).GetString(), FormatBytes(down).GetString());
|
||||
} else {
|
||||
str.FormatL(_TRF("%u 本地连接断开\r\n"), id);
|
||||
}
|
||||
LogLine(true, str.GetString());
|
||||
}
|
||||
|
||||
void CProxyMapDlg::OnReceive()
|
||||
@@ -214,81 +483,119 @@ void CProxyMapDlg::OnReceive()
|
||||
|
||||
void CProxyMapDlg::OnReceiveComplete()
|
||||
{
|
||||
if (m_iocpLocal == NULL)
|
||||
return;
|
||||
|
||||
if (m_iocpLocal->m_TcpServer->HasStarted() == FALSE || m_bIsClosed)
|
||||
if (m_iocpLocal == NULL || !m_iocpLocal->HasStarted() || m_bIsClosed)
|
||||
return;
|
||||
|
||||
LPBYTE buf = m_ContextObject->m_DeCompressionBuffer.GetBuffer(0);
|
||||
DWORD index = *(DWORD*)&buf[1];
|
||||
TCHAR szMsg[200];
|
||||
ULONG len = m_ContextObject->m_DeCompressionBuffer.GetBufferLength();
|
||||
if (len < 5)
|
||||
return;
|
||||
|
||||
CONNID id = 0;
|
||||
memcpy(&id, &buf[1], sizeof(CONNID));
|
||||
CString str;
|
||||
|
||||
switch (buf[0]) {
|
||||
case TOKEN_PROXY_CONNECT_RESULT: {
|
||||
char msg_request_co_ok[] = { 0X05, 0X00, 0X00, 0X01, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00 }; // Request connect OK
|
||||
if (len < 11)
|
||||
break;
|
||||
// [token][id:4][ip:4][port:2];端口为 0 表示客户端连不上目标。
|
||||
const bool ok = !(buf[9] == 0 && buf[10] == 0);
|
||||
BYTE reply[10] = { SOCKS5_VER, (BYTE)(ok ? SOCKS5_REP_SUCCEEDED : SOCKS5_REP_REFUSED), 0, SOCKS5_ATYP_IPV4, 0, 0, 0, 0, 0, 0 };
|
||||
memcpy(&reply[4], &buf[5], 6);
|
||||
m_iocpLocal->Send(id, reply, sizeof(reply));
|
||||
|
||||
BYTE sendbuf[10] = "";
|
||||
sendbuf[0] = 5;
|
||||
sendbuf[1] = (buf[9] || buf[10]) ? 0 : 5;
|
||||
sendbuf[2] = 0;
|
||||
sendbuf[3] = 1;
|
||||
memcpy(&sendbuf[4], &buf[5], 6);
|
||||
|
||||
ClientContext* pContext_proxy = NULL;
|
||||
if (m_iocpLocal->m_TcpServer->GetConnectionExtra((CONNID)index, (PVOID*)&pContext_proxy) && pContext_proxy != nullptr) {
|
||||
if (sendbuf[1] == 0) {
|
||||
pContext_proxy->m_bProxyConnected = 2;
|
||||
wsprintf(szMsg, _TRF("%d 连接成功\r\n"), index);
|
||||
} else
|
||||
wsprintf(szMsg, _TRF("%d 连接失败\r\n"), index);
|
||||
m_iocpLocal->Send(pContext_proxy, sendbuf, sizeof(sendbuf));
|
||||
AddLog(szMsg);
|
||||
// 进入隧道阶段,取走握手期间粘在 CONNECT 请求后面的字节。
|
||||
std::vector<BYTE> buffered;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
auto it = m_sessions.find(id);
|
||||
if (it != m_sessions.end()) {
|
||||
it->second.lastTick = GetTickCount64();
|
||||
if (ok) {
|
||||
it->second.state = ST_TUNNEL;
|
||||
buffered.swap(it->second.pending);
|
||||
it->second.bytesToTarget += buffered.size(); // 记账要和转发一致
|
||||
} else {
|
||||
it->second.pending.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
// 应答先于数据:SOCKS5 客户端要等到应答才认为隧道可用(curl 甚至会先等这条
|
||||
// 10 字节回复再发请求),顺序反了它会把数据当垃圾丢掉。
|
||||
if (ok && !buffered.empty())
|
||||
SendProxyPacket(COMMAND_PROXY_DATA, id, buffered.data(), (UINT)buffered.size());
|
||||
if (ok)
|
||||
str.FormatL(_TRF("%u 连接成功\r\n"), id);
|
||||
else
|
||||
str.FormatL(_TRF("%u 连接失败\r\n"), id);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case TOKEN_PROXY_BIND_RESULT:
|
||||
break;
|
||||
case TOKEN_PROXY_CLOSE: {
|
||||
wsprintf(szMsg, _T("%d TOKEN_PROXY_CLOSE\r\n"), index);
|
||||
|
||||
m_iocpLocal->Disconnect(index);
|
||||
AddLog(szMsg);
|
||||
}
|
||||
break;
|
||||
case TOKEN_PROXY_DATA: {
|
||||
ClientContext* pContext_proxy = NULL;
|
||||
BOOL ok = FALSE;
|
||||
if (m_iocpLocal->m_TcpServer->GetConnectionExtra((CONNID)index, (PVOID*)&pContext_proxy) && pContext_proxy != nullptr) {
|
||||
ok = m_iocpLocal->Send(pContext_proxy, &buf[5], m_ContextObject->m_DeCompressionBuffer.GetBufferLength() - 5);
|
||||
if (ok == FALSE) {
|
||||
wsprintf(szMsg, _T("%d TOKEN_PROXY_CLOSE\r\n"), index);
|
||||
m_iocpLocal->Disconnect(index);
|
||||
AddLog(szMsg);
|
||||
return;
|
||||
}
|
||||
wsprintf(szMsg, _TRF("%d ==>收 %d bytes\r\n"), index, m_ContextObject->m_DeCompressionBuffer.GetBufferLength() - 5);
|
||||
AddLog(szMsg);
|
||||
case TOKEN_PROXY_CLOSE:
|
||||
str.FormatL(_TRF("%u 客户端请求断开\r\n"), id);
|
||||
m_iocpLocal->Disconnect(id);
|
||||
break;
|
||||
case TOKEN_PROXY_DATA:
|
||||
// 空数据包不转发(Send 对 nSize == 0 直接返回 FALSE,不能当成连接出错)。
|
||||
if (len <= 5)
|
||||
break;
|
||||
if (!m_iocpLocal->Send(id, &buf[5], len - 5)) {
|
||||
str.FormatL(_TRF("%u 下行发送失败, 断开\r\n"), id);
|
||||
m_iocpLocal->Disconnect(id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
auto it = m_sessions.find(id);
|
||||
if (it != m_sessions.end()) {
|
||||
LocalSession& s = it->second;
|
||||
s.bytesFromTarget += len - 5;
|
||||
const ULONGLONG now = GetTickCount64();
|
||||
if (now - s.lastLogTick >= PROXY_LOG_INTERVAL_MS) {
|
||||
s.lastLogTick = now;
|
||||
str.FormatL(_TRF("%u >> 下行 %s\r\n"), id, FormatBytes(s.bytesFromTarget).GetString());
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
default:
|
||||
// 传输发生异常数据
|
||||
break;
|
||||
return;
|
||||
}
|
||||
if (!str.IsEmpty())
|
||||
LogLine(false, str.GetString());
|
||||
}
|
||||
|
||||
void CProxyMapDlg::AddLog(TCHAR* lpText)
|
||||
void CProxyMapDlg::OnTimer(UINT_PTR nIDEvent)
|
||||
{
|
||||
if (m_bIsClosed == TRUE) return;
|
||||
m_Edit.SetSel(-1, -1);
|
||||
m_Edit.ReplaceSel(lpText);
|
||||
}
|
||||
|
||||
void CProxyMapDlg::AddLog_other(TCHAR* lpText)
|
||||
{
|
||||
if (m_bIsClosed == TRUE) return;
|
||||
m_EditOther.SetSel(-1, -1);
|
||||
m_EditOther.ReplaceSel(lpText);
|
||||
if (nIDEvent == IDT_PROXY_LOG_FLUSH) {
|
||||
// 一次性定时器:攒够一批日志就刷新控件。
|
||||
KillTimer(IDT_PROXY_LOG_FLUSH);
|
||||
FlushLog();
|
||||
} else if (nIDEvent == IDT_PROXY_HANDSHAKE && m_iocpLocal != NULL && !m_bIsClosed) {
|
||||
// 握手(含 CONNECTING 等客户端回结果)卡住就清掉,免得每点一次页面就在
|
||||
// 服务端留一条永远不动的本地连接。隧道阶段是长连接,不参与超时。
|
||||
const ULONGLONG now = GetTickCount64();
|
||||
std::vector<CONNID> stale;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_sessLock);
|
||||
for (auto& kv : m_sessions) {
|
||||
if (kv.second.state != ST_TUNNEL &&
|
||||
now - kv.second.lastTick > PROXY_HANDSHAKE_TIMEOUT_MS) {
|
||||
stale.push_back(kv.first);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (CONNID id : stale) {
|
||||
CString str;
|
||||
str.FormatL(_TRF("%u 握手超时, 断开\r\n"), id);
|
||||
LogLine(true, str.GetString());
|
||||
m_iocpLocal->Disconnect(id);
|
||||
}
|
||||
}
|
||||
__super::OnTimer(nIDEvent);
|
||||
}
|
||||
|
||||
void CProxyMapDlg::OnSize(UINT nType, int cx, int cy)
|
||||
|
||||
@@ -3,65 +3,94 @@
|
||||
#include "ProxyConnectServer.h"
|
||||
#include "Resource.h"
|
||||
|
||||
// 这个库比较大,且只在需要代理映射时使用
|
||||
// 如有需要,需手动开启并链接这个库
|
||||
// https://github.com/ldcsaa/HP-Socket
|
||||
// 惠普 socket - High Performance socket
|
||||
#define ENABLE_HPSOCKET 0
|
||||
|
||||
#if ENABLE_HPSOCKET
|
||||
#ifdef _WIN64
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "HPSocket_x64D.lib")
|
||||
#else
|
||||
#pragma comment(lib, "HPSocket_x64.lib")
|
||||
#endif
|
||||
|
||||
#else
|
||||
#ifdef _DEBUG
|
||||
#pragma comment(lib, "HPSocket_D.lib")
|
||||
#else
|
||||
#pragma comment(lib, "HPSocket.lib")
|
||||
#endif
|
||||
|
||||
#endif
|
||||
#endif
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
/////////////////////////////////////////////////////////////////////////////
|
||||
// CProxyMapDlg dialog
|
||||
typedef struct {
|
||||
BYTE Ver; // Version Number
|
||||
BYTE CMD; // 0x01==TCP CONNECT,0x02==TCP BIND,0x03==UDP ASSOCIATE
|
||||
BYTE RSV;
|
||||
BYTE ATYP;
|
||||
BYTE IP_LEN;
|
||||
BYTE szIP;
|
||||
} Socks5Info;
|
||||
|
||||
//
|
||||
// 代理映射的「本地侧」:在本机监听一个 SOCKS5 端口,把浏览器/curl 的连接
|
||||
// 转发到目标主机的客户端,再由客户端连真正的目标。本文件只处理 SOCKS5 与
|
||||
// 代理报文,socket 层在 ProxyConnectServer(自实现,不再依赖 HP-Socket)。
|
||||
//
|
||||
// 代理测试: curl --socks5 127.0.0.1:5543 https://www.example.com
|
||||
class CProxyMapDlg : public DialogBase
|
||||
{
|
||||
public:
|
||||
CProxyMapDlg(CWnd* pParent = NULL, Server* pIOCPServer = NULL, ClientContext* pContext = NULL);
|
||||
virtual ~CProxyMapDlg();
|
||||
|
||||
enum { IDD = IDD_PROXY };
|
||||
|
||||
static void CALLBACK NotifyProc(void* user, ClientContext* pContext, UINT nCode);
|
||||
// 监听器回调(运行在 accept 线程 / 每连接中继线程内)
|
||||
static void CALLBACK NotifyProc(void* user, CONNID id, const BYTE* pData, UINT nLen, UINT nCode);
|
||||
// 流控回调(运行在该连接的中继线程内):主连接发送队列堆积时暂停读取本地连接
|
||||
static BOOL CALLBACK CanRecvProc(void* user, CONNID id);
|
||||
|
||||
void OnReceiveComplete();
|
||||
void OnReceive();
|
||||
void AddLog(TCHAR* lpText);
|
||||
void AddLog_other(TCHAR* lpText);
|
||||
virtual void DoDataExchange(CDataExchange* pDX);
|
||||
virtual void OnCancel();
|
||||
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
|
||||
virtual BOOL OnInitDialog();
|
||||
afx_msg void OnSize(UINT nType, int cx, int cy);
|
||||
afx_msg void OnTimer(UINT_PTR nIDEvent);
|
||||
afx_msg LRESULT OnProxyLog(WPARAM wParam, LPARAM lParam);
|
||||
DECLARE_MESSAGE_MAP()
|
||||
|
||||
private:
|
||||
CProxyConnectServer* m_iocpLocal;
|
||||
// SOCKS5 握手的阶段。只有 ST_TUNNEL 之后流里才是裸数据。
|
||||
enum {
|
||||
ST_GREETING = 0, // 等客户端的 VER/NMETHODS
|
||||
ST_REQUEST = 1, // 已回「无需认证」,等 CONNECT 请求
|
||||
ST_CONNECTING = 2, // CONNECT 已交给客户端,等它回结果
|
||||
ST_TUNNEL = 3 // 隧道已建立,字节原样转发
|
||||
};
|
||||
|
||||
// 每条本机连接的「本地侧」状态。
|
||||
struct LocalSession {
|
||||
int state = ST_GREETING;
|
||||
bool connectSent = false; // 是否已向客户端下发过 CONNECT(决定断开时要不要回 CLOSE)
|
||||
ULONGLONG lastTick = 0; // 最近一次收到数据 / 状态推进的时刻(GetTickCount64)
|
||||
// 隧道字节数(连接结束时打一行汇总)。分片级日志会淹没界面、拖慢 UI 线程,
|
||||
// 300MB 的下载能产生上万条消息。
|
||||
ULONGLONG bytesToTarget = 0; // 本机 -> 客户端
|
||||
ULONGLONG bytesFromTarget = 0; // 客户端 -> 本机
|
||||
ULONGLONG lastLogTick = 0; // 上次打印进度日志的时刻
|
||||
// 握手阶段攒下的字节。TCP 是流:一次 recv 可能是半条消息,也可能连隧道数据一起
|
||||
// 带过来,所以先攒着,按状态机逐条切分。
|
||||
std::vector<BYTE> pending;
|
||||
};
|
||||
|
||||
void OnLocalConnect(CONNID id);
|
||||
void OnLocalReceive(CONNID id, const BYTE* pData, UINT nLen);
|
||||
void OnLocalDisconnect(CONNID id);
|
||||
// 按 SOCKS5 字节流推进握手。需要下发的报文放进 toLocal(回本机客户端)/
|
||||
// toClient(发给客户端的 CONNECT),由调用方在锁外发送。
|
||||
// 返回 false 表示协议不符,调用方应断开这条连接。
|
||||
bool ParseSocks5(CONNID id, LocalSession& s, std::vector<BYTE>& toLocal, std::vector<BYTE>& toClient);
|
||||
|
||||
// 组 [token][id:4][payload] 发给客户端(与客户端 CProxyManager 的协议一致)。
|
||||
BOOL SendProxyPacket(BYTE token, CONNID id, const BYTE* pData, UINT nLen);
|
||||
void LogLine(bool other, LPCTSTR text);
|
||||
// 日志框是只读的(EM_REPLACESEL 无效),文本先在 buffer 里累积,再由 FlushLog
|
||||
// 合并刷进控件(每行都 SetWindowText 会拖死 UI 线程)。
|
||||
void AppendLog(CString& buffer, LPCTSTR text);
|
||||
void FlushLog();
|
||||
|
||||
CProxyConnectServer* m_iocpLocal;
|
||||
CEdit m_Edit;
|
||||
USHORT m_nPort;
|
||||
CEdit m_EditOther;
|
||||
USHORT m_nPort;
|
||||
|
||||
std::mutex m_sessLock;
|
||||
std::map<CONNID, LocalSession> m_sessions;
|
||||
|
||||
// 两个日志框的全文(只在 UI 线程读写)。
|
||||
CString m_strLog;
|
||||
CString m_strLogOther;
|
||||
bool m_bLogDirtyMain = false;
|
||||
bool m_bLogDirtyOther = false;
|
||||
bool m_bLogFlushPending = false;
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
Binary file not shown.
|
After Width: | Height: | Size: 822 B |
@@ -64,6 +64,7 @@ res/
|
||||
|--------|------|----------|
|
||||
| `note.bmp` | 修改备注 | 右键菜单 |
|
||||
| `EditGroup.bmp` | 修改分组 | 右键菜单 |
|
||||
| `CopyName.bmp` | 复制名称 | 右键菜单 |
|
||||
| `AddWatch.bmp` | 添加关注 | 右键菜单 |
|
||||
| `LoginNotify.bmp` | 上线提醒 | 右键菜单 |
|
||||
| `AdminRun.bmp` | 直接执行代码 | 右键菜单 |
|
||||
|
||||
@@ -295,6 +295,7 @@
|
||||
#define IDB_BITMAP_PREVIEW_QUALITY 413
|
||||
#define IDB_BITMAP_FILE_SPEED 414
|
||||
#define IDB_BITMAP_DISCLAIMER 415
|
||||
#define IDB_BITMAP_COPYNAME 416
|
||||
#define IDC_MESSAGE 1000
|
||||
#define IDC_ONLINE 1001
|
||||
#define IDC_STATIC_TIPS 1002
|
||||
@@ -1111,14 +1112,19 @@
|
||||
#define ID_EXPERIMENT_TLS_ENABLE 33094
|
||||
#define ID_EXPERIMENT_TLS_DISABLE 33095
|
||||
#define ID_MSGLOG_WHITELIST_IP 33096
|
||||
#define ID_ONLINE_COPY_NAME 33097
|
||||
// 协议切换(在线主机列表右键菜单,与「实验功能」平级)
|
||||
#define ID_PROTO_SWITCH_TCP 33098
|
||||
#define ID_PROTO_SWITCH_WS 33099
|
||||
#define ID_PROTO_SWITCH_WSS 33100
|
||||
#define ID_EXIT_FULLSCREEN 40001
|
||||
|
||||
// Next default values for new objects
|
||||
//
|
||||
//
|
||||
#ifdef APSTUDIO_INVOKED
|
||||
#ifndef APSTUDIO_READONLY_SYMBOLS
|
||||
#define _APS_NEXT_RESOURCE_VALUE 416
|
||||
#define _APS_NEXT_COMMAND_VALUE 33097
|
||||
#define _APS_NEXT_RESOURCE_VALUE 417
|
||||
#define _APS_NEXT_COMMAND_VALUE 33101
|
||||
#define _APS_NEXT_CONTROL_VALUE 2621
|
||||
#define _APS_NEXT_SYMED_VALUE 105
|
||||
#endif
|
||||
|
||||
@@ -1153,6 +1153,22 @@ func main() {
|
||||
log.Info("ConnAuth HMAC verification enabled for device sub-connections (YAMA_CONN_AUTH_KEY)")
|
||||
}
|
||||
|
||||
// Optional WebSocket transport on the device port, for devices that can only
|
||||
// reach the server through a reverse proxy on a shared port (nginx on 443).
|
||||
// YAMA_WS_PATH restricts upgrades to one request path (empty = any path).
|
||||
// YAMA_TRUSTED_PROXIES lists the IPs/CIDRs allowed to report a device's real
|
||||
// address via X-Forwarded-For / X-Real-IP (default: loopback only).
|
||||
wsPath := strings.TrimSpace(os.Getenv("YAMA_WS_PATH"))
|
||||
trustedProxies := splitCSV(os.Getenv("YAMA_TRUSTED_PROXIES"))
|
||||
if wsPath != "" {
|
||||
log.Info("WebSocket transport on device port enabled: path=%s", wsPath)
|
||||
} else {
|
||||
log.Info("WebSocket transport on device port enabled: any path")
|
||||
}
|
||||
if len(trustedProxies) > 0 {
|
||||
log.Info("Trusting forwarded client IPs from: %s", strings.Join(trustedProxies, ", "))
|
||||
}
|
||||
|
||||
// Create servers for each port
|
||||
var servers []*server.Server
|
||||
for _, port := range ports {
|
||||
@@ -1163,6 +1179,8 @@ func main() {
|
||||
config.PerIPConnRateLimit = envInt("YAMA_PERIP_CONN_RATE", config.PerIPConnRateLimit)
|
||||
config.TLSCertFile = tlsCert
|
||||
config.TLSKeyFile = tlsKey
|
||||
config.WSPath = wsPath
|
||||
config.TrustedProxies = trustedProxies
|
||||
|
||||
srv := server.New(config)
|
||||
srv.SetLogger(log.WithPrefix(fmt.Sprintf("Server:%d", port)))
|
||||
|
||||
@@ -61,6 +61,10 @@ type Context struct {
|
||||
closed atomic.Bool
|
||||
sendLock sync.Mutex
|
||||
server *Manager
|
||||
|
||||
// peerIPOverride replaces the address derived from RemoteAddr when a
|
||||
// trusted reverse proxy reports the device's real address.
|
||||
peerIPOverride string
|
||||
}
|
||||
|
||||
// FlagType represents the protocol flag type
|
||||
@@ -156,12 +160,28 @@ func (c *Context) IsClosed() bool {
|
||||
|
||||
// GetPeerIP returns the peer IP address
|
||||
func (c *Context) GetPeerIP() string {
|
||||
c.mu.RLock()
|
||||
override := c.peerIPOverride
|
||||
c.mu.RUnlock()
|
||||
if override != "" {
|
||||
return override
|
||||
}
|
||||
if host, _, err := net.SplitHostPort(c.RemoteAddr); err == nil {
|
||||
return host
|
||||
}
|
||||
return c.RemoteAddr
|
||||
}
|
||||
|
||||
// SetPeerIP overrides the address reported by GetPeerIP. The server uses it
|
||||
// when a trusted reverse proxy reports a device's real address, so per-IP
|
||||
// accounting, logging and the ConnAuth sub-connection binding all see the
|
||||
// device rather than the proxy.
|
||||
func (c *Context) SetPeerIP(ip string) {
|
||||
c.mu.Lock()
|
||||
c.peerIPOverride = ip
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// AliveTime returns how long the connection has been alive
|
||||
func (c *Context) AliveTime() time.Duration {
|
||||
return time.Since(c.OnlineTime)
|
||||
|
||||
+76
-13
@@ -42,6 +42,17 @@ type Config struct {
|
||||
PerIPConnRateLimit int // max new connections per PerIPConnRateWindow per IP (0 = unlimited)
|
||||
PerIPConnRateWindow time.Duration // window for PerIPConnRateLimit
|
||||
|
||||
// WebSocket transport. Devices that can only reach the server through a
|
||||
// reverse proxy on a shared port (e.g. nginx on 443) upgrade to WebSocket;
|
||||
// the device port then carries the unchanged app protocol inside binary
|
||||
// frames. WSPath restricts the upgrade to one request path ("" = any).
|
||||
WSPath string
|
||||
|
||||
// TrustedProxies lists the IPs/CIDRs whose X-Forwarded-For / X-Real-IP
|
||||
// headers are believed. Only connections from these peers are allowed to
|
||||
// report a different device address; empty defaults to loopback.
|
||||
TrustedProxies []string
|
||||
|
||||
// TLSCertFile / TLSKeyFile enable optional one-way TLS on the device port.
|
||||
// When both are set the server loads the cert and auto-detects TLS clients
|
||||
// by their ClientHello; plaintext clients keep working unchanged. Both empty
|
||||
@@ -87,6 +98,10 @@ type Server struct {
|
||||
// wrapTLS consults it to sniff and wrap incoming connections.
|
||||
tlsCfg *tls.Config
|
||||
|
||||
// trustedProxies are the peers allowed to report a device's real address
|
||||
// via X-Forwarded-For / X-Real-IP (the reverse proxy in front of us).
|
||||
trustedProxies []*net.IPNet
|
||||
|
||||
running atomic.Bool
|
||||
wg sync.WaitGroup
|
||||
ctx context.Context
|
||||
@@ -109,6 +124,7 @@ func New(config Config) *Server {
|
||||
cancel: cancel,
|
||||
logger: logger.New(logger.DefaultConfig()).WithPrefix("Server"),
|
||||
}
|
||||
s.trustedProxies = parseTrustedProxies(config.TrustedProxies)
|
||||
|
||||
return s
|
||||
}
|
||||
@@ -356,38 +372,85 @@ func (s *Server) acceptLoop() {
|
||||
continue
|
||||
}
|
||||
|
||||
// Check connection limit before spawning goroutine
|
||||
// Check connection limit before spawning goroutine.
|
||||
if s.manager.Count() >= s.config.MaxConnections {
|
||||
s.logger.Warn("Max connections reached, rejecting new connection from %s", conn.RemoteAddr())
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
// Per-IP connection cap + accept rate. Rejecting here (before any
|
||||
// buffer allocation or goroutine) is cheap, and a rejected device
|
||||
// simply retries on its reconnect loop.
|
||||
if !s.ipLimit.allow(peerIP(conn.RemoteAddr())) {
|
||||
s.logger.Warn("Per-IP connection limit reached, rejecting %s", conn.RemoteAddr())
|
||||
peer := peerIP(conn.RemoteAddr())
|
||||
counted, allowed := s.limitDirectPeer(peer)
|
||||
if !allowed {
|
||||
s.logger.Warn("Per-IP connection limit reached, rejecting %s", peer)
|
||||
_ = conn.Close()
|
||||
continue
|
||||
}
|
||||
|
||||
// Handle each connection in its own goroutine
|
||||
go s.handleConnection(conn)
|
||||
go s.handleConnection(conn, counted)
|
||||
}
|
||||
}
|
||||
|
||||
// handleConnection handles a single connection
|
||||
func (s *Server) handleConnection(rawConn net.Conn) {
|
||||
// limitDirectPeer applies the per-IP cap and accept rate to a freshly accepted
|
||||
// peer, before the goroutine is spawned and before any sniffing read: a peer
|
||||
// that opens sockets and never sends a full ClientHello / upgrade would
|
||||
// otherwise hold a goroutine and a reader for up to ReadTimeout each, with no
|
||||
// limit at all. Peers that are trusted proxies are exempt and report
|
||||
// counted=false — every device behind a proxy arrives from the proxy's
|
||||
// address, so they are limited later by the address their proxy reports.
|
||||
func (s *Server) limitDirectPeer(peer string) (counted, allowed bool) {
|
||||
if s.trustedProxy(peer) {
|
||||
return false, true
|
||||
}
|
||||
if !s.ipLimit.allow(peer) {
|
||||
return false, false
|
||||
}
|
||||
return true, true
|
||||
}
|
||||
|
||||
// handleConnection handles a single connection. peerCapped reports whether
|
||||
// acceptLoop already counted this peer against the per-IP limiter (direct
|
||||
// peers only), in which case the count is released here when the connection
|
||||
// ends.
|
||||
func (s *Server) handleConnection(rawConn net.Conn, peerCapped bool) {
|
||||
peer := peerIP(rawConn.RemoteAddr())
|
||||
if peerCapped {
|
||||
defer s.ipLimit.release(peer)
|
||||
}
|
||||
|
||||
// Sniff and (when TLS is enabled) wrap TLS peers; plaintext passes through.
|
||||
conn := s.wrapTLS(rawConn)
|
||||
|
||||
// Sniff for a WebSocket upgrade. Proxied devices (nginx on a shared port)
|
||||
// arrive as a plaintext HTTP upgrade after the proxy terminated TLS.
|
||||
conn, realIP := s.wrapWebSocket(conn, peer)
|
||||
if conn == nil {
|
||||
return
|
||||
}
|
||||
|
||||
if !peerCapped {
|
||||
// Proxied device: limit by the forwarded address so one device behind
|
||||
// the proxy cannot consume the whole budget for everyone else.
|
||||
limitIP := peer
|
||||
if realIP != "" {
|
||||
limitIP = realIP
|
||||
}
|
||||
if !s.ipLimit.allow(limitIP) {
|
||||
s.logger.Warn("Per-IP connection limit reached, rejecting %s (peer %s)", limitIP, peer)
|
||||
_ = conn.Close()
|
||||
return
|
||||
}
|
||||
defer s.ipLimit.release(limitIP)
|
||||
}
|
||||
|
||||
// Create context
|
||||
ctx := connection.NewContext(conn, nil)
|
||||
|
||||
// Always release the per-IP slot on every exit path, including the
|
||||
// manager.Add failure below (a rare accept/add race).
|
||||
defer s.ipLimit.release(ctx.GetPeerIP())
|
||||
if realIP != "" {
|
||||
// Report the device's real address everywhere GetPeerIP is consulted
|
||||
// (per-IP accounting, logging, ConnAuth sub-connection binding).
|
||||
ctx.SetPeerIP(realIP)
|
||||
}
|
||||
|
||||
// Add to manager
|
||||
if err := s.manager.Add(ctx); err != nil {
|
||||
|
||||
@@ -93,6 +93,35 @@ func TestPeerIP(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// The per-IP cap must apply to direct peers before any sniffing read, so a
|
||||
// peer that connects and stays silent cannot hold unbounded goroutines and
|
||||
// readers. Peers that are trusted proxies are exempt (and counted later by the
|
||||
// forwarded address), because all devices behind a proxy share its address.
|
||||
func TestLimitDirectPeerBeforeSniff(t *testing.T) {
|
||||
cfg := DefaultConfig()
|
||||
cfg.PerIPMaxConnections = 1
|
||||
cfg.PerIPConnRateLimit = 0 // concurrent cap only
|
||||
s := New(cfg)
|
||||
|
||||
if counted, ok := s.limitDirectPeer("203.0.113.5"); !ok || !counted {
|
||||
t.Fatalf("first direct peer: counted=%v ok=%v, want true/true", counted, ok)
|
||||
}
|
||||
// A second silent socket from the same address must be refused outright.
|
||||
if counted, ok := s.limitDirectPeer("203.0.113.5"); ok || counted {
|
||||
t.Fatalf("second direct peer: counted=%v ok=%v, want false/false", counted, ok)
|
||||
}
|
||||
// Loopback is a trusted proxy by default: exempt from the peer cap here.
|
||||
if counted, ok := s.limitDirectPeer("127.0.0.1"); !ok || counted {
|
||||
t.Fatalf("trusted proxy: counted=%v ok=%v, want false/true", counted, ok)
|
||||
}
|
||||
|
||||
// Releasing the slot frees capacity again.
|
||||
s.ipLimit.release("203.0.113.5")
|
||||
if _, ok := s.limitDirectPeer("203.0.113.5"); !ok {
|
||||
t.Fatal("after release the address should be allowed again")
|
||||
}
|
||||
}
|
||||
|
||||
// A peer that sends bytes which never assemble into a complete packet (here an
|
||||
// HTTP-mask envelope with no terminating CRLF CRLF) must be disconnected once
|
||||
// the per-connection buffer cap is exceeded, rather than allowed to grow it
|
||||
@@ -110,7 +139,8 @@ func TestHandleConnectionBufferCap(t *testing.T) {
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
srv.handleConnection(serverConn)
|
||||
// false: acceptLoop was bypassed, so the peer was not pre-counted.
|
||||
srv.handleConnection(serverConn, false)
|
||||
close(done)
|
||||
}()
|
||||
|
||||
|
||||
@@ -0,0 +1,523 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// WebSocket transport for devices that can only reach the server through a
|
||||
// reverse proxy (nginx) on a shared port such as 443.
|
||||
//
|
||||
// The app protocol is unchanged: the WS layer is a transparent byte-stream
|
||||
// tunnel. A device connects to the proxy with a normal WebSocket upgrade,
|
||||
// nginx terminates TLS and proxies the (now plaintext) upgrade to the device
|
||||
// port, and this file completes the handshake and carries the existing parser
|
||||
// traffic inside binary frames.
|
||||
//
|
||||
// Upgrade request detection happens after the TLS sniff in handleConnection,
|
||||
// so a proxied wss connection (nginx terminates TLS) and a direct wss
|
||||
// connection (YAMA_TLS_CERT set, client speaks wss end to end) both work.
|
||||
|
||||
const (
|
||||
wsMagicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
|
||||
wsOpContinuation = 0x0
|
||||
wsOpText = 0x1
|
||||
wsOpBinary = 0x2
|
||||
wsOpClose = 0x8
|
||||
wsOpPing = 0x9
|
||||
wsOpPong = 0xA
|
||||
|
||||
// wsMaxHandshakeBytes caps the upgrade request head we are willing to
|
||||
// buffer before rejecting the peer.
|
||||
wsMaxHandshakeBytes = 8 * 1024
|
||||
|
||||
// wsHandshakeTimeout bounds reading the request head once "GET " was seen.
|
||||
wsHandshakeTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
var (
|
||||
errWSProtocol = errors.New("websocket: protocol error")
|
||||
errWSHandshake = errors.New("websocket: bad handshake")
|
||||
|
||||
// wsUpgradePrefix identifies an HTTP request whose first token is GET. The
|
||||
// app protocol never starts a connection with these bytes (its flags are
|
||||
// "Shine"/"HELL"/"POST" variants), so this is unambiguous.
|
||||
wsUpgradePrefix = []byte("GET ")
|
||||
)
|
||||
|
||||
// wrapWebSocket sniffs the already TLS-sniffed connection for an HTTP
|
||||
// WebSocket upgrade. When the peer is not upgrading, conn is returned
|
||||
// unchanged. When the upgrade completes, the returned net.Conn frames all
|
||||
// reads/writes, and realIP carries the client address reported by a trusted
|
||||
// reverse proxy (empty otherwise). A failed upgrade returns (nil, "").
|
||||
func (s *Server) wrapWebSocket(conn net.Conn, peer string) (net.Conn, string) {
|
||||
br := bufio.NewReader(conn)
|
||||
// Bound the sniff even when the server has no ReadTimeout: a peer that opens a
|
||||
// socket and never sends the prefix would otherwise hold the goroutine (and its
|
||||
// per-IP slot) for as long as it likes. When ReadTimeout is configured and
|
||||
// shorter, keep the tighter bound.
|
||||
sniffTimeout := wsHandshakeTimeout
|
||||
if s.config.ReadTimeout > 0 && s.config.ReadTimeout < sniffTimeout {
|
||||
sniffTimeout = s.config.ReadTimeout
|
||||
}
|
||||
_ = conn.SetReadDeadline(time.Now().Add(sniffTimeout))
|
||||
hdr, err := br.Peek(len(wsUpgradePrefix))
|
||||
_ = conn.SetReadDeadline(time.Time{})
|
||||
if err != nil {
|
||||
// Peer never sent enough to identify itself; let the normal read loop
|
||||
// surface EOF/timeout exactly as it would without the sniff.
|
||||
return &bufferedConn{Conn: conn, r: br}, ""
|
||||
}
|
||||
if !bytes.Equal(hdr, wsUpgradePrefix) {
|
||||
return &bufferedConn{Conn: conn, r: br}, ""
|
||||
}
|
||||
|
||||
req, err := readWSRequest(br, conn)
|
||||
if err != nil {
|
||||
s.logger.Debug("wrapWebSocket: reject %s: %v", conn.RemoteAddr(), err)
|
||||
writeWSReject(conn, err)
|
||||
_ = conn.Close()
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
if s.config.WSPath != "" && req.path != s.config.WSPath {
|
||||
s.logger.Debug("wrapWebSocket: reject %s: path %q != %q", conn.RemoteAddr(), req.path, s.config.WSPath)
|
||||
writeWSReject(conn, errWSProtocol)
|
||||
_ = conn.Close()
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
accept := wsAcceptKey(req.key)
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(wsHandshakeTimeout))
|
||||
resp := "HTTP/1.1 101 Switching Protocols\r\n" +
|
||||
"Upgrade: websocket\r\n" +
|
||||
"Connection: Upgrade\r\n" +
|
||||
"Sec-WebSocket-Accept: " + accept + "\r\n\r\n"
|
||||
_, werr := io.WriteString(conn, resp)
|
||||
_ = conn.SetWriteDeadline(time.Time{})
|
||||
if werr != nil {
|
||||
_ = conn.Close()
|
||||
return nil, ""
|
||||
}
|
||||
|
||||
realIP := ""
|
||||
if s.trustedProxy(peer) {
|
||||
realIP = reqForwardedIP(req.headers)
|
||||
}
|
||||
if realIP != "" {
|
||||
s.logger.Info("WebSocket device from %s (forwarded by %s)", realIP, peer)
|
||||
} else {
|
||||
s.logger.Info("WebSocket device from %s", peer)
|
||||
}
|
||||
return newWSConn(conn, br), realIP
|
||||
}
|
||||
|
||||
// wsRequest is the parsed subset of an upgrade request the server needs.
|
||||
type wsRequest struct {
|
||||
path string
|
||||
key string
|
||||
headers map[string]string // lower-cased names; repeated headers joined by ", "
|
||||
}
|
||||
|
||||
// readWSRequest reads and validates the HTTP upgrade head. The buffered reader
|
||||
// is left positioned at the first byte after the head so any frames the peer
|
||||
// pipelined behind the request are preserved.
|
||||
func readWSRequest(br *bufio.Reader, conn net.Conn) (*wsRequest, error) {
|
||||
_ = conn.SetReadDeadline(time.Now().Add(wsHandshakeTimeout))
|
||||
defer func() { _ = conn.SetReadDeadline(time.Time{}) }()
|
||||
|
||||
total := 0
|
||||
line, err := readWSLine(br, &total)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
parts := strings.Fields(line)
|
||||
if len(parts) != 3 || parts[0] != "GET" || !strings.HasPrefix(parts[2], "HTTP/1.") {
|
||||
return nil, errWSHandshake
|
||||
}
|
||||
req := &wsRequest{headers: make(map[string]string)}
|
||||
req.path = parts[1]
|
||||
if i := strings.IndexByte(req.path, '?'); i >= 0 {
|
||||
req.path = req.path[:i]
|
||||
}
|
||||
|
||||
for {
|
||||
line, err = readWSLine(br, &total)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if line == "" {
|
||||
break
|
||||
}
|
||||
name, value, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
return nil, errWSHandshake
|
||||
}
|
||||
name = strings.ToLower(strings.TrimSpace(name))
|
||||
value = strings.TrimSpace(value)
|
||||
if prev, dup := req.headers[name]; dup {
|
||||
req.headers[name] = prev + ", " + value
|
||||
} else {
|
||||
req.headers[name] = value
|
||||
}
|
||||
}
|
||||
|
||||
if !headerHasToken(req.headers["upgrade"], "websocket") ||
|
||||
!headerHasToken(req.headers["connection"], "upgrade") {
|
||||
return nil, errWSHandshake
|
||||
}
|
||||
req.key = req.headers["sec-websocket-key"]
|
||||
if req.key == "" {
|
||||
return nil, errWSHandshake
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// readWSLine reads one CRLF-terminated line, rejecting the peer as soon as the
|
||||
// accumulated head exceeds wsMaxHandshakeBytes. The input is peer-controlled:
|
||||
// a plain ReadString would buffer a newline-free line without limit.
|
||||
func readWSLine(br *bufio.Reader, total *int) (string, error) {
|
||||
var line []byte
|
||||
for {
|
||||
chunk, err := br.ReadSlice('\n')
|
||||
line = append(line, chunk...)
|
||||
*total += len(chunk)
|
||||
if *total > wsMaxHandshakeBytes {
|
||||
return "", errWSProtocol
|
||||
}
|
||||
if err == bufio.ErrBufferFull {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimRight(string(line), "\r\n"), nil
|
||||
}
|
||||
}
|
||||
|
||||
// headerHasToken reports whether a comma-separated header value contains token
|
||||
// (case-insensitive), as required for Connection: keep-alive, Upgrade.
|
||||
func headerHasToken(value, token string) bool {
|
||||
for _, part := range strings.Split(value, ",") {
|
||||
if strings.EqualFold(strings.TrimSpace(part), token) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// reqForwardedIP extracts the device's real address from a proxy's forwarded
|
||||
// headers. The LAST X-Forwarded-For entry wins, not the first: nginx's
|
||||
// $proxy_add_x_forwarded_for appends the address it accepted the connection
|
||||
// from, so whatever a client prepends is ignored — the same rule web/ws.go's
|
||||
// clientIP applies. Trusting the first entry would let a device rotate its key
|
||||
// through the per-IP budget, the login throttle and the ConnAuth peer binding.
|
||||
// X-Real-IP is only a fallback for proxies configured to set that and not XFF.
|
||||
// Only IP literals are accepted, so a header cannot inject an arbitrary peer key.
|
||||
func reqForwardedIP(headers map[string]string) string {
|
||||
if xff := headers["x-forwarded-for"]; xff != "" {
|
||||
last := strings.TrimSpace(xff[strings.LastIndexByte(xff, ',')+1:])
|
||||
if ip := headerIP(last); ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
return headerIP(headers["x-real-ip"])
|
||||
}
|
||||
|
||||
func headerIP(s string) string {
|
||||
s = strings.TrimSpace(s)
|
||||
if i := strings.LastIndexByte(s, ':'); i > 0 && strings.Count(s, ":") == 1 {
|
||||
// strip an IPv4:port pair, but leave bare IPv6 literals alone
|
||||
if net.ParseIP(s[:i]) != nil {
|
||||
s = s[:i]
|
||||
}
|
||||
}
|
||||
if ip := net.ParseIP(s); ip != nil {
|
||||
return ip.String()
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// wsAcceptKey computes Sec-WebSocket-Accept: base64(SHA1(key + magic GUID)).
|
||||
func wsAcceptKey(key string) string {
|
||||
h := sha1.New()
|
||||
io.WriteString(h, key)
|
||||
io.WriteString(h, wsMagicGUID)
|
||||
return base64.StdEncoding.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func writeWSReject(conn net.Conn, reason error) {
|
||||
status := "400 Bad Request"
|
||||
body := "bad request"
|
||||
if errors.Is(reason, errWSProtocol) {
|
||||
body = "protocol error"
|
||||
}
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(wsHandshakeTimeout))
|
||||
fmt.Fprintf(conn, "HTTP/1.1 %s\r\nContent-Type: text/plain\r\nContent-Length: %d\r\nConnection: close\r\n\r\n%s",
|
||||
status, len(body), body)
|
||||
}
|
||||
|
||||
// trustedProxy reports whether peer is allowed to set the device's real IP via
|
||||
// forwarded headers. Without this check any direct client could spoof its
|
||||
// address and, with it, the per-IP limits and the ConnAuth peer binding.
|
||||
func (s *Server) trustedProxy(peer string) bool {
|
||||
ip := net.ParseIP(peer)
|
||||
if ip == nil {
|
||||
return false
|
||||
}
|
||||
for _, n := range s.trustedProxies {
|
||||
if n.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// parseTrustedProxies converts configured IPs/CIDRs into networks. An empty or
|
||||
// unparsable list falls back to loopback, the only sensible default for a
|
||||
// proxy running on the same host as the server.
|
||||
func parseTrustedProxies(list []string) []*net.IPNet {
|
||||
var nets []*net.IPNet
|
||||
for _, item := range list {
|
||||
item = strings.TrimSpace(item)
|
||||
if item == "" {
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(item, "/") {
|
||||
if ip := net.ParseIP(item); ip != nil {
|
||||
bits := 32
|
||||
if ip.To4() == nil {
|
||||
bits = 128
|
||||
}
|
||||
item = fmt.Sprintf("%s/%d", ip.String(), bits)
|
||||
}
|
||||
}
|
||||
if _, n, err := net.ParseCIDR(item); err == nil {
|
||||
nets = append(nets, n)
|
||||
}
|
||||
}
|
||||
if len(nets) == 0 {
|
||||
_, v4, _ := net.ParseCIDR("127.0.0.0/8")
|
||||
_, v6, _ := net.ParseCIDR("::1/128")
|
||||
nets = append(nets, v4, v6)
|
||||
}
|
||||
return nets
|
||||
}
|
||||
|
||||
// wsConn presents a WebSocket connection as a net.Conn byte stream: each Write
|
||||
// becomes one binary frame and Read returns the concatenated payload of data
|
||||
// frames, transparently answering pings and closes. Frame payloads are streamed
|
||||
// rather than buffered whole, so a multi-megabyte upload allocates nothing here.
|
||||
type wsConn struct {
|
||||
conn net.Conn
|
||||
r *bufio.Reader
|
||||
|
||||
writeMu sync.Mutex
|
||||
closeMu sync.Mutex
|
||||
closed bool
|
||||
|
||||
// state of the data frame currently being read
|
||||
remaining int64
|
||||
masked bool
|
||||
mask [4]byte
|
||||
maskPos byte
|
||||
}
|
||||
|
||||
func newWSConn(conn net.Conn, r *bufio.Reader) *wsConn {
|
||||
return &wsConn{conn: conn, r: r}
|
||||
}
|
||||
|
||||
// Read implements net.Conn.
|
||||
func (c *wsConn) Read(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
for {
|
||||
if c.remaining > 0 {
|
||||
n := len(p)
|
||||
if int64(n) > c.remaining {
|
||||
n = int(c.remaining)
|
||||
}
|
||||
nr, err := io.ReadFull(c.r, p[:n])
|
||||
if nr > 0 {
|
||||
if c.masked {
|
||||
for i := 0; i < nr; i++ {
|
||||
p[i] ^= c.mask[c.maskPos]
|
||||
c.maskPos = (c.maskPos + 1) & 3
|
||||
}
|
||||
}
|
||||
c.remaining -= int64(nr)
|
||||
}
|
||||
if err != nil {
|
||||
return nr, err
|
||||
}
|
||||
return nr, nil
|
||||
}
|
||||
|
||||
opcode, fin, length, masked, err := c.readFrameHeader()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if opcode >= 0x8 {
|
||||
if !fin || length > 125 {
|
||||
return 0, errWSProtocol
|
||||
}
|
||||
payload, err := c.readControlPayload(int(length), masked)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch opcode {
|
||||
case wsOpClose:
|
||||
_ = c.writeFrame(wsOpClose, payload[:min(len(payload), 125)])
|
||||
return 0, io.EOF
|
||||
case wsOpPing:
|
||||
if err := c.writeFrame(wsOpPong, payload); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
case wsOpPong:
|
||||
// ignore
|
||||
default:
|
||||
return 0, errWSProtocol
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
switch opcode {
|
||||
case wsOpBinary, wsOpText, wsOpContinuation:
|
||||
default:
|
||||
return 0, errWSProtocol
|
||||
}
|
||||
if length == 0 {
|
||||
continue
|
||||
}
|
||||
c.remaining = length
|
||||
c.masked = masked
|
||||
c.maskPos = 0
|
||||
}
|
||||
}
|
||||
|
||||
// readFrameHeader reads and validates a frame header. Frames from the client
|
||||
// are normally masked; unmasked data frames are tolerated because the only
|
||||
// speakers on this port are YAMA's own clients.
|
||||
func (c *wsConn) readFrameHeader() (opcode byte, fin bool, length int64, masked bool, err error) {
|
||||
var hdr [2]byte
|
||||
if _, err = io.ReadFull(c.r, hdr[:]); err != nil {
|
||||
return
|
||||
}
|
||||
if hdr[0]&0x70 != 0 {
|
||||
return 0, false, 0, false, errWSProtocol // RSV bits set without a negotiated extension
|
||||
}
|
||||
fin = hdr[0]&0x80 != 0
|
||||
opcode = hdr[0] & 0x0f
|
||||
masked = hdr[1]&0x80 != 0
|
||||
length = int64(hdr[1] & 0x7f)
|
||||
|
||||
switch length {
|
||||
case 126:
|
||||
var ext [2]byte
|
||||
if _, err = io.ReadFull(c.r, ext[:]); err != nil {
|
||||
return
|
||||
}
|
||||
length = int64(binary.BigEndian.Uint16(ext[:]))
|
||||
case 127:
|
||||
var ext [8]byte
|
||||
if _, err = io.ReadFull(c.r, ext[:]); err != nil {
|
||||
return
|
||||
}
|
||||
u := binary.BigEndian.Uint64(ext[:])
|
||||
if u > 1<<62 {
|
||||
return 0, false, 0, false, errWSProtocol
|
||||
}
|
||||
length = int64(u)
|
||||
}
|
||||
|
||||
if masked {
|
||||
if _, err = io.ReadFull(c.r, c.mask[:]); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return opcode, fin, length, masked, nil
|
||||
}
|
||||
|
||||
func (c *wsConn) readControlPayload(n int, masked bool) ([]byte, error) {
|
||||
payload := make([]byte, n)
|
||||
if _, err := io.ReadFull(c.r, payload); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if masked {
|
||||
for i := range payload {
|
||||
payload[i] ^= c.mask[i&3]
|
||||
}
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
// Write implements net.Conn: one binary frame per call. The app protocol's
|
||||
// sends are already whole packets (Context.Send), so this keeps writes atomic
|
||||
// and lets the peer deliver each packet as it was produced.
|
||||
func (c *wsConn) Write(p []byte) (int, error) {
|
||||
if err := c.writeFrame(wsOpBinary, p); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// writeFrame emits one FIN frame with the given opcode.
|
||||
func (c *wsConn) writeFrame(opcode byte, payload []byte) error {
|
||||
var hdr [10]byte
|
||||
hdr[0] = 0x80 | opcode
|
||||
n := 2
|
||||
switch {
|
||||
case len(payload) < 126:
|
||||
hdr[1] = byte(len(payload))
|
||||
case len(payload) <= 0xffff:
|
||||
hdr[1] = 126
|
||||
binary.BigEndian.PutUint16(hdr[2:], uint16(len(payload)))
|
||||
n = 4
|
||||
default:
|
||||
hdr[1] = 127
|
||||
binary.BigEndian.PutUint64(hdr[2:], uint64(len(payload)))
|
||||
n = 10
|
||||
}
|
||||
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
bufs := net.Buffers{hdr[:n], payload}
|
||||
if _, err := bufs.WriteTo(c.conn); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Close sends a best-effort close frame and closes the transport.
|
||||
func (c *wsConn) Close() error {
|
||||
c.closeMu.Lock()
|
||||
if c.closed {
|
||||
c.closeMu.Unlock()
|
||||
return nil
|
||||
}
|
||||
c.closed = true
|
||||
c.closeMu.Unlock()
|
||||
|
||||
_ = c.conn.SetWriteDeadline(time.Now().Add(time.Second))
|
||||
_ = c.writeFrame(wsOpClose, nil)
|
||||
return c.conn.Close()
|
||||
}
|
||||
|
||||
func (c *wsConn) LocalAddr() net.Addr { return c.conn.LocalAddr() }
|
||||
func (c *wsConn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() }
|
||||
|
||||
func (c *wsConn) SetDeadline(t time.Time) error { return c.conn.SetDeadline(t) }
|
||||
func (c *wsConn) SetReadDeadline(t time.Time) error { return c.conn.SetReadDeadline(t) }
|
||||
func (c *wsConn) SetWriteDeadline(t time.Time) error { return c.conn.SetWriteDeadline(t) }
|
||||
@@ -0,0 +1,407 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// wsTestPair dials a loopback listener, runs the server side of wrapWebSocket
|
||||
// on the accepted connection, performs the upgrade handshake, and returns both
|
||||
// ends. The loopback peer makes the test connection a trusted proxy, so the
|
||||
// forwarded-address path is exercised too.
|
||||
func wsTestPair(t *testing.T, s *Server, path string, extra map[string]string) (*wsConn, net.Conn, *bufio.Reader, string, string) {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
type result struct {
|
||||
conn net.Conn
|
||||
ip string
|
||||
}
|
||||
resCh := make(chan result, 1)
|
||||
go func() {
|
||||
srv, err := ln.Accept()
|
||||
if err != nil {
|
||||
resCh <- result{}
|
||||
return
|
||||
}
|
||||
conn, ip := s.wrapWebSocket(srv, peerIP(srv.RemoteAddr()))
|
||||
resCh <- result{conn, ip}
|
||||
}()
|
||||
|
||||
cli, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { cli.Close() })
|
||||
_ = cli.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
|
||||
// Write the upgrade request concurrently: the server blocks in its sniff
|
||||
// until the first bytes arrive.
|
||||
var b strings.Builder
|
||||
b.WriteString("GET " + path + " HTTP/1.1\r\n")
|
||||
b.WriteString("Host: yama.example.com\r\n")
|
||||
b.WriteString("Upgrade: websocket\r\n")
|
||||
b.WriteString("Connection: Upgrade\r\n")
|
||||
b.WriteString("Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n")
|
||||
b.WriteString("Sec-WebSocket-Version: 13\r\n")
|
||||
for k, v := range extra {
|
||||
b.WriteString(k + ": " + v + "\r\n")
|
||||
}
|
||||
b.WriteString("\r\n")
|
||||
go func() { _, _ = io.WriteString(cli, b.String()) }()
|
||||
|
||||
br := bufio.NewReader(cli)
|
||||
head := &strings.Builder{}
|
||||
for {
|
||||
line, err := br.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("read response: %v", err)
|
||||
}
|
||||
head.WriteString(line)
|
||||
if line == "\r\n" || line == "\n" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
res := <-resCh
|
||||
if res.conn == nil {
|
||||
t.Fatalf("wrapWebSocket rejected the connection:\n%s", head.String())
|
||||
}
|
||||
t.Cleanup(func() { res.conn.Close() })
|
||||
wc, ok := res.conn.(*wsConn)
|
||||
if !ok {
|
||||
t.Fatalf("wrapWebSocket returned %T, want *wsConn", res.conn)
|
||||
}
|
||||
_ = wc.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
return wc, cli, br, head.String(), res.ip
|
||||
}
|
||||
|
||||
// clientFrame builds a masked client frame (the only form a server should see).
|
||||
func clientFrame(opcode byte, payload []byte) []byte {
|
||||
var hdr []byte
|
||||
hdr = append(hdr, 0x80|opcode) // FIN + opcode
|
||||
mask := [4]byte{0x37, 0xfa, 0x21, 0x3d}
|
||||
n := len(payload)
|
||||
switch {
|
||||
case n < 126:
|
||||
hdr = append(hdr, byte(n)|0x80)
|
||||
case n <= 0xffff:
|
||||
hdr = append(hdr, 126|0x80, byte(n>>8), byte(n))
|
||||
default:
|
||||
hdr = append(hdr, 127|0x80)
|
||||
var ext [8]byte
|
||||
binary.BigEndian.PutUint64(ext[:], uint64(n))
|
||||
hdr = append(hdr, ext[:]...)
|
||||
}
|
||||
hdr = append(hdr, mask[:]...)
|
||||
body := make([]byte, n)
|
||||
for i := range payload {
|
||||
body[i] = payload[i] ^ mask[i&3]
|
||||
}
|
||||
return append(hdr, body...)
|
||||
}
|
||||
|
||||
// serverFrame reads one unmasked frame produced by the server.
|
||||
func serverFrame(t *testing.T, br *bufio.Reader) (byte, []byte) {
|
||||
t.Helper()
|
||||
var hdr [2]byte
|
||||
if _, err := io.ReadFull(br, hdr[:]); err != nil {
|
||||
t.Fatalf("read frame header: %v", err)
|
||||
}
|
||||
n := int(hdr[1] & 0x7f)
|
||||
switch n {
|
||||
case 126:
|
||||
var ext [2]byte
|
||||
if _, err := io.ReadFull(br, ext[:]); err != nil {
|
||||
t.Fatalf("read ext len: %v", err)
|
||||
}
|
||||
n = int(binary.BigEndian.Uint16(ext[:]))
|
||||
case 127:
|
||||
var ext [8]byte
|
||||
if _, err := io.ReadFull(br, ext[:]); err != nil {
|
||||
t.Fatalf("read ext len: %v", err)
|
||||
}
|
||||
n = int(binary.BigEndian.Uint64(ext[:]))
|
||||
}
|
||||
if hdr[1]&0x80 != 0 {
|
||||
t.Fatalf("server frame is masked")
|
||||
}
|
||||
payload := make([]byte, n)
|
||||
if _, err := io.ReadFull(br, payload); err != nil {
|
||||
t.Fatalf("read frame payload: %v", err)
|
||||
}
|
||||
return hdr[0] & 0x0f, payload
|
||||
}
|
||||
|
||||
func TestWebSocketUpgradeAndTunnel(t *testing.T) {
|
||||
s := New(DefaultConfig())
|
||||
// A device that prepends its own XFF entry must not be believed: nginx
|
||||
// appends the address it accepted the connection from on the right.
|
||||
wc, cli, br, head, realIP := wsTestPair(t, s, "/api/socket", map[string]string{
|
||||
"X-Forwarded-For": "203.0.113.9, 198.51.100.20",
|
||||
})
|
||||
if !strings.HasPrefix(head, "HTTP/1.1 101 ") {
|
||||
t.Fatalf("unexpected response head:\n%s", head)
|
||||
}
|
||||
// RFC 6455 sample key -> known accept value.
|
||||
if !strings.Contains(head, "Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") {
|
||||
t.Fatalf("missing/incorrect accept key:\n%s", head)
|
||||
}
|
||||
if realIP != "198.51.100.20" {
|
||||
t.Fatalf("forwarded real IP = %q, want 198.51.100.20 (last XFF entry)", realIP)
|
||||
}
|
||||
|
||||
// Client -> server: app bytes arrive as a plain stream.
|
||||
payload := []byte("Shine\x00\x00\x00\x03abc")
|
||||
if _, err := cli.Write(clientFrame(wsOpBinary, payload)); err != nil {
|
||||
t.Fatalf("write frame: %v", err)
|
||||
}
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(wc, got); err != nil {
|
||||
t.Fatalf("read tunneled bytes: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("tunneled bytes = %q, want %q", got, payload)
|
||||
}
|
||||
|
||||
// Server -> client: each Write becomes one binary frame.
|
||||
if _, err := wc.Write([]byte("pong-data")); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
opcode, body := serverFrame(t, br)
|
||||
if opcode != wsOpBinary || string(body) != "pong-data" {
|
||||
t.Fatalf("server frame = opcode %d payload %q", opcode, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketPingPongAndClose(t *testing.T) {
|
||||
s := New(DefaultConfig())
|
||||
wc, cli, br, _, _ := wsTestPair(t, s, "/x", nil)
|
||||
|
||||
// A ping is answered with a pong carrying the same payload, and the app
|
||||
// stream is unaffected.
|
||||
if _, err := cli.Write(clientFrame(wsOpPing, []byte("hi"))); err != nil {
|
||||
t.Fatalf("write ping: %v", err)
|
||||
}
|
||||
readDone := make(chan error, 1)
|
||||
go func() {
|
||||
buf := make([]byte, 8)
|
||||
_, err := wc.Read(buf)
|
||||
readDone <- err
|
||||
}()
|
||||
opcode, body := serverFrame(t, br)
|
||||
if opcode != wsOpPong || string(body) != "hi" {
|
||||
t.Fatalf("pong = opcode %d payload %q", opcode, body)
|
||||
}
|
||||
|
||||
// A close frame ends the pending Read with EOF and is echoed.
|
||||
if _, err := cli.Write(clientFrame(wsOpClose, []byte{0x03, 0xe8})); err != nil {
|
||||
t.Fatalf("write close: %v", err)
|
||||
}
|
||||
if err := <-readDone; err != io.EOF {
|
||||
t.Fatalf("Read after close = %v, want io.EOF", err)
|
||||
}
|
||||
opcode, _ = serverFrame(t, br)
|
||||
if opcode != wsOpClose {
|
||||
t.Fatalf("close echo opcode = %d", opcode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketLargeFrameStreams(t *testing.T) {
|
||||
s := New(DefaultConfig())
|
||||
wc, cli, _, _, _ := wsTestPair(t, s, "/x", nil)
|
||||
|
||||
payload := bytes.Repeat([]byte("0123456789ABCDEF"), 64*1024) // 1 MiB
|
||||
frame := clientFrame(wsOpBinary, payload)
|
||||
go func() { _, _ = cli.Write(frame) }()
|
||||
|
||||
got := make([]byte, len(payload))
|
||||
if _, err := io.ReadFull(wc, got); err != nil {
|
||||
t.Fatalf("read large frame: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, payload) {
|
||||
t.Fatalf("large frame corrupted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWebSocketRejectsBadHandshake(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
req string
|
||||
path string
|
||||
allow bool
|
||||
}{
|
||||
{
|
||||
name: "not an upgrade",
|
||||
req: "GET / HTTP/1.1\r\nHost: h\r\n\r\n",
|
||||
},
|
||||
{
|
||||
name: "missing key",
|
||||
req: "GET / HTTP/1.1\r\nHost: h\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n",
|
||||
},
|
||||
{
|
||||
name: "wrong path",
|
||||
req: "GET /other HTTP/1.1\r\nHost: h\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
|
||||
"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n",
|
||||
path: "/api/socket",
|
||||
},
|
||||
{
|
||||
name: "path match with query string",
|
||||
req: "GET /api/socket?v=1 HTTP/1.1\r\nHost: h\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n",
|
||||
path: "/api/socket",
|
||||
allow: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
cfg := DefaultConfig()
|
||||
cfg.WSPath = tt.path
|
||||
s := New(cfg)
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
defer ln.Close()
|
||||
|
||||
resCh := make(chan net.Conn, 1)
|
||||
go func() {
|
||||
srv, err := ln.Accept()
|
||||
if err != nil {
|
||||
resCh <- nil
|
||||
return
|
||||
}
|
||||
conn, _ := s.wrapWebSocket(srv, peerIP(srv.RemoteAddr()))
|
||||
resCh <- conn
|
||||
}()
|
||||
|
||||
cli, err := net.Dial("tcp", ln.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatalf("dial: %v", err)
|
||||
}
|
||||
defer cli.Close()
|
||||
_ = cli.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
if _, err := io.WriteString(cli, tt.req); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
|
||||
conn := <-resCh
|
||||
if tt.allow {
|
||||
if conn == nil {
|
||||
t.Fatalf("connection rejected, want accepted")
|
||||
}
|
||||
return
|
||||
}
|
||||
if conn != nil {
|
||||
t.Fatalf("connection accepted, want rejected")
|
||||
}
|
||||
br := bufio.NewReader(cli)
|
||||
line, err := br.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatalf("read reject response: %v", err)
|
||||
}
|
||||
if !strings.HasPrefix(line, "HTTP/1.1 400 ") {
|
||||
t.Fatalf("reject status = %q", strings.TrimSpace(line))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWSForwardedIP(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
headers map[string]string
|
||||
want string
|
||||
}{
|
||||
{"x-real-ip", map[string]string{"x-real-ip": "198.51.100.7"}, "198.51.100.7"},
|
||||
{"xff single", map[string]string{"x-forwarded-for": "198.51.100.8"}, "198.51.100.8"},
|
||||
// The rightmost entry is the one the trusted proxy appended; a device
|
||||
// that prepends a made-up address must not be able to choose its key.
|
||||
{"xff chain takes rightmost", map[string]string{"x-forwarded-for": "198.51.100.9, 10.0.0.1, 10.0.0.2"}, "10.0.0.2"},
|
||||
{"spoofed xff head ignored", map[string]string{"x-forwarded-for": "1.2.3.4, 198.51.100.10"}, "198.51.100.10"},
|
||||
{"xff wins over x-real-ip", map[string]string{"x-real-ip": "198.51.100.7", "x-forwarded-for": "198.51.100.9"}, "198.51.100.9"},
|
||||
{"garbage rightmost falls back", map[string]string{"x-forwarded-for": "198.51.100.11, not-an-ip"}, ""},
|
||||
{"x-real-ip fallback", map[string]string{"x-real-ip": "198.51.100.7", "x-forwarded-for": "not-an-ip"}, "198.51.100.7"},
|
||||
{"v4 with port", map[string]string{"x-real-ip": "198.51.100.7:5555"}, "198.51.100.7"},
|
||||
{"ipv6 literal", map[string]string{"x-real-ip": "2001:db8::1"}, "2001:db8::1"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := reqForwardedIP(tt.headers); got != tt.want {
|
||||
t.Errorf("reqForwardedIP(%v) = %q, want %q", tt.headers, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A header line that never ends must be rejected as soon as the handshake
|
||||
// budget is exhausted, not buffered until the process runs out of memory.
|
||||
func TestReadWSLineBounded(t *testing.T) {
|
||||
br := bufio.NewReader(bytes.NewReader(bytes.Repeat([]byte{'A'}, 1<<20)))
|
||||
total := 0
|
||||
_, err := readWSLine(br, &total)
|
||||
if !errors.Is(err, errWSProtocol) {
|
||||
t.Fatalf("err = %v, want errWSProtocol", err)
|
||||
}
|
||||
if total > wsMaxHandshakeBytes+br.Size() {
|
||||
t.Fatalf("read %d bytes, want at most %d", total, wsMaxHandshakeBytes+br.Size())
|
||||
}
|
||||
|
||||
// A normal line still parses.
|
||||
br = bufio.NewReader(strings.NewReader("GET /api/ws HTTP/1.1\r\n"))
|
||||
total = 0
|
||||
line, err := readWSLine(br, &total)
|
||||
if err != nil || line != "GET /api/ws HTTP/1.1" {
|
||||
t.Fatalf("line = %q, err = %v", line, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustedProxies(t *testing.T) {
|
||||
s := New(DefaultConfig())
|
||||
if !s.trustedProxy("127.0.0.1") || !s.trustedProxy("::1") {
|
||||
t.Fatal("loopback must be trusted by default")
|
||||
}
|
||||
if s.trustedProxy("203.0.113.9") {
|
||||
t.Fatal("public peer must not be trusted by default")
|
||||
}
|
||||
|
||||
cfg := DefaultConfig()
|
||||
cfg.TrustedProxies = []string{"10.0.0.0/8", "203.0.113.9"}
|
||||
s = New(cfg)
|
||||
if !s.trustedProxy("10.1.2.3") || !s.trustedProxy("203.0.113.9") {
|
||||
t.Fatal("configured proxies must be trusted")
|
||||
}
|
||||
if s.trustedProxy("127.0.0.1") {
|
||||
t.Fatal("an explicit list replaces the loopback defaults")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHeaderHasToken(t *testing.T) {
|
||||
tests := []struct {
|
||||
value string
|
||||
token string
|
||||
want bool
|
||||
}{
|
||||
{"Upgrade", "upgrade", true},
|
||||
{"keep-alive, Upgrade", "upgrade", true},
|
||||
{"upgrade, keep-alive", "upgrade", true},
|
||||
{"keep-alive", "upgrade", false},
|
||||
{"", "upgrade", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := headerHasToken(tt.value, tt.token); got != tt.want {
|
||||
t.Errorf("headerHasToken(%q, %q) = %v, want %v", tt.value, tt.token, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+573
-215
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user